Compare commits

...

492 Commits

Author SHA1 Message Date
Pol Dellaiera
1a22c919a6 chore: Merge composer.json files. 2021-06-08 11:16:57 +02:00
Pol Dellaiera
68755989b5 chore: Add Monorepo Builder configuration. 2021-06-08 11:16:57 +02:00
Pol Dellaiera
0f5ee5bc86 chore: Update composer.json. 2021-06-08 11:16:57 +02:00
1967d6ea4c Merge branch 'features/household-context' into 'master'
Create an household context

See merge request Chill-Projet/chill-bundles!74
2021-06-07 15:04:44 +00:00
0fe70d00ec Merge branch 'remove-uneeded-service-definition' into 'master'
[simplification] Remove custom service definitions.

See merge request Chill-Projet/chill-bundles!72
2021-06-07 08:29:55 +00:00
Pol Dellaiera
7a33c37b51 Fix path. 2021-06-04 15:52:13 +02:00
Pol Dellaiera
a6c4b4eb55 Remove custom service definitions. 2021-06-04 15:52:12 +02:00
3e57ff3ffa Merge remote-tracking branch 'origin/master' into features/household-context 2021-06-04 15:11:36 +02:00
6cbbce03c4 Merge branch 'features/household' into 'master'
Manage household

See merge request Chill-Projet/chill-bundles!70
2021-06-04 13:10:42 +00:00
ef98111a2f Merge remote-tracking branch 'origin/master' into features/household 2021-06-04 15:03:00 +02:00
55fa16ce56 fix missing postgresql extension: correct class name 2021-06-04 14:54:14 +02:00
80ccb76794 Merge branch 'master' into 38_modal_on-the-fly 2021-06-04 14:18:54 +02:00
nobohan
0ce814cf52 hotfix: delete duplicate key in ChillPersonBundle messages translation 2021-06-04 09:34:36 +02:00
nobohan
f6d4d32ce4 fix conflict when merging 2021-06-03 15:11:09 +02:00
937be1af3a fix html5 birthdate field on modal form OnTheFly 2021-06-03 14:34:52 +02:00
nobohan
43fb020272 address: remove serializer config (it is autowired) 2021-06-03 13:01:24 +02:00
nobohan
f26fafb2f2 address: remove comment 2021-06-03 10:35:27 +02:00
nobohan
e1e3051d00 address: correct customizeQuery 2021-06-03 10:33:09 +02:00
nobohan
a659263af6 addresses: translations 2021-06-03 10:27:17 +02:00
nobohan
9333b6d2df address: correct customizeQuery 2021-06-03 10:22:20 +02:00
4d0cfbb396 OnTheFly modal, Person Sub-component: create/edit form, show 2021-06-02 22:29:09 +02:00
e9caa7b4b8 add groups on household serialization 2021-06-02 21:44:49 +02:00
261acdfd24 Merge branch 'features/household' into features/household-context 2021-06-02 16:48:54 +02:00
17481798fb fix duplicate in messages.fr.yml 2021-06-02 16:38:59 +02:00
edb8aa1dfe Merge branch 'master' into features/household 2021-06-02 16:28:24 +02:00
93a67c9ab9 Merge branch 'fix-person-tests'
Conflicts:
	src/Bundle/ChillPersonBundle/translations/messages.fr.yml
2021-06-02 16:25:37 +02:00
980a305456 Merge branch 'dune-risky'
Conflicts:
	src/Bundle/ChillActivityBundle/config/services.yaml
	src/Bundle/ChillPersonBundle/translations/messages.fr.yml
2021-06-02 16:23:45 +02:00
0158c6f2ed add tests for household 2021-06-02 16:21:01 +02:00
ff5b0bc258 add list for addresses 2021-06-02 16:20:46 +02:00
a133f56dce add routes for household addresses, members, and addresses_moves 2021-06-02 15:45:39 +02:00
fa556bbba1 basic context for household 2021-06-02 11:44:36 +02:00
e8f3c499ee Merge branch 'dune-risky' into fix-person-tests 2021-06-02 00:47:14 +02:00
cfd9f1bab1 replace call to entity by class FQDN 2021-06-02 00:46:55 +02:00
nobohan
8011293b28 address form: add the possibility to create a new address 2021-06-01 21:55:34 +02:00
4562ed46db OnTheFly modal: adapt footer button for show/edit cases (bug minor)
[BUG] to reproduce:
* clic first on show item button
* in modal clic edit button
* close modal
* clic again on show item button
2021-06-01 10:48:34 +02:00
cd52f7e6e8 Merge branch 'fix-person-tests' into features/household 2021-05-31 21:40:24 +02:00
126ffc55bf Merge branch 'fix-getParticipationsContainsPerson' into 'master'
Fix `::getParticipationsContainsPerson`.

See merge request Chill-Projet/chill-bundles!50
2021-05-31 19:35:33 +00:00
f49c54d51f fix redirection after creating accompanying course in test 2021-05-31 21:31:02 +02:00
1410213258 Merge remote-tracking branch 'origin/master' into fix-person-tests 2021-05-31 21:17:56 +02:00
35e0b98687 temporarily remove test for person duplicate 2021-05-31 21:16:31 +02:00
8f1091b8a3 Merge branch '50-ajout-problematique-sociale-modele' into 'master'
Add many2many relation between socialIssue and accompanying period + api endpoint

See merge request Chill-Projet/chill-bundles!53
2021-05-31 19:11:15 +00:00
c269bfe278 fix type-hinting for person repository 2021-05-31 21:09:14 +02:00
041b1dfc51 Controller action to move members of an household 2021-05-31 20:42:07 +02:00
718d6c2375 add basic on-the-fly sub-components, to show/edit/create person/thirdparty 2021-05-31 19:25:37 +02:00
158b572879 replace all links and buttons involved by OnTheFly component 2021-05-31 15:52:26 +02:00
68059a9938 add new OnTheFly vue sub-component 2021-05-31 12:59:11 +02:00
543f6b20dd firstname and lastname in same column 2021-05-31 11:39:15 +02:00
ace3b1969e Rename membership edition and add more fixtures 2021-05-28 18:26:22 +02:00
edc86af659 add tests for moving houshold 2021-05-28 18:01:20 +02:00
87ba68971c first impl of person Mover + add fixtures 2021-05-28 16:41:37 +02:00
94bcbac06a add extension btree_gist to postgres 2021-05-28 13:55:06 +02:00
74520330b1 add position for household and prefix tables names 2021-05-28 13:25:41 +02:00
nobohan
935006eae3 addresses form: add default country value 2021-05-28 12:31:08 +02:00
nobohan
165012b302 address: POST an address 2021-05-28 10:14:54 +02:00
nobohan
057db09847 addresses: improve address multiselect 2021-05-28 09:06:07 +02:00
nobohan
063076d0cb address: use multiselect for city and address selection 2021-05-27 15:15:20 +02:00
nobohan
bcf2b9d834 address: use multiselect for country selection 2021-05-27 14:49:41 +02:00
nobohan
64d28106c8 address: POST a new address: treat the postcode 2021-05-27 12:34:45 +02:00
85dda8b680 hide flex-table test on page AccompanyingCourse history 2021-05-27 11:34:49 +02:00
2e1201418a Merge branch 'fix-activity-menubuilder-definition' into 'master'
fix activityBundle menuBuilder definition

See merge request Chill-Projet/chill-bundles!69
2021-05-27 08:40:29 +00:00
a9fb916843 fix activityBundle menuBuilder definition 2021-05-27 10:37:24 +02:00
e26e3ac67b Merge branch '59_parcours_resu_2' 2021-05-27 09:28:23 +02:00
562c72f7bb missing comma 2021-05-27 00:06:00 +02:00
6602e1b286 fix wording in timeline accompanying period test 2021-05-27 00:03:22 +02:00
b69aaeafd9 fix tests for search 2021-05-26 23:54:00 +02:00
aa473b5f70 fix errors on tests in person bundle 2021-05-26 23:25:36 +02:00
124e36b9d4 fix declaration of entity rendering 2021-05-26 22:58:28 +02:00
b88765c344 fix tests 2021-05-26 22:57:00 +02:00
f3427d6754 fix declaration of entity rendering 2021-05-26 22:56:35 +02:00
df00ac66f5 Merge remote-tracking branch 'origin/master' into fix-person-tests 2021-05-26 22:44:45 +02:00
2b12e61fbd Merge remote-tracking branch 'origin/fix-getParticipationsContainsPerson' into fix-person-tests 2021-05-26 22:38:25 +02:00
151e8deaeb fix some tests for person bundle 2021-05-26 22:37:37 +02:00
acbe93f9cf Merge remote-tracking branch 'origin/dune-risky' into fix-person-tests 2021-05-26 21:57:09 +02:00
358410cde1 Remove dead code 2021-05-26 19:44:58 +00:00
06c74ed5ed add menu into section 2021-05-26 21:14:42 +02:00
25c986cc61 fix rendering for timeline entries in center context 2021-05-26 18:10:51 +02:00
cad8174333 apply timelineSingleQuery on events 2021-05-26 18:05:02 +02:00
6c8f1f77ff improve flex-table and flex-box 2021-05-26 18:03:54 +02:00
75c586fbf8 fix documentation for timeline 2021-05-26 17:58:58 +02:00
2cb9dfc250 add tasks to global timeline 2021-05-26 17:50:54 +02:00
3b2d4142c1 Merge branch 'master' into 'gitlab-ci-fix-initialization'
# Conflicts:
#   phpunit.xml.dist
2021-05-26 14:33:58 +00:00
9a6bab7ba2 Update phpunit.xml.dist 2021-05-26 14:27:31 +00:00
c2bbee299c remove tests for person bundle 2021-05-26 13:56:42 +00:00
f4db9be557 remove tests for person, which are not fixed 2021-05-26 13:43:41 +00:00
5449efdd97 Increase memory for running phpunit 2021-05-26 13:35:38 +00:00
7896d288e7 Increase memory_limit for some operations 2021-05-26 13:31:25 +00:00
b98d6fa505 launch a bash command for debugging 2021-05-26 13:25:29 +00:00
e4d1b951a3 Merge branch 'fix-missing-dependency' into 'master'
Fix repositories - add typing - add missing methods - remove obsolete phpdoc

See merge request Chill-Projet/chill-bundles!60
2021-05-26 13:22:25 +00:00
ae8e5bc2e3 Merge branch 'master' into 'fix-accompanying-period-opening'
# Conflicts:
#   src/Bundle/ChillPersonBundle/Controller/AccompanyingCourseApiController.php
2021-05-26 13:11:23 +00:00
9b66f7a83f Merge branch 'fix_load_fixtures' into 'master'
Fix load fixtures

See merge request Chill-Projet/chill-bundles!66
2021-05-26 11:04:43 +00:00
Pol Dellaiera
13d5b7078e Prevent infinite loop and memory leak. 2021-05-26 10:44:35 +02:00
37996651c4 Search list with periods, html/scss refactoring 2021-05-26 00:09:25 +02:00
Marc Ducobu
679665d9db Handle parent deletion in associated tables (ThirdPartyBundle) 2021-05-25 23:47:15 +02:00
Marc Ducobu
1d4edd5b7b Handle parent deletion in associated tables (PersonBundle) 2021-05-25 23:46:05 +02:00
Marc Ducobu
f1c77277f3 Handle parent deletion in associated tables (MainBundle) 2021-05-25 23:45:08 +02:00
6264171c0c Merge branch 'period-in-list-result' into 59_parcours_resu_2 2021-05-25 22:00:58 +02:00
902d8b52d3 Merge branch 'master' into 59_parcours_resu_2 2021-05-25 21:51:06 +02:00
caeb75ce13 vue requestor component, flex-table design 2021-05-25 21:44:15 +02:00
2f27674e05 flex table (row) design 2021-05-25 20:40:05 +02:00
ce9070e641 redirect to resume page after confirm action 2021-05-25 19:09:50 +02:00
5350a09951 apply timeline for report 2021-05-25 19:07:09 +02:00
31252461c9 load vue banner component for each page of AccompanyingCourse context
* vue css and js loaded from layout.html.twig
* rename 'show' template to 'edit' template
* overwrite js block for 'edit' template (load all component, not only banner)
2021-05-25 19:05:51 +02:00
73790db700 Merge branch 'add-doctrine-dbal-configuration-in-the-bundle' into 'master'
Add Doctrine DBAL postgis configuration in the bundle.

See merge request Chill-Projet/chill-bundles!65
2021-05-25 16:52:23 +00:00
nobohan
72795be040 post new address - WIP 2021-05-25 17:54:21 +02:00
fc2a2da75f page blocs design 2021-05-25 15:36:07 +02:00
nobohan
e88e9b1a6f addresses: add groups annotation to Country, postal code & address reference 2021-05-25 15:07:32 +02:00
nobohan
f7dea7f041 address selection: fix leaflet icon anchor + css for the form 2021-05-25 15:07:32 +02:00
nobohan
57a35f88be addresses reference: remove the load Adressess references command (has moved to the Vendee app) 2021-05-25 15:05:52 +02:00
nobohan
1b1eb45d15 address: improve load addresse reference command" 2021-05-25 15:05:52 +02:00
nobohan
65859f62f3 address selection: filter addresses based on cities 2021-05-25 15:05:52 +02:00
nobohan
4cc308c936 address selection: filter cities based on country 2021-05-25 15:05:52 +02:00
nobohan
2f28cb16ef addresses: import address reference: add pagination and error handling 2021-05-25 15:05:52 +02:00
nobohan
73ee77b8b2 addresses: import reference address from WFS using httpClientInterface 2021-05-25 15:05:52 +02:00
nobohan
830cda64e0 addresses: add symfony http-client as a dependency 2021-05-25 15:05:52 +02:00
nobohan
3bc510d116 addresses: add pagination in WFS request (WIP) 2021-05-25 15:05:52 +02:00
nobohan
5f8a506c84 addresses: add postcode in address reference load command 2021-05-25 15:05:52 +02:00
nobohan
bbb9dc2561 address reference: command for loading addresse reference (WIP) 2021-05-25 15:05:52 +02:00
nobohan
b51575fc49 address selection: order preferred countries 2021-05-25 15:05:51 +02:00
nobohan
fee37b5af3 address selection: use API points for Country and PostalCode + remove obsolet Address Controller 2021-05-25 15:05:51 +02:00
nobohan
0afcf3d79e address selection: move marker on the leaflet map on update map 2021-05-25 15:05:51 +02:00
juminet
743b456030 Merge branch 'add-api-for-person' into 'master'
Add api for person

See merge request Chill-Projet/chill-bundles!61
2021-05-25 12:59:59 +00:00
0dbd42ba5b Merge branch '139_demandeur' into 'master'
139 suite et fin

See merge request Chill-Projet/chill-bundles!62
2021-05-25 12:39:00 +00:00
7efbf2fce8 59 résumé, flex person position 2021-05-25 10:49:11 +02:00
9b1a66c992 fix query in timeline in activity and person bundle 2021-05-25 09:48:19 +02:00
Pol Dellaiera
cb897cfef1 Move Doctrine DBAL configuration in the appropriate and already existing code section. 2021-05-25 08:05:18 +02:00
Pol Dellaiera
bafbc2dd74 Add Doctrine DBAL postgis configuration in the bundle.
This can now be removed totally from the user application.
2021-05-25 07:57:12 +02:00
74541f360b fix activity timeline using TimelineSingleQuery 2021-05-24 20:26:33 +02:00
20a14c9ff4 cleaning chillmain.scss 2021-05-24 13:19:37 +02:00
cdade50d76 display person and thirdparty informations in accompanyingCourse index template (twig) 2021-05-24 11:23:03 +02:00
d4f96ee25f add 'with_icon' option in twig address macro 2021-05-24 11:22:27 +02:00
ca33580831 improve how refresh height sum and anchors position 2021-05-23 14:41:53 +02:00
64e37c5235 corrections 2021-05-23 14:03:43 +02:00
bf576e171c corrections 2021-05-23 12:35:47 +02:00
3f2fe6a138 Merge branch '_sticky_nav' into 139_demandeur 2021-05-23 11:51:38 +02:00
f18ccce814 comment console.log 2021-05-23 11:51:02 +02:00
2386a35eb7 fix bottom page exception + listen size changes too in main container 2021-05-23 11:47:01 +02:00
1fbda740a7 stickNav map elements switch active when scrolling 2021-05-23 11:13:21 +02:00
d35e1fe21e stickyNav item in a subcomponent 2021-05-23 10:16:18 +02:00
771b9eb616 anchors wip 2021-05-23 00:49:02 +02:00
4261ddcde4 cleaning 2021-05-23 00:10:26 +02:00
6ee03b7ebb top computed 2021-05-23 00:07:43 +02:00
1217578202 fix absolute / fixed navbar position 2021-05-22 23:42:25 +02:00
c7b6788288 Merge branch '139_demandeur' into _sticky_nav 2021-05-22 09:58:55 +02:00
02f1d2ff8a rename subcomponent 2021-05-22 09:56:09 +02:00
bb677152c9 sticky nav better position 2021-05-21 23:45:48 +02:00
ad6519fb87 minimalist squares navmap 2021-05-21 22:59:51 +02:00
d08f2e0e11 referrer component 2021-05-21 22:59:06 +02:00
73aeca0916 allow to import existing person from normalizer 2021-05-21 20:24:24 +02:00
080a54231f Merge remote-tracking branch 'origin/master' into add-api-for-person 2021-05-21 20:19:38 +02:00
b403569b16 improve and clean socialIssues 2021-05-21 19:47:39 +02:00
3abfb02962 Merge branch '_multiselect_store' into 139_demandeur 2021-05-21 19:23:45 +02:00
11a6d08023 add reactives social issues in banner 2021-05-21 19:16:09 +02:00
69ecc42055 enable fetch post/delete socialIssues 2021-05-21 19:06:16 +02:00
5f74c5297a move subcomponents in subfolder 2021-05-21 19:03:42 +02:00
34fcefa1bd temporary fix to allow creation on persons without centers 2021-05-21 18:31:20 +02:00
c9e6935f15 fix requirements on POST route 2021-05-21 18:30:52 +02:00
21cc0007fb transformValue to payload, body and method 2021-05-21 18:24:32 +02:00
ebe3bc5f7b add route for creating a person, and post api 2021-05-21 18:05:03 +02:00
132f11298e now i have to find id+method from payload 2021-05-21 17:05:14 +02:00
21f75c8a63 dont use mapActions 2021-05-21 16:54:25 +02:00
c1e1f65715 action resolve commit payload, but fetch body+method 2021-05-21 16:44:59 +02:00
Pol Dellaiera
5cc5e6a1f7 Fix missing dependency. 2021-05-21 16:35:26 +02:00
Pol Dellaiera
1f4735caac Fix missing ::find method. 2021-05-21 16:35:13 +02:00
Pol Dellaiera
d672a29dda Remove obsolete documentation, fix typing here and there. 2021-05-21 16:34:42 +02:00
68ebd60bc8 options managed by data, not store 2021-05-21 16:22:33 +02:00
4d12796289 get options and display selected 2021-05-21 16:08:26 +02:00
857298b8b8 add api Method GET on person 2021-05-21 16:04:18 +02:00
220f1ea0eb Merge branch '139_demandeur' into 'master'
139 Demandeur

See merge request Chill-Projet/chill-bundles!43
2021-05-21 12:53:03 +00:00
a88acd34fd design and translations 2021-05-21 11:41:36 +02:00
8ae113c872 person search rendering more reponsive 2021-05-20 19:20:06 +02:00
098a2ea620 improve AccompanyingCourse ux design 2021-05-20 18:42:40 +02:00
6a62b46dec first impl 2021-05-20 17:41:37 +02:00
8bd75429c1 improve AccompanyingCourse ux design 2021-05-20 16:45:47 +02:00
199e5a73d8 confirm modal "are you sure ?" 2021-05-20 15:43:10 +02:00
54d03275cf place html anchors: top, bottom of page + for each form section 2021-05-20 14:35:32 +02:00
8683f8faf3 titles: size and interaction 2021-05-20 13:24:53 +02:00
821b67723c Banner vue component fully manage AccompanyingCourse banner 2021-05-20 12:59:58 +02:00
ae1146c79c Confirm post request, change state step and hide components 2021-05-20 11:45:29 +02:00
050c325195 renaming AccompanyingCourse component in 'Banner' 2021-05-20 11:07:00 +02:00
5e0d869d9b Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-20 09:53:33 +02:00
32b8de8997 implements trackable on accompanying period 2021-05-19 23:08:13 +02:00
9f1f7ad3f7 skeleton for page "index accompanying course" 2021-05-19 22:36:47 +02:00
9da4c1ebeb get SocialIssues List in multiselect 2021-05-19 22:20:16 +02:00
9b7a52064a page 'create a course' for draft accompanying course 2021-05-19 22:15:04 +02:00
faad3f5f47 add menu for creating an accompanying period 2021-05-19 21:48:40 +02:00
Pol Dellaiera
7595d70ada Fix ::getPersons.
1. Add more typing informations.
2021-05-19 19:10:03 +02:00
Pol Dellaiera
484259c8ab Fix ::canBeReOpened.
1. Fix call to `::getOpenParticipationContainsPerson` instead of `::getParticipationsContainsPerson`.
2. Use early returns to reduce cyclomatic complexity.
3. Avoid storing variable that are used only once.
2021-05-19 19:10:03 +02:00
Pol Dellaiera
a6e0b16032 Fix ::getOpenParticipationContainsPerson
1. The filter predicate must return a boolean
2. The $person variable is not needed
2021-05-19 19:10:03 +02:00
Pol Dellaiera
9d34968b88 Fix ::getParticipationsContainsPerson.
1. `::getParticipations()` does not accept any argument.
2. The filter predicate must return a boolean.
2021-05-19 19:10:03 +02:00
f548121312 wip 2021-05-19 18:29:24 +02:00
1ecb1abc80 Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-19 16:22:28 +02:00
28a45992c6 first vue multiselect implementation 2021-05-19 16:18:56 +02:00
c39097f164 removeComment button replaced by link
that allows to keep it both inside <form> and in <ul class="record_actions">
2021-05-19 16:18:56 +02:00
30b127bc88 vue-component dev style more discrete, + disable flashbag for comment 2021-05-19 16:17:57 +02:00
25d7fc36a4 action to create an accompanyinig period 2021-05-19 16:14:36 +02:00
03bd1674e1 fix resource repository 2021-05-19 16:13:19 +02:00
b018a50a7e encore_entry_link_tags allows to use <style scoped> in vue files 2021-05-19 16:07:37 +02:00
4440cf8a24 add missing declaration property 2021-05-19 16:00:06 +02:00
6bd7a0105d Merge branch 'quick-fix-crud' into 'master'
Crud : fix sprintf pbm

See merge request Chill-Projet/chill-bundles!55
2021-05-19 13:15:35 +00:00
Marc Ducobu
51c2408878 Crud : fix sprintf pbm 2021-05-19 15:00:13 +02:00
242c77a30c partially revert 75ba07f18 (17/05) 2021-05-19 13:40:51 +02:00
22aa4afc02 action: confirm accompanying period + create workflow 2021-05-19 13:20:59 +02:00
04e9e30972 quick fix for banner 2021-05-19 11:44:09 +02:00
d536da3581 initialcomment: conditionnal delete button 2021-05-19 10:37:29 +02:00
27f49b2aa3 fix initialComment with patch endpoint 2021-05-19 10:34:17 +02:00
912a8d53af Merge branch 'fix_issue_43_add_entities' into 'master'
LoadFixtures, replacing Array() by []

See merge request Chill-Projet/chill-bundles!54
2021-05-18 18:13:41 +00:00
9ef397e935 fix docblock 2021-05-18 20:12:03 +02:00
eca8172c6d doc for multi-types denormalizer 2021-05-18 20:11:49 +02:00
f3802e36b3 documentation for api 2021-05-18 19:58:29 +02:00
2f9c7c38b5 fix read group on scope 2021-05-18 19:58:16 +02:00
Marc Ducobu
d73fd697dd Array() -> [] 2021-05-18 19:21:52 +02:00
f35889339d remove comment in constructor 2021-05-18 19:20:50 +02:00
8e95166c24 fix replacing an initial comment in accompanying period 2021-05-18 19:19:22 +02:00
30c53b17f7 documentation for get/index social issues api endpoint 2021-05-18 19:13:30 +02:00
2610730219 add initial comment to accompanying period 2021-05-18 19:04:09 +02:00
5dd99d201b Merge remote-tracking branch 'origin/master' into 50-ajout-problematique-sociale-modele 2021-05-18 17:30:28 +02:00
d327dae9fa Merge remote-tracking branch 'origin/139_demandeur' into 139_demandeur 2021-05-18 17:24:28 +02:00
2bdbb20154 Merge remote-tracking branch 'origin/master' into 139_demandeur 2021-05-18 17:24:09 +02:00
14bd211a5f add api endpoint for adding/remove social issue on accompanying period 2021-05-18 17:18:35 +02:00
35627203e6 remove props for ToggleFlags component 2021-05-18 16:23:40 +02:00
f978636d57 add intensity in teleported toggleFlags 2021-05-18 16:14:10 +02:00
e095cac7e0 Merge branch '50-ajout-problematique-sociale-modele' into 139_demandeur 2021-05-18 16:11:18 +02:00
c5b0d6e2bd Merge branch '20-use-fqdn-in-person-creation-form' into 'master'
Use FQDN in PersonCreation form

See merge request Chill-Projet/chill-bundles!52
2021-05-18 14:06:57 +00:00
Pol Dellaiera
905cb66011 Merge branch 'fix-services-repository-loading' into 'master'
Update repositories service discovery.

See merge request Chill-Projet/chill-bundles!34
2021-05-18 12:13:34 +00:00
eaac97221f add many2many relation between socialIssue and accompanying period + api endpoint 2021-05-18 13:48:11 +02:00
Pol Dellaiera
893c38fba4 Fix collateral things. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
f867f4985d Add a note about the custom service definition for the repository. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
aebeefcf80 Use repositories as services. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
3fc6c0c479 refactor: Update entities. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
ce854cb58f refactor: Upgrade repositories. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
ed4f1344c2 Service autodiscovery, autowire and autoconfigure. 2021-05-18 12:02:00 +02:00
Marc Ducobu
86dbe527d8 Adding missing arguments for services 2021-05-18 12:02:00 +02:00
Pol Dellaiera
69a56fb433 Update repositories service discovery. 2021-05-18 12:02:00 +02:00
Pol Dellaiera
a7fad0ca1b tests: Update relevant tests but it seems that it is currently broken. 2021-05-18 12:00:58 +02:00
Pol Dellaiera
9b8c34a9be Symfony form: use FQDN instead of custom constant. 2021-05-18 12:00:58 +02:00
5acc78507e building Confirm component 2021-05-18 10:59:06 +02:00
1722cf721e init SocialIssue, Referrer and Confirm components 2021-05-18 09:57:10 +02:00
75ba07f181 course banner: opening date by user 2021-05-17 22:50:28 +02:00
5b635fbe58 fix input value for radio selection in AddPersons modal
selected value is different for radio or checkbox
for radio value is an object, for checkbox vaue is an array of objects
2021-05-17 22:19:23 +02:00
e0dc0a8fdb add Comment component, make POST comment request 2021-05-17 16:10:36 +02:00
2aa13dceff catchError mutation 2021-05-17 15:56:14 +02:00
ea477a9842 add accompanying period opening/closing to global timeline 2021-05-17 13:24:50 +02:00
73653744d7 Prepare for deprecation of class Role, and add method to filter centers 2021-05-17 13:23:58 +02:00
55264da092 prepare postComment fetch request 2021-05-17 12:05:46 +02:00
38f5854c6d AddPersons, move/rename files 2021-05-17 12:04:22 +02:00
3c6d3f30d2 teleport toggle flags in header 2021-05-17 11:25:20 +02:00
a6d6a962cd Merge branch 'issue_43_add_entities' into 'master'
Add fixtures for social work

See merge request Chill-Projet/chill-bundles!46
2021-05-17 08:24:36 +00:00
6256d6a19e Apply 1 suggestion(s) to 1 file(s) 2021-05-17 08:23:21 +00:00
8841af8d2b remove references to no-static container 2021-05-17 10:07:23 +02:00
0a9b8ba0b0 remove test that concerns old code 2021-05-17 10:05:03 +02:00
9710f8be63 display resources table row 2021-05-14 21:25:30 +02:00
d872bf65dd reactive toggle flags emergency and confidential 2021-05-14 20:42:22 +02:00
c3ef8d112c first impl for global timeline: apply on activities 2021-05-14 16:25:56 +02:00
f2a4347de7 Merge branch 'master' into fix-person-tests 2021-05-14 10:24:35 +02:00
51a4880fdb Merge branch 'fix-gitlab-ci-with-postgis' into 'master'
Update .gitlab-ci.yml - change db image

See merge request Chill-Projet/chill-bundles!51
2021-05-14 08:24:10 +00:00
a4d22b0fcb Update .gitlab-ci.yml - change db image 2021-05-14 08:16:28 +00:00
8d051800a4 Merge branch 'fix-accompagnyingperiod' into 'master'
Make sure the called method has the proper name.

See merge request Chill-Projet/chill-bundles!48
2021-05-14 07:58:33 +00:00
Pol Dellaiera
c0b59162a1 Rename ::participationsContainsPerson($person); in ::getParticipationsContainsPerson($person);. 2021-05-14 08:32:22 +02:00
0e53a081c7 Merge branch 'fix-person-tests' into 139_demandeur 2021-05-13 21:44:22 +02:00
d76f6d716f exclude tests which concerns exports for persons 2021-05-13 21:44:09 +02:00
f1d5d9840e add route for scope on participation 2021-05-13 17:44:54 +02:00
f3eb418409 test sur création et retrait commentaire 2021-05-13 17:31:46 +02:00
3e85529468 add route for comment + track update/creation of entities 2021-05-13 17:25:24 +02:00
05798688d0 refactore method addRemoveSomething, and add test for resources 2021-05-13 16:29:05 +02:00
01f35eed04 rename all interlocutor in resource 2021-05-13 11:09:07 +02:00
aef97cca32 fetch post resource 2021-05-13 10:59:24 +02:00
87e2ac9386 handling multi types and acc-period/repositories endpoint 2021-05-13 00:54:44 +02:00
4a04628d5b adapt payload body to entity convention with type + id 2021-05-12 18:50:18 +02:00
0af78f814c Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-12 18:34:03 +02:00
929d40ff6e add particiaption to openapi 2021-05-12 18:32:15 +02:00
68f6642ff2 Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-12 17:52:49 +02:00
91e4d585ff add a discrimnator type on onbjects 2021-05-12 17:51:37 +02:00
eac42581a6 interlocutors: actions, mutations, fetch request (wip) 2021-05-12 17:40:23 +02:00
Marc Ducobu
4e50d0ace9 Merge branch 'fix-style-stuff2' into 'master'
Fix style stuff2

See merge request Chill-Projet/chill-bundles!47
2021-05-12 14:06:46 +00:00
Marc Ducobu
0b54adeb59 Removing spaces at the end of line 2021-05-12 16:04:42 +02:00
Marc Ducobu
5d23de4862 Removing spaces at the end of line 2021-05-12 16:04:27 +02:00
Marc Ducobu
eda454cb9d Add fixtures for social work 2021-05-12 15:40:40 +02:00
6da8f1c107 when passed option uniq, suggestions are with radio button, not checkbox 2021-05-12 15:26:46 +02:00
4fb487dcef requestor logic, is_anonymous patch request 2021-05-12 14:49:26 +02:00
0d6a339b53 Merge branch '_23_addresses_form_2' into 139_demandeur 2021-05-12 10:45:47 +02:00
c6525be444 get countries when opening modal + fix select placeholders 2021-05-12 10:43:12 +02:00
cb846891d6 add store postAddress fetch request 2021-05-12 09:54:37 +02:00
2aed37757e Merge branch '_23_addresses_form_2' of gitlab.com:Chill-Projet/chill-bundles into _23_addresses_form_2 2021-05-11 23:53:50 +02:00
444159b52a cleaning AddAdress refactor 2021-05-11 23:52:56 +02:00
7aed8e83ea refactoring AddAddress component 2021-05-11 23:41:32 +02:00
f7a807473d send 400 bad request on invalid json 2021-05-11 21:30:24 +02:00
f8e91c325d oups, forget a flush :) 2021-05-11 21:20:30 +02:00
a448405ce5 Add a denormalizer for fetching entities by id 2021-05-11 20:37:56 +02:00
a4989f99d6 Use annoations for serialization 2021-05-11 19:49:41 +02:00
3f64db3b3a remove 'u' from date normalizer 2021-05-11 19:11:22 +02:00
nobohan
7ee5ca0753 address selection: add API points for PostalCode and Country 2021-05-11 16:03:11 +02:00
41254db72f Merge branch '139_demandeur' into _23_addresses_form_2 2021-05-11 15:51:06 +02:00
nobohan
15e301b889 address selection: add more fields 2021-05-11 15:32:02 +02:00
061a7dd537 patch request for accompanying period 2021-05-11 15:05:26 +02:00
nobohan
c3926991ac address selection: fix leaflet icon url + others fix (WIP) 2021-05-11 14:56:56 +02:00
nobohan
ea0b2407df address selection: add leaflet css + add fields for the address extra information (WIP)' 2021-05-11 13:50:11 +02:00
569679238c add InterlocutorItem subcomponent 2021-05-11 13:49:43 +02:00
ed17f78da5 requestor, add checkbox isAnonymous 2021-05-11 13:48:40 +02:00
dfd9230541 Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-11 12:52:03 +02:00
65b751642f documentation for api 2021-05-11 10:33:52 +02:00
d6fd827f8b interlocutors wip 2021-05-10 22:02:21 +02:00
162b0099b2 addpersons modal title from outside component 2021-05-10 21:42:02 +02:00
e0b689174a oups 2021-05-10 19:19:11 +02:00
edf4430fb1 Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-10 19:15:03 +02:00
040884a039 when option uniq is true, display message if you select multiple suggestions 2021-05-10 19:13:50 +02:00
f7c08f02c2 add and remove requestor functions 2021-05-10 18:46:21 +02:00
nobohan
2fe38945d2 Address selection: add a leaflet map 2021-05-10 17:31:22 +02:00
cece152c0b fix test for api requestors 2021-05-10 17:04:34 +02:00
4e31b3e424 Merge branch '139_demandeur' of gitlab.com:Chill-Projet/chill-bundles into 139_demandeur 2021-05-10 16:36:32 +02:00
109bf5ec5d suggestions, flex position for little screens + thirdparty links 2021-05-10 16:33:41 +02:00
4f3f16d9b0 Set requestor for accompanying period 2021-05-10 15:59:58 +02:00
nobohan
fe5745831c Address selection: add selectCountry and selectCity components 2021-05-10 15:21:38 +02:00
3447117742 fix postParticipation with new search endpoint structure 2021-05-10 14:17:48 +02:00
143f8f43fa pass options in search endpoint 2021-05-10 14:02:25 +02:00
36326a2a70 improve suggestions display, with more details, and different according to the entity 2021-05-10 13:27:41 +02:00
52637c2919 rewrite method add participation for new period's methods 2021-05-10 13:24:57 +02:00
f3a8552829 rewrite methods for participation 2021-05-10 13:21:28 +02:00
bfdfd19711 add uniq key property, allow multiple entity in suggestions 2021-05-10 13:11:58 +02:00
nobohan
efb9bc938a Address selection: add store + addressSuggestion 2021-05-10 12:12:04 +02:00
dcd1856ebb adapt api endpoint, resolve id parameter passed in api functions 2021-05-10 10:47:21 +02:00
43f3270171 add requestor, wip 2021-05-09 09:24:02 +02:00
b7fcac8f39 Merge branch 'selectAll' into addPersons_nostore 2021-05-09 09:16:12 +02:00
e521d06702 addpersons better ux with reset and selectall features 2021-05-09 09:11:49 +02:00
a260274549 addpersons better ux with reset features 2021-05-09 00:39:18 +02:00
b37a7d2690 requestor call AddPersons modal, and pass options until api (wip) 2021-05-08 21:14:46 +02:00
242c2b31a3 remove store AddPersons module 2021-05-08 20:59:47 +02:00
57c420e9dd no store for AddPersons, move store in data component
note: this allow to use same addPersons component
to add participations, requestor, or interlocutors.
each addPersons component has his own data()
2021-05-08 20:58:46 +02:00
ac67f56b09 bind options and key inside AddPersons component (wip) 2021-05-08 15:34:15 +02:00
b24eb93c57 addNewPersons() method is called out of addPerson component
note: this allow to use same addPersons component
to add participations, requestor, or interlocutors
2021-05-08 12:12:58 +02:00
0f59be04a7 accompanyingCourse steps, flags, .. translations and pills appearence 2021-05-08 11:42:42 +02:00
54eb15ea35 disable close participation button when is closed 2021-05-08 11:20:53 +02:00
a85f170e2d fix delete route change + fix closeParticipation row position 2021-05-08 10:56:43 +02:00
226f71ab2b requestor, just display datas 2021-05-07 21:37:14 +02:00
a887326611 Merge remote-tracking branch 'origin/136-add-search-endpoint' into 139_demandeur 2021-05-07 19:27:19 +02:00
8ed2e7585d fix random thid party 2021-05-07 19:22:47 +02:00
7a1ad24f0e add endoint /api/1.0/search.json?q=xxx with fake data
See https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/136
2021-05-07 19:11:10 +02:00
nobohan
b934c2eeaf add POC of a vuejs component (opens a modal) for address selection 2021-05-07 17:38:15 +02:00
de0e3f7dfd move test in a test component, clean requestor component 2021-05-07 16:53:29 +02:00
44c9a65505 cleaning console log 2021-05-07 16:22:02 +02:00
038d7ad2e1 load third party fixtures 2021-05-07 16:07:53 +02:00
nobohan
c1b727b1c8 Add API endpoints for Address and AddressReference (again) 2021-05-07 16:02:39 +02:00
a63c38b6aa Merge branch '37_modal_add-persons' 2021-05-07 15:46:38 +02:00
8915c42008 endpoint DELETE participation works ! 2021-05-07 15:44:08 +02:00
503293a359 Merge branch 'master' into '37_modal_add-persons'
# Conflicts:
#   src/Bundle/ChillPersonBundle/Entity/AccompanyingPeriod.php
#   src/Bundle/ChillPersonBundle/chill.webpack.config.js
2021-05-07 13:35:48 +00:00
7bdf71315a move Modal component in ChillMainAssets 2021-05-07 15:28:50 +02:00
6f5d457122 renaming store state dict name 2021-05-07 15:16:27 +02:00
b4274264a7 create addPersons store module, move state/getters/mutations/actions in module 2021-05-07 15:04:36 +02:00
8002725c87 fix doc for api 2021-05-07 12:42:49 +02:00
2c9edf3741 Set Collection normalization to fit into specs from https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/136 2021-05-07 12:13:24 +02:00
3f562449e1 Merge branch 'issue23_addresses' into 'master'
Issue23 addresses

See merge request Chill-Projet/chill-bundles!12
2021-05-07 09:27:56 +00:00
1cce39bcb5 Merge branch 'bootstrap-api' into 'master'
Bootstrap api

See merge request Chill-Projet/chill-bundles!35
2021-05-07 09:14:11 +00:00
c93d5ceb16 remove references to ->getContainer in favor of static:: 2021-05-07 10:56:49 +02:00
ad690db886 display reset link + minor changes 2021-05-07 10:36:50 +02:00
nobohan
1b8462b40d update validto field in chill_main_address for legacy 2021-05-07 10:27:11 +02:00
Pol Dellaiera
8c98f2cf6e Update .gitignore file. 2021-05-07 09:04:29 +02:00
f3260f57a4 fix display elements order
selectAndSuggested method in store getter, is callable in all components,
and make union of two arrays: suggested and selected

* we need to have selected in last position (required for isChecked method to work well)
* but we want to display selected in first position (for better ux)

then, we use double inversion to obtain good behaviour
2021-05-06 19:23:28 +02:00
b4ad0128e4 manage selected and suggested arrays: fix duplicate 2021-05-06 19:15:25 +02:00
e1c8278f71 Merge branch 'fix-return-type' into 'master'
Fix return type of Person::getAddresses().

See merge request Chill-Projet/chill-bundles!39
2021-05-06 15:05:35 +00:00
Pol Dellaiera
ed3f46ce7f Fix return type. 2021-05-06 17:01:11 +02:00
33457d3cbc Merge branch 'fix-accompanying-period-opening' into bootstrap-api 2021-05-06 16:02:13 +02:00
6df8e6dec8 add person suite to phpunit 2021-05-06 15:55:02 +02:00
f9b8f13dd6 Merge branch 'fix-accompanying-period-opening' into fix-person-tests 2021-05-06 15:50:34 +02:00
e919b4322e fix accompanying period/remove person 2021-05-06 15:49:38 +02:00
7503c845df Merge branch 'dev-undefined-index' into 'master'
fix undefined index in person edit form

See merge request Chill-Projet/chill-bundles!26
2021-05-06 13:47:13 +00:00
3686a294d3 fix return type for person::getAddresses 2021-05-06 13:57:44 +02:00
b6131379f9 Merge remote-tracking branch 'origin/master' into bootstrap-api 2021-05-06 13:20:12 +02:00
e1fcc41ace avoiding duplicates between selected and suggested (wip)
see comments in store/index.js
2021-05-06 13:16:26 +02:00
f2a04cebe6 configure origin route into chillMainExtension 2021-05-06 13:12:18 +02:00
c693002ddb documentation for api - prepend config 2021-05-06 13:11:59 +02:00
ee77c8540a fix typos 2021-05-06 13:00:59 +02:00
a536d2780e fix state mutation for closeParticipation 2021-05-06 12:57:53 +02:00
f880598052 documentation for api 2021-05-06 12:56:19 +02:00
e7985ea52f customize controller for origin 2021-05-06 12:55:40 +02:00
f56dc65021 fix argument order 2021-05-06 12:55:12 +02:00
nobohan
4770758aee add migrations for addresse on household + add linkedtothirdparty on address 2021-05-06 12:36:58 +02:00
90fe484d81 fix api for rendering a single item 2021-05-06 12:18:47 +02:00
2b8bbe019d first impl for index action 2021-05-06 12:08:45 +02:00
9e1c151402 réinitialize suggested, avoiding double with selected (wip) 2021-05-06 10:57:04 +02:00
088e522292 Merge branch 'master' into _31_interface_creation_parcours 2021-05-06 10:55:22 +02:00
b8e6e98a74 fix payload error with add participation 2021-05-06 10:44:15 +02:00
2db847ada2 Merge branch 'drupol-fix-person-addresses' into 'master'
Fix person addresses

See merge request Chill-Projet/chill-bundles!33
2021-05-06 07:14:54 +00:00
07e0692783 bootstrap api and apply on accompanying period 2021-05-06 00:14:36 +02:00
e78d53064b closeParticipation fetch DELETE request 2021-05-05 21:48:00 +02:00
e6fcb5ff22 Merge branch '_test_closePerson' into _31_interface_creation_parcours 2021-05-05 20:47:39 +02:00
f02e33fda7 first impl for api 2021-05-05 20:33:34 +02:00
1bbec9efae improve addpersons store cycle: init query, selections and suggestions 2021-05-05 19:25:28 +02:00
3b53c4451c fix modal ux counter position 2021-05-05 18:45:51 +02:00
30f490959b for each selected, loop for post participation, then get response and commit state 2021-05-05 18:44:26 +02:00
nobohan
0a894b0db1 add new fields on Address and Household 2021-05-05 18:24:58 +02:00
c20e9507d5 prepare close participation button (wip) 2021-05-05 15:03:58 +02:00
f89c690f1b add scratch fontawesome 'remove' button 2021-05-05 13:36:45 +02:00
Pol Dellaiera
7819c1204c Merge branch '4-remove-unused-main-test-route' into 'master'
Issue #4: Remove obsolete route.

Closes #4

See merge request Chill-Projet/chill-bundles!31
2021-05-05 10:30:03 +00:00
nobohan
f61af9d02a add household and householdmembers entities + migration 2021-05-05 11:44:55 +02:00
Pol Dellaiera
e470a6a97e Merge remote-tracking branch 'tmp/fix-person-last-address' into drupol-fix-person-addresses 2021-05-05 11:24:18 +02:00
Pol Dellaiera
cd8c47449b Issue #4: Remove obsolete route. 2021-05-05 11:11:25 +02:00
120e7cade5 simplify store suggested array 2021-05-05 11:11:13 +02:00
ac550e05e8 improve addPersons modal ux 2021-05-05 09:29:57 +02:00
d6e7fadb4f Merge branch 'issue_43_admin_prosoc' into 'master'
URGENT : Fix namespace pbm

See merge request Chill-Projet/chill-bundles!30
2021-05-05 07:00:05 +00:00
Marc Ducobu
2be1c08c44 Fix namespace pbm 2021-05-04 19:14:50 +02:00
nobohan
86c177bbbb remove vuejs address component 2021-05-04 17:26:47 +02:00
Pol Dellaiera
d426d28ba0 Merge branch 'add-readme' into 'master'
docs: Add root README file.

See merge request Chill-Projet/chill-bundles!29
2021-05-04 13:14:14 +00:00
Pol Dellaiera
72e69fc0b3 docs: Add root README file. 2021-05-04 14:49:36 +02:00
cc8de353d4 moving selected counter + cleaning code 2021-05-04 10:48:58 +02:00
4495a5d33b Union suggested and selected results 2021-05-03 23:15:38 +02:00
9dffe30aad Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-05-03 22:53:47 +02:00
d393e74896 save checkboxes state in store 2021-05-03 22:44:28 +02:00
daf083dc88 save checkboxes state in store 2021-05-03 21:02:15 +02:00
nobohan
ce859697b5 Use json endpoint for showing address with Vuejs Components (WIP) 2021-05-03 17:16:45 +02:00
nobohan
1587c762f8 better fixture for AddressReference 2021-05-03 14:34:23 +02:00
nobohan
17c01d9b46 fix fixture for address reference 2021-05-03 12:18:21 +02:00
a1bb9ea352 modal addPerson design, search field: focus and position fixed 2021-05-03 11:52:06 +02:00
nobohan
a1895ec65f fixture for addressReference - WIP 2021-05-03 11:18:31 +02:00
nobohan
c5faa0b99d update the address fixture by adding some points 2021-05-03 09:28:05 +02:00
nobohan
e9d142f3e8 define legacy functions for Address 2021-05-03 09:28:05 +02:00
nobohan
91860afd80 check if point value is null for 2 methods in PointType 2021-05-03 09:28:05 +02:00
nobohan
bec0700d39 Point model: better handling of exception 2021-05-03 09:28:05 +02:00
nobohan
05d3d7f5c7 update twig template and AddressType following the changes in Address entity 2021-05-03 09:28:05 +02:00
nobohan
ebff36d257 add unit test for class Point 2021-05-03 09:28:05 +02:00
nobohan
a709b3afb6 add addressReference in Chill Main + migration 2021-05-03 09:28:05 +02:00
nobohan
69a3c6a9b2 refine the migration comment 2021-05-03 09:28:05 +02:00
juminet
8c33d876e8 code formatting in PointType 2021-05-03 09:28:05 +02:00
nobohan
1ec2fbcc16 translated exception messages in English 2021-05-03 09:28:05 +02:00
juminet
bc4e29141b syntax (null -> NULL and == -> ===) 2021-05-03 09:28:05 +02:00
nobohan
e90ea31683 add type hinting in Point and PointException 2021-05-03 09:28:05 +02:00
juminet
7c99f0b3e0 array synatx: array() -> [] 2021-05-03 09:28:05 +02:00
nobohan
c089960707 add type hinting in Point and PointException 2021-05-03 09:28:05 +02:00
nobohan
0b2f29f1e8 add migration for address 2021-05-03 09:28:05 +02:00
nobohan
9a4f50472a add point type + Address: add Point field : fix dependency injection of the Point type 2021-05-03 09:28:05 +02:00
nobohan
7d1a1c4004 #32 add point type + Address: add Point field + add null on nullable fields 2021-05-03 09:28:05 +02:00
nobohan
ebd58d4229 add more fields to Address entity + rename streetAddress1 and streetAddress2 2021-05-03 09:25:41 +02:00
nobohan
dd48795f64 #23 enable postgis in a chil main migration 2021-05-03 09:25:41 +02:00
3d45b6687f adding addPersons component with modal, search field and basic suggestions 2021-04-30 23:18:57 +02:00
35e6d36ce0 fetch postParticipation request, catch fetch error, store mutation+action 2021-04-30 16:33:49 +02:00
4900c81c11 improve inheritance with translations i18n.js files
vue-i18n --> chill main i18n ---( )---> app index
chill bundle i18n --> app i18n --^
2021-04-30 16:32:06 +02:00
52472b0ec3 Merge branch 'fix-tests-main' into 'master'
Fix tests for chill main bundle

See merge request Chill-Projet/chill-bundles!24
2021-04-29 22:35:47 +00:00
ec68e6f761 make inheritance for vue translations i18n.js files
By importing only the app i18n file,
we benefit from the whole inherited chain:

app i18n < chill bundle i18n < chill main bundle i18n
2021-04-29 18:32:22 +02:00
25bd170f6b improve modal system, test when a modal call next modal 2021-04-29 15:49:25 +02:00
6939b4a313 Merge branch 'master' into _31_interface_creation_parcours 2021-04-29 14:19:02 +02:00
d18922ed98 permit multiple modals in same component 2021-04-29 14:04:40 +02:00
e8bf242c42 Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-29 12:44:29 +02:00
2050460bb3 add modal system, added/removed managed by vue, appearence managed by bootstrap
Modal component is an hybrid solution between :
- Vue3 modal implementation
  => with 'v-if:showModal' directive:parameter, html scope is added/removed not just shown/hidden
  => with slot we can pass content from parent component
  => some classes are passed from parent component
- Bootstrap 4.4 _modal.scss module
  => using bootstrap css classes, the modal have a responsive behaviour,
  => modal design can be configured using css classes (size, scroll)

See
* https://v3.vuejs.org/examples/modal.html#modal-component
* https://github.com/bootstrap-vue/bootstrap-vue/issues/5196
2021-04-29 12:40:28 +02:00
nobohan
4add30e895 add fixture for parcours: replace createQuery by createQueryBuilder 2021-04-29 12:23:41 +02:00
e1dbfdafd7 test modals with vue and modals with bootstrap 2021-04-28 22:01:05 +02:00
75becb2294 Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-28 21:58:52 +02:00
94e494361f adding show/edit links (prepare modal) + save button 2021-04-28 18:00:46 +02:00
cab3b1059d ChillMainBundle: use localize function 2021-04-28 15:56:50 +02:00
nobohan
d27bdf68fb Merge branch '_31_interface_creation_parcours' of https://gitlab.com/Chill-Projet/chill-bundles into _31_interface_creation_parcours
merge..
2021-04-28 12:24:29 +02:00
nobohan
82b82920e1 add 2 fixtures for parcours 2021-04-28 12:24:25 +02:00
4bb3eadf91 renaming vuejs root dir 2021-04-28 11:41:15 +02:00
4c82e65c1f Merge branch '14-correctif-creation-personne' into 'master'
Use injected EntityManager - fix property visibility.

See merge request Chill-Projet/chill-bundles!25
2021-04-28 08:36:34 +00:00
cf4d7df7ad Merge branch 'bootstrap-serializer' into 'master'
Bootstrap serializer

See merge request Chill-Projet/chill-bundles!17
2021-04-28 08:32:02 +00:00
86d13410c3 Merge branch 'bootstrap-serializer' into fix-tests-main 2021-04-28 10:29:53 +02:00
19fdf2a503 Add test for AccompanyingCourseController 2021-04-28 10:28:10 +02:00
3a0c25c871 fix addPerson feature with vue3+store+i18n 2021-04-28 10:10:16 +02:00
083338da8d Merge branch 'master' into _31_interface_creation_parcours 2021-04-28 08:54:20 +02:00
37e5c9ceaa Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-28 08:49:32 +02:00
Pol Dellaiera
5448238697 Set final keyword - remove redundant information in phpdoc. 2021-04-28 07:21:19 +02:00
Pol Dellaiera
c5250a1059 Use injected EntityManager - fix property visibility. 2021-04-27 23:07:59 +02:00
b2c1a7b8de Merge remote-tracking branch 'origin/master' into fix-tests-main 2021-04-27 22:50:32 +02:00
49c6915c0a Merge branch 'vendee_27' into 'master'
Vendee 27

See merge request Chill-Projet/chill-bundles!21
2021-04-27 20:49:59 +00:00
b4583fc6dc improve serializers 2021-04-27 22:48:48 +02:00
f7c508939c Add test for AccompanyingCourseController 2021-04-27 22:40:00 +02:00
4cf77a9b0e adapt multi components to new store and new api endpoints
* base of i18n (yarn add new deps)
2021-04-27 22:03:39 +02:00
a2160bef7d WIP: first implementation for test 2021-04-27 19:33:34 +02:00
nobohan
c2a4a95eba add a fixture for accompanying period - wip 2021-04-27 18:52:37 +02:00
8641d6bdce try to fix correct values for redis 2021-04-27 18:06:58 +02:00
5f4d513aa6 try to connect to redis in gitlab-ci 2021-04-27 17:57:09 +02:00
f47b15de39 try to fix .gitlab-ci with correct redis parameters 2021-04-27 17:52:12 +02:00
7426dc02cf currently restrict to chill main test suite 2021-04-27 17:18:46 +02:00
a570160aed update chill app to working commit 2021-04-27 17:18:26 +02:00
6e81ef0065 tests: update chill-app subprojet ref 2021-04-27 17:09:41 +02:00
e3cc76c689 tests/ChillPersonBundle: use type casting 2021-04-27 17:03:31 +02:00
b43f43fa0b ChillPersonBundle: persist new Persons 2021-04-27 16:53:57 +02:00
7596bd5a06 fix tests for chill main 2021-04-27 16:33:44 +02:00
f02d6df262 tests/ChillPersonBundle: in sf4 container is a static method of KernelTestCase 2021-04-27 15:15:41 +02:00
e4e2138765 tests/ChillPersonBundle: replace testGenderIsNull with crafted form as html input now prevents user form not selecting a gender 2021-04-27 15:15:41 +02:00
395735e6f7 tests/ChillPersonBundle: remove broken obsolete testFirstnameTooLong, html input and doctrine contrains are working 2021-04-27 15:15:41 +02:00
2c96c02261 tests/ChillPersonBundle: the gender input has three options: man, women and undefined 2021-04-27 15:15:41 +02:00
53813f8f29 tests/ChillPersonBundle: use mutualized getClientAuthenticated() 2021-04-27 15:15:41 +02:00
Marc Ducobu
b8ef0d28f5 Migration for AccompanyingPeriodWork, AccompanyongPeriodWokGoal & SocialWork/Evaluation 2021-04-27 15:15:02 +02:00
Marc Ducobu
e973c4013f Correct namespace 2021-04-27 15:11:31 +02:00
01f9d03b14 init vuex store 2021-04-27 15:11:13 +02:00
Marc Ducobu
0f9a395dfc Entites for AccomanyingPeriodWork, AccomanyingPeriodWorkGoal & Social/WorkEvaluation 2021-04-27 15:10:56 +02:00
Marc Ducobu
38ac3badef Integration rmq Julien 2021-04-27 11:24:26 +02:00
Marc Ducobu
cda32fb925 Pbm migration double 2021-04-26 17:19:10 +02:00
Marc Ducobu
58cb34f39b Creation of entities : SocialIssue / Social Action / Result / Goal 2021-04-26 17:09:54 +02:00
66426f5102 serializer on accompanying course
Two new routes:

* `GET /{_locale}/person/api/1.0/accompanying-course/{parcours_id}/show.json`: get a json representation for a course
* `POST /{_locale}/person/api/1.0/accompanying-course/{parcours_id}/participation.json`:
add a particitipation to course. Usage:

    `curl -v --cookie "PHPSESSID=fed98aa23e40cb36e630f84155aea3bb;" -X
POST --data '{ "id": 481 }'
http://localhost:8001/fr/person/api/1.0/accompanying-course/270/participation.json`

    Will add the person with id "481" to the course.
2021-04-26 17:01:22 +02:00
Pol Dellaiera
03243605da Remove unrelated code style change. 2021-04-02 11:18:52 +02:00
Pol Dellaiera
48e2d2ceab Do not use DateTimeImmutable. 2021-04-02 11:18:48 +02:00
Pol Dellaiera
777fb25860 tests: Add missing test based on review's feedback. 2021-04-02 11:12:50 +02:00
Pol Dellaiera
03601b9707 Update Person::getLastAddress() based on feedback. 2021-04-02 11:11:24 +02:00
c205bbddd3 writing test to reproduce bug 2021-03-08 10:26:12 +01:00
361 changed files with 18959 additions and 2579 deletions

3
.gitignore vendored
View File

@@ -1,8 +1,8 @@
.composer/*
composer.phar
composer.lock
docs/build/
.php_cs.cache
###> symfony/framework-bundle ###
/.env.local
@@ -19,3 +19,4 @@ docs/build/
/phpunit.xml
.phpunit.result.cache
###< phpunit/phpunit ###

View File

@@ -11,14 +11,15 @@ before_script:
- PGPASSWORD=$POSTGRES_PASSWORD psql -U $POSTGRES_USER -h db -c "CREATE EXTENSION IF NOT EXISTS unaccent; CREATE EXTENSION IF NOT EXISTS pg_trgm;"
# Install and run Composer
- curl -sS https://getcomposer.org/installer | php
- php composer.phar install
- php -d memory_limit=2G composer.phar install
- php tests/app/bin/console doctrine:migrations:migrate -n
- php tests/app/bin/console doctrine:fixtures:load -n
- php -d memory_limit=2G tests/app/bin/console doctrine:fixtures:load -n
- echo "before_script finished"
# Bring in any services we need http://docs.gitlab.com/ee/ci/docker/using_docker_images.html#what-is-a-service
# See http://docs.gitlab.com/ee/ci/services/README.html for examples.
services:
- name: postgres:12
- name: postgis/postgis:12-3.1-alpine
alias: db
- name: redis
alias: redis
@@ -30,8 +31,12 @@ variables:
POSTGRES_PASSWORD: postgres
# fetch the chill-app using git submodules
GIT_SUBMODULE_STRATEGY: recursive
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_URL: redis://redis:6379
# Run our tests
test:
script:
- bin/phpunit --colors=never
- php -d memory_limit=3G bin/phpunit --colors=never

9
README.md Normal file
View File

@@ -0,0 +1,9 @@
# Chill framework
Documentation of the Chill software.
The online documentation can be found at http://docs.chill.social
See the [`docs`][1] directory for more.
[1]: docs/README.md

View File

@@ -1,88 +1,110 @@
{
"name": "chill-project/chill-bundles",
"license": "AGPL-3.0-only",
"type": "library",
"description": "Most used bundles for chill-project",
"keywords": ["chill", "social worker"],
"authors": [
{
"name": "Champs-Libres",
"email": "info@champs-libres.coop",
"homepage": "http://www.champs-libres.coop"
}
],
"type": "library",
"require": {
"components/jquery": ">=1.7.1",
"league/csv": "^9.6",
"phpoffice/phpspreadsheet": "~1.2",
"robloach/component-installer": "*"
},
"config": {
"vendor-dir": "tests/app/vendor",
"bin-dir": "bin"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"fakerphp/faker": "^1.13",
"nelmio/alice": "^3.8",
"phpunit/phpunit": "^9.5",
"symfony/debug-bundle": "^5.1",
"symfony/dotenv": "^5.1",
"symfony/maker-bundle": "^1.20",
"symfony/phpunit-bridge": "^5.2",
"symfony/stopwatch": "^5.1",
"symfony/var-dumper": "4.*",
"symfony/web-profiler-bundle": "^5.0",
"symplify/monorepo-builder": "^9.2"
},
"autoload": {
"psr-4": {
"Chill\\ActivityBundle\\": "src/Bundle/ChillActivityBundle",
"Chill\\BudgetBundle\\": "src/Bundle/ChillBudgetBundle",
"Chill\\CustomFieldsBundle\\": "src/Bundle/ChillCustomFieldsBundle",
"Chill\\DocStoreBundle\\": "src/Bundle/ChillDocStoreBundle",
"Chill\\EventBundle\\": "src/Bundle/ChillEventBundle",
"Chill\\FamilyMemberBundle\\": "src/Bundle/ChillFamilyMemberBundle",
"Chill\\MainBundle\\": "src/Bundle/ChillMainBundle",
"Chill\\PersonBundle\\": "src/Bundle/ChillPersonBundle",
"Chill\\ReportBundle\\": "src/Bundle/ChillReportBundle",
"Chill\\TaskBundle\\": "src/Bundle/ChillTaskBundle",
"Chill\\ThirdPartyBundle\\": "src/Bundle/ChillThirdPartyBundle"
"Chill\\AMLI\\BudgetBundle\\": "src/Bundle/ChillBudgetBundle/",
"Chill\\AMLI\\FamilyMembersBundle\\": "src/Bundle/ChillFamilyMembersBundle/",
"Chill\\ActivityBundle\\": "src/Bundle/ChillActivityBundle/",
"Chill\\CustomFieldsBundle\\": "src/Bundle/ChillCustomFieldsBundle/",
"Chill\\DocStoreBundle\\": "src/Bundle/ChillDocStoreBundle/",
"Chill\\EventBundle\\": "src/Bundle/ChillEventBundle/",
"Chill\\MainBundle\\": "src/Bundle/ChillMainBundle/",
"Chill\\PersonBundle\\": "src/Bundle/ChillPersonBundle/",
"Chill\\ReportBundle\\": "src/Bundle/ChillReportBundle/",
"Chill\\TaskBundle\\": "src/Bundle/ChillTaskBundle/",
"Chill\\ThirdPartyBundle\\": "src/Bundle/ChillThirdPartyBundle/"
}
},
"autoload-dev": {
"psr-4": {
"App\\": "tests/app/src/"
}
"classmap": [
"src/Bundle/ChillActivityBundle/Resources/test/Fixtures/App/app/AppKernel.php",
"src/Bundle/ChillCustomFieldsBundle/Resources/test/Fixtures/App/app/AppKernel.php",
"src/Bundle/ChillMainBundle/Resources/test/Fixtures/App/app/AppKernel.php",
"src/Bundle/ChillPersonBundle/Resources/test/Fixtures/App/app/AppKernel.php",
"src/Bundle/ChillReportBundle/Resources/test/Fixtures/App/app/AppKernel.php"
]
},
"require": {
"champs-libres/async-uploader-bundle": "dev-sf4",
"graylog2/gelf-php": "^1.5",
"symfony/form": "4.*",
"symfony/twig-bundle": "^4.4",
"twig/extra-bundle": "^2.12|^3.0",
"twig/twig": "^2.12|^3.0",
"composer/package-versions-deprecated": "^1.10",
"doctrine/doctrine-bundle": "^2.1",
"doctrine/doctrine-migrations-bundle": "^3.0",
"doctrine/orm": "^2.7",
"symfony/asset": "4.*",
"symfony/monolog-bundle": "^3.5",
"symfony/security-bundle": "4.*",
"symfony/translation": "4.*",
"symfony/validator": "4.*",
"sensio/framework-extra-bundle": "^5.5",
"symfony/yaml": "4.*",
"symfony/webpack-encore-bundle": "^1.11",
"knplabs/knp-menu": "^3.1",
"knplabs/knp-menu-bundle": "^3.0",
"symfony/templating": "4.*",
"twig/intl-extra": "^3.0",
"symfony/workflow": "4.*",
"symfony/expression-language": "4.*",
"knplabs/knp-time-bundle": "^1.12",
"symfony/intl": "4.*",
"symfony/swiftmailer-bundle": "^3.5",
"league/csv": "^9.6",
"phpoffice/phpspreadsheet": "^1.16",
"symfony/browser-kit": "^5.2",
"symfony/css-selector": "^5.2",
"twig/markdown-extra": "^3.3",
"erusev/parsedown": "^1.7",
"symfony/serializer": "^5.2"
},
"conflict": {
"symfony/symfony": "*"
},
"require-dev": {
"fakerphp/faker": "^1.13",
"phpunit/phpunit": "^7.0",
"symfony/dotenv": "^5.1",
"symfony/maker-bundle": "^1.20",
"doctrine/doctrine-fixtures-bundle": "^3.3",
"symfony/stopwatch": "^5.1",
"symfony/web-profiler-bundle": "^5.0",
"symfony/var-dumper": "4.*",
"symfony/debug-bundle": "^5.1",
"symfony/phpunit-bridge": "^5.2"
"extra": {
"component": {
"scripts": [
"select2.js"
],
"files": [
"select2.js",
"select2_locale_*.js",
"select2.css",
"select2-bootstrap.css",
"select2-spinner.gif",
"select2.png",
"select2x2.png"
]
},
"app-migrations-dir": [
"Resources/test/Fixtures/App/app/DoctrineMigrations",
"Resources/test/Fixtures/App/DoctrineMigrations"
],
"symfony-app-dir": [
"Tests/Fixtures/App/app",
"Tests/Fixtures/App/",
"Test/Fixtures/App/app/"
]
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
}
"merge": "vendor/bin/monorepo-builder merge --ansi",
"propagate": "vendor/bin/monorepo-builder propagate --ansi",
"validate-monorepo": "vendor/bin/monorepo-builder validate --ansi",
"release": "vendor/bin/monorepo-builder release patch --ansi",
"localize": "vendor/bin/monorepo-builder localize-composer-paths"
},
"config": {
"vendor-dir": "tests/app/vendor",
"bin-dir": "bin"
}
"replace": {
"chill-project/activity": "self.version",
"chill-project/budget": "self.version",
"chill-project/chill-doc-store": "self.version",
"chill-project/custom-fields": "self.version",
"chill-project/event": "self.version",
"chill-project/family-members": "self.version",
"chill-project/main": "self.version",
"chill-project/person": "self.version",
"chill-project/report": "self.version",
"chill-project/task": "self.version",
"chill-project/third-party": "self.version",
"ivaynberg/select2": "self.version"
},
"minimum-stability": "dev",
"prefer-stable": true
}

View File

@@ -0,0 +1,747 @@
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
.. _api:
API
###
Chill provides a basic framework to build REST api.
Basic configuration
*******************
Configure a route
=================
Follow those steps to build a REST api:
1. Create your model;
2. Configure the API;
You can also:
* hook into the controller to customize some steps;
* add more route and steps
.. note::
Useful links:
* `How to use annotation to configure serialization <https://symfony.com/doc/current/serializer.html>`_
* `How to create your custom normalizer <https://symfony.com/doc/current/serializer/custom_normalizer.html>`_
Auto-loading the routes
=======================
Ensure that those lines are present in your file `app/config/routing.yml`:
.. code-block:: yaml
chill_cruds:
resource: 'chill_main_crud_route_loader:load'
type: service
Create your model
=================
Create your model on the usual way:
.. code-block:: php
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\OriginRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=OriginRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_origin")
*/
class Origin
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="json")
*/
private $label;
/**
* @ORM\Column(type="date_immutable", nullable=true)
*/
private $noActiveAfter;
// .. getters and setters
}
Configure api
=============
Configure the api using Yaml (see the full configuration: :ref:`api_full_configuration`):
.. code-block:: yaml
# config/packages/chill_main.yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/accompanying-period/origin'
class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin'
name: accompanying_period_origin
base_role: 'ROLE_USER'
actions:
_index:
methods:
GET: true
HEAD: true
_entity:
methods:
GET: true
HEAD: true
.. note::
If you are working on a shared bundle (aka "The chill bundles"), you should define your configuration inside the class :code:`ChillXXXXBundleExtension`, using the "prependConfig" feature:
.. code-block:: php
namespace Chill\PersonBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Class ChillPersonExtension
* Loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
* @package Chill\PersonBundle\DependencyInjection
*/
class ChillPersonExtension extends Extension implements PrependExtensionInterface
{
public function prepend(ContainerBuilder $container)
{
$this->prependCruds($container);
}
/**
* @param ContainerBuilder $container
*/
protected function prependCruds(ContainerBuilder $container)
{
$container->prependExtensionConfig('chill_main', [
'apis' => [
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class,
'name' => 'accompanying_period_origin',
'base_path' => '/api/1.0/person/accompanying-period/origin',
'controller' => \Chill\PersonBundle\Controller\OpeningApiController::class,
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
]
]
]);
}
}
The :code:`_index` and :code:`_entity` action
*********************************************
The :code:`_index` and :code:`_entity` action are default actions:
* they will call a specific method in the default controller;
* they will generate defined routes:
Index:
Name: :code:`chill_api_single_accompanying_period_origin__index`
Path: :code:`/api/1.0/person/accompanying-period/origin.{_format}`
Entity:
Name: :code:`chill_api_single_accompanying_period_origin__entity`
Path: :code:`/api/1.0/person/accompanying-period/origin/{id}.{_format}`
Role
****
By default, the key `base_role` is used to check ACL. Take care of creating the :code:`Voter` required to take that into account.
For index action, the role will be called with :code:`NULL` as :code:`$subject`. The retrieved entity will be the subject for single queries.
You can also define a role for each method. In this case, this role is used for the given method, and, if any, the base role is taken into account.
.. code-block:: yaml
# config/packages/chill_main.yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/bla/bla'
class: 'Chill\PersonBundle\Entity\Blah'
name: bla
actions:
_entity:
methods:
GET: true
HEAD: true
roles:
GET: MY_ROLE_SEE
HEAD: MY ROLE_SEE
Customize the controller
************************
You can customize the controller by hooking into the default actions. Take care of extending :code:`Chill\MainBundle\CRUD\Controller\ApiController`.
.. code-block:: php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OpeningApiController extends ApiController
{
protected function customizeQuery(string $action, Request $request, $qb): void
{
$qb->where($qb->expr()->gt('e.noActiveAfter', ':now'))
->orWhere($qb->expr()->isNull('e.noActiveAfter'));
$qb->setParameter('now', new \DateTime('now'));
}
}
And set your controller in configuration:
.. code-block:: yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/accompanying-period/origin'
class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin'
name: accompanying_period_origin
# add a controller
controller: 'Chill\PersonBundle\Controller\OpeningApiController'
base_role: 'ROLE_USER'
actions:
_index:
methods:
GET: true
HEAD: true
_entity:
methods:
GET: true
HEAD: true
Create your own actions
***********************
You can add your own actions:
.. code-block:: yaml
chill_main:
apis:
-
class: Chill\PersonBundle\Entity\AccompanyingPeriod
name: accompanying_course
base_path: /api/1.0/person/accompanying-course
controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController
actions:
# add a custom participation:
participation:
methods:
POST: true
DELETE: true
GET: false
HEAD: false
PUT: false
roles:
POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
GET: null
HEAD: null
PUT: null
single-collection: single
The key :code:`single-collection` with value :code:`single` will add a :code:`/{id}/ + "action name"` (in this example, :code:`/{id}/participation`) into the path, after the base path. If the value is :code:`collection`, no id will be set, but the action name will be append to the path.
Then, create the corresponding action into your controller:
.. code-block:: php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent;
use Chill\PersonBundle\Entity\Person;
class AccompanyingCourseApiController extends ApiController
{
protected EventDispatcherInterface $eventDispatcher;
protected ValidatorInterface $validator;
public function __construct(EventDispatcherInterface $eventDispatcher, $validator)
{
$this->eventDispatcher = $eventDispatcher;
$this->validator = $validator;
}
public function participationApi($id, Request $request, $_format)
{
/** @var AccompanyingPeriod $accompanyingPeriod */
$accompanyingPeriod = $this->getEntity('participation', $id, $request);
$person = $this->getSerializer()
->deserialize($request->getContent(), Person::class, $_format, []);
if (NULL === $person) {
throw new BadRequestException('person id not found');
}
$this->onPostCheckACL('participation', $request, $accompanyingPeriod, $_format);
switch ($request->getMethod()) {
case Request::METHOD_POST:
$participation = $accompanyingPeriod->addPerson($person);
break;
case Request::METHOD_DELETE:
$participation = $accompanyingPeriod->removePerson($person);
break;
default:
throw new BadRequestException("This method is not supported");
}
$errors = $this->validator->validate($accompanyingPeriod);
if ($errors->count() > 0) {
// only format accepted
return $this->json($errors);
}
$this->getDoctrine()->getManager()->flush();
return $this->json($participation);
}
}
Managing association
********************
ManyToOne association
=====================
In ManyToOne association, you can add associated entities using the :code:`PATCH` request. By default, the serializer deserialize entities only with their id and discriminator type, if any.
Example:
.. code-block:: bash
curl -X 'PATCH' \
'http://localhost:8001/api/1.0/person/accompanying-course/2668.json' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
# see the data sent to the server: \
-d '{
"type": "accompanying_period",
"id": 2668,
"origin": { "id": 11 }
}'
ManyToMany associations
=======================
In OneToMany association, you can easily create route for adding and removing entities, using :code:`POST` and :code:`DELETE` requests.
Prepare your entity, creating the methods :code:`addYourEntity` and :code:`removeYourEntity`:
.. code-block:: php
namespace Chill\PersonBundle\Entity;
use Chill\MainBundle\Entity\Scope;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
/**
* AccompanyingPeriod Class
*
* @ORM\Entity
* @ORM\Table(name="chill_person_accompanying_period")
* @DiscriminatorMap(typeProperty="type", mapping={
* "accompanying_period"=AccompanyingPeriod::class
* })
*/
class AccompanyingPeriod
{
/**
* @var Collection
* @ORM\ManyToMany(
* targetEntity=Scope::class,
* cascade={}
* )
* @Groups({"read"})
*/
private $scopes;
public function addScope(Scope $scope): self
{
$this->scopes[] = $scope;
return $this;
}
public function removeScope(Scope $scope): void
{
$this->scopes->removeElement($scope);
}
Create your route into the configuration:
.. code-block:: yaml
chill_main:
apis:
-
class: Chill\PersonBundle\Entity\AccompanyingPeriod
name: accompanying_course
base_path: /api/1.0/person/accompanying-course
controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController
actions:
scope:
methods:
POST: true
DELETE: true
GET: false
HEAD: false
PUT: false
PATCH: false
roles:
POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
GET: null
HEAD: null
PUT: null
PATCH: null
controller_action: null
path: null
single-collection: single
This will create a new route, which will accept two methods: DELETE and POST:
.. code-block:: raw
+--------------+---------------------------------------------------------------------------------------+
| Property | Value |
+--------------+---------------------------------------------------------------------------------------+
| Route Name | chill_api_single_accompanying_course_scope |
| Path | /api/1.0/person/accompanying-course/{id}/scope.{_format} |
| Path Regex | {^/api/1\.0/person/accompanying\-course/(?P<id>[^/]++)/scope\.(?P<_format>[^/]++)$}sD |
| Host | ANY |
| Host Regex | |
| Scheme | ANY |
| Method | POST|DELETE |
| Requirements | {id}: \d+ |
| Class | Symfony\Component\Routing\Route |
| Defaults | _controller: csapi_accompanying_course_controller:scopeApi |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+---------------------------------------------------------------------------------------+
Then, create the controller action. Call the method:
.. code-block:: php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Entity\Scope;
class MyController extends ApiController
{
public function scopeApi($id, Request $request, string $_format): Response
{
return $this->addRemoveSomething('scope', $id, $request, $_format, 'scope', Scope::class, [ 'groups' => [ 'read' ] ]);
}
}
This will allow to add a scope by his id, and delete them.
Curl requests:
.. code-block:: bash
# add a scope with id 5
curl -X 'POST' \
'http://localhost:8001/api/1.0/person/accompanying-course/2868/scope.json' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
-d '{
"type": "scope",
"id": 5
}'
# remove a scope with id 5
curl -X 'DELETE' \
'http://localhost:8001/api/1.0/person/accompanying-course/2868/scope.json' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
-d '{
"id": 5,
"type": "scope"
}'
Deserializing an association where multiple types are allowed
=============================================================
Sometimes, multiples types are allowed as association to one entity:
.. code-block:: php
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Doctrine\ORM\Mapping as ORM;
class Resource
{
/**
* @ORM\ManyToOne(targetEntity=ThirdParty::class)
* @ORM\JoinColumn(nullable=true)
*/
private $thirdParty;
/**
* @ORM\ManyToOne(targetEntity=Person::class)
* @ORM\JoinColumn(nullable=true)
*/
private $person;
/**
*
* @param $resource Person|ThirdParty
*/
public function setResource($resource): self
{
// ...
}
/**
* @return ThirdParty|Person
* @Groups({"read", "write"})
*/
public function getResource()
{
return $this->person ?? $this->thirdParty;
}
}
This is not well taken into account by the Symfony serializer natively.
You must, then, create your own CustomNormalizer. You can help yourself using this:
.. code-block:: php
namespace Chill\PersonBundle\Serializer\Normalizer;
use Chill\PersonBundle\Entity\Person;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Chill\PersonBundle\Entity\AccompanyingPeriod\Resource;
use Chill\PersonBundle\Repository\AccompanyingPeriod\ResourceRepository;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\ObjectToPopulateTrait;
use Symfony\Component\Serializer\Exception;
use Chill\MainBundle\Serializer\Normalizer\DiscriminatedObjectDenormalizer;
class AccompanyingPeriodResourceNormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
use ObjectToPopulateTrait;
public function __construct(ResourceRepository $repository)
{
$this->repository = $repository;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
// .. snipped for brevity
if ($resource === NULL) {
$resource = new Resource();
}
if (\array_key_exists('resource', $data)) {
$res = $this->denormalizer->denormalize(
$data['resource'],
// call for a "multiple type"
DiscriminatedObjectDenormalizer::TYPE,
$format,
// into the context, we add the list of allowed types:
[
DiscriminatedObjectDenormalizer::ALLOWED_TYPES =>
[
Person::class, ThirdParty::class
]
]
);
$resource->setResource($res);
}
return $resource;
}
public function supportsDenormalization($data, string $type, string $format = null)
{
return $type === Resource::class;
}
}
Serialization for collection
****************************
A specific model has been defined for returning collection:
.. code-block:: json
{
"count": 49,
"results": [
],
"pagination": {
"more": true,
"next": "/api/1.0/search.json&q=xxxx......&page=2",
"previous": null,
"first": 0,
"items_per_page": 1
}
}
Where this is relevant, this model should be re-used in custom controller actions.
In custom actions, this can be achieved quickly by assembling results into a :code:`Chill\MainBundle\Serializer\Model\Collection`. The pagination information is given by using :code:`Paginator` (see :ref:`Pagination <pagination-ref>`).
.. code-block:: php
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\MainBundle\Pagination\PaginatorInterface;
class MyController extends AbstractController
{
protected function serializeCollection(PaginatorInterface $paginator, $entities): Response
{
$model = new Collection($entities, $paginator);
return $this->json($model, Response::HTTP_OK, [], $context);
}
}
.. _api_full_configuration:
Full configuration example
**************************
.. code-block:: yaml
apis:
-
class: Chill\PersonBundle\Entity\AccompanyingPeriod
name: accompanying_course
base_path: /api/1.0/person/accompanying-course
controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController
actions:
_entity:
roles:
GET: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
HEAD: null
POST: null
DELETE: null
PUT: null
controller_action: null
path: null
single-collection: single
methods:
GET: true
HEAD: true
POST: false
DELETE: false
PUT: false
participation:
methods:
POST: true
DELETE: true
GET: false
HEAD: false
PUT: false
roles:
POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
GET: null
HEAD: null
PUT: null
controller_action: null
# the requirements for the route. Will be set to `[ 'id' => '\d+' ]` if left empty.
requirements: []
path: null
single-collection: single
base_role: null

View File

@@ -16,6 +16,7 @@ As Chill rely on the `symfony <http://symfony.com>`_ framework, reading the fram
Instructions to create a new bundle <create-a-new-bundle.rst>
CRUD (Create - Update - Delete) for one entity <crud.rst>
Helpers for building a REST API <api.rst>
Routing <routing.rst>
Menus <menus.rst>
Forms <forms.rst>

View File

@@ -7,6 +7,8 @@
Free Documentation License".
.. _pagination-ref:
Pagination
##########
@@ -15,7 +17,7 @@ The Bundle :code:`Chill\MainBundle` provides a **Pagination** api which allow yo
A simple example
****************
In the controller, get the :class:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance.
In the controller, get the :code:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance.
.. literalinclude:: pagination/example.php

View File

@@ -97,7 +97,7 @@ The has the following signature :
*
* @param string $context
* @param mixed[] $args the argument to the context.
* @return string[]
* @return TimelineSingleQuery
* @throw \LogicException if the context is not supported
*/
public function fetchQuery($context, array $args);
@@ -163,18 +163,16 @@ The has the following signature :
The `fetchQuery` function
^^^^^^^^^^^^^^^^^^^^^^^^^
The fetchQuery function help to build the UNION query to gather events. This function should return an associative array MUST have the following key :
The fetchQuery function help to build the UNION query to gather events. This function should return an instance of :code:`TimelineSingleQuery`. For you convenience, this object may be build using an associative array with the following keys:
* `id` : the name of the id column
* `type`: a string to indicate the type
* `date`: the name of the datetime column, used to order entities by date
* `FROM` (in capital) : the FROM clause. May contains JOIN instructions
* `FROM`: the FROM clause. May contains JOIN instructions
* `WHERE`: the WHERE clause;
* `parameters`: the parameters to pass to the query
Those key are optional:
* `WHERE` (in capital) : the WHERE clause.
Where relevant, the data must be quoted to avoid SQL injection.
The parameters should be replaced into the query by :code:`?`. They will be replaced into the query using prepared statements.
`$context` and `$args` are defined by the bundle which will call the timeline rendering. You may use them to build a different query depending on this context.
@@ -186,6 +184,15 @@ For instance, if the context is `'person'`, the args will be this array :
'person' => $person //a \Chill\PersonBundle\Entity\Person entity
);
For the context :code:`center`, the args will be:
.. code-block:: php
array(
'centers' => [ ] // an array of \Chill\MainBundle\Entity\Center entities
);
You should find in the bundle documentation which contexts are arguments the bundle defines.
.. note::
@@ -199,13 +206,12 @@ Example of an implementation :
namespace Chill\ReportBundle\Timeline;
use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Chill\MainBundle\Timeline\TimelineSingleQuery;
use Doctrine\ORM\EntityManager;
/**
* Provide report for inclusion in timeline
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
class TimelineReportProvider implements TimelineProviderInterface
{
@@ -227,16 +233,17 @@ Example of an implementation :
$metadata = $this->em->getClassMetadata('ChillReportBundle:Report');
return array(
return TimelineSingleQuery::fromArray([
'id' => $metadata->getColumnName('id'),
'type' => 'report',
'date' => $metadata->getColumnName('date'),
'FROM' => $metadata->getTableName(),
'WHERE' => sprintf('%s = %d',
'WHERE' => sprintf('%s = ?',
$metadata
->getAssociationMapping('person')['joinColumns'][0]['name'],
$args['person']->getId())
);
->getAssociationMapping('person')['joinColumns'][0]['name'])
)
'parameters' => [ $args['person']->getId() ]
]);
}
//....

View File

@@ -82,7 +82,7 @@ Chill will be available at ``http://localhost:8001.`` Currently, there isn't any
.. code-block:: bash
docker-compose exec --user $(id -u) php bin/console doctrine:fixtures:load
docker-compose exec --user $(id -u) php bin/console doctrine:fixtures:load --purge-with-truncate
There are several users available:

45
monorepo-builder.php Normal file
View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\ComposerJsonManipulator\ValueObject\ComposerJsonSection;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\PushNextDevReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\PushTagReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\SetCurrentMutualDependenciesReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\SetNextMutualDependenciesReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\TagVersionReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\UpdateBranchAliasReleaseWorker;
use Symplify\MonorepoBuilder\Release\ReleaseWorker\UpdateReplaceReleaseWorker;
use Symplify\MonorepoBuilder\ValueObject\Option;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters = $containerConfigurator->parameters();
// where are the packages located?
$parameters->set(Option::PACKAGE_DIRECTORIES, [
// default value
__DIR__ . '/src/Bundle',
]);
// for "merge" command
$parameters->set(
Option::DATA_TO_APPEND,
[
ComposerJsonSection::REQUIRE_DEV => [
'phpunit/phpunit' => '^9.5',
],
]
);
$services = $containerConfigurator->services();
# release workers - in order to execute
$services->set(UpdateReplaceReleaseWorker::class);
$services->set(SetCurrentMutualDependenciesReleaseWorker::class);
$services->set(TagVersionReleaseWorker::class);
$services->set(PushTagReleaseWorker::class);
$services->set(SetNextMutualDependenciesReleaseWorker::class);
$services->set(UpdateBranchAliasReleaseWorker::class);
$services->set(PushNextDevReleaseWorker::class);
};

View File

@@ -18,12 +18,20 @@
<testsuite name="MainBundle">
<directory suffix="Test.php">src/Bundle/ChillMainBundle/Tests/</directory>
</testsuite>
<testsuite name="PersonBundle">
<directory suffix="Test.php">src/Bundle/ChillPersonBundle/Tests/</directory>
<!-- test for export will be runned later -->
<exclude>src/Bundle/ChillPersonBundle/Tests/Export/*</exclude>
<!-- we are rewriting accompanying periods... Work in progress -->
<exclude>src/Bundle/ChillPersonBundle/Tests/Controller/AccompanyingPeriodControllerTest.php</exclude>
<!-- we are rewriting address, Work in progress -->
<exclude>src/Bundle/ChillPersonBundle/Tests/Controller/PersonAddressControllerTest.php</exclude>
<!-- find a solution to create multiple configs -->
<exclude>src/Bundle/ChillPersonBundle/Tests/Controller/PersonControllerUpdateWithHiddenFieldsTest.php</exclude>
<!-- temporarily removed, the time to find a fix -->
<exclude>src/Bundle/ChillPersonBundle/Tests/Controller/PersonDuplicateControllerViewTest.php</exclude>
</testsuite>
</testsuites>
</testsuites>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />

View File

@@ -52,7 +52,6 @@ class ChillActivityExtension extends Extension implements PrependExtensionInterf
$loader->load('services/export.yaml');
$loader->load('services/repositories.yaml');
$loader->load('services/fixtures.yaml');
$loader->load('services/menu.yaml');
$loader->load('services/controller.yaml');
$loader->load('services/form.yaml');
$loader->load('services/templating.yaml');

View File

@@ -38,7 +38,7 @@ use Chill\MainBundle\Validator\Constraints\Entity\UserCircleConsistency;
* Class Activity
*
* @package Chill\ActivityBundle\Entity
* @ORM\Entity()
* @ORM\Entity(repositoryClass="Chill\ActivityBundle\Repository\ActivityRepository")
* @ORM\Table(name="activity")
* @ORM\HasLifecycleCallbacks()
* @UserCircleConsistency(

View File

@@ -0,0 +1,169 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2021, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\Activity;
use Chill\PersonBundle\Entity\Person;
use Chill\ActivityBundle\Repository\ActivityRepository;
use Chill\ActivityBundle\Security\Authorization\ActivityVoter;
use Chill\MainBundle\Entity\Scope;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Orx;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\EntityManagerInterface;
final class ActivityACLAwareRepository
{
private AuthorizationHelper $authorizationHelper;
private TokenStorageInterface $tokenStorage;
private ActivityRepository $repository;
private EntityManagerInterface $em;
public function __construct(
AuthorizationHelper $authorizationHelper,
TokenStorageInterface $tokenStorage,
ActivityRepository $repository,
EntityManagerInterface $em
) {
$this->authorizationHelper = $authorizationHelper;
$this->tokenStorage = $tokenStorage;
$this->repository = $repository;
$this->em = $em;
}
public function queryTimelineIndexer(string $context, array $args = []): array
{
$metadataActivity = $this->em->getClassMetadata(Activity::class);
$from = $this->getFromClauseCenter($args);
[$where, $parameters] = $this->getWhereClause($context, $args);
return [
'id' => $metadataActivity->getTableName()
.'.'.$metadataActivity->getColumnName('id'),
'type' => 'activity',
'date' => $metadataActivity->getTableName()
.'.'.$metadataActivity->getColumnName('date'),
'FROM' => $from,
'WHERE' => $where,
'parameters' => $parameters
];
}
private function getFromClauseCenter(array $args): string
{
$metadataActivity = $this->em->getClassMetadata(Activity::class);
$metadataPerson = $this->em->getClassMetadata(Person::class);
$associationMapping = $metadataActivity->getAssociationMapping('person');
return $metadataActivity->getTableName().' JOIN '
.$metadataPerson->getTableName().' ON '
.$metadataPerson->getTableName().'.'.
$associationMapping['joinColumns'][0]['referencedColumnName']
.' = '
.$associationMapping['joinColumns'][0]['name']
;
}
private function getWhereClause(string $context, array $args): array
{
$where = '';
$parameters = [];
$metadataActivity = $this->em->getClassMetadata(Activity::class);
$metadataPerson = $this->em->getClassMetadata(Person::class);
$activityToPerson = $metadataActivity->getAssociationMapping('person')['joinColumns'][0]['name'];
$activityToScope = $metadataActivity->getAssociationMapping('scope')['joinColumns'][0]['name'];
$personToCenter = $metadataPerson->getAssociationMapping('center')['joinColumns'][0]['name'];
// acls:
$role = new Role(ActivityVoter::SEE);
$reachableCenters = $this->authorizationHelper->getReachableCenters($this->tokenStorage->getToken()->getUser(),
$role);
if (count($reachableCenters) === 0) {
// insert a dummy condition
return 'FALSE = TRUE';
}
if ($context === 'person') {
// we start with activities having the person_id linked to person
$where .= sprintf('%s = ? AND ', $activityToPerson);
$parameters[] = $person->getId();
}
// we add acl (reachable center and scopes)
$where .= '('; // first loop for the for centers
$centersI = 0; // like centers#i
foreach ($reachableCenters as $center) {
// we pass if not in centers
if (!\in_array($center, $args['centers'])) {
continue;
}
// we get all the reachable scopes for this center
$reachableScopes = $this->authorizationHelper->getReachableScopes($this->tokenStorage->getToken()->getUser(), $role, $center);
// we get the ids for those scopes
$reachablesScopesId = array_map(
function(Scope $scope) { return $scope->getId(); },
$reachableScopes
);
// if not the first center
if ($centersI > 0) {
$where .= ') OR (';
}
// condition for the center
$where .= sprintf(' %s.%s = ? ', $metadataPerson->getTableName(), $personToCenter);
$parameters[] = $center->getId();
// begin loop for scopes
$where .= ' AND (';
$scopesI = 0; //like scope#i
foreach ($reachablesScopesId as $scopeId) {
if ($scopesI > 0) {
$where .= ' OR ';
}
$where .= sprintf(' %s.%s = ? ', $metadataActivity->getTableName(), $activityToScope);
$parameters[] = $scopeId;
$scopesI ++;
}
// close loop for scopes
$where .= ') ';
$centersI++;
}
// close loop for centers
$where .= ')';
return [$where, $parameters];
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2021, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\ActivityBundle\Repository;
use Chill\ActivityBundle\Entity\Activity;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method AccompanyingPeriodParticipation|null find($id, $lockMode = null, $lockVersion = null)
* @method AccompanyingPeriodParticipation|null findOneBy(array $criteria, array $orderBy = null)
* @method AccompanyingPeriodParticipation[] findAll()
* @method AccompanyingPeriodParticipation[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ActivityRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Activity::class);
}
}

View File

@@ -1,11 +1,11 @@
{% import 'ChillActivityBundle:ActivityReason:macro.html.twig' as m %}
<div>
<h3>{{ activity.date|format_date('long') }}<span class="activity"> / {{ 'Activity'|trans }}</span></h3>
<h3>{{ activity.date|format_date('long') }}<span class="activity"> / {{ 'Activity'|trans }}</span>{% if 'person' != context %} / {{ activity.person|chill_entity_render_box({'addLink': true}) }}{% endif %}</h3>
<div class="statement">
<span class="statement">{{ '%user% has done an %activity_type%'|trans(
{
'%user%' : user,
'%user%' : activity.user,
'%activity_type%': activity.type.name|localize_translatable_string,
'%date%' : activity.date|format_date('long') }
) }}</span>
@@ -29,13 +29,13 @@
<ul class="record_actions">
<li>
<a href="{{ path('chill_activity_activity_show', { 'person_id': person.id, 'id': activity.id} ) }}" class="sc-button bt-view">
<a href="{{ path('chill_activity_activity_show', { 'person_id': activity.person.id, 'id': activity.id} ) }}" class="sc-button bt-view">
{{ 'Show the activity'|trans }}
</a>
</li>
{% if is_granted('CHILL_ACTIVITY_UPDATE', activity) %}
<li>
<a href="{{ path('chill_activity_activity_edit', { 'person_id': person.id, 'id': activity.id} ) }}" class="sc-button bt-edit">
<a href="{{ path('chill_activity_activity_edit', { 'person_id': activity.person.id, 'id': activity.id} ) }}" class="sc-button bt-edit">
{{ 'Edit the activity'|trans }}
</a>
</li>

View File

@@ -21,6 +21,7 @@
namespace Chill\ActivityBundle\Timeline;
use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Chill\ActivityBundle\Repository\ActivityACLAwareRepository;
use Doctrine\ORM\EntityManager;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
@@ -28,13 +29,13 @@ use Symfony\Component\Security\Core\Role\Role;
use Doctrine\ORM\Mapping\ClassMetadata;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Entity\Scope;
use Chill\ActivityBundle\Entity\Activity;
use Chill\MainBundle\Timeline\TimelineSingleQuery;
/**
* Provide activity for inclusion in timeline
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @author Champs Libres <info@champs-libres.coop>
*/
*/
class TimelineActivityProvider implements TimelineProviderInterface
{
@@ -55,6 +56,10 @@ class TimelineActivityProvider implements TimelineProviderInterface
* @var \Chill\MainBundle\Entity\User
*/
protected $user;
protected ActivityACLAwareRepository $aclAwareRepository;
private const SUPPORTED_CONTEXTS = [ 'center', 'person'];
/**
* TimelineActivityProvider constructor.
@@ -66,11 +71,13 @@ class TimelineActivityProvider implements TimelineProviderInterface
public function __construct(
EntityManager $em,
AuthorizationHelper $helper,
TokenStorageInterface $storage
TokenStorageInterface $storage,
ActivityACLAwareRepository $aclAwareRepository
)
{
$this->em = $em;
$this->helper = $helper;
$this->aclAwareRepository = $aclAwareRepository;
if (!$storage->getToken()->getUser() instanceof \Chill\MainBundle\Entity\User)
{
@@ -86,67 +93,69 @@ class TimelineActivityProvider implements TimelineProviderInterface
*/
public function fetchQuery($context, array $args)
{
$this->checkContext($context);
if ('center' === $context) {
return TimelineSingleQuery::fromArray($this->aclAwareRepository
->queryTimelineIndexer($context, $args));
}
$metadataActivity = $this->em->getClassMetadata('ChillActivityBundle:Activity');
$metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person');
$metadataActivity = $this->em->getClassMetadata(Activity::class);
[$where, $parameters] = $this->getWhereClauseForPerson($args['person']);
return array(
return TimelineSingleQuery::fromArray([
'id' => $metadataActivity->getTableName()
.'.'.$metadataActivity->getColumnName('id'),
'type' => 'activity',
'date' => $metadataActivity->getTableName()
.'.'.$metadataActivity->getColumnName('date'),
'FROM' => $this->getFromClause($metadataActivity, $metadataPerson),
'WHERE' => $this->getWhereClause($metadataActivity, $metadataPerson,
$args['person'])
);
'FROM' => $this->getFromClausePerson($args['person']),
'WHERE' => $where,
'parameters' => $parameters
]);
}
private function getWhereClause(ClassMetadata $metadataActivity,
ClassMetadata $metadataPerson, Person $person)
private function getWhereClauseForPerson(Person $person)
{
$role = new Role('CHILL_ACTIVITY_SEE');
$reachableCenters = $this->helper->getReachableCenters($this->user,
$role);
$parameters = [];
$metadataActivity = $this->em->getClassMetadata(Activity::class);
$associationMapping = $metadataActivity->getAssociationMapping('person');
if (count($reachableCenters) === 0) {
return 'FALSE = TRUE';
$role = new Role('CHILL_ACTIVITY_SEE');
$reachableScopes = $this->helper->getReachableScopes($this->user,
$role, $person->getCenter());
$whereClause = sprintf(' {activity.person_id} = ? AND {activity.scope_id} IN ({scopes_ids}) ');
$scopes_ids = [];
// first parameter: activity.person_id
$parameters[] = $person->getId();
// loop on reachable scopes
foreach ($reachableScopes as $scope) {
if (\in_array($scope->getId(), $scopes_ids)) {
continue;
}
$scopes_ids[] = '?';
$parameters[] = $scope->getId();
}
// we start with activities having the person_id linked to person
// (currently only context "person" is supported)
$whereClause = sprintf('%s = %d',
$associationMapping['joinColumns'][0]['name'],
$person->getId());
// we add acl (reachable center and scopes)
$centerAndScopeLines = array();
foreach ($reachableCenters as $center) {
$reachablesScopesId = array_map(
function(Scope $scope) { return $scope->getId(); },
$this->helper->getReachableScopes($this->user, $role,
$person->getCenter())
);
$centerAndScopeLines[] = sprintf('(%s = %d AND %s IN (%s))',
$metadataPerson->getTableName().'.'.
$metadataPerson->getAssociationMapping('center')['joinColumns'][0]['name'],
$center->getId(),
$metadataActivity->getTableName().'.'.
return [
\strtr(
$whereClause,
[
'{activity.person_id}' => $associationMapping['joinColumns'][0]['name'],
'{activity.scope_id}' => $metadataActivity->getTableName().'.'.
$metadataActivity->getAssociationMapping('scope')['joinColumns'][0]['name'],
implode(',', $reachablesScopesId));
}
$whereClause .= ' AND ('.implode(' OR ', $centerAndScopeLines).')';
return $whereClause;
'{scopes_ids}' => \implode(", ", $scopes_ids)
,
]
),
$parameters
];
}
private function getFromClause(ClassMetadata $metadataActivity,
ClassMetadata $metadataPerson)
private function getFromClausePerson()
{
$metadataActivity = $this->em->getClassMetadata(Activity::class);
$metadataPerson = $this->em->getClassMetadata(Person::class);
$associationMapping = $metadataActivity->getAssociationMapping('person');
return $metadataActivity->getTableName().' JOIN '
@@ -157,14 +166,14 @@ class TimelineActivityProvider implements TimelineProviderInterface
.$associationMapping['joinColumns'][0]['name']
;
}
/**
*
* {@inheritDoc}
*/
public function getEntities(array $ids)
{
$activities = $this->em->getRepository('ChillActivityBundle:Activity')
$activities = $this->em->getRepository(Activity::class)
->findBy(array('id' => $ids));
$result = array();
@@ -183,14 +192,13 @@ class TimelineActivityProvider implements TimelineProviderInterface
{
$this->checkContext($context);
return array(
return [
'template' => 'ChillActivityBundle:Timeline:activity_person_context.html.twig',
'template_data' => array(
'template_data' => [
'activity' => $entity,
'person' => $args['person'],
'user' => $entity->getUser()
)
);
'context' => $context
]
];
}
/**
@@ -210,7 +218,7 @@ class TimelineActivityProvider implements TimelineProviderInterface
*/
private function checkContext($context)
{
if ($context !== 'person') {
if (FALSE === \in_array($context, self::SUPPORTED_CONTEXTS)) {
throw new \LogicException("The context '$context' is not "
. "supported. Currently only 'person' is supported");
}

View File

@@ -3,13 +3,17 @@
"description": "This bundle extend chill for recording the different activities of the user",
"type": "symfony-bundle",
"license": "AGPL-3.0",
"keywords" : ["chill", "social work"],
"homepage" : "https://github.com/Chill-project/Activity",
"keywords": ["chill", "social work"],
"homepage": "https://github.com/Chill-project/Activity",
"autoload": {
"psr-4": { "Chill\\ActivityBundle\\": "" }
"psr-4": {
"Chill\\ActivityBundle\\": ""
}
},
"autoload-dev": {
"classmap": [ "Resources/test/Fixtures/App/app/AppKernel.php" ]
"classmap": [
"Resources/test/Fixtures/App/app/AppKernel.php"
]
},
"authors": [
{
@@ -17,10 +21,6 @@
"email": "info@champs-libres.coop"
}
],
"require": {
},
"require-dev": {
},
"scripts": {
"post-install-cmd": [
"ComposerBundleMigration\\Composer\\Migrations::synchronizeMigrations",

View File

@@ -22,6 +22,14 @@ services:
- '@doctrine.orm.entity_manager'
- '@chill.main.security.authorization.helper'
- '@security.token_storage'
- '@Chill\ActivityBundle\Repository\ActivityACLAwareRepository'
public: true
tags:
- { name: chill.timeline, context: 'person' }
- { name: chill.timeline, context: 'center' }
Chill\ActivityBundle\Menu\:
autowire: true
autoconfigure: true
resource: '../Menu/'
tags: ['chill.menu_builder']

View File

@@ -1,8 +0,0 @@
services:
Chill\ActivityBundle\Menu\MenuBuilder:
arguments:
$authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper'
$tokenStorage: '@Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface'
$translator: '@Symfony\Component\Translation\TranslatorInterface'
tags:
- { name: 'chill.menu_builder' }

View File

@@ -1,18 +1,32 @@
---
services:
chill_activity.repository.activity_type:
class: Doctrine\ORM\EntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityType'
chill_activity.repository.reason:
class: Doctrine\ORM\EntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityReason'
chill_activity.repository.reason_category:
class: Doctrine\ORM\EntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'Chill\ActivityBundle\Entity\ActivityReasonCategory'
Chill\ActivityBundle\Repository\ActivityRepository:
tags: [doctrine.repository_service]
arguments:
- '@Doctrine\Persistence\ManagerRegistry'
Chill\ActivityBundle\Repository\ActivityACLAwareRepository:
arguments:
$tokenStorage: '@Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface'
$authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper'
$repository: '@Chill\ActivityBundle\Repository\ActivityRepository'
$em: '@Doctrine\ORM\EntityManagerInterface'

View File

@@ -3,13 +3,12 @@
"description": "This bundle extend chill for recording element of a budget for peoples",
"type": "symfony-bundle",
"license": "AGPL-3.0",
"keywords" : ["chill", "social work"],
"homepage" : "https://framagit.org/Chill-project/BudgetBundle",
"keywords": ["chill", "social work"],
"homepage": "https://framagit.org/Chill-project/BudgetBundle",
"autoload": {
"psr-4": { "Chill\\AMLI\\BudgetBundle\\": "" }
},
"autoload-dev": {
"classmap": [ "Resources/test/Fixtures/App/app/AppKernel.php" ]
"psr-4": {
"Chill\\AMLI\\BudgetBundle\\": ""
}
},
"authors": [
{
@@ -17,13 +16,8 @@
"email": "info@champs-libres.coop"
}
],
"require": {
},
"require-dev": {
},
"extra": {
"app-migrations-dir": "Resources/test/Fixtures/App/app/DoctrineMigrations",
"symfony-app-dir": "Test/Fixtures/App/app/"
"app-migrations-dir": "Resources/test/Fixtures/App/app/DoctrineMigrations"
},
"minimum-stability": "dev",
"prefer-stable": true

View File

@@ -3,25 +3,25 @@
"license": "AGPL-3.0",
"type": "symfony-bundle",
"description": "This bundle allow to add custom fields on entities.",
"keywords" : ["chill", "social work"],
"homepage" : "https://github.com/Chill-project/CustomFields",
"keywords": ["chill", "social work"],
"homepage": "https://github.com/Chill-project/CustomFields",
"autoload": {
"psr-4": { "Chill\\CustomFieldsBundle\\": "" }
"psr-4": {
"Chill\\CustomFieldsBundle\\": ""
}
},
"autoload-dev": {
"classmap": [ "Resources/test/Fixtures/App/app/AppKernel.php" ]
"classmap": [
"Resources/test/Fixtures/App/app/AppKernel.php"
]
},
"authors" : [
"authors": [
{
"name": "Champs-Libres",
"email": "info@champs-libres.coop",
"homepage": "http://www.champs-libres.coop"
}
],
"require": {
},
"require-dev": {
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {

View File

@@ -3,9 +3,9 @@
"description": "A Chill bundle to store documents",
"type": "symfony-bundle",
"autoload": {
"psr-4": { "Chill\\DocStoreBundle\\" : "" }
},
"require": {
"psr-4": {
"Chill\\DocStoreBundle\\": ""
}
},
"license": "AGPL-3.0"
}

View File

@@ -23,6 +23,7 @@ namespace Chill\EventBundle\Timeline;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Timeline\TimelineProviderInterface;
use Chill\MainBundle\Timeline\TimelineSingleQuery;
use Doctrine\ORM\EntityManager;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
@@ -88,13 +89,14 @@ class TimelineEventProvider implements TimelineProviderInterface
$metadataParticipation = $this->em->getClassMetadata('ChillEventBundle:Participation');
$metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person');
$query = array(
$query = TimelineSingleQuery::fromArray([
'id' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('id'),
'type' => 'event',
'date' => $metadataEvent->getTableName().'.'.$metadataEvent->getColumnName('date'),
'FROM' => $this->getFromClause($metadataEvent, $metadataParticipation, $metadataPerson),
'WHERE' => $this->getWhereClause($metadataEvent, $metadataParticipation, $metadataPerson, $args['person'])
);
'WHERE' => $this->getWhereClause($metadataEvent, $metadataParticipation, $metadataPerson, $args['person']),
'parameters' => []
]);
return $query;
}
@@ -238,4 +240,4 @@ class TimelineEventProvider implements TimelineProviderInterface
);
}
}
}

View File

@@ -3,16 +3,18 @@
"description": "This bundle extend chill software. This bundle allow to define event and participation to those events.",
"type": "symfony-bundle",
"license": "AGPL-3.0-only",
"keywords" : ["chill", "social work"],
"homepage" : "https://git.framasoft.org/Chill-project/Chill-Group",
"keywords": ["chill", "social work"],
"homepage": "https://git.framasoft.org/Chill-project/Chill-Group",
"autoload": {
"psr-4": { "Chill\\EventBundle\\": "" }
"psr-4": {
"Chill\\EventBundle\\": ""
}
},
"support": {
"issues": "https://git.framasoft.org/Chill-project/Chill-Event/issues",
"source": "https://git.framasoft.org/Chill-project/Chill-Event",
"docs" : "http://docs.chill.social",
"email": "dev@listes.chill.social"
"docs": "http://docs.chill.social",
"email": "dev@listes.chill.social"
},
"authors": [
{
@@ -20,11 +22,7 @@
"email": "info@champs-libres.coop"
}
],
"require": {
},
"require-dev": {
},
"suggest" : {
"suggest": {
"chill-project/group": "dev-master@dev"
},
"scripts": {

View File

@@ -3,13 +3,12 @@
"description": "This bundle extend chill for recording family members into a file",
"type": "symfony-bundle",
"license": "AGPL-3.0-or-later",
"keywords" : ["chill", "social work"],
"homepage" : "https://framagit.org/Chill-project/Chill-FamilyMembers",
"keywords": ["chill", "social work"],
"homepage": "https://framagit.org/Chill-project/Chill-FamilyMembers",
"autoload": {
"psr-4": { "Chill\\AMLI\\FamilyMembersBundle\\": "" }
},
"autoload-dev": {
"classmap": [ "Resources/test/Fixtures/App/app/AppKernel.php" ]
"psr-4": {
"Chill\\AMLI\\FamilyMembersBundle\\": ""
}
},
"authors": [
{
@@ -17,13 +16,8 @@
"email": "info@champs-libres.coop"
}
],
"require": {
},
"require-dev": {
},
"extra": {
"app-migrations-dir": "Resources/test/Fixtures/App/app/DoctrineMigrations",
"symfony-app-dir": "Test/Fixtures/App/app/"
"app-migrations-dir": "Resources/test/Fixtures/App/app/DoctrineMigrations"
},
"minimum-stability": "dev",
"prefer-stable": true

View File

@@ -0,0 +1,77 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\CRUD\CompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
use Chill\MainBundle\Routing\MenuComposer;
use Symfony\Component\DependencyInjection\Definition;
/**
*
*
*/
class CRUDControllerCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$crudConfig = $container->getParameter('chill_main_crud_route_loader_config');
$apiConfig = $container->getParameter('chill_main_api_route_loader_config');
foreach ($crudConfig as $crudEntry) {
$this->configureCrudController($container, $crudEntry, 'crud');
}
foreach ($apiConfig as $crudEntry) {
$this->configureCrudController($container, $crudEntry, 'api');
}
}
/**
* Add a controller for each definition, and add a methodCall to inject crud configuration to controller
*/
private function configureCrudController(ContainerBuilder $container, array $crudEntry, string $apiOrCrud): void
{
$controllerClass = $crudEntry['controller'];
$controllerServiceName = 'cs'.$apiOrCrud.'_'.$crudEntry['name'].'_controller';
if ($container->hasDefinition($controllerClass)) {
$controller = $container->getDefinition($controllerClass);
$container->removeDefinition($controllerClass);
$alreadyDefined = true;
} else {
$controller = new Definition($controllerClass);
$alreadyDefined = false;
}
$controller->addTag('controller.service_arguments');
if (FALSE === $alreadyDefined) {
$controller->setAutoconfigured(true);
$controller->setPublic(true);
}
$param = 'chill_main_'.$apiOrCrud.'_config_'.$crudEntry['name'];
$container->setParameter($param, $crudEntry);
$controller->addMethodCall('setCrudConfig', ['%'.$param.'%']);
$container->setDefinition($controllerServiceName, $controller);
}
}

View File

@@ -0,0 +1,251 @@
<?php
namespace Chill\MainBundle\CRUD\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Pagination\PaginatorInterface;
class AbstractCRUDController extends AbstractController
{
/**
* The crud configuration
*
* This configuration si defined by `chill_main['crud']` or `chill_main['apis']`
*
* @var array
*/
protected array $crudConfig = [];
/**
* get the instance of the entity with the given id
*
* @param string $id
* @return object
* @throw Symfony\Component\HttpKernel\Exception\NotFoundHttpException if the object is not found
*/
protected function getEntity($action, $id, Request $request): object
{
$e = $this->getDoctrine()
->getRepository($this->getEntityClass())
->find($id);
if (NULL === $e) {
throw $this->createNotFoundException(sprintf("The object %s for id %s is not found", $this->getEntityClass(), $id));
}
return $e;
}
/**
* Create an entity.
*
* @param string $action
* @param Request $request
* @return object
*/
protected function createEntity(string $action, Request $request): object
{
$type = $this->getEntityClass();
return new $type;
}
/**
* Count the number of entities
*
* By default, count all entities. You can customize the query by
* using the method `customizeQuery`.
*
* @param string $action
* @param Request $request
* @return int
*/
protected function countEntities(string $action, Request $request, $_format): int
{
return $this->buildQueryEntities($action, $request)
->select('COUNT(e)')
->getQuery()
->getSingleScalarResult()
;
}
/**
* Query the entity.
*
* By default, get all entities. You can customize the query by using the
* method `customizeQuery`.
*
* The method `orderEntity` is called internally to order entities.
*
* It returns, by default, a query builder.
*
*/
protected function queryEntities(string $action, Request $request, string $_format, PaginatorInterface $paginator)
{
$query = $this->buildQueryEntities($action, $request)
->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
->setMaxResults($paginator->getItemsPerPage());
// allow to order queries and return the new query
return $this->orderQuery($action, $query, $request, $paginator, $_format);
}
/**
* Add ordering fields in the query build by self::queryEntities
*
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{
return $query;
}
/**
* Build the base query for listing all entities.
*
* This method is used internally by `countEntities` `queryEntities`
*
* This base query does not contains any `WHERE` or `SELECT` clauses. You
* can add some by using the method `customizeQuery`.
*
* The alias for the entity is "e".
*
* @param string $action
* @param Request $request
* @return QueryBuilder
*/
protected function buildQueryEntities(string $action, Request $request)
{
$qb = $this->getDoctrine()->getManager()
->createQueryBuilder()
->select('e')
->from($this->getEntityClass(), 'e')
;
$this->customizeQuery($action, $request, $qb);
return $qb;
}
protected function customizeQuery(string $action, Request $request, $query): void {}
/**
* Get the result of the query
*/
protected function getQueryResult(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query)
{
return $query->getQuery()->getResult();
}
protected function onPreIndex(string $action, Request $request, string $_format): ?Response
{
return null;
}
/**
* method used by indexAction
*/
protected function onPreIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator): ?Response
{
return null;
}
/**
* method used by indexAction
*/
protected function onPostIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query): ?Response
{
return null;
}
/**
* method used by indexAction
*/
protected function onPostIndexFetchQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $entities): ?Response
{
return null;
}
/**
* Get the complete FQDN of the class
*
* @return string the complete fqdn of the class
*/
protected function getEntityClass(): string
{
return $this->crudConfig['class'];
}
/**
* called on post fetch entity
*/
protected function onPostFetchEntity(string $action, Request $request, $entity, $_format): ?Response
{
return null;
}
/**
* Called on post check ACL
*/
protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response
{
return null;
}
/**
* check the acl. Called by every action.
*
* By default, check the role given by `getRoleFor` for the value given in
* $entity.
*
* Throw an \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
* if not accessible.
*
* @throws \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
*/
protected function checkACL(string $action, Request $request, string $_format, $entity = null)
{
$this->denyAccessUnlessGranted($this->getRoleFor($action, $request, $entity, $_format), $entity);
}
/**
*
* @return string the crud name
*/
protected function getCrudName(): string
{
return $this->crudConfig['name'];
}
protected function getActionConfig(string $action)
{
return $this->crudConfig['actions'][$action];
}
/**
* Set the crud configuration
*
* Used by the container to inject configuration for this crud.
*/
public function setCrudConfig(array $config): void
{
$this->crudConfig = $config;
}
/**
* @return PaginatorFactory
*/
protected function getPaginatorFactory(): PaginatorFactory
{
return $this->container->get('chill_main.paginator_factory');
}
protected function getValidator(): ValidatorInterface
{
return $this->get('validator');
}
}

View File

@@ -0,0 +1,517 @@
<?php
namespace Chill\MainBundle\CRUD\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
class ApiController extends AbstractCRUDController
{
/**
* The view action.
*
* Some steps may be overriden during this process of rendering:
*
* This method:
*
* 1. fetch the entity, using `getEntity`
* 2. launch `onPostFetchEntity`. If postfetch is an instance of Response,
* this response is returned.
* 2. throw an HttpNotFoundException if entity is null
* 3. check ACL using `checkACL` ;
* 4. launch `onPostCheckACL`. If the result is an instance of Response,
* this response is returned ;
* 5. Serialize the entity and return the result. The serialization context is given by `getSerializationContext`
*
*/
protected function entityGet(string $action, Request $request, $id, $_format = 'html'): Response
{
$entity = $this->getEntity($action, $id, $request, $_format);
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
if ($postFetch instanceof Response) {
return $postFetch;
}
$response = $this->checkACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onBeforeSerialize($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
if ($_format === 'json') {
$context = $this->getContextForSerialization($action, $request, $_format, $entity);
return $this->json($entity, Response::HTTP_OK, [], $context);
} else {
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This format is not implemented");
}
}
public function onBeforeSerialize(string $action, Request $request, $_format, $entity): ?Response
{
return null;
}
/**
* Base method for handling api action
*
* @return void
*/
public function entityApi(Request $request, $id, $_format): Response
{
switch ($request->getMethod()) {
case Request::METHOD_GET:
case Request::METHOD_HEAD:
return $this->entityGet('_entity', $request, $id, $_format);
case Request::METHOD_PUT:
case Request::METHOD_PATCH:
return $this->entityPut('_entity', $request, $id, $_format);
case Request::METHOD_POST:
return $this->entityPostAction('_entity', $request, $id, $_format);
default:
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This method is not implemented");
}
}
public function entityPost(Request $request, $_format): Response
{
switch($request->getMethod()) {
case Request::METHOD_POST:
return $this->entityPostAction('_entity', $request, $_format);
default:
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This method is not implemented");
}
}
protected function entityPostAction($action, Request $request, string $_format): Response
{
$entity = $this->createEntity($action, $request);
try {
$entity = $this->deserialize($action, $request, $_format, $entity);
} catch (NotEncodableValueException $e) {
throw new BadRequestException("invalid json", 400, $e);
}
$errors = $this->validate($action, $request, $_format, $entity);
$response = $this->onAfterValidation($action, $request, $_format, $entity, $errors);
if ($response instanceof Response) {
return $response;
}
if ($errors->count() > 0) {
$response = $this->json($errors);
$response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
return $response;
}
$response = $this->checkACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$this->getDoctrine()->getManager()->persist($entity);
$this->getDoctrine()->getManager()->flush();
$response = $this->onAfterFlush($action, $request, $_format, $entity, $errors);
if ($response instanceof Response) {
return $response;
}
$response = $this->onBeforeSerialize($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
return $this->json(
$entity,
Response::HTTP_OK,
[],
$this->getContextForSerializationPostAlter($action, $request, $_format, $entity)
);
}
public function entityPut($action, Request $request, $id, string $_format): Response
{
$entity = $this->getEntity($action, $id, $request, $_format);
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
if ($postFetch instanceof Response) {
return $postFetch;
}
if (NULL === $entity) {
throw $this->createNotFoundException(sprintf("The %s with id %s "
. "is not found", $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onBeforeSerialize($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
try {
$entity = $this->deserialize($action, $request, $_format, $entity);
} catch (NotEncodableValueException $e) {
throw new BadRequestException("invalid json", 400, $e);
}
$errors = $this->validate($action, $request, $_format, $entity);
$response = $this->onAfterValidation($action, $request, $_format, $entity, $errors);
if ($response instanceof Response) {
return $response;
}
if ($errors->count() > 0) {
$response = $this->json($errors);
$response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
return $response;
}
$this->getDoctrine()->getManager()->flush();
$response = $this->onAfterFlush($action, $request, $_format, $entity, $errors);
if ($response instanceof Response) {
return $response;
}
return $this->json(
$entity,
Response::HTTP_OK,
[],
$this->getContextForSerializationPostAlter($action, $request, $_format, $entity)
);
}
protected function onAfterValidation(string $action, Request $request, string $_format, $entity, ConstraintViolationListInterface $errors, array $more = []): ?Response
{
return null;
}
protected function onAfterFlush(string $action, Request $request, string $_format, $entity, ConstraintViolationListInterface $errors, array $more = []): ?Response
{
return null;
}
protected function getValidationGroups(string $action, Request $request, string $_format, $entity): ?array
{
return null;
}
protected function validate(string $action, Request $request, string $_format, $entity, array $more = []): ConstraintViolationListInterface
{
$validationGroups = $this->getValidationGroups($action, $request, $_format, $entity);
return $this->getValidator()->validate($entity, null, $validationGroups);
}
/**
* Deserialize the content of the request into the class associated with the curd
*/
protected function deserialize(string $action, Request $request, string $_format, $entity = null): object
{
$default = [];
if (NULL !== $entity) {
$default[AbstractNormalizer::OBJECT_TO_POPULATE] = $entity;
}
$context = \array_merge(
$default,
$this->getContextForSerialization($action, $request, $_format, $entity)
);
return $this->getSerializer()->deserialize($request->getContent(), $this->getEntityClass(), $_format, $context);
}
/**
* Base action for indexing entities
*/
public function indexApi(Request $request, string $_format)
{
switch ($request->getMethod()) {
case Request::METHOD_GET:
case REQUEST::METHOD_HEAD:
return $this->indexApiAction('_index', $request, $_format);
default:
throw $this->createNotFoundException("This method is not supported");
}
}
/**
* Build an index page.
*
* Some steps may be overriden during this process of rendering.
*
* This method:
*
* 1. Launch `onPreIndex`
* x. check acl. If it does return a response instance, return it
* x. launch `onPostCheckACL`. If it does return a response instance, return it
* 1. count the items, using `countEntities`
* 2. build a paginator element from the the number of entities ;
* 3. Launch `onPreIndexQuery`. If it does return a response instance, return it
* 3. build a query, using `queryEntities`
* x. fetch the results, using `getQueryResult`
* x. Launch `onPostIndexFetchQuery`. If it does return a response instance, return it
* 4. Serialize the entities in a Collection, using `SerializeCollection`
*
* @param string $action
* @param Request $request
* @return type
*/
protected function indexApiAction($action, Request $request, $_format)
{
$this->onPreIndex($action, $request, $_format);
$response = $this->checkACL($action, $request, $_format);
if ($response instanceof Response) {
return $response;
}
if (!isset($entity)) {
$entity = '';
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$totalItems = $this->countEntities($action, $request, $_format);
$paginator = $this->getPaginatorFactory()->create($totalItems);
$response = $this->onPreIndexBuildQuery($action, $request, $_format, $totalItems,
$paginator);
if ($response instanceof Response) {
return $response;
}
$query = $this->queryEntities($action, $request, $_format, $paginator);
$response = $this->onPostIndexBuildQuery($action, $request, $_format, $totalItems,
$paginator, $query);
if ($response instanceof Response) {
return $response;
}
$entities = $this->getQueryResult($action, $request, $_format, $totalItems, $paginator, $query);
$response = $this->onPostIndexFetchQuery($action, $request, $_format, $totalItems,
$paginator, $entities);
if ($response instanceof Response) {
return $response;
}
return $this->serializeCollection($action, $request, $_format, $paginator, $entities);
}
/**
* Add or remove an associated entity, using `add` and `remove` methods.
*
* This method:
*
* 1. Fetch the base entity (throw 404 if not found)
* 2. checkACL,
* 3. run onPostCheckACL, return response if any,
* 4. deserialize posted data into the entity given by $postedDataType, with the context in $postedDataContext
* 5. run 'add+$property' for POST method, or 'remove+$property' for DELETE method
* 6. validate the base entity (not the deserialized one). Groups are fetched from getValidationGroups, validation is perform by `validate`
* 7. run onAfterValidation
* 8. if errors, return a 422 response with errors
* 9. flush the data
* 10. run onAfterFlush
* 11. return a 202 response for DELETE with empty body, or HTTP 200 for post with serialized posted entity
*
* @param string action
* @param mixed id
* @param Request $request
* @param string $_format
* @param string $property the name of the property. This will be used to make a `add+$property` and `remove+$property` method
* @param string $postedDataType the type of the posted data (the content)
* @param string $postedDataContext a context to deserialize posted data (the content)
* @throw BadRequestException if unable to deserialize the posted data
* @throw BadRequestException if the method is not POST or DELETE
*
*/
protected function addRemoveSomething(string $action, $id, Request $request, string $_format, string $property, string $postedDataType, $postedDataContext = []): Response
{
$entity = $this->getEntity($action, $id, $request);
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
if ($postFetch instanceof Response) {
return $postFetch;
}
$response = $this->checkACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
$response = $this->onBeforeSerialize($action, $request, $_format, $entity);
if ($response instanceof Response) {
return $response;
}
try {
$postedData = $this->getSerializer()->deserialize($request->getContent(), $postedDataType, $_format, $postedDataContext);
} catch (\Symfony\Component\Serializer\Exception\UnexpectedValueException $e) {
throw new BadRequestException(sprintf("Unable to deserialize posted ".
"data: %s", $e->getMessage()), 0, $e);
}
switch ($request->getMethod()) {
case Request::METHOD_DELETE:
// oups... how to use property accessor to remove element ?
$entity->{'remove'.\ucfirst($property)}($postedData);
break;
case Request::METHOD_POST:
$entity->{'add'.\ucfirst($property)}($postedData);
break;
default:
throw new BadRequestException("this method is not supported");
}
$errors = $this->validate($action, $request, $_format, $entity, [$postedData]);
$response = $this->onAfterValidation($action, $request, $_format, $entity, $errors, [$postedData]);
if ($response instanceof Response) {
return $response;
}
if ($errors->count() > 0) {
// only format accepted
return $this->json($errors, 422);
}
$this->getDoctrine()->getManager()->flush();
$response = $this->onAfterFlush($action, $request, $_format, $entity, $errors, [$postedData]);
if ($response instanceof Response) {
return $response;
}
switch ($request->getMethod()) {
case Request::METHOD_DELETE:
return $this->json('', Response::HTTP_OK);
case Request::METHOD_POST:
return $this->json(
$postedData,
Response::HTTP_OK,
[],
$this->getContextForSerializationPostAlter($action, $request, $_format, $entity, [$postedData])
);
}
}
/**
* Serialize collections
*
*/
protected function serializeCollection(string $action, Request $request, string $_format, PaginatorInterface $paginator, $entities): Response
{
$model = new Collection($entities, $paginator);
$context = $this->getContextForSerialization($action, $request, $_format, $entities);
return $this->json($model, Response::HTTP_OK, [], $context);
}
protected function getContextForSerialization(string $action, Request $request, string $_format, $entity): array
{
switch ($request->getMethod()) {
case Request::METHOD_GET:
return [ 'groups' => [ 'read' ]];
case Request::METHOD_PUT:
case Request::METHOD_PATCH:
case Request::METHOD_POST:
return [ 'groups' => [ 'write' ]];
default:
throw new \LogicException("get context for serialization is not implemented for this method");
}
}
/**
* Get the context for serialization post alter query (in case of
* PATCH, PUT, or POST method)
*
* This is called **after** the entity was altered.
*/
protected function getContextForSerializationPostAlter(string $action, Request $request, string $_format, $entity, array $more = []): array
{
return [ 'groups' => [ 'read' ]];
}
/**
* get the role given from the config.
*/
protected function getRoleFor(string $action, Request $request, $entity, $_format): string
{
$actionConfig = $this->getActionConfig($action);
if (NULL !== $actionConfig['roles'][$request->getMethod()]) {
return $actionConfig['roles'][$request->getMethod()];
}
if ($this->crudConfig['base_role']) {
return $this->crudConfig['base_role'];
}
throw new \RuntimeException(sprintf("the config does not have any role for the ".
"method %s nor a global role for the whole action. Add those to your ".
"configuration or override the required method", $request->getMethod()));
}
protected function getSerializer(): SerializerInterface
{
return $this->get('serializer');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -23,6 +23,9 @@ namespace Chill\MainBundle\CRUD\Routing;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\CRUD\Controller\CRUDController;
/**
* Class CRUDRoutesLoader
@@ -32,24 +35,34 @@ use Symfony\Component\Routing\RouteCollection;
*/
class CRUDRoutesLoader extends Loader
{
/**
* @var array
*/
protected $config = [];
protected array $crudConfig = [];
protected array $apiCrudConfig = [];
/**
* @var bool
*/
private $isLoaded = false;
private const ALL_SINGLE_METHODS = [
Request::METHOD_GET,
Request::METHOD_POST,
Request::METHOD_PUT,
Request::METHOD_DELETE
];
private const ALL_INDEX_METHODS = [ Request::METHOD_GET, Request::METHOD_HEAD ];
/**
* CRUDRoutesLoader constructor.
*
* @param $config
* @param $crudConfig the config from cruds
* @param $apicrudConfig the config from api_crud
*/
public function __construct($config)
public function __construct(array $crudConfig, array $apiConfig)
{
$this->config = $config;
$this->crudConfig = $crudConfig;
$this->apiConfig = $apiConfig;
}
/**
@@ -63,53 +76,153 @@ class CRUDRoutesLoader extends Loader
}
/**
* @return RouteCollection
* Load routes for CRUD and CRUD Api
*/
public function load($resource, $type = null)
public function load($resource, $type = null): RouteCollection
{
if (true === $this->isLoaded) {
throw new \RuntimeException('Do not add the "CRUD" loader twice');
}
$collection = new RouteCollection();
foreach ($this->config as $config) {
$collection->addCollection($this->loadConfig($config));
foreach ($this->crudConfig as $crudConfig) {
$collection->addCollection($this->loadCrudConfig($crudConfig));
}
foreach ($this->apiConfig as $crudConfig) {
$collection->addCollection($this->loadApi($crudConfig));
}
return $collection;
}
/**
* @param $config
* Load routes for CRUD (without api)
*
* @param $crudConfig
* @return RouteCollection
*/
protected function loadConfig($config): RouteCollection
protected function loadCrudConfig($crudConfig): RouteCollection
{
$collection = new RouteCollection();
foreach ($config['actions'] as $name => $action) {
$controller ='cscrud_'.$crudConfig['name'].'_controller';
foreach ($crudConfig['actions'] as $name => $action) {
// defaults (controller name)
$defaults = [
'_controller' => 'cscrud_'.$config['name'].'_controller'.':'.($action['controller_action'] ?? $name)
'_controller' => $controller.':'.($action['controller_action'] ?? $name)
];
if ($name === 'index') {
$path = "{_locale}".$config['base_path'];
$path = "{_locale}".$crudConfig['base_path'];
$route = new Route($path, $defaults);
} elseif ($name === 'new') {
$path = "{_locale}".$config['base_path'].'/'.$name;
$path = "{_locale}".$crudConfig['base_path'].'/'.$name;
$route = new Route($path, $defaults);
} else {
$path = "{_locale}".$config['base_path'].($action['path'] ?? '/{id}/'.$name);
$path = "{_locale}".$crudConfig['base_path'].($action['path'] ?? '/{id}/'.$name);
$requirements = $action['requirements'] ?? [
'{id}' => '\d+'
];
$route = new Route($path, $defaults, $requirements);
}
$collection->add('chill_crud_'.$config['name'].'_'.$name, $route);
$collection->add('chill_crud_'.$crudConfig['name'].'_'.$name, $route);
}
return $collection;
}
/**
* Load routes for api single
*
* @param $crudConfig
* @return RouteCollection
*/
protected function loadApi(array $crudConfig): RouteCollection
{
$collection = new RouteCollection();
$controller ='csapi_'.$crudConfig['name'].'_controller';
foreach ($crudConfig['actions'] as $name => $action) {
// filter only on single actions
$singleCollection = $action['single-collection'] ?? $name === '_entity' ? 'single' : NULL;
if ('collection' === $singleCollection) {
// continue;
}
// compute default action
switch ($name) {
case '_entity':
$controllerAction = 'entityApi';
break;
case '_index':
$controllerAction = 'indexApi';
break;
default:
$controllerAction = $name.'Api';
break;
}
$defaults = [
'_controller' => $controller.':'.($action['controller_action'] ?? $controllerAction)
];
// path are rewritten
// if name === 'default', we rewrite it to nothing :-)
$localName = \in_array($name, [ '_entity', '_index' ]) ? '' : '/'.$name;
if ('collection' === $action['single-collection'] || '_index' === $name) {
$localPath = $action['path'] ?? $localName.'.{_format}';
} else {
$localPath = $action['path'] ?? '/{id}'.$localName.'.{_format}';
}
$path = $crudConfig['base_path'].$localPath;
$requirements = $action['requirements'] ?? [ '{id}' => '\d+' ];
$methods = \array_keys(\array_filter($action['methods'], function($value, $key) { return $value; },
ARRAY_FILTER_USE_BOTH));
if (count($methods) === 0) {
throw new \RuntimeException("The api configuration named \"{$crudConfig['name']}\", action \"{$name}\", ".
"does not have any allowed methods. You should remove this action from the config ".
"or allow, at least, one method");
}
if ('_entity' === $name && \in_array(Request::METHOD_POST, $methods)) {
unset($methods[\array_search(Request::METHOD_POST, $methods)]);
$entityPostRoute = $this->createEntityPostRoute($name, $crudConfig, $action,
$controller);
$collection->add("chill_api_single_{$crudConfig['name']}_{$name}_create",
$entityPostRoute);
}
if (count($methods) === 0) {
// the only method was POST,
// continue to next
continue;
}
$route = new Route($path, $defaults, $requirements);
$route->setMethods($methods);
$collection->add('chill_api_single_'.$crudConfig['name'].'_'.$name, $route);
}
return $collection;
}
private function createEntityPostRoute(string $name, $crudConfig, array $action, $controller): Route
{
$localPath = $action['path'].'.{_format}';
$defaults = [
'_controller' => $controller.':'.($action['controller_action'] ?? 'entityPost')
];
$path = $crudConfig['base_path'].$localPath;
$requirements = $action['requirements'] ?? [];
$route = new Route($path, $defaults, $requirements);
$route->setMethods([ Request::METHOD_POST ]);
return $route;
}
}

View File

@@ -14,6 +14,7 @@ use Chill\MainBundle\DependencyInjection\CompilerPass\NotificationCounterCompile
use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass;
use Chill\MainBundle\CRUD\CompilerPass\CRUDControllerCompilerPass;
use Chill\MainBundle\Templating\Entity\CompilerPass as RenderEntityCompilerPass;
@@ -33,5 +34,6 @@ class ChillMainBundle extends Bundle
$container->addCompilerPass(new ACLFlagsCompilerPass());
$container->addCompilerPass(new GroupingCenterCompilerPass());
$container->addCompilerPass(new RenderEntityCompilerPass());
$container->addCompilerPass(new CRUDControllerCompilerPass());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
/**
* Class AddressReferenceAPIController
*
* @package Chill\MainBundle\Controller
* @author Champs Libres
*/
class AddressReferenceAPIController extends ApiController
{
protected function customizeQuery(string $action, Request $request, $qb): void
{
if ($request->query->has('postal_code')) {
$qb->where('e.postcode = :postal_code')
->setParameter('postal_code', $request->query->get('postal_code'));
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
/**
* Class PostalCodeAPIController
*
* @package Chill\MainBundle\Controller
* @author Champs Libres
*/
class PostalCodeAPIController extends ApiController
{
protected function customizeQuery(string $action, Request $request, $qb): void
{
if ($request->query->has('country')) {
$qb->where('e.country = :country')
->setParameter('country', $request->query->get('country'));
}
}
}

View File

@@ -22,6 +22,7 @@
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\Serializer\Model\Collection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Search\UnknowSearchDomainException;
@@ -34,6 +35,7 @@ use Symfony\Component\HttpFoundation\JsonResponse;
use Chill\MainBundle\Search\SearchProvider;
use Symfony\Contracts\Translation\TranslatorInterface;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Search\SearchApi;
/**
* Class SearchController
@@ -42,32 +44,24 @@ use Chill\MainBundle\Pagination\PaginatorFactory;
*/
class SearchController extends AbstractController
{
/**
*
* @var SearchProvider
*/
protected $searchProvider;
protected SearchProvider $searchProvider;
/**
*
* @var TranslatorInterface
*/
protected $translator;
protected TranslatorInterface $translator;
/**
*
* @var PaginatorFactory
*/
protected $paginatorFactory;
protected PaginatorFactory $paginatorFactory;
protected SearchApi $searchApi;
function __construct(
SearchProvider $searchProvider,
TranslatorInterface $translator,
PaginatorFactory $paginatorFactory
PaginatorFactory $paginatorFactory,
SearchApi $searchApi
) {
$this->searchProvider = $searchProvider;
$this->translator = $translator;
$this->paginatorFactory = $paginatorFactory;
$this->searchApi = $searchApi;
}
@@ -152,6 +146,19 @@ class SearchController extends AbstractController
array('results' => $results, 'pattern' => $pattern)
);
}
public function searchApi(Request $request, $_format): JsonResponse
{
//TODO this is an incomplete implementation
$query = $request->query->get('q', '');
$results = $this->searchApi->getResults($query, 0, 150);
$paginator = $this->paginatorFactory->create(count($results));
$collection = new Collection($results, $paginator);
return $this->json($collection);
}
public function advancedSearchListAction(Request $request)
{

View File

@@ -0,0 +1,91 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres Coopérative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Timeline\TimelineBuilder;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class TimelineCenterController extends AbstractController
{
protected TimelineBuilder $timelineBuilder;
protected PaginatorFactory $paginatorFactory;
private Security $security;
public function __construct(
TimelineBuilder $timelineBuilder,
PaginatorFactory $paginatorFactory,
Security $security
) {
$this->timelineBuilder = $timelineBuilder;
$this->paginatorFactory = $paginatorFactory;
$this->security = $security;
}
/**
* @Route("/{_locale}/center/timeline",
* name="chill_center_timeline",
* methods={"GET"}
* )
*/
public function centerAction(Request $request)
{
// collect reachable center for each group
$user = $this->security->getUser();
$centers = [];
foreach ($user->getGroupCenters() as $group) {
$centers[] = $group->getCenter();
}
if (0 === count($centers)) {
throw $this->createNotFoundException();
}
$nbItems = $this->timelineBuilder->countItems('center',
[ 'centers' => $centers ]
);
$paginator = $this->paginatorFactory->create($nbItems);
return $this->render('@ChillMain/Timeline/index.html.twig', array
(
'timeline' => $this->timelineBuilder->getTimelineHTML(
'center',
[ 'centers' => $centers ],
$paginator->getCurrentPage()->getFirstItemNumber(),
$paginator->getItemsPerPage()
),
'nb_items' => $nbItems,
'paginator' => $paginator
)
);
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Chill\MainBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Persistence\ObjectManager;
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
use Chill\MainBundle\Entity\AddressReference;
use Chill\MainBundle\Doctrine\Model\Point;
/**
* Load reference addresses into database
*
* @author Champs Libres
*/
class LoadAddressReferences extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface {
protected $faker;
public function __construct()
{
$this->faker = \Faker\Factory::create('fr_FR');
}
/**
*
* @var ContainerInterface
*/
private $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getOrder() {
return 51;
}
/**
* Create a random point
*
* @return Point
*/
private function getRandomPoint()
{
$lonBrussels = 4.35243;
$latBrussels = 50.84676;
$lon = $lonBrussels + 0.01 * rand(-5, 5);
$lat = $latBrussels + 0.01 * rand(-5, 5);
return Point::fromLonLat($lon, $lat);
}
/**
* Create a random reference address
*
* @return AddressReference
*/
private function getRandomAddressReference()
{
$ar= new AddressReference();
$ar->setRefId($this->faker->numerify('ref-id-######'));
$ar->setStreet($this->faker->streetName);
$ar->setStreetNumber(rand(0,199));
$ar ->setPoint($this->getRandomPoint());
$ar->setPostcode($this->getReference(
LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)]
));
$ar->setMunicipalityCode($ar->getPostcode()->getCode());
return $ar
;
}
public function load(ObjectManager $manager) {
echo "loading some reference address... \n";
for ($i=0; $i<10; $i++) {
$ar = $this->getRandomAddressReference();
$manager->persist($ar);
}
$manager->flush();
}
}

View File

@@ -55,11 +55,11 @@ class LoadCenters extends AbstractFixture implements OrderedFixtureInterface
public function load(ObjectManager $manager)
{
foreach (static::$centers as $new) {
$centerA = new Center();
$centerA->setName($new['name']);
$center = new Center();
$center->setName($new['name']);
$manager->persist($centerA);
$this->addReference($new['ref'], $centerA);
$manager->persist($center);
$this->addReference($new['ref'], $center);
static::$refs[] = $new['ref'];
}

View File

@@ -35,6 +35,9 @@ use Chill\MainBundle\Doctrine\DQL\OverlapsI;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Chill\MainBundle\Doctrine\DQL\Replace;
use Chill\MainBundle\Doctrine\Type\NativeDateIntervalType;
use Chill\MainBundle\Doctrine\Type\PointType;
use Symfony\Component\HttpFoundation\Request;
/**
* Class ChillMainExtension
@@ -47,11 +50,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
{
/**
* widget factory
*
*
* @var WidgetFactoryInterface[]
*/
protected $widgetFactories = array();
/**
* @param WidgetFactoryInterface $factory
*/
@@ -59,7 +62,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
{
$this->widgetFactories[] = $factory;
}
/**
* @return WidgetFactoryInterface[]
*/
@@ -67,7 +70,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
{
return $this->widgetFactories;
}
/**
* {@inheritDoc}
* @param array $configs
@@ -79,31 +82,31 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
// configuration for main bundle
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('chill_main.installation_name',
$config['installation_name']);
$container->setParameter('chill_main.available_languages',
$config['available_languages']);
$container->setParameter('chill_main.routing.resources',
$config['routing']['resources']);
$container->setParameter('chill_main.routing.resources',
$config['routing']['resources']);
$container->setParameter('chill_main.pagination.item_per_page',
$config['pagination']['item_per_page']);
$container->setParameter('chill_main.notifications',
$container->setParameter('chill_main.notifications',
$config['notifications']);
$container->setParameter('chill_main.redis',
$container->setParameter('chill_main.redis',
$config['redis']);
$container->setParameter('chill_main.phone_helper',
$container->setParameter('chill_main.phone_helper',
$config['phone_helper'] ?? []);
// add the key 'widget' without the key 'enable'
$container->setParameter('chill_main.widgets',
isset($config['widgets']['homepage']) ?
$container->setParameter('chill_main.widgets',
isset($config['widgets']['homepage']) ?
array('homepage' => $config['widgets']['homepage']):
array()
);
@@ -131,10 +134,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
$loader->load('services/templating.yaml');
$loader->load('services/timeline.yaml');
$loader->load('services/search.yaml');
$this->configureCruds($container, $config['cruds'], $loader);
$loader->load('services/serializer.yaml');
$this->configureCruds($container, $config['cruds'], $config['apis'], $loader);
}
/**
* @param array $config
* @param ContainerBuilder $container
@@ -144,11 +148,11 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
{
return new Configuration($this->widgetFactories, $container);
}
/**
* @param ContainerBuilder $container
*/
public function prepend(ContainerBuilder $container)
public function prepend(ContainerBuilder $container)
{
//add installation_name and date_format to globals
$chillMainConfig = $container->getExtensionConfig($this->getAlias());
@@ -163,97 +167,185 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
'form_themes' => array('@ChillMain/Form/fields.html.twig')
);
$container->prependExtensionConfig('twig', $twigConfig);
//add DQL function to ORM (default entity_manager)
$container->prependExtensionConfig('doctrine', array(
'orm' => array(
'dql' => array(
'string_functions' => array(
'unaccent' => Unaccent::class,
'GET_JSON_FIELD_BY_KEY' => GetJsonFieldByKey::class,
'AGGREGATE' => JsonAggregate::class,
'REPLACE' => Replace::class,
),
'numeric_functions' => [
'JSONB_EXISTS_IN_ARRAY' => JsonbExistsInArray::class,
'SIMILARITY' => Similarity::class,
'OVERLAPSI' => OverlapsI::class
]
)
)
));
$container
->prependExtensionConfig(
'doctrine',
[
'orm' => [
'dql' => [
'string_functions' => [
'unaccent' => Unaccent::class,
'GET_JSON_FIELD_BY_KEY' => GetJsonFieldByKey::class,
'AGGREGATE' => JsonAggregate::class,
'REPLACE' => Replace::class,
],
'numeric_functions' => [
'JSONB_EXISTS_IN_ARRAY' => JsonbExistsInArray::class,
'SIMILARITY' => Similarity::class,
'OVERLAPSI' => OverlapsI::class,
],
],
],
],
);
//add dbal types (default entity_manager)
$container->prependExtensionConfig('doctrine', array(
'dbal' => [
'types' => [
'dateinterval' => \Chill\MainBundle\Doctrine\Type\NativeDateIntervalType::class
]
]
));
$container
->prependExtensionConfig(
'doctrine',
[
'dbal' => [
// This is mandatory since we are using postgis as database.
'mapping_types' => [
'geometry' => 'string',
],
'types' => [
'dateinterval' => [
'class' => NativeDateIntervalType::class
],
'point' => [
'class' => PointType::class
]
]
]
]
);
//add current route to chill main
$container->prependExtensionConfig('chill_main', array(
'routing' => array(
'resources' => array(
'@ChillMainBundle/config/routes.yaml'
)
)
));
//add a channel to log app events
$container->prependExtensionConfig('monolog', array(
'channels' => array('chill')
));
//add crud api
$this->prependCruds($container);
}
/**
* @param ContainerBuilder $container
* @param array $config the config under 'cruds' key
* @return null
* Load parameter for configuration and set parameters for api
*/
protected function configureCruds(ContainerBuilder $container, $config, Loader\YamlFileLoader $loader)
protected function configureCruds(
ContainerBuilder $container,
array $crudConfig,
array $apiConfig,
Loader\YamlFileLoader $loader
): void
{
if (count($config) === 0) {
if (count($crudConfig) === 0) {
return;
}
$loader->load('services/crud.yaml');
$container->setParameter('chill_main_crud_route_loader_config', $config);
$definition = new Definition();
$definition
->setClass(\Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader::class)
->addArgument('%chill_main_crud_route_loader_config%')
;
$container->setDefinition('chill_main_crud_route_loader', $definition);
$alreadyExistingNames = [];
foreach ($config as $crudEntry) {
$controller = $crudEntry['controller'];
$controllerServiceName = 'cscrud_'.$crudEntry['name'].'_controller';
$name = $crudEntry['name'];
// check for existing crud names
if (\in_array($name, $alreadyExistingNames)) {
throw new LogicException(sprintf("the name %s is defined twice in CRUD", $name));
}
if (!$container->has($controllerServiceName)) {
$controllerDefinition = new Definition($controller);
$controllerDefinition->addTag('controller.service_arguments');
$controllerDefinition->setAutoconfigured(true);
$controllerDefinition->setClass($crudEntry['controller']);
$container->setDefinition($controllerServiceName, $controllerDefinition);
}
$container->setParameter('chill_main_crud_config_'.$name, $crudEntry);
$container->getDefinition($controllerServiceName)
->addMethodCall('setCrudConfig', ['%chill_main_crud_config_'.$name.'%']);
}
$container->setParameter('chill_main_crud_route_loader_config', $crudConfig);
$container->setParameter('chill_main_api_route_loader_config', $apiConfig);
// Note: the controller are loaded inside compiler pass
}
/**
* @param ContainerBuilder $container
*/
protected function prependCruds(ContainerBuilder $container)
{
$container->prependExtensionConfig('chill_main', [
'apis' => [
[
'class' => \Chill\MainBundle\Entity\Address::class,
'name' => 'address',
'base_path' => '/api/1.0/main/address',
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_POST => true,
Request::METHOD_HEAD => true
]
],
]
],
[
'controller' => \Chill\MainBundle\Controller\AddressReferenceAPIController::class,
'class' => \Chill\MainBundle\Entity\AddressReference::class,
'name' => 'address_reference',
'base_path' => '/api/1.0/main/address-reference',
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
],
[
'controller' => \Chill\MainBundle\Controller\PostalCodeAPIController::class,
'class' => \Chill\MainBundle\Entity\PostalCode::class,
'name' => 'postal_code',
'base_path' => '/api/1.0/main/postal-code',
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
],
[
'class' => \Chill\MainBundle\Entity\Country::class,
'name' => 'country',
'base_path' => '/api/1.0/main/country',
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
]
]
]);
}
}

View File

@@ -8,6 +8,7 @@ use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
/**
@@ -140,7 +141,7 @@ class Configuration implements ConfigurationInterface
->scalarNode('controller_action')
->defaultNull()
->info('the method name to call in the route. Will be set to the action name if left empty.')
->example("'action'")
->example("action")
->end()
->scalarNode('path')
->defaultNull()
@@ -168,6 +169,80 @@ class Configuration implements ConfigurationInterface
->end()
->end()
->arrayNode('apis')
->defaultValue([])
->arrayPrototype()
->children()
->scalarNode('class')->cannotBeEmpty()->isRequired()->end()
->scalarNode('controller')
->cannotBeEmpty()
->defaultValue(\Chill\MainBundle\CRUD\Controller\ApiController::class)
->end()
->scalarNode('name')->cannotBeEmpty()->isRequired()->end()
->scalarNode('base_path')->cannotBeEmpty()->isRequired()->end()
->scalarNode('base_role')->defaultNull()->end()
->arrayNode('actions')
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('controller_action')
->defaultNull()
->info('the method name to call in the controller. Will be set to the concatenation '.
'of action name + \'Api\' if left empty.')
->example("showApi")
->end()
->scalarNode('path')
->defaultNull()
->info('the path that will be **appended** after the base path. Do not forget to add ' .
'arguments for the method. By default, will set to the action name, including an `{id}` '.
'parameter. A suffix of action name will be appended, except if the action name '.
'is "_entity".')
->example('/{id}/my-action')
->end()
->arrayNode('requirements')
->ignoreExtraKeys(false)
->info('the requirements for the route. Will be set to `[ \'id\' => \'\d+\' ]` if left empty.')
->end()
->enumNode('single-collection')
->values(['single', 'collection'])
->defaultValue('single')
->info('indicates if the returned object is a single element or a collection. '.
'If the action name is `_index`, this value will always be considered as '.
'`collection`')
->end()
->arrayNode('methods')
->addDefaultsIfNotSet()
->info('the allowed methods')
->children()
->booleanNode(Request::METHOD_GET)->defaultTrue()->end()
->booleanNode(Request::METHOD_HEAD)->defaultTrue()->end()
->booleanNode(Request::METHOD_POST)->defaultFalse()->end()
->booleanNode(Request::METHOD_DELETE)->defaultFalse()->end()
->booleanNode(Request::METHOD_PUT)->defaultFalse()->end()
->booleanNode(Request::METHOD_PATCH)->defaultFalse()->end()
->end()
->end()
->arrayNode('roles')
->addDefaultsIfNotSet()
->info("The role require for each http method")
->children()
->scalarNode(Request::METHOD_GET)->defaultNull()->end()
->scalarNode(Request::METHOD_HEAD)->defaultNull()->end()
->scalarNode(Request::METHOD_POST)->defaultNull()->end()
->scalarNode(Request::METHOD_DELETE)->defaultNull()->end()
->scalarNode(Request::METHOD_PUT)->defaultNull()->end()
->scalarNode(Request::METHOD_PATCH)->defaultNull()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end() // end of root/children
->end() // end of root
;

View File

@@ -0,0 +1,65 @@
<?php
namespace Chill\MainBundle\Doctrine\Event;
use Chill\MainBundle\Entity\User;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Symfony\Component\Security\Core\Security;
class TrackCreateUpdateSubscriber implements EventSubscriber
{
private Security $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* {@inheritDoc}
*/
public function getSubscribedEvents()
{
return [
Events::prePersist,
Events::preUpdate
];
}
public function prePersist(LifecycleEventArgs $args): void
{
$object = $args->getObject();
if ($object instanceof TrackCreationInterface
&& $this->security->getUser() instanceof User) {
$object->setCreatedBy($this->security->getUser());
$object->setCreatedAt(new \DateTimeImmutable('now'));
}
$this->onUpdate($object);
}
public function preUpdate(LifecycleEventArgs $args): void
{
$object = $args->getObject();
$this->onUpdate($object);
}
protected function onUpdate(object $object): void
{
if ($object instanceof TrackUpdateInterface
&& $this->security->getUser() instanceof User) {
$object->setUpdatedBy($this->security->getUser());
$object->setUpdatedAt(new \DateTimeImmutable('now'));
}
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace Chill\MainBundle\Doctrine\Model;
use \JsonSerializable;
/**
* Description of Point
*
*/
class Point implements JsonSerializable {
private ?float $lat = null;
private ?float $lon = null;
public static string $SRID = '4326';
private function __construct(?float $lon, ?float $lat)
{
$this->lat = $lat;
$this->lon = $lon;
}
public function toGeoJson(): string
{
$array = $this->toArrayGeoJson();
return \json_encode($array);
}
public function jsonSerialize(): array
{
return $this->toArrayGeoJson();
}
public function toArrayGeoJson(): array
{
return [
"type" => "Point",
"coordinates" => [ $this->lon, $this->lat ]
];
}
/**
*
* @return string
*/
public function toWKT(): string
{
return 'SRID='.self::$SRID.';POINT('.$this->lon.' '.$this->lat.')';
}
/**
*
* @param type $geojson
* @return Point
*/
public static function fromGeoJson(string $geojson): Point
{
$a = json_decode($geojson);
//check if the geojson string is correct
if (NULL === $a or !isset($a->type) or !isset($a->coordinates)){
throw PointException::badJsonString($geojson);
}
if ($a->type != 'Point'){
throw PointException::badGeoType();
}
$lat = $a->coordinates[1];
$lon = $a->coordinates[0];
return Point::fromLonLat($lon, $lat);
}
public static function fromLonLat(float $lon, float $lat): Point
{
if (($lon > -180 && $lon < 180) && ($lat > -90 && $lat < 90))
{
return new Point($lon, $lat);
} else {
throw PointException::badCoordinates($lon, $lat);
}
}
public static function fromArrayGeoJson(array $array): Point
{
if ($array['type'] == 'Point' &&
isset($array['coordinates']))
{
return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]);
}
}
public function getLat(): float
{
return $this->lat;
}
public function getLon(): float
{
return $this->lon;
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Chill\MainBundle\Doctrine\Model;
use \Exception;
/**
* Description of PointException
*
*/
class PointException extends Exception {
public static function badCoordinates($lon, $lat): self
{
return new self("Input coordinates are not valid in the used coordinate system (longitude = $lon , latitude = $lat)");
}
public static function badJsonString($str): self
{
return new self("The JSON string is not valid: $str");
}
public static function badGeoType(): self
{
return new self("The geoJSON object type is not valid");
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
interface TrackCreationInterface
{
public function setCreatedBy(User $user): self;
public function setCreatedAt(\DateTimeInterface $datetime): self;
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
interface TrackUpdateInterface
{
public function setUpdatedBy(User $user): self;
public function setUpdatedAt(\DateTimeInterface $datetime): self;
}

View File

@@ -0,0 +1,75 @@
<?php
namespace Chill\MainBundle\Doctrine\Type;
use Chill\MainBundle\Doctrine\Model\Point;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Chill\MainBundle\Doctrine\Model\PointException;
/**
* A Type for Doctrine to implement the Geography Point type
* implemented by Postgis on postgis+postgresql databases
*
*/
class PointType extends Type {
const POINT = 'point';
/**
*
* @param array $fieldDeclaration
* @param AbstractPlatform $platform
* @return type
*/
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return 'geometry(POINT,'.Point::$SRID.')';
}
/**
*
* @param type $value
* @param AbstractPlatform $platform
* @return Point
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if ($value === NULL){
return NULL;
} else {
return Point::fromGeoJson($value);
}
}
public function getName()
{
return self::POINT;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value === NULL){
return NULL;
} else {
return $value->toWKT();
}
}
public function canRequireSQLConversion()
{
return true;
}
public function convertToPHPValueSQL($sqlExpr, $platform)
{
return 'ST_AsGeoJSON('.$sqlExpr.') ';
}
public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
{
return $sqlExpr;
}
}

View File

@@ -4,6 +4,9 @@ namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Chill\MainBundle\Doctrine\Model\Point;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
/**
* Address
@@ -20,6 +23,7 @@ class Address
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @groups({"write"})
*/
private $id;
@@ -27,23 +31,82 @@ class Address
* @var string
*
* @ORM\Column(type="string", length=255)
* @groups({"write"})
*/
private $streetAddress1 = '';
private $street = '';
/**
* @var string
*
* @ORM\Column(type="string", length=255)
* @groups({"write"})
*/
private $streetAddress2 = '';
private $streetNumber = '';
/**
* @var PostalCode
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
* @groups({"write"})
*/
private $postcode;
/**
* @var string|null
*
* @ORM\Column(type="string", length=16, nullable=true)
* @groups({"write"})
*/
private $floor;
/**
* @var string|null
*
* @ORM\Column(type="string", length=16, nullable=true)
* @groups({"write"})
*/
private $corridor;
/**
* @var string|null
*
* @ORM\Column(type="string", length=16, nullable=true)
* @groups({"write"})
*/
private $steps;
/**
* @var string|null
*
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"write"})
*/
private $buildingName;
/**
* @var string|null
*
* @ORM\Column(type="string", length=16, nullable=true)
* @groups({"write"})
*/
private $flat;
/**
* @var string|null
*
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"write"})
*/
private $distribution;
/**
* @var string|null
*
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"write"})
*/
private $extra;
/**
* Indicates when the address starts validation. Used to build an history
* of address. By default, the current date.
@@ -51,29 +114,62 @@ class Address
* @var \DateTime
*
* @ORM\Column(type="date")
* @groups({"write"})
*/
private $validFrom;
/**
* Indicates when the address ends. Used to build an history
* of address.
*
* @var \DateTime|null
*
* @ORM\Column(type="date", nullable=true)
* @groups({"write"})
*/
private $validTo;
/**
* True if the address is a "no address", aka homeless person, ...
* @groups({"write"})
*
* @var bool
*/
private $isNoAddress = false;
/**
* A geospatial field storing the coordinates of the Address
*
* @var Point|null
*
* @ORM\Column(type="point", nullable=true)
* @groups({"write"})
*/
private $point;
/**
* A ThirdParty reference for person's addresses that are linked to a third party
*
* @var ThirdParty|null
*
* @ORM\ManyToOne(targetEntity="Chill\ThirdPartyBundle\Entity\ThirdParty")
* @groups({"write"})
* @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $linkedToThirdParty;
/**
* A list of metadata, added by customizable fields
*
*
* @var array
*/
private $customs = [];
public function __construct()
{
$this->validFrom = new \DateTime();
}
/**
* Get id
*
@@ -85,7 +181,7 @@ class Address
}
/**
* Set streetAddress1
* Set streetAddress1 (legacy function)
*
* @param string $streetAddress1
*
@@ -93,23 +189,23 @@ class Address
*/
public function setStreetAddress1($streetAddress1)
{
$this->streetAddress1 = $streetAddress1 === NULL ? '' : $streetAddress1;
$this->street = $streetAddress1 === NULL ? '' : $streetAddress1;
return $this;
}
/**
* Get streetAddress1
* Get streetAddress1 (legacy function)
*
* @return string
*/
public function getStreetAddress1()
{
return $this->streetAddress1;
return $this->street;
}
/**
* Set streetAddress2
* Set streetAddress2 (legacy function)
*
* @param string $streetAddress2
*
@@ -117,19 +213,19 @@ class Address
*/
public function setStreetAddress2($streetAddress2)
{
$this->streetAddress2 = $streetAddress2 === NULL ? '' : $streetAddress2;
$this->streetNumber = $streetAddress2 === NULL ? '' : $streetAddress2;
return $this;
}
/**
* Get streetAddress2
* Get streetAddress2 (legacy function)
*
* @return string
*/
public function getStreetAddress2()
{
return $this->streetAddress2;
return $this->streetNumber;
}
/**
@@ -155,7 +251,7 @@ class Address
{
return $this->postcode;
}
/**
* @return \DateTime
*/
@@ -173,19 +269,19 @@ class Address
$this->validFrom = $validFrom;
return $this;
}
/**
* Get IsNoAddress
*
*
* Indicate true if the address is a fake address (homeless, ...)
*
*
* @return bool
*/
public function getIsNoAddress(): bool
{
return $this->isNoAddress;
}
/**
* @return bool
*/
@@ -196,9 +292,9 @@ class Address
/**
* Set IsNoAddress
*
*
* Indicate true if the address is a fake address (homeless, ...)
*
*
* @param bool $isNoAddress
* @return $this
*/
@@ -207,10 +303,10 @@ class Address
$this->isNoAddress = $isNoAddress;
return $this;
}
/**
* Get customs informations in the address
*
*
* @return array
*/
public function getCustoms(): array
@@ -220,27 +316,27 @@ class Address
/**
* Store custom informations in the address
*
*
* @param array $customs
* @return $this
*/
public function setCustoms(array $customs): self
{
$this->customs = $customs;
return $this;
}
/**
* Validate the address.
*
*
* Check that:
*
*
* * if the address is not home address:
* * the postal code is present
* * the valid from is not null
* * the address street 1 is greater than 2
*
*
* @param ExecutionContextInterface $context
* @param array $payload
*/
@@ -252,18 +348,18 @@ class Address
->atPath('validFrom')
->addViolation();
}
if ($this->isNoAddress()) {
return;
}
if (empty($this->getStreetAddress1())) {
$context
->buildViolation("address.street1-should-be-set")
->atPath('streetAddress1')
->addViolation();
}
if (!$this->getPostcode() instanceof PostalCode) {
$context
->buildViolation("address.postcode-should-be-set")
@@ -271,7 +367,7 @@ class Address
->addViolation();
}
}
/**
* @param Address $original
* @return Address
@@ -286,5 +382,149 @@ class Address
;
}
public function getStreet(): ?string
{
return $this->street;
}
public function setStreet(string $street): self
{
$this->street = $street;
return $this;
}
public function getStreetNumber(): ?string
{
return $this->streetNumber;
}
public function setStreetNumber(string $streetNumber): self
{
$this->streetNumber = $streetNumber;
return $this;
}
public function getFloor(): ?string
{
return $this->floor;
}
public function setFloor(?string $floor): self
{
$this->floor = $floor;
return $this;
}
public function getCorridor(): ?string
{
return $this->corridor;
}
public function setCorridor(?string $corridor): self
{
$this->corridor = $corridor;
return $this;
}
public function getSteps(): ?string
{
return $this->steps;
}
public function setSteps(?string $steps): self
{
$this->steps = $steps;
return $this;
}
public function getBuildingName(): ?string
{
return $this->buildingName;
}
public function setBuildingName(?string $buildingName): self
{
$this->buildingName = $buildingName;
return $this;
}
public function getFlat(): ?string
{
return $this->flat;
}
public function setFlat(?string $flat): self
{
$this->flat = $flat;
return $this;
}
public function getDistribution(): ?string
{
return $this->distribution;
}
public function setDistribution(?string $distribution): self
{
$this->distribution = $distribution;
return $this;
}
public function getExtra(): ?string
{
return $this->extra;
}
public function setExtra(?string $extra): self
{
$this->extra = $extra;
return $this;
}
public function getValidTo(): ?\DateTimeInterface
{
return $this->validTo;
}
public function setValidTo(\DateTimeInterface $validTo): self
{
$this->validTo = $validTo;
return $this;
}
public function getPoint(): ?Point
{
return $this->point;
}
public function setPoint(?Point $point): self
{
$this->point = $point;
return $this;
}
public function getLinkedToThirdParty()
{
return $this->linkedToThirdParty;
}
public function setLinkedToThirdParty($linkedToThirdParty): self
{
$this->linkedToThirdParty = $linkedToThirdParty;
return $this;
}
}

View File

@@ -0,0 +1,173 @@
<?php
namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Chill\MainBundle\Doctrine\Model\Point;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\Entity()
* @ORM\Table(name="chill_main_address_reference")
* @ORM\HasLifecycleCallbacks()
*/
class AddressReference
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @groups({"read"})
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @groups({"read"})
*/
private $refId;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"read"})
*/
private $street;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"read"})
*/
private $streetNumber;
/**
* @var PostalCode
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
* @groups({"read"})
*/
private $postcode;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"read"})
*/
private $municipalityCode;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @groups({"read"})
*/
private $source;
/**
* A geospatial field storing the coordinates of the Address
*
* @var Point
*
* @ORM\Column(type="point")
* @groups({"read"})
*/
private $point;
public function getId(): ?int
{
return $this->id;
}
public function getRefId(): ?string
{
return $this->refId;
}
public function setRefId(string $refId): self
{
$this->refId = $refId;
return $this;
}
public function getStreet(): ?string
{
return $this->street;
}
public function setStreet(?string $street): self
{
$this->street = $street;
return $this;
}
public function getStreetNumber(): ?string
{
return $this->streetNumber;
}
public function setStreetNumber(?string $streetNumber): self
{
$this->streetNumber = $streetNumber;
return $this;
}
/**
* Set postcode
*
* @param PostalCode $postcode
*
* @return Address
*/
public function setPostcode(PostalCode $postcode = null)
{
$this->postcode = $postcode;
return $this;
}
/**
* Get postcode
*
* @return PostalCode
*/
public function getPostcode()
{
return $this->postcode;
}
public function getMunicipalityCode(): ?string
{
return $this->municipalityCode;
}
public function setMunicipalityCode(?string $municipalityCode): self
{
$this->municipalityCode = $municipalityCode;
return $this;
}
public function getSource(): ?string
{
return $this->source;
}
public function setSource(?string $source): self
{
$this->source = $source;
return $this;
}
public function getPoint(): ?Point
{
return $this->point;
}
public function setPoint(?Point $point): self
{
$this->point = $point;
return $this;
}
}

View File

@@ -3,6 +3,7 @@
namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* Country
@@ -20,6 +21,7 @@ class Country
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @groups({"read"})
*/
private $id;
@@ -27,13 +29,16 @@ class Country
* @var string
*
* @ORM\Column(type="json_array")
* @groups({"read"})
*
*/
private $name;
/**
* @var string
*
* @ORM\Column(type="string", length=3)
* @groups({"read"})
*/
private $countryCode;
@@ -41,7 +46,7 @@ class Country
/**
* Get id
*
* @return integer
* @return integer
*/
public function getId()
{
@@ -57,20 +62,20 @@ class Country
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
@@ -90,12 +95,12 @@ class Country
/**
*
* @param string $countryCode
* @param string $countryCode
*/
public function setCountryCode($countryCode)
{
$this->countryCode = $countryCode;
return $this;
}
}

View File

@@ -3,6 +3,7 @@
namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* PostalCode
@@ -25,6 +26,7 @@ class PostalCode
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @groups({"read"})
*/
private $id;
@@ -32,6 +34,7 @@ class PostalCode
* @var string
*
* @ORM\Column(type="string", length=255, name="label")
* @groups({"read"})
*/
private $name;
@@ -39,6 +42,7 @@ class PostalCode
* @var string
*
* @ORM\Column(type="string", length=100)
* @groups({"read"})
*/
private $code;
@@ -46,6 +50,7 @@ class PostalCode
* @var Country
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\Country")
* @groups({"read"})
*/
private $country;

View File

@@ -24,13 +24,16 @@ use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Chill\MainBundle\Entity\RoleScope;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
/**
* @ORM\Entity()
* @ORM\Table(name="scopes")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region")
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @DiscriminatorMap(typeProperty="type", mapping={
* "scope"=Scope::class
* })
*/
class Scope
{
@@ -40,6 +43,7 @@ class Scope
* @ORM\Id
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @Groups({"read"})
*/
private $id;
@@ -49,6 +53,7 @@ class Scope
* @var array
*
* @ORM\Column(type="json_array")
* @Groups({"read"})
*/
private $name = [];

View File

@@ -7,6 +7,7 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
/**
* User
@@ -14,6 +15,9 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
* @ORM\Entity(repositoryClass="Chill\MainBundle\Repository\UserRepository")
* @ORM\Table(name="users")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region")
* @DiscriminatorMap(typeProperty="type", mapping={
* "user"=User::class
* })
*/
class User implements AdvancedUserInterface {

View File

@@ -33,8 +33,8 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
* A type to create/update Address entity
*
* Options:
*
* - `has_valid_from` (boolean): show if an entry "has valid from" must be
*
* - `has_valid_from` (boolean): show if an entry "has valid from" must be
* shown.
* - `null_if_empty` (boolean): replace the address type by null if the street
* or the postCode is empty. This is useful when the address is not required and
@@ -45,10 +45,10 @@ class AddressType extends AbstractType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('streetAddress1', TextType::class, array(
->add('street', TextType::class, array(
'required' => !$options['has_no_address'] // true if has no address is false
))
->add('streetAddress2', TextType::class, array(
->add('streetNumber', TextType::class, array(
'required' => false
))
->add('postCode', PostalCodeType::class, array(
@@ -57,7 +57,7 @@ class AddressType extends AbstractType
'required' => !$options['has_no_address'] // true if has no address is false
))
;
if ($options['has_valid_from']) {
$builder
->add('validFrom', DateType::class, array(
@@ -67,7 +67,7 @@ class AddressType extends AbstractType
)
);
}
if ($options['has_no_address']) {
$builder
->add('isNoAddress', ChoiceType::class, [
@@ -79,12 +79,12 @@ class AddressType extends AbstractType
'label' => 'address.address_homeless'
]);
}
if ($options['null_if_empty'] === TRUE) {
$builder->setDataMapper(new AddressDataMapper());
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver

View File

@@ -27,6 +27,7 @@ use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Form\Type\DataTransformer\ObjectToIdTransformer;
use Doctrine\Persistence\ObjectManager;
use Chill\MainBundle\Form\Type\Select2ChoiceType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
/**
* Extends choice to allow adding select2 library on widget
@@ -41,15 +42,26 @@ class Select2CountryType extends AbstractType
*/
private $requestStack;
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
* @var ObjectManager
*/
private $em;
public function __construct(RequestStack $requestStack,ObjectManager $em)
public function __construct(
RequestStack $requestStack,
ObjectManager $em,
TranslatableStringHelper $translatableStringHelper
)
{
$this->requestStack = $requestStack;
$this->em = $em;
$this->translatableStringHelper = $translatableStringHelper;
}
public function getBlockPrefix()
@@ -75,7 +87,7 @@ class Select2CountryType extends AbstractType
$choices = array();
foreach ($countries as $c) {
$choices[$c->getId()] = $c->getName()[$locale];
$choices[$c->getId()] = $this->translatableStringHelper->localize($c->getName());
}
asort($choices, SORT_STRING | SORT_FLAG_CASE);

View File

@@ -27,6 +27,7 @@ use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Form\Type\DataTransformer\MultipleObjectsToIdTransformer;
use Doctrine\Persistence\ObjectManager;
use Chill\MainBundle\Form\Type\Select2ChoiceType;
use Chill\MainBundle\Templating\TranslatableStringHelper;
/**
* Extends choice to allow adding select2 library on widget for languages (multiple)
@@ -43,10 +44,21 @@ class Select2LanguageType extends AbstractType
*/
private $em;
public function __construct(RequestStack $requestStack,ObjectManager $em)
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct(
RequestStack $requestStack,
ObjectManager $em,
TranslatableStringHelper $translatableStringHelper
)
{
$this->requestStack = $requestStack;
$this->em = $em;
$this->translatableStringHelper = $translatableStringHelper;
}
public function getBlockPrefix()
@@ -72,7 +84,7 @@ class Select2LanguageType extends AbstractType
$choices = array();
foreach ($languages as $l) {
$choices[$l->getId()] = $l->getName()[$locale];
$choices[$l->getId()] = $this->translatableStringHelper->localize($l->getName());
}
asort($choices, SORT_STRING | SORT_FLAG_CASE);

View File

@@ -0,0 +1,50 @@
<?php
namespace Chill\MainBundle\Repository;
use Chill\MainBundle\Entity\AddressReference;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method AddressReference|null find($id, $lockMode = null, $lockVersion = null)
* @method AddressReference|null findOneBy(array $criteria, array $orderBy = null)
* @method AddressReference[] findAll()
* @method AddressReference[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class AddressReferenceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, AddressReference::class);
}
// /**
// * @return AddressReference[] Returns an array of AddressReference objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('a')
->andWhere('a.exampleField = :val')
->setParameter('val', $value)
->orderBy('a.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?AddressReference
{
return $this->createQueryBuilder('a')
->andWhere('a.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}

View File

@@ -23,12 +23,12 @@
// @import "bootstrap/scss/button-group";
// @import "bootstrap/scss/input-group";
// @import "bootstrap/scss/custom-forms";
// @import "bootstrap/scss/nav";
@import "bootstrap/scss/nav";
// @import "bootstrap/scss/navbar";
// @import "bootstrap/scss/card";
// @import "bootstrap/scss/breadcrumb";
// @import "bootstrap/scss/pagination";
// @import "bootstrap/scss/badge";
@import "bootstrap/scss/badge";
// @import "bootstrap/scss/jumbotron";
// @import "bootstrap/scss/alert";
// @import "bootstrap/scss/progress";
@@ -41,7 +41,7 @@
// @import "bootstrap/scss/popover";
// @import "bootstrap/scss/carousel";
// @import "bootstrap/scss/spinners";
// @import "bootstrap/scss/utilities";
@import "bootstrap/scss/utilities";
// @import "bootstrap/scss/print";
@import "custom";

View File

@@ -9,6 +9,12 @@ div.chill_address {
margin: 0 0 0 1.5em;
text-indent: -1.5em;
}
&.chill_address_address--multiline {
p {
display: block;
}
}
}
}

View File

@@ -9,6 +9,11 @@ ul.record_actions li {
ul.record_actions, ul.record_actions_column {
display: flex;
justify-content: flex-end;
&.record_actions--left {
justify-content: flex-start;
}
padding: 0.5em 0;
flex-wrap: wrap-reverse;

View File

@@ -5,7 +5,7 @@
@include button($green, $white);
}
&.bt-reset, &.bt-delete {
&.bt-reset, &.bt-delete, &.bt-remove {
@include button($red, $white);
}
@@ -24,6 +24,7 @@
&.bt-save::before,
&.bt-new::before,
&.bt-delete::before,
&.bt-remove::before,
&.bt-update::before,
&.bt-edit::before,
&.bt-cancel::before,
@@ -56,7 +57,12 @@
// add a trash
content: "";
}
&.bt-remove::before {
// add a times
content: "";
}
&.bt-edit::before, &.bt-update::before {
// add a pencil
content: "";
@@ -94,6 +100,7 @@
&.bt-save::before,
&.bt-new::before,
&.bt-delete::before,
&.bt-remove::before,
&.bt-update::before,
&.bt-edit::before,
&.bt-cancel::before,
@@ -123,6 +130,7 @@
&.bt-save::before,
&.bt-new::before,
&.bt-delete::before,
&.bt-remove::before,
&.bt-update::before,
&.bt-edit::before,
&.bt-cancel::before,

View File

@@ -1,21 +1,57 @@
/*
* NOTE 2021.04
* scss/chill.scss is the main sass file for the new chill.2
* scss/chillmain.scss is the main sass file for the new chill.2
* scratch will be replaced by bootstrap, please avoid to edit in modules/scratch/_custom.scss
*
* when possible, try to use bootstrap class naming
* when possible, try to use bootstrap html class
*/
/* [hack] /!\ Contourne le positionnement problématique du div#content_conainter suivant,
* car sa position: relative le place au-dessus du bandeau et les liens sont incliquables */
div.subheader {
height: 130px;
}
/*
* Specific rules
*/
// [scratch] un bouton 'disabled' non clickable
.sc-button {
&.disabled {
cursor: default;
&.bt-remove {
background-color: #d9d9d9;
}
}
}
// [debug] un affichage discret pour le debug
.discret {
color: grey;
margin-right: 1em;
}
// reserre la hauteur des rangées de tableau (ul.record_actions prennait trop de place)
table {
ul.record_actions {
margin: 0;
padding: 0.5em;
}
}
/*
* ACCOMPANYING_COURSE
* Header custom for Accompanying Course
*/
div#header-accompanying_course-name {
background: none repeat scroll 0 0 #718596;
color: #FFF;
padding-top: 1em;
padding-bottom: 1em;
h1 {
margin: 0.4em 0;
}
span {
a {
color: white;
@@ -25,7 +61,6 @@ div#header-accompanying_course-name {
}
}
}
div#header-accompanying_course-details {
background: none repeat scroll 0 0 #718596ab;
color: #FFF;
@@ -33,25 +68,196 @@ div#header-accompanying_course-details {
padding-bottom: 1em;
}
/* /!\ Contourne le positionnement problématique du div#content_conainter suivant,
* car sa position: relative le place au-dessus du bandeau et les liens sont incliquables */
div.subheader {
height: 130px;
/*
* FLEX RESPONSIVE TABLE/BLOCK PRESENTATION
*/
div.flex-bloc,
div.flex-table {
h2, h3, h4, dl, p {
margin: 0;
}
h2, h3, h4 {
color: var(--chill-blue);
}
}
div.vue-component {
padding: 1.5em;
margin: 2em 0;
border: 2px dashed grey;
position: relative;
&:before {
content: "vuejs component";
position: absolute;
left: 1.5em;
top: -0.9em;
background-color: white;
color: grey;
padding: 0 0.3em;
}
dd { margin-left: 1em; }
/*
* Bloc appearance
*/
div.flex-bloc {
box-sizing: border-box;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: stretch;
align-content: stretch;
div.item-bloc {
flex-grow: 0; flex-shrink: 1; flex-basis: 50%;
margin: 0;
border: 1px solid #000;
padding: 1em;
border-top: 0;
&:nth-child(1), &:nth-child(2) {
border-top: 1px solid #000;
}
border-left: 0;
&:nth-child(odd) {
border-left: 1px solid #000;
}
//background-color: #e6e6e6;
display: flex;
flex-direction: column;
div.item-row {
flex-grow: 1; flex-shrink: 1; flex-basis: auto;
display: flex;
flex-direction: column;
div.item-col {
&:first-child {
flex-grow: 0; flex-shrink: 0; flex-basis: auto;
}
&:last-child {
flex-grow: 1; flex-shrink: 1; flex-basis: auto;
display: flex;
.list-content { // ul, dl, or div
}
ul.record_actions {
margin: 0;
align-self: flex-end;
flex-grow: 1; flex-shrink: 0; flex-basis: auto;
li {
margin-right: 5px;
}
}
}
}
}
}
@media only screen and (max-width: 945px) { margin: auto -0.2em; }
@media only screen and (max-width: 935px) { margin: auto -0.5em; }
@media only screen and (max-width: 920px) { margin: auto -0.9em; }
@media only screen and (max-width: 900px) {
flex-direction: column;
margin: auto 0;
div.item-bloc {
border-left: 1px solid #000;
&:nth-child(2) {
border-top: 0;
}
}
}
}
/*
* Table appearance
*/
div.flex-table {
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
div.item-bloc {
display: flex;
flex-direction: column;
padding: 1em;
border: 1px solid #000;
border-top: 0;
&:first-child {
border-top: 1px solid #000;
}
&:nth-child(even) {
background-color: #e6e6e6;
}
div.item-row {
display: flex;
flex-direction: row;
&:not(:first-child) {
margin-top: 0.5em;
border-top: 1px dotted #0000004f;
padding-top: 0.5em;
flex-direction: column;
}
div.item-col {
&:first-child {
flex-grow: 0; flex-shrink: 0; flex-basis: 33%;
}
&:last-child {
flex-grow: 1; flex-shrink: 1; flex-basis: auto;
display: flex;
justify-content: flex-end;
.list-content { // ul, dl, or div
}
ul.record_actions {
margin: 0;
align-self: flex-start;
flex-grow: 1; flex-shrink: 0; flex-basis: auto;
li {
margin-right: 5px;
}
}
}
}
@media only screen and (max-width: 900px) {
flex-direction: column;
div.item-col {
&:last-child {
ul.record_actions {
align-self: flex-end;
}
}
}
}
// neutralize
div.chill_address div.chill_address_address p { text-indent: 0; }
}
}
}
/*
* Address form
*/
div.address_form {
display: flex;
flex-direction: column;
div.address_form__header {
}
div.address_form__select {
display: flex;
flex-direction: row;
justify-content: space-between;
div.address_form__select__body {
display: flex;
flex-direction: column;
flex-grow: 1;
}
div.address_form__select__map {
margin: 0px 20px;
div#address_map {
height:400px;
width:400px;
}
}
}
div.address_form__more {
}
}

View File

@@ -0,0 +1,60 @@
<template>
<div v-if="address.address">
{{ address.address.street }}, {{ address.address.streetNumber }}
</div>
<div v-if="address.city">
{{ address.city.code }} {{ address.city.name }}
</div>
<div v-if="address.country">
{{ address.country.name }}
</div>
<add-address
@addNewAddress="addNewAddress">
</add-address>
</template>
<script>
import { mapState } from 'vuex';
import AddAddress from '../_components/AddAddress.vue';
export default {
name: 'App',
components: {
AddAddress
},
computed: {
address() {
return this.$store.state.address;
}
},
methods: {
addNewAddress({ address, modal }) {
console.log('@@@ CLICK button addNewAdress', address);
let newAddress = {
'isNoAddress': address.isNoAddress,
'street': address.selected.address.street,
'streetNumber': address.selected.address.streetNumber,
'postcode': {'id': address.selected.city.id },
'floor': address.floor,
'corridor': address.corridor,
'steps': address.steps,
'flat': address.flat,
'buildingName': address.buildingName,
'distribution': address.distribution,
'extra': address.extra
};
if (address.selected.address.point !== undefined){
newAddress = Object.assign(newAddress, {'point': address.selected.address.point.coordinates});
}
this.$store.dispatch('addAddress', newAddress);
modal.showModal = false;
}
}
};
</script>

View File

@@ -0,0 +1,16 @@
import { createApp } from 'vue'
import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n'
import { addressMessages } from './js/i18n'
import { store } from './store'
import App from './App.vue';
const i18n = _createI18n(addressMessages);
const app = createApp({
template: `<app></app>`,
})
.use(store)
.use(i18n)
.component('app', App)
.mount('#address');

View File

@@ -0,0 +1,23 @@
const addressMessages = {
fr: {
add_an_address_title: 'Ajouter une adresse',
select_an_address_title: 'Sélectionner une adresse',
fill_an_address: 'Compléter l\'adresse',
select_country: 'Choisir le pays',
select_city: 'Choisir une localité',
select_address: 'Choisir une adresse',
create_address: 'Appuyer sur "Entrée" pour créer une nouvelle adresse',
isNoAddress: 'Pas d\'adresse complète',
floor: 'Étage',
corridor: 'Couloir',
steps: 'Escalier',
flat: 'Appartement',
buildingName: 'Nom du batiment',
extra: 'Complément d\'adresse',
distribution: 'Service particulier de distribution'
}
};
export {
addressMessages
};

View File

@@ -0,0 +1,45 @@
import 'es6-promise/auto';
import { createStore } from 'vuex';
import { postAddress } from '../../_api/AddAddress'
const debug = process.env.NODE_ENV !== 'production';
const store = createStore({
strict: debug,
state: {
address: {},
errorMsg: []
},
getters: {
},
mutations: {
catchError(state, error) {
state.errorMsg.push(error);
},
addAddress(state, address) {
console.log('@M addAddress address', address);
state.address = address;
}
},
actions: {
addAddress({ commit }, payload) {
console.log('@A addAddress payload', payload);
//commit('addAddress', payload); // à remplacer par la suite
//fetch POST qui envoie l'adresse, et récupère la confirmation que c'est ok.
//La confirmation est l'adresse elle-même.
postAddress(payload)
.then(address => new Promise((resolve, reject) => {
commit('addAddress', address);
resolve();
}))
.catch((error) => {
commit('catchError', error);
});
}
}
});
export { store };

View File

@@ -0,0 +1,75 @@
/*
* Endpoint chill_api_single_country__index
* method GET, get Country Object
* @returns {Promise} a promise containing all Country object
*/
const fetchCountries = () => {
console.log('<<< fetching countries');
const url = `/api/1.0/main/country.json?item_per_page=1000`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
/*
* Endpoint chill_api_single_postal_code__index
* method GET, get Country Object
* @returns {Promise} a promise containing all Postal Code objects filtered with country
*/
const fetchCities = (country) => {
console.log('<<< fetching cities for', country);
const url = `/api/1.0/main/postal-code.json?item_per_page=1000&country=${country.id}`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
/*
* Endpoint chill_api_single_address_reference__index
* method GET, get AddressReference Object
* @returns {Promise} a promise containing all AddressReference objects filtered with postal code
*/
const fetchReferenceAddresses = (postalCode) => {
console.log('<<< fetching references addresses for', postalCode);
//TODO deal with huge number of addresses... we should do suggestion...
const url = `/api/1.0/main/address-reference.json?item_per_page=1000&postal_code=${postalCode.id}`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
/*
* Endpoint chill_api_single_address__entity__create
* method POST, post Address Object
* @returns {Promise}
*/
const postAddress = (address) => {
console.log(address);
const url = `/api/1.0/main/address.json?`;
const body = address;
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(body)
}).then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
export {
fetchCountries,
fetchCities,
fetchReferenceAddresses,
postAddress
};

View File

@@ -0,0 +1,205 @@
<template>
<button class="sc-button bt-create centered mt-4" @click="openModal">
{{ $t('add_an_address_title') }}
</button>
<teleport to="body">
<modal v-if="modal.showModal"
v-bind:modalDialogClass="modal.modalDialogClass"
@close="modal.showModal = false">
<template v-slot:header>
<h3 class="modal-title">{{ $t('add_an_address_title') }}</h3>
</template>
<template v-slot:body>
<div class="address_form">
<div class="address_form__header">
<h4>{{ $t('select_an_address_title') }}</h4>
</div>
<div class="address_form__select">
<div class="address_form__select__body">
<label for="isNoAddress">
<input type="checkbox"
name="isNoAddress"
v-bind:placeholder="$t('isNoAddress')"
v-model="isNoAddress"
v-bind:value="value"/>
{{ $t('isNoAddress') }}
</label>
<country-selection
v-bind:address="address"
v-bind:getCities="getCities">
</country-selection>
<city-selection
v-bind:address="address"
v-bind:getReferenceAddresses="getReferenceAddresses">
</city-selection>
<address-selection
v-bind:address="address"
v-bind:updateMapCenter="updateMapCenter">
</address-selection>
</div>
<div class="address_form__select__map">
<address-map
v-bind:address="address"
ref="addressMap">
</address-map>
</div>
</div>
<div class="address_form__more">
<address-more
v-if="!isNoAddress"
v-bind:address="address">
</address-more>
</div>
</div>
</template>
<template v-slot:footer>
<button class="sc-button green"
@click.prevent="$emit('addNewAddress', { address, modal })">
<i class="fa fa-plus fa-fw"></i>{{ $t('action.add')}}
</button>
</template>
</modal>
</teleport>
</template>
<script>
import Modal from './Modal';
import { fetchCountries, fetchCities, fetchReferenceAddresses } from '../_api/AddAddress'
import CountrySelection from './AddAddress/CountrySelection';
import CitySelection from './AddAddress/CitySelection';
import AddressSelection from './AddAddress/AddressSelection';
import AddressMap from './AddAddress/AddressMap';
import AddressMore from './AddAddress/AddressMore'
export default {
name: 'AddAddresses',
components: {
Modal,
CountrySelection,
CitySelection,
AddressSelection,
AddressMap,
AddressMore
},
props: [
],
emits: ['addNewAddress'],
data() {
return {
modal: {
showModal: false,
modalDialogClass: "modal-dialog-scrollable modal-xl"
},
address: {
loaded: {
countries: [],
cities: [],
addresses: [],
},
selected: {
country: {},
city: {},
address: {},
},
addressMap: {
center : [48.8589, 2.3469], // Note: LeafletJs demands [lat, lon] cfr https://macwright.com/lonlat/
zoom: 12
},
isNoAddress: false,
floor: null,
corridor: null,
steps: null,
floor: null,
flat: null,
buildingName: null,
extra: null,
distribution: null,
},
errorMsg: {}
}
},
computed: {
isNoAddress: {
set(value) {
console.log('value', value);
this.address.isNoAddress = value;
},
get() {
return this.address.isNoAddress;
}
}
},
mounted() {
this.getCountries();
},
methods: {
openModal() {
this.modal.showModal = true;
this.resetAll();
//this.$nextTick(function() {
// this.$refs.search.focus(); // positionner le curseur à l'ouverture de la modale
//})
},
getCountries() {
console.log('getCountries');
fetchCountries().then(countries => new Promise((resolve, reject) => {
this.address.loaded.countries = countries.results;
resolve()
}))
.catch((error) => {
this.errorMsg.push(error.message);
});
},
getCities(country) {
console.log('getCities for', country.name);
fetchCities(country).then(cities => new Promise((resolve, reject) => {
this.address.loaded.cities = cities.results;
resolve()
}))
.catch((error) => {
this.errorMsg.push(error.message);
});
},
getReferenceAddresses(city) {
console.log('getReferenceAddresses for', city.name);
fetchReferenceAddresses(city).then(addresses => new Promise((resolve, reject) => {
console.log('addresses', addresses);
this.address.loaded.addresses = addresses.results;
resolve();
}))
.catch((error) => {
this.errorMsg.push(error.message);
});
},
updateMapCenter(point) {
console.log('point', point);
this.address.addressMap.center[0] = point.coordinates[1]; // TODO use reverse()
this.address.addressMap.center[1] = point.coordinates[0];
this.$refs.addressMap.update(); // cast child methods
},
resetAll() {
console.log('reset all selected');
this.address.loaded.addresses = [];
this.address.selected.address = {};
this.address.loaded.cities = [];
this.address.selected.city = {};
this.address.selected.country = {};
console.log('cities and addresses', this.address.loaded.cities, this.address.loaded.addresses);
}
}
}
</script>

View File

@@ -0,0 +1,50 @@
<template>
<div class="container">
<div id='address_map'></div>
</div>
</template>
<script>
import L from 'leaflet';
import markerIconPng from 'leaflet/dist/images/marker-icon.png'
import 'leaflet/dist/leaflet.css';
let map;
let marker;
export default {
name: 'AddressMap',
props: ['address'],
computed: {
center() {
return this.address.addressMap.center;
},
},
methods:{
init() {
map = L.map('address_map').setView([48.8589, 2.3469], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
const markerIcon = L.icon({
iconUrl: markerIconPng,
iconAnchor: [12, 41],
});
marker = L.marker([48.8589, 2.3469], {icon: markerIcon}).addTo(map);
},
update() {
console.log('update map with : ', this.address.addressMap.center)
marker.setLatLng(this.address.addressMap.center);
map.setView(this.address.addressMap.center, 12);
}
},
mounted(){
this.init()
}
}
</script>

View File

@@ -0,0 +1,112 @@
<template>
<div>
<h4>{{ $t('fill_an_address') }}</h4>
<input
type="text"
name="floor"
:placeholder="$t('floor')"
v-model="floor"/>
<input
type="text"
name="corridor"
:placeholder="$t('corridor')"
v-model="corridor"/>
<input
type="text"
name="steps"
:placeholder="$t('steps')"
v-model="steps"/>
<input
type="text"
name="flat"
:placeholder="$t('flat')"
v-model="flat"/>
<input
type="text"
name="buildingName"
:placeholder="$t('buildingName')"
v-model="buildingName"/>
<input
type="text"
name="extra"
:placeholder="$t('extra')"
v-model="extra"/>
<input
type="text"
name="distribution"
:placeholder="$t('distribution')"
v-model="distribution"/>
</div>
</template>
<script>
export default {
name: "AddressMore",
props: ['address'],
computed: {
floor: {
set(value) {
console.log('value', value);
this.address.floor = value;
},
get() {
return this.address.floor;
}
},
corridor: {
set(value) {
console.log('value', value);
this.address.corridor = value;
},
get() {
return this.address.corridor;
}
},
steps: {
set(value) {
console.log('value', value);
this.address.steps = value;
},
get() {
return this.address.steps;
}
},
flat: {
set(value) {
console.log('value', value);
this.address.flat = value;
},
get() {
return this.address.flat;
}
},
buildingName: {
set(value) {
console.log('value', value);
this.address.buildingName = value;
},
get() {
return this.address.buildingName;
}
},
extra: {
set(value) {
console.log('value', value);
this.address.extra = value;
},
get() {
return this.address.extra;
}
},
distribution: {
set(value) {
console.log('value', value);
this.address.distribution = value;
},
get() {
return this.address.distribution;
}
}
}
}
</script>

View File

@@ -0,0 +1,56 @@
<template>
<div class="container">
<VueMultiselect
v-model="value"
@select="selectAddress"
name="field"
track-by="id"
label="value"
:custom-label="transName"
:taggable="true"
:multiple="false"
@tag="addAddress"
:placeholder="$t('select_address')"
:tagPlaceholder="$t('create_address')"
:options="addresses">
</VueMultiselect>
</div>
</template>
<script>
import VueMultiselect from 'vue-multiselect';
export default {
name: 'AddressSelection',
components: { VueMultiselect },
props: ['address', 'updateMapCenter'],
data() {
return {
value: null
}
},
computed: {
addresses() {
return this.address.loaded.addresses;
}
},
methods: {
transName(value) {
return value.streetNumber === undefined ? value.street : `${value.street}, ${value.streetNumber}`
},
selectAddress(value) {
this.address.selected.address = value;
this.updateMapCenter(value.point);
},
addAddress (newAddress) {
const address = {
street: newAddress
};
this.value = address;
this.address.selected.address = address;
}
}
};
</script>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>

View File

@@ -0,0 +1,45 @@
<template>
<div class="container">
<VueMultiselect
v-model="value"
@select="selectCity"
name="field"
track-by="id"
label="value"
:custom-label="transName"
:placeholder="$t('select_city')"
:options="cities">
</VueMultiselect>
</div>
</template>
<script>
import VueMultiselect from 'vue-multiselect';
export default {
name: 'CitySelection',
components: { VueMultiselect },
props: ['address', 'getReferenceAddresses'],
data() {
return {
value: null
}
},
methods: {
transName(value) {
return `${value.code}-${value.name}`
},
selectCity(value) {
this.address.selected.city = value;
this.getReferenceAddresses(value);
},
},
computed: {
cities() {
return this.address.loaded.cities;
}
}
};
</script>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>

View File

@@ -0,0 +1,59 @@
<template>
<div class="container">
<VueMultiselect
v-model="value"
name="field"
track-by="id"
label="name"
:custom-label="transName"
:placeholder="$t('select_country')"
:options="countries"
@select="selectCountry">
</VueMultiselect>
</div>
</template>
<script>
import VueMultiselect from 'vue-multiselect';
export default {
name: 'CountrySelection',
components: { VueMultiselect },
props: ['address', 'getCities'],
data() {
return {
value: this.address.loaded.countries.filter(c => c.countryCode === 'FR')[0]
}
},
methods: {
init() {
if (this.value !== undefined) {
this.getCities(this.value);
}
},
transName ({ name }) {
return name.fr //TODO multilang
},
selectCountry(value) {
console.log(value);
this.address.selected.country = value;
this.getCities(value);
},
},
mounted(){
this.init()
},
computed: {
countries() {
const countries = this.address.loaded.countries;
let orderedCountries = [];
orderedCountries.push(...countries.filter(c => c.countryCode === 'FR'))
orderedCountries.push(...countries.filter(c => c.countryCode === 'BE'))
orderedCountries.push(...countries.filter(c => c.countryCode !== 'FR').filter(c => c.countryCode !== 'BE'))
return orderedCountries;
}
}
};
</script>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>

View File

@@ -0,0 +1,80 @@
<template>
<transition name="modal">
<div class="modal-mask">
<!-- :: styles bootstrap :: -->
<div class="modal-dialog" :class="modalDialogClass">
<div class="modal-content">
<div class="modal-header">
<slot name="header"></slot>
<button class="close sc-button grey" @click="$emit('close')">
<i class="fa fa-times" aria-hidden="true"></i></button>
</div>
<div class="body-head">
<slot name="body-head"></slot>
</div>
<div class="modal-body">
<slot name="body"></slot>
</div>
<div class="modal-footer">
<button class="sc-button cancel" @click="$emit('close')">{{ $t('action.close') }}</button>
<slot name="footer"></slot>
</div>
</div>
</div>
<!-- :: end styles bootstrap :: -->
</div>
</transition>
</template>
<script>
/*
* This Modal component is a mix between Vue3 modal implementation
* [+] with 'v-if:showModal' directive:parameter, html scope is added/removed not just shown/hidden
* [+] with slot we can pass content from parent component
* [+] some classes are passed from parent component
* and Bootstrap 4.6 _modal.scss module
* [+] using bootstrap css classes, the modal have a responsive behaviour,
* [+] modal design can be configured using css classes (size, scroll)
*/
export default {
name: 'Modal',
props: ['modalDialogClass'],
emits: ['close']
}
</script>
<style lang="scss">
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.75);
display: table;
transition: opacity 0.3s ease;
}
.modal-header .close { // bootstrap classes, override sc-button 0 radius
border-top-right-radius: 0.3rem;
}
/*
* The following styles are auto-applied to elements with
* transition="modal" when their visibility is toggled
* by Vue.js.
*
* You can easily play with the modal transition by editing
* these styles.
*/
.modal-enter {
opacity: 0;
}
.modal-leave-active {
opacity: 0;
}
.modal-enter .modal-container,
.modal-leave-active .modal-container {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
</style>

View File

@@ -0,0 +1,153 @@
<template>
<a class="sc-button" target="_blank"
:class="classAction"
:title="$t(titleAction)"
@click="openModal">
{{ buttonText }}
</a>
<teleport to="body">
<modal v-if="modal.showModal"
:modalDialogClass="modal.modalDialogClass"
@close="modal.showModal = false">
<template v-slot:header>
<h3 class="modal-title">{{ $t(titleModal) }}</h3>
</template>
<template v-slot:body v-if="type === 'person'">
<on-the-fly-person
v-bind:id="id"
v-bind:type="type"
v-bind:action="action"
ref="castPerson">
</on-the-fly-person>
</template>
<template v-slot:body v-else-if="type === 'thirdparty'">
<on-the-fly-thirdparty
v-bind:id="id"
v-bind:type="type"
v-bind:action="action"
ref="castThirdparty">
</on-the-fly-thirdparty>
</template>
<template v-slot:body v-else>
<on-the-fly-create
v-bind:action="action"
ref="castNew">
</on-the-fly-create>
</template>
<template v-slot:footer>
<button v-if="action === 'show'"
@click="changeActionTo('edit')"
class="sc-button bt-update"> <!-- @click.prevent="$emit('..', ..)" -->
</button>
<button v-else
class="sc-button bt-save"
@click="saveAction"
> <!--
-->
{{ $t('action.save')}}
</button>
</template>
</modal>
</teleport>
</template>
<script>
import Modal from 'ChillMainAssets/vuejs/_components/Modal.vue';
import OnTheFlyPerson from 'ChillPersonAssets/vuejs/_components/OnTheFly/Person.vue';
import OnTheFlyThirdparty from './OnTheFly/ThirdParty.vue';
import OnTheFlyCreate from './OnTheFly/Create.vue';
export default {
name: 'OnTheFly',
components: {
Modal,
OnTheFlyPerson,
OnTheFlyThirdparty,
OnTheFlyCreate
},
props: ['type', 'id', 'action', 'buttonText'],
data() {
return {
modal: {
showModal: false,
modalDialogClass: "modal-dialog-scrollable modal-xl"
},
action: this.action
}
},
computed: {
action() {
return this.$data.action;
},
classAction() {
switch (this.action) {
case 'show':
return 'bt-show';
case 'edit':
return 'bt-update';
case 'create':
return 'bt-create';
}
},
titleAction() {
switch (this.action) {
case 'show':
return 'action.show';
case 'edit':
return 'action.edit';
case 'create':
return 'action.create';
}
},
titleModal() {
switch (this.action) {
case 'show':
return 'onthefly.show.' + this.type;
case 'edit':
return 'onthefly.edit.' + this.type;
case 'create':
return 'onthefly.create.title';
}
}
},
methods: {
openModal() {
this.modal.showModal = true;
this.$nextTick(function() {
//this.$refs.search.focus();
})
},
changeActionTo(action) {
// [BUG] clic first on show item button; in modal clic edit button; close modal; clic again on show item button
this.$data.action = action;
},
saveAction() {
console.log('saveAction');
if (this.type === 'person') {
this.$refs.castPerson.postData();
} else if (this.type === 'thirdparty') {
this.$refs.castThirdparty.postData();
} else {
// saveAction() ==cast=to==> child.castByType() ==cast=to==> grand-child.postData()
this.$refs.castNew.castByType();
}
this.modal.showModal = false;
}
}
}
</script>
<style lang="css" scoped>
a {
cursor: pointer;
}
</style>

View File

@@ -0,0 +1,84 @@
<template>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link" :class="{ active: isActive('person') }">
<label for="person">
<input type="radio" name="person" v-model="radioType" value="person">
{{ $t('onthefly.create.person') }}
</label>
</a>
</li>
<li class="nav-item">
<a class="nav-link" :class="{ active: isActive('thirdparty') }">
<label for="thirdparty">
<input type="radio" name="thirdparty" v-model="radioType" value="thirdparty">
{{ $t('onthefly.create.thirdparty') }}
</label>
</a>
</li>
</ul>
<div class="my-4">
<on-the-fly-person
v-if="type === 'person'"
v-bind:action="action"
ref="castPerson">
</on-the-fly-person>
<on-the-fly-thirdparty
v-if="type === 'thirdparty'"
v-bind:action="action"
ref="castThirdparty">
</on-the-fly-thirdparty>
</div>
</template>
<script>
import OnTheFlyPerson from 'ChillPersonAssets/vuejs/_components/OnTheFly/Person.vue';
import OnTheFlyThirdparty from './ThirdParty.vue'; // TODO move in ChillThirdpartyAssets
export default {
name: "OnTheFlyCreate",
props: ['action'],
components: {
OnTheFlyPerson,
OnTheFlyThirdparty
},
data() {
return {
type: 'person' //by default
}
},
computed: {
radioType: {
set(type) {
this.type = type;
},
get() {
return this.type;
}
}
},
methods: {
isActive(tab) {
return (this.type === tab) ? true : false;
},
castByType() {
console.log('saveActionByType');
if (this.type === 'person') {
this.$refs.castPerson.postData();
} else if (this.type === 'thirdparty') {
this.$refs.castThirdparty.postData();
} else {
throw Error('Invalid type of entity');
}
}
}
}
</script>
<style lang="css" scoped>
label {
cursor: pointer;
}
</style>

View File

@@ -0,0 +1,23 @@
<template>
<div v-if="action === 'show'">
show
thirdparty
{{ id }}
</div>
<div v-else-if="action === 'edit' || action === 'create'">
{{ action }}
thirdparty
{{ id }}
</div>
</template>
<script>
export default {
name: "OnTheFlyThirdParty",
props: ['id', 'type', 'action']
}
// TODO move in ChillThirdpartyAssets
</script>
<style lang="css" scoped>
</style>

View File

@@ -0,0 +1,79 @@
import { createI18n } from 'vue-i18n'
const datetimeFormats = {
fr: {
short: {
year: "numeric",
month: "numeric",
day: "numeric"
},
text: {
year: "numeric",
month: "long",
day: "numeric",
},
long: {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
hour12: false
}
}
};
const messages = {
fr: {
action: {
actions: "Actions",
show: "Voir",
edit: "Modifier",
create: "Créer",
remove: "Enlever",
delete: "Supprimer",
save: "Enregistrer",
add: "Ajouter",
show_modal: "Ouvrir une modale",
ok: "OK",
cancel: "Annuler",
close: "Fermer",
back: "Retour",
check_all: "cocher tout",
reset: "réinitialiser"
},
nav: {
next: "Suivant",
previous: "Précédent",
top: "Haut",
bottom: "Bas",
},
onthefly: {
show: {
person: "Détails de l'usager",
thirdparty: "Détails du tiers"
},
edit: {
person: "Modifier un usager",
thirdparty: "Modifier un tiers"
},
create: {
button: "Créer \"{q}\"",
title: "Créer à la volée…",
person: "un nouvel usager",
thirdparty: "un nouveau tiers"
},
}
}
};
const _createI18n = (appMessages) => {
Object.assign(messages.fr, appMessages.fr);
return createI18n({
locale: 'fr',
fallbackLocale: 'fr',
datetimeFormats,
messages,
})
};
export { _createI18n }

View File

@@ -0,0 +1,16 @@
<div class="chill_address">
{% if options['has_no_address'] == true and address.isNoAddress == true %}
<div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div>
{% endif %}
<div class="chill_address_address {% if options['multiline'] %}chill_address_address--multiline{% endif %}">
{% if address.street is not empty %}<p class="street street1">{{ address.street }}</p>{% endif %}
{% if address.streetNumber is not empty %}<p class="street street2">{{ address.streetNumber }}</p>{% endif %}
{% if address.postCode is not empty %}
<p class="postalCode"><span class="code">{{ address.postCode.code }}</span> <span class="name">{{ address.postCode.name }}</span></p>
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>
{% endif %}
</div>
{%- if options['with_valid_from'] == true -%}
<span class="address_since">{{ 'Since %date%'|trans( { '%date%' : address.validFrom|format_date('long') } ) }}</span>
{%- endif -%}
</div>

View File

@@ -1,13 +1,14 @@
{%- macro _render(address, options) -%}
{%- set options = { 'with_valid_from' : true }|merge(options|default({})) -%}
{%- set options = { 'has_no_address' : false }|merge(options|default({})) -%}
{%- set options = { 'with_icon' : false }|merge(options|default({})) -%}
<div class="chill_address">
{% if options['has_no_address'] == true and address.isNoAddress == true %}
<div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div>
{% endif %}
<div class="chill_address_address">
{% if address.streetAddress1 is not empty %}<p class="street street1">{{ address.streetAddress1 }}</p>{% endif %}
{% if address.streetAddress2 is not empty %}<p class="street street2">{{ address.streetAddress2 }}</p>{% endif %}
<div class="chill_address_address">{% if options['with_icon'] == true %}<i class="fa fa-fw fa-map-marker"></i>{% endif %}
{% if address.street is not empty %}<p class="street street1">{{ address.street }}</p>{% endif %}
{% if address.streetNumber is not empty %}<p class="street street2">{{ address.streetNumber }}</p>{% endif %}
{% if address.postCode is not empty %}
<p class="postalCode"><span class="code">{{ address.postCode.code }}</span> <span class="name">{{ address.postCode.name }}</span></p>
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>

View File

@@ -1,4 +1,4 @@
<footer class="footer">
<p>{{ 'This program is free software: you can redistribute it and/or modify it under the terms of the <strong>GNU Affero General Public License</strong>'|trans|raw }}
<br/> <a href="https://{{ app.request.locale }}.wikibooks.org/wiki/Chill" target="_blank">{{ 'User manual'|trans }}</a></p>
</footer>
<br/> <a name="bottom" href="https://{{ app.request.locale }}.wikibooks.org/wiki/Chill" target="_blank">{{ 'User manual'|trans }}</a></p>
</footer>

View File

@@ -1 +1 @@
<img class="logo" src="{{ asset('build/images/logo-chill-sans-slogan_white.png') }}">
<img name="top" class="logo" src="{{ asset('build/images/logo-chill-sans-slogan_white.png') }}">

View File

@@ -0,0 +1,7 @@
<div class="timeline">
{% for result in results %}
<div class="timeline-item {% if loop.index0 is even %}even{% else %}odd{% endif %}">
{% include result.template with result.template_data %}
</div>
{% endfor %}
</div>

View File

@@ -1,7 +1,15 @@
<div class="timeline">
{% for result in results %}
<div class="timeline-item {% if loop.index0 is even %}even{% else %}odd{% endif %}">
{% include result.template with result.template_data %}
</div>
{% endfor %}
</div>
{% extends "@ChillMain/layout.html.twig" %}
{% block content %}
<div id="container content">
<div class="grid-8 centered">
<h1>{{ 'Global timeline'|trans }}</h1>
{{ timeline|raw }}
{% if nb_items > paginator.getItemsPerPage %}
{{ chill_pagination(paginator) }}
{% endif %}
</div>
</div>
{% endblock content %}

View File

@@ -68,6 +68,14 @@ class SectionMenuBuilder implements LocalMenuBuilderInterface
'icons' => ['home'],
'order' => 0
]);
$menu->addChild($this->translator->trans('Global timeline'), [
'route' => 'chill_center_timeline',
])
->setExtras([
'order' => 10
]
);
if ($this->authorizationChecker->isGranted(ChillExportVoter::EXPORT)) {
$menu->addChild($this->translator->trans('Export Menu'), [

View File

@@ -0,0 +1,36 @@
<?php
namespace Chill\MainBundle\Search\Model;
class Result
{
private float $relevance;
/**
* mixed an arbitrary result
*/
private $result;
/**
* @param float $relevance
* @param $result
*/
public function __construct(float $relevance, $result)
{
$this->relevance = $relevance;
$this->result = $result;
}
public function getRelevance(): float
{
return $this->relevance;
}
public function getResult()
{
return $this->result;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Chill\MainBundle\Search;
use Chill\PersonBundle\Entity\Person;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Doctrine\ORM\EntityManagerInterface;
use Chill\MainBundle\Search\SearchProvider;
use Symfony\Component\VarDumper\Resources\functions\dump;
/**
* ***Warning*** This is an incomplete implementation ***Warning***
*/
class SearchApi
{
private EntityManagerInterface $em;
private SearchProvider $search;
public function __construct(EntityManagerInterface $em, SearchProvider $search)
{
$this->em = $em;
$this->search = $search;
}
/**
* @return Model/Result[]
*/
public function getResults(string $query, int $offset, int $maxResult): array
{
// **warning again**: this is an incomplete implementation
$results = [];
foreach ($this->getPersons($query) as $p) {
$results[] = new Model\Result((float)\rand(0, 100) / 100, $p);
}
foreach ($this->getThirdParties($query) as $t) {
$results[] = new Model\Result((float)\rand(0, 100) / 100, $t);
}
\usort($results, function(Model\Result $a, Model\Result $b) {
return ($a->getRelevance() <=> $b->getRelevance()) * -1;
});
return $results;
}
public function countResults(string $query): int
{
return 0;
}
private function getThirdParties(string $query)
{
$thirdPartiesIds = $this->em->createQuery('SELECT t.id FROM '.ThirdParty::class.' t')
->getScalarResult();
$nbResults = rand(0, 15);
if ($nbResults === 1) {
$nbResults++;
} elseif ($nbResults === 0) {
return [];
}
$ids = \array_map(function ($e) use ($thirdPartiesIds) { return $thirdPartiesIds[$e]['id'];},
\array_rand($thirdPartiesIds, $nbResults));
$a = $this->em->getRepository(ThirdParty::class)
->findById($ids);
return $a;
}
private function getPersons(string $query)
{
$params = [
SearchInterface::SEARCH_PREVIEW_OPTION => false
];
$search = $this->search->getResultByName($query, 'person_regular', 0, 50, $params, 'json');
$ids = \array_map(function($r) { return $r['id']; }, $search['results']);
if (count($ids) === 0) {
return [];
}
return $this->em->getRepository(Person::class)
->findById($ids)
;
}
}

View File

@@ -204,7 +204,7 @@ class SearchProvider
}
public function getResultByName($pattern, $name, $start = 0, $limit = 50,
array $options = array(), $format)
array $options = array(), $format = 'html')
{
$terms = $this->parse($pattern);
$search = $this->getByName($name);

View File

@@ -110,8 +110,6 @@ class AuthorizationHelper
return false;
}
$role = ($attribute instanceof Role) ? $attribute : new Role($attribute);
foreach ($user->getGroupCenters() as $groupCenter){
//filter on center
if ($groupCenter->getCenter()->getId() === $entity->getCenter()->getId()) {
@@ -119,8 +117,7 @@ class AuthorizationHelper
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role allow to reach the required role
if ($this->isRoleReached($role,
new Role($roleScope->getRole()))){
if ($this->isRoleReached($attribute, $roleScope->getRole())) {
//if yes, we have a right on something...
// perform check on scope if necessary
if ($entity instanceof HasScopeInterface) {
@@ -149,12 +146,15 @@ class AuthorizationHelper
* and optionnaly Scope
*
* @param User $user
* @param Role $role
* @param string|Role $role
* @param null|Scope $scope
* @return Center[]
*/
public function getReachableCenters(User $user, Role $role, Scope $scope = null)
public function getReachableCenters(User $user, $role, Scope $scope = null)
{
if ($role instanceof Role) {
$role = $role->getRole();
}
$centers = array();
foreach ($user->getGroupCenters() as $groupCenter){
@@ -162,8 +162,7 @@ class AuthorizationHelper
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role,
new Role($roleScope->getRole()))) {
if ($this->isRoleReached($role, $roleScope->getRole())) {
if ($scope === null) {
$centers[] = $groupCenter->getCenter();
break 1;
@@ -180,6 +179,30 @@ class AuthorizationHelper
return $centers;
}
/**
* Filter an array of centers, return only center which are reachable
*
* @param User $user The user
* @param array $centers a list of centers which are going to be filtered
* @param string|Center $role
*/
public function filterReachableCenters(User $user, array $centers, $role): array
{
$results = [];
if ($role instanceof Role) {
$role = $role->getRole();
}
foreach ($centers as $center) {
if ($this->userCanReachCenter($user, $center, $role)) {
$results[] = $center;
}
}
return $results;
}
/**
* Return all reachable scope for a given user, center and role
@@ -191,8 +214,12 @@ class AuthorizationHelper
* @param Center $center
* @return Scope[]
*/
public function getReachableScopes(User $user, Role $role, Center $center)
public function getReachableScopes(User $user, $role, Center $center)
{
if ($role instanceof Role) {
$role = $role->getRole();
}
return $this->getReachableCircles($user, $role, $center);
}
@@ -200,12 +227,15 @@ class AuthorizationHelper
* Return all reachable circle for a given user, center and role
*
* @param User $user
* @param Role $role
* @param string|Role $role
* @param Center $center
* @return Scope[]
*/
public function getReachableCircles(User $user, Role $role, Center $center)
public function getReachableCircles(User $user, $role, Center $center)
{
if ($role instanceof Role) {
$role = $role->getRole();
}
$scopes = array();
foreach ($user->getGroupCenters() as $groupCenter){
@@ -215,9 +245,7 @@ class AuthorizationHelper
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role,
new Role($roleScope->getRole()))) {
if ($this->isRoleReached($role, $roleScope->getRole())) {
$scopes[] = $roleScope->getScope();
}
}
@@ -269,10 +297,10 @@ class AuthorizationHelper
* @param Role $parentRole The role which should give access to $childRole
* @return boolean true if the child role is granted by parent role
*/
protected function isRoleReached(Role $childRole, Role $parentRole)
protected function isRoleReached($childRole, $parentRole)
{
$reachableRoles = $this->roleHierarchy
->getReachableRoles([$parentRole]);
->getReachableRoleNames([$parentRole]);
return in_array($childRole, $reachableRoles);
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Chill\MainBundle\Serializer\Model;
use Chill\MainBundle\Pagination\PaginatorInterface;
class Collection
{
private PaginatorInterface $paginator;
private $items;
public function __construct($items, PaginatorInterface $paginator)
{
$this->items = $items;
$this->paginator = $paginator;
}
public function getPaginator(): PaginatorInterface
{
return $this->paginator;
}
public function getItems()
{
return $this->items;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Address;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class AddressNormalizer implements NormalizerAwareInterface, NormalizerInterface
{
use NormalizerAwareTrait;
public function normalize($address, string $format = null, array $context = [])
{
$data['address_id'] = $address->getId();
$data['text'] = $address->getStreet().', '.$address->getBuildingName();
$data['postcode']['name'] = $address->getPostCode()->getName();
return $data;
}
public function supportsNormalization($data, string $format = null)
{
return $data instanceof Address;
}
}

View File

@@ -0,0 +1,83 @@
<?php
/*
*
* Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Repository\CenterRepository;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
*
*
*/
class CenterNormalizer implements NormalizerInterface, DenormalizerInterface
{
private CenterRepository $repository;
public function __construct(CenterRepository $repository)
{
$this->repository = $repository;
}
public function normalize($center, string $format = null, array $context = array())
{
/** @var Center $center */
return [
'id' => $center->getId(),
'type' => 'center',
'name' => $center->getName()
];
}
public function supportsNormalization($data, string $format = null): bool
{
return $data instanceof Center;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
if (FALSE === \array_key_exists('type', $data)) {
throw new InvalidArgumentException('missing "type" key in data');
}
if ('center' !== $data['type']) {
throw new InvalidArgumentException('type should be equal to "center"');
}
if (FALSE === \array_key_exists('id', $data)) {
throw new InvalidArgumentException('missing "id" key in data');
}
$center = $this->repository->find($data['id']);
if (null === $center) {
throw new UnexpectedValueException("The type with id {$data['id']} does not exists");
}
return $center;
}
public function supportsDenormalization($data, string $type, string $format = null)
{
return $type === Center::class;
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Serializer\Model\Collection;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
public function supportsNormalization($data, string $format = null): bool
{
return $data instanceof Collection;
}
public function normalize($collection, string $format = null, array $context = [])
{
/** @var $collection Collection */
/** @var $collection Chill\MainBundle\Pagination\PaginatorInterface */
$paginator = $collection->getPaginator();
$data['count'] = $paginator->getTotalItems();
$pagination['first'] = $paginator->getCurrentPageFirstItemNumber();
$pagination['items_per_page'] = $paginator->getItemsPerPage();
$pagination['next'] = $paginator->hasNextPage() ?
$paginator->getNextPage()->generateUrl() : null;
$pagination['previous'] = $paginator->hasPreviousPage() ?
$paginator->getPreviousPage()->generateUrl() : null;
$pagination['more'] = $paginator->hasNextPage();
$data['pagination'] = $pagination;
// normalize results
$data['results'] = $this->normalizer->normalize($collection->getItems(),
$format, $context);
return $data;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/*
*
* Copyright (C) 2014-2021, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
class DateNormalizer implements NormalizerInterface, DenormalizerInterface
{
public function normalize($date, string $format = null, array $context = array())
{
/** @var \DateTimeInterface $date */
return [
'datetime' => $date->format(\DateTimeInterface::ISO8601)
];
}
public function supportsNormalization($data, string $format = null): bool
{
return $data instanceof \DateTimeInterface;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
switch ($type) {
case \DateTime::class:
return \DateTime::createFromFormat(\DateTimeInterface::ISO8601, $data['datetime']);
case \DateTimeInterface::class:
case \DateTimeImmutable::class:
default:
return \DateTimeImmutable::createFromFormat(\DateTimeInterface::ISO8601, $data['datetime']);
}
}
public function supportsDenormalization($data, string $type, string $format = null): bool
{
return $type === \DateTimeInterface::class ||
$type === \DateTime::class ||
$type === \DateTimeImmutable::class ||
(\is_array($data) && array_key_exists('datetime', $data));
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Chill\MainBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Exception\RuntimeException;
/**
* Denormalize an object given a list of supported class
*/
class DiscriminatedObjectDenormalizer implements ContextAwareDenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* The type to set for enabling this type
*/
public const TYPE = '@multi';
/**
* Should be present in context and contains an array of
* allowed types.
*/
public const ALLOWED_TYPES = 'denormalize_multi.allowed_types';
/**
* {@inheritDoc}
*/
public function denormalize($data, string $type, string $format = null, array $context = [])
{
foreach ($context[self::ALLOWED_TYPES] as $localType) {
if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) {
try {
return $this->denormalizer->denormalize($data, $localType, $format, $context); } catch (RuntimeException $e) {
$lastException = $e;
}
}
}
throw new RuntimeException(sprintf("Could not find any denormalizer for those ".
"ALLOWED_TYPES: %s", \implode(", ", $context[self::ALLOWED_TYPES])));
}
/**
* {@inheritDoc}
*/
public function supportsDenormalization($data, string $type, string $format = null, array $context = [])
{
if (self::TYPE !== $type) {
return false;
}
if (0 === count($context[self::ALLOWED_TYPES] ?? [])) {
throw new \LogicException("The context should contains a list of
allowed types");
}
foreach ($context[self::ALLOWED_TYPES] as $localType) {
if ($this->denormalizer->supportsDenormalization($data, $localType, $format)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Chill\MainBundle\Serializer\Normalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Doctrine\ORM\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface as SerializerMetadata;
class DoctrineExistingEntityNormalizer implements DenormalizerInterface
{
private EntityManagerInterface $em;
private ClassMetadataFactoryInterface $serializerMetadataFactory;
public function __construct(EntityManagerInterface $em, ClassMetadataFactoryInterface $serializerMetadataFactory)
{
$this->em = $em;
$this->serializerMetadataFactory = $serializerMetadataFactory;
}
public function denormalize($data, string $type, string $format = null, array $context = [])
{
if (\array_key_exists(AbstractNormalizer::OBJECT_TO_POPULATE, $context)) {
return $context[AbstractNormalizer::OBJECT_TO_POPULATE];
}
return $this->em->getRepository($type)
->find($data['id']);
}
public function supportsDenormalization($data, string $type, string $format = null)
{
if (FALSE === \is_array($data)) {
return false;
}
if (FALSE === \array_key_exists('id', $data)) {
return false;
}
if (FALSE === $this->em->getClassMetadata($type) instanceof ClassMetadata) {
return false;
}
// does have serializer metadata, and class discriminator ?
if ($this->serializerMetadataFactory->hasMetadataFor($type)) {
$classDiscriminator = $this->serializerMetadataFactory
->getMetadataFor($type)->getClassDiscriminatorMapping();
if ($classDiscriminator) {
$typeProperty = $classDiscriminator->getTypeProperty();
// check that only 2 keys
// that the second key is property
// and that the type match the class for given type property
return count($data) === 2
&& \array_key_exists($typeProperty, $data)
&& $type === $classDiscriminator->getClassForType($data[$typeProperty]);
}
}
// we do not have any class discriminator. Check that the id is the only one key
return count($data) === 1;
}
}

Some files were not shown because too many files have changed in this diff Show More