Add UserGroup to chill (import from branch ticket-app-master)

Import the UserGrou feature from ticket-app-master branch. This includes:

- import all the entities and migrations, modification of typescript types, templating, and so on;
- apply some verification and formatting rules, like:
  - reformat file on chill.api.specs.yaml (MainBundle)
  - reformat file on types.ts (Main Bundle)

Migrations kept the same filename.
This commit is contained in:
Julien Fastré 2024-09-26 11:17:50 +02:00
parent 42438d5bb5
commit b4fa478177
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB
16 changed files with 823 additions and 259 deletions

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
class UserGroupApiController extends ApiController {}

View File

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\DataFixtures\ORM;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Doctrine\Persistence\ObjectManager;
class LoadUserGroup extends Fixture implements FixtureGroupInterface
{
public static function getGroups(): array
{
return ['user-group'];
}
public function load(ObjectManager $manager)
{
$centerASocial = $manager->getRepository(User::class)->findOneBy(['username' => 'center a_social']);
$centerBSocial = $manager->getRepository(User::class)->findOneBy(['username' => 'center b_social']);
$multiCenter = $manager->getRepository(User::class)->findOneBy(['username' => 'multi_center']);
$administrativeA = $manager->getRepository(User::class)->findOneBy(['username' => 'center a_administrative']);
$administrativeB = $manager->getRepository(User::class)->findOneBy(['username' => 'center b_administrative']);
$level1 = $this->generateLevelGroup('Niveau 1', '#eec84aff', '#000000ff', 'level');
$level1->addUser($centerASocial)->addUser($centerBSocial);
$manager->persist($level1);
$level2 = $this->generateLevelGroup('Niveau 2', ' #e2793dff', '#000000ff', 'level');
$level2->addUser($multiCenter);
$manager->persist($level2);
$level3 = $this->generateLevelGroup('Niveau 3', ' #df4949ff', '#000000ff', 'level');
$level3->addUser($multiCenter);
$manager->persist($level3);
$tss = $this->generateLevelGroup('Travailleur sociaux', '#43b29dff', '#000000ff', '');
$tss->addUser($multiCenter)->addUser($centerASocial)->addUser($centerBSocial);
$manager->persist($tss);
$admins = $this->generateLevelGroup('Administratif', '#334d5cff', '#000000ff', '');
$admins->addUser($administrativeA)->addUser($administrativeB);
$manager->persist($admins);
$manager->flush();
}
private function generateLevelGroup(string $title, string $backgroundColor, string $foregroundColor, string $excludeKey): UserGroup
{
$userGroup = new UserGroup();
return $userGroup
->setLabel(['fr' => $title])
->setBackgroundColor($backgroundColor)
->setForegroundColor($foregroundColor)
->setExcludeKey($excludeKey)
;
}
}

View File

@ -24,6 +24,7 @@ use Chill\MainBundle\Controller\LocationTypeController;
use Chill\MainBundle\Controller\NewsItemController; use Chill\MainBundle\Controller\NewsItemController;
use Chill\MainBundle\Controller\RegroupmentController; use Chill\MainBundle\Controller\RegroupmentController;
use Chill\MainBundle\Controller\UserController; use Chill\MainBundle\Controller\UserController;
use Chill\MainBundle\Controller\UserGroupApiController;
use Chill\MainBundle\Controller\UserJobApiController; use Chill\MainBundle\Controller\UserJobApiController;
use Chill\MainBundle\Controller\UserJobController; use Chill\MainBundle\Controller\UserJobController;
use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface; use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
@ -59,6 +60,7 @@ use Chill\MainBundle\Entity\LocationType;
use Chill\MainBundle\Entity\NewsItem; use Chill\MainBundle\Entity\NewsItem;
use Chill\MainBundle\Entity\Regroupment; use Chill\MainBundle\Entity\Regroupment;
use Chill\MainBundle\Entity\User; use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Entity\UserJob; use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Form\CenterType; use Chill\MainBundle\Form\CenterType;
use Chill\MainBundle\Form\CivilityType; use Chill\MainBundle\Form\CivilityType;
@ -803,6 +805,21 @@ class ChillMainExtension extends Extension implements
], ],
], ],
], ],
[
'class' => UserGroup::class,
'controller' => UserGroupApiController::class,
'name' => 'user-group',
'base_path' => '/api/1.0/main/user-group',
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true,
],
],
],
],
], ],
]); ]);
} }

View File

@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
#[ORM\Entity]
#[ORM\Table(name: 'chill_main_user_group')]
#[Serializer\DiscriminatorMap(typeProperty: 'type', mapping: ['user_group' => UserGroup::class])]
class UserGroup
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER, nullable: false)]
#[Serializer\Groups(['read'])]
private ?int $id = null;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::JSON, nullable: false, options: ['default' => '[]'])]
#[Serializer\Groups(['read'])]
private array $label = [];
/**
* @var \Doctrine\Common\Collections\Collection<int, \Chill\MainBundle\Entity\User>
*/
#[ORM\ManyToMany(targetEntity: User::class)]
#[ORM\JoinTable(name: 'chill_main_user_group_user')]
private Collection $users;
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: false, options: ['default' => '#ffffffff'])]
#[Serializer\Groups(['read'])]
private string $backgroundColor = '#ffffffff';
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: false, options: ['default' => '#000000ff'])]
#[Serializer\Groups(['read'])]
private string $foregroundColor = '#000000ff';
/**
* Groups with same exclude key are mutually exclusive: adding one in a many-to-one relationship
* will exclude others.
*
* An empty string means "no exclusion"
*/
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: false, options: ['default' => ''])]
#[Serializer\Groups(['read'])]
private string $excludeKey = '';
public function __construct()
{
$this->users = new ArrayCollection();
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->contains($user)) {
$this->users->removeElement($user);
}
return $this;
}
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): array
{
return $this->label;
}
public function getUsers(): Collection
{
return $this->users;
}
public function getForegroundColor(): string
{
return $this->foregroundColor;
}
public function getExcludeKey(): string
{
return $this->excludeKey;
}
public function getBackgroundColor(): string
{
return $this->backgroundColor;
}
public function setForegroundColor(string $foregroundColor): self
{
$this->foregroundColor = $foregroundColor;
return $this;
}
public function setBackgroundColor(string $backgroundColor): self
{
$this->backgroundColor = $backgroundColor;
return $this;
}
public function setExcludeKey(string $excludeKey): self
{
$this->excludeKey = $excludeKey;
return $this;
}
public function setLabel(array $label): self
{
$this->label = $label;
return $this;
}
/**
* Checks if the current object is an instance of the UserGroup class.
*
* In use in twig template, to discriminate when there an object can be polymorphic.
*
* @return bool returns true if the current object is an instance of UserGroup, false otherwise
*/
public function isUserGroup(): bool
{
return true;
}
}

View File

@ -1,6 +1,6 @@
export interface DateTime { export interface DateTime {
datetime: string; datetime: string;
datetime8601: string datetime8601: string;
} }
export interface Civility { export interface Civility {
@ -12,8 +12,8 @@ export interface Job {
id: number; id: number;
type: "user_job"; type: "user_job";
label: { label: {
"fr": string; // could have other key. How to do that in ts ? fr: string; // could have other key. How to do that in ts ?
} };
} }
export interface Center { export interface Center {
@ -26,8 +26,8 @@ export interface Scope {
id: number; id: number;
type: "scope"; type: "scope";
name: { name: {
"fr": string fr: string;
} };
} }
export interface User { export interface User {
@ -42,15 +42,26 @@ export interface User {
// todo: mainCenter; mainJob; etc.. // todo: mainCenter; mainJob; etc..
} }
export interface UserGroup {
type: "chill_main_user_group" | "user_group";
id: number;
label: TranslatableString;
backgroundColor: string;
foregroundColor: string;
excludeKey: string;
}
export type UserGroupOrUser = User | UserGroup;
export interface UserAssociatedInterface { export interface UserAssociatedInterface {
type: "user"; type: "user";
id: number; id: number;
}; }
export type TranslatableString = { export type TranslatableString = {
fr?: string; fr?: string;
nl?: string; nl?: string;
} };
export interface Postcode { export interface Postcode {
id: number; id: number;
@ -62,7 +73,7 @@ export interface Postcode {
export type Point = { export type Point = {
type: "Point"; type: "Point";
coordinates: [lat: number, lon: number]; coordinates: [lat: number, lon: number];
} };
export interface Country { export interface Country {
id: number; id: number;
@ -70,7 +81,7 @@ export interface Country {
code: string; code: string;
} }
export type AddressRefStatus = 'match'|'to_review'|'reviewed'; export type AddressRefStatus = "match" | "to_review" | "reviewed";
export interface Address { export interface Address {
type: "address"; type: "address";
@ -98,7 +109,7 @@ export interface Address {
} }
export interface AddressWithPoint extends Address { export interface AddressWithPoint extends Address {
point: Point point: Point;
} }
export interface AddressReference { export interface AddressReference {
@ -138,7 +149,7 @@ export interface Location {
createdBy: User | null; createdBy: User | null;
updatedAt: DateTime | null; updatedAt: DateTime | null;
updatedBy: User | null; updatedBy: User | null;
email: string | null email: string | null;
name: string; name: string;
phonenumber1: string | null; phonenumber1: string | null;
phonenumber2: string | null; phonenumber2: string | null;

View File

@ -0,0 +1 @@
<span class="badge-user-group" style="color: {{ user_group.foregroundColor }}; background-color: {{ user_group.backgroundColor }};">{{ user_group.label|localize_translatable_string }}</span>

View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Templating\Entity;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Twig\Environment;
final readonly class UserGroupRender implements UserGroupRenderInterface
{
public function __construct(private TranslatableStringHelperInterface $translatableStringHelper, private Environment $environment) {}
public function renderBox($entity, array $options): string
{
/* @var $entity UserGroup */
return $this->environment->render('@ChillMain/Entity/user_group.html.twig', ['user_group' => $entity]);
}
public function renderString($entity, array $options): string
{
/* @var $entity UserGroup */
return $this->translatableStringHelper->localize($entity->getLabel());
}
public function supports(object $entity, array $options): bool
{
return $entity instanceof UserGroup;
}
}

View File

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Templating\Entity;
interface UserGroupRenderInterface extends ChillEntityRenderInterface {}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class UserGroupDoNotExclude extends Constraint
{
public string $message = 'The groups {{ excluded_groups }} do exclude themselves. Please choose one between them';
public string $code = 'e16c8226-0090-11ef-8560-f7239594db09';
public function getTargets()
{
return [self::PROPERTY_CONSTRAINT];
}
public function validatedBy()
{
return \Chill\MainBundle\Validation\Validator\UserGroupDoNotExclude::class;
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Validation\Validator;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
final class UserGroupDoNotExclude extends ConstraintValidator
{
public function __construct(private readonly TranslatableStringHelperInterface $translatableStringHelper) {}
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof \Chill\MainBundle\Validation\Constraint\UserGroupDoNotExclude) {
throw new UnexpectedTypeException($constraint, UserGroupDoNotExclude::class);
}
if (null === $value) {
return;
}
if (!is_iterable($value)) {
throw new UnexpectedValueException($value, 'iterable');
}
$groups = [];
foreach ($value as $gr) {
if ($gr instanceof UserGroup) {
$groups[$gr->getExcludeKey()][] = $gr;
}
}
foreach ($groups as $excludeKey => $groupByKey) {
if ('' === $excludeKey) {
continue;
}
if (1 < count($groupByKey)) {
$excludedGroups = implode(
', ',
array_map(
fn (UserGroup $group) => $this->translatableStringHelper->localize($group->getLabel()),
$groupByKey
)
);
$this->context
->buildViolation($constraint->message)
->setCode($constraint->code)
->setParameters(['excluded_groups' => $excludedGroups])
->addViolation();
}
}
}
}

View File

@ -29,6 +29,42 @@ components:
type: string type: string
text: text:
type: string type: string
UserById:
type: object
properties:
id:
type: integer
type:
type: string
enum:
- user
UserGroup:
type: object
properties:
id:
type: integer
type:
type: string
enum:
- user_group
label:
type: object
additionalProperties: true
backgroundColor:
type: string
foregroundColor:
type: string
exclusionKey:
type: string
UserGroupById:
type: object
properties:
id:
type: integer
type:
type: string
enum:
- user_group
Center: Center:
type: object type: object
properties: properties:
@ -236,7 +272,7 @@ paths:
minItems: 2 minItems: 2
maxItems: 2 maxItems: 2
postcode: postcode:
$ref: "#/components/schemas/PostalCode" $ref: '#/components/schemas/PostalCode'
steps: steps:
type: string type: string
street: street:
@ -934,6 +970,22 @@ paths:
schema: schema:
type: array type: array
items: items:
$ref: "#/components/schemas/NewsItem" $ref: '#/components/schemas/NewsItem'
403:
description: "Unauthorized"
/1.0/main/user-group.json:
get:
tags:
- user-group
summary: Return a list of users-groups
responses:
200:
description: "ok"
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/UserGroup'
403: 403:
description: "Unauthorized" description: "Unauthorized"

View File

@ -56,6 +56,10 @@ services:
Chill\MainBundle\Templating\Entity\UserRender: ~ Chill\MainBundle\Templating\Entity\UserRender: ~
Chill\MainBundle\Templating\Entity\UserGroupRender: ~
Chill\MainBundle\Templating\Entity\UserGroupRenderInterface:
alias: Chill\MainBundle\Templating\Entity\UserGroupRender
Chill\MainBundle\Templating\Listing\: Chill\MainBundle\Templating\Listing\:
resource: './../../Templating/Listing' resource: './../../Templating/Listing'

View File

@ -3,6 +3,9 @@ services:
autowire: true autowire: true
autoconfigure: true autoconfigure: true
Chill\MainBundle\Validation\:
resource: '../../Validation'
chill_main.validator_user_circle_consistency: chill_main.validator_user_circle_consistency:
class: Chill\MainBundle\Validator\Constraints\Entity\UserCircleConsistencyValidator class: Chill\MainBundle\Validator\Constraints\Entity\UserCircleConsistencyValidator
arguments: arguments:

View File

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\Migrations\Main;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20240416145021 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create tables for user_group';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE SEQUENCE chill_main_user_group_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE chill_main_user_group (id INT NOT NULL, label JSON DEFAULT \'[]\' NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE TABLE chill_main_user_group_user (usergroup_id INT NOT NULL, user_id INT NOT NULL, PRIMARY KEY(usergroup_id, user_id))');
$this->addSql('CREATE INDEX IDX_1E07F044D2112630 ON chill_main_user_group_user (usergroup_id)');
$this->addSql('CREATE INDEX IDX_1E07F044A76ED395 ON chill_main_user_group_user (user_id)');
$this->addSql('ALTER TABLE chill_main_user_group_user ADD CONSTRAINT FK_1E07F044D2112630 FOREIGN KEY (usergroup_id) REFERENCES chill_main_user_group (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE chill_main_user_group_user ADD CONSTRAINT FK_1E07F044A76ED395 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
$this->addSql('DROP SEQUENCE chill_main_user_group_id_seq');
$this->addSql('DROP TABLE chill_main_user_group_user');
$this->addSql('DROP TABLE chill_main_user_group');
}
}

View File

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\Migrations\Main;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20240422091752 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add colors and exclude string to user groups';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE chill_main_user_group ADD backgroundColor TEXT DEFAULT \'#ffffffff\' NOT NULL');
$this->addSql('ALTER TABLE chill_main_user_group ADD foregroundColor TEXT DEFAULT \'#000000ff\' NOT NULL');
$this->addSql('ALTER TABLE chill_main_user_group ADD excludeKey TEXT DEFAULT \'\' NOT NULL');
$this->addSql('ALTER INDEX idx_1e07f044d2112630 RENAME TO IDX_738BC82BD2112630');
$this->addSql('ALTER INDEX idx_1e07f044a76ed395 RENAME TO IDX_738BC82BA76ED395');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE chill_main_user_group DROP backgroundColor');
$this->addSql('ALTER TABLE chill_main_user_group DROP foregroundColor');
$this->addSql('ALTER TABLE chill_main_user_group DROP excludeKey');
$this->addSql('ALTER INDEX idx_738bc82bd2112630 RENAME TO idx_1e07f044d2112630');
$this->addSql('ALTER INDEX idx_738bc82ba76ed395 RENAME TO idx_1e07f044a76ed395');
}
}

View File

@ -3,8 +3,10 @@
*/ */
span.badge-user, span.badge-user,
span.badge-user-group,
span.badge-person, span.badge-person,
span.badge-thirdparty { span.badge-thirdparty {
margin: 0.2rem 0.1rem;
display: inline-block; display: inline-block;
padding: 0 0.5em !important; padding: 0 0.5em !important;
background-color: $white; background-color: $white;
@ -18,6 +20,11 @@ span.badge-thirdparty {
} }
} }
span.badge-user-group {
font-weight: 600;
border-width: 0px;
}
span.badge-user { span.badge-user {
border-bottom-width: 1px; border-bottom-width: 1px;
&.system { &.system {