mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-09-14 10:44:58 +00:00
Compare commits
271 Commits
375-notifi
...
testing-20
Author | SHA1 | Date | |
---|---|---|---|
cf36070c82
|
|||
8ee836eec3
|
|||
388030952b
|
|||
82a08f1e27
|
|||
925fbaed6d
|
|||
c407c3029f
|
|||
81b6ae193c
|
|||
51168ac3c4
|
|||
12ee091d09
|
|||
49607e431f
|
|||
ea4cbfe3b9
|
|||
9d00b8ae60
|
|||
00350b9efc
|
|||
9a50dad671
|
|||
4206d17345
|
|||
110a2e894f
|
|||
a0daf4428f
|
|||
f78b8cad9c
|
|||
6b0c85cdf0
|
|||
92b71af239
|
|||
a0db7cd7e6 | |||
011b6a29e4 | |||
527dc971d7 | |||
43e5bc8337
|
|||
845e582c44
|
|||
f3e04bd2bf
|
|||
96e95dd8f1 | |||
c40e790425
|
|||
3a016aa12a
|
|||
be448c650e
|
|||
9f32b5ac48
|
|||
e89f5e4713
|
|||
e79d6d670b
|
|||
9adbde0308
|
|||
fe31cfd544
|
|||
e8bca6a502
|
|||
b0918ddd09 | |||
a368e68abb | |||
85b9784eef | |||
26fd16ab07 | |||
9a3fef862e | |||
2c01516f71 | |||
246546b313 | |||
bfe658d4fd | |||
7ea6638c3a | |||
b04f0a9aa4
|
|||
ebdfa04843
|
|||
be213d5b5c
|
|||
4d1032c115
|
|||
e43dfc9a20
|
|||
b11684fb3b
|
|||
b8826c6c0f
|
|||
a996b05ead
|
|||
cfcecf1cdc
|
|||
b6985e0e5f
|
|||
6d76b94644
|
|||
ff6ec45575
|
|||
f3fd18e6fb
|
|||
c8851a8e8a
|
|||
abdfe49c33
|
|||
e933f3e781
|
|||
fb1c34f9c1
|
|||
d506409d93
|
|||
9be8a533ff
|
|||
b414b27ba9
|
|||
8521672660
|
|||
3f5ce5f841
|
|||
e1404bf16d
|
|||
65b7ed0755
|
|||
a74118e5d4
|
|||
828739edf5
|
|||
d0811c8118
|
|||
176bff0551
|
|||
66c089e862
|
|||
aa44577484
|
|||
8c59cbc6a0
|
|||
8c5a7ac3e1
|
|||
a6e523ee0a
|
|||
d49058805a
|
|||
73496e0e1f
|
|||
973450110b
|
|||
0f6b10aa0a
|
|||
edeb8edbea
|
|||
fc8e3789e0
|
|||
52a80f9621
|
|||
5632697c05
|
|||
75932b0e29
|
|||
7e2bf91e09
|
|||
0581b59dbd
|
|||
4661ba9932
|
|||
f85b0c8cf7
|
|||
e701e96187
|
|||
d9d151aa89
|
|||
a14ed78e25
|
|||
420dd4f868
|
|||
3d9b9ea672
|
|||
9f12b42961
|
|||
2842548c17
|
|||
35f5501489
|
|||
5e2d960a19
|
|||
4129283a58
|
|||
f807d62dab
|
|||
5a7bba83f7
|
|||
50c75dff1a
|
|||
e37f3e7c37
|
|||
b6375cad6c
|
|||
8516c87a14
|
|||
8c5abbff74
|
|||
e0f94ae900
|
|||
f683e45b6e
|
|||
b1b7fb6401
|
|||
8fa06e143d
|
|||
ec3d901d2f
|
|||
f12d689382
|
|||
1c04219859
|
|||
2b88593e64
|
|||
ee65c46d2a
|
|||
7c239eaf6a
|
|||
694b1f3c1f
|
|||
80b9ce3c3e
|
|||
3f218e7183
|
|||
a2713041da
|
|||
3a904e8ea1
|
|||
6f1a26742d
|
|||
0d0a626f50
|
|||
ec5f4ed1d6
|
|||
d9251239f7
|
|||
b2d3d806b6
|
|||
8e952cc966
|
|||
1c4ee37507
|
|||
8331a836f2
|
|||
2482dcc62e
|
|||
f9a55a1bfd
|
|||
15aa565caf
|
|||
566b72ec9e
|
|||
bb42ee25ff
|
|||
aebeca1d7a
|
|||
1955249a60
|
|||
3b0a4e9c73
|
|||
b5fd9cf4af
|
|||
bb30ddc876
|
|||
5ebb53173e
|
|||
d1d6a00ebf
|
|||
e48bec490c
|
|||
128d365a72
|
|||
10f66afdcd
|
|||
89aed74355
|
|||
b3bf405c5b | |||
9124fa68e8
|
|||
68b61b7d8a
|
|||
80d8f967fa
|
|||
1375a41de2
|
|||
4fa4d3b65c | |||
bd4c34cc1d | |||
4cea678e93 | |||
5e6833975b | |||
f523b9adb3 | |||
a211549432 | |||
17b1363113 | |||
3356ed8e57 | |||
2a7fa517ee | |||
95972399a1 | |||
85781c8e14 | |||
00eb435896 | |||
ed71cffd6a | |||
ae679e6997 | |||
e1d308fd97 | |||
d9acda67e3 | |||
e88da74882 | |||
591c44d1a0 | |||
bf04b7981c | |||
df33eec30f | |||
c657c98918 | |||
ef5eb5b907 | |||
d683fe002d | |||
555bbca59b | |||
e9e9d5c458 | |||
b1842a33ae | |||
6afeaccf24 | |||
fb76bac480 | |||
6ded185289 | |||
95adc29f9d | |||
4d0c3e683f | |||
018aafc773 | |||
c4aea4efc2 | |||
225e3ca13f | |||
8c1fa7956a | |||
e253d1b276 | |||
a52aac2d98 | |||
9e8cf60dd8 | |||
7682d81d50 | |||
5d31ce96c1 | |||
81ef64a246 | |||
49d1f78001 | |||
0d0f3528e2 | |||
d97d5e689a | |||
95d80ce13e | |||
668720984d | |||
245c3fa121 | |||
1af3e4c7ec | |||
5d0fc7a189 | |||
483d50e776 | |||
b4c6ccf309 | |||
ac6a81cbd8 | |||
9503cb89b6 | |||
b130dbdcdc | |||
b2b1865837 | |||
ec5c4d51b3 | |||
180437f637
|
|||
0c2508d26d
|
|||
b2d8d21f04
|
|||
6a2aa77ecc
|
|||
e7cd9e00f9
|
|||
39f60b5b34
|
|||
c9c29b9105
|
|||
fb806a9579
|
|||
70ca4acafb
|
|||
bd61eedfbb
|
|||
80ce7f0bf1
|
|||
1ebf838bde
|
|||
85a9c6bb67
|
|||
db073fc920
|
|||
46ebfca28f
|
|||
22a2605381
|
|||
4f6a7116a4
|
|||
cac7d33a44
|
|||
0609e3f4c3
|
|||
3a738179f2
|
|||
a789bf5e1c
|
|||
0a21fada42
|
|||
4f030eb11a
|
|||
0d2a487ae7
|
|||
6cb23344fc
|
|||
da0d7a3b9e
|
|||
fcc61aa4c0
|
|||
21ec96b75c
|
|||
93f934152f
|
|||
49f4cce72a
|
|||
e69b679938
|
|||
229f9b7125
|
|||
4fc433cd63
|
|||
2c91d2e10f
|
|||
4302506471 | |||
09b7558e92 | |||
6ba5c91ee6 | |||
535409e529 | |||
9979378e78 | |||
58291c7402 | |||
3d397c0145 | |||
d84f3ee5ad | |||
6db16e6d0b | |||
ed60c6aaa3 | |||
13b1d20ade | |||
5999c73c98 | |||
580366de6d | |||
7f69f21b64 | |||
683a0bc4e9 | |||
4d6d40629f | |||
2185791665 | |||
bf14c92567 | |||
7c1c1ed800 | |||
3b3659f13f | |||
ebfdc57fcf | |||
a562690512 | |||
1751c65731
|
|||
791f5bb4be
|
|||
2c812fc5fe
|
|||
1f1d38acef
|
|||
057c34610d
|
|||
732b7dc8f7
|
|||
cb068cdee7
|
6
.changes/unreleased/DX-20250401-144728.yaml
Normal file
6
.changes/unreleased/DX-20250401-144728.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: DX
|
||||
body: Allow TranslatableMessage in flash messages
|
||||
time: 2025-04-01T14:47:28.814268801+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
44
.changes/unreleased/DX-20250407-121010.yaml
Normal file
44
.changes/unreleased/DX-20250407-121010.yaml
Normal file
@@ -0,0 +1,44 @@
|
||||
kind: DX
|
||||
body: |
|
||||
Rewrite exports to run them asynchronously
|
||||
|
||||
changelog: |
|
||||
- Add new methods to serialize data using the rector rule
|
||||
- Remove all references to the Request in filters, aggregators, filters. Actually, the most frequent occurence is `$security->getUser()`.
|
||||
- Refactor manually the initializeQuery method
|
||||
- Remove the injection of ExportManager into the constructor of each export element:
|
||||
|
||||
```diff
|
||||
|
||||
- class MyFormatter implements FormatterInterface
|
||||
+ class MyFormatter implements FormatterInterface, \Chill\MainBundle\Export\ExportManagerAwareInterface
|
||||
{
|
||||
+ use \Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
|
||||
- public function __construct(private ExportManager $exportmanager) {}
|
||||
|
||||
public function MyMethod(): void
|
||||
{
|
||||
- $this->exportManager->getFilter('alias');
|
||||
+ $this->getExportManager()->getFilter('alias');
|
||||
}
|
||||
}
|
||||
```
|
||||
- configure messenger to handle export in a queue:
|
||||
|
||||
```diff
|
||||
# config/packages/messenger.yaml
|
||||
framework:
|
||||
messenger:
|
||||
routing:
|
||||
+ 'Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage': priority
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
time: 2025-04-07T12:10:10.682561327+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: Add columns or tables
|
6
.changes/unreleased/DX-20250430-144550.yaml
Normal file
6
.changes/unreleased/DX-20250430-144550.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: DX
|
||||
body: Remove dead code for wopi-link module
|
||||
time: 2025-04-30T14:45:50.406111606+02:00
|
||||
custom:
|
||||
Issue: "352"
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/DX-20250528-165813.yaml
Normal file
6
.changes/unreleased/DX-20250528-165813.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: DX
|
||||
body: Replace library node-sass by sass, and upgrade bootstrap to version 5.3 (yarn upgrade / install is required)
|
||||
time: 2025-05-28T16:58:13.226870341+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Feature-20250211-142243.yaml
Normal file
6
.changes/unreleased/Feature-20250211-142243.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Feature
|
||||
body: Allow the merge of two accompanying period works
|
||||
time: 2025-02-11T14:22:43.134106669+01:00
|
||||
custom:
|
||||
Issue: "359"
|
||||
SchemaChange: No schema change
|
7
.changes/unreleased/Feature-20250424-142211.yaml
Normal file
7
.changes/unreleased/Feature-20250424-142211.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
kind: Feature
|
||||
body: Add the document file name to the document title when a user upload a document,
|
||||
unless there is already a document title.
|
||||
time: 2025-04-24T14:22:11.800975422+02:00
|
||||
custom:
|
||||
Issue: "377"
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Feature-20250520-095628.yaml
Normal file
6
.changes/unreleased/Feature-20250520-095628.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Feature
|
||||
body: Add desactivation date for social action and issue csv export
|
||||
time: 2025-05-20T09:56:28.108941934+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Feature-20250523-133341.yaml
Normal file
6
.changes/unreleased/Feature-20250523-133341.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Feature
|
||||
body: Add Emoji and Fullscreen feature to ckeditor configuration
|
||||
time: 2025-05-23T13:33:41.645095128+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Feature-20250523-133434.yaml
Normal file
6
.changes/unreleased/Feature-20250523-133434.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Feature
|
||||
body: Create editor which allow us to toggle between rich and simple text editor
|
||||
time: 2025-05-23T13:34:34.56795603+02:00
|
||||
custom:
|
||||
Issue: "321"
|
||||
SchemaChange: No schema change
|
@@ -1,6 +0,0 @@
|
||||
kind: Feature
|
||||
body: Show filters on list pages unfolded by default
|
||||
time: 2025-07-22T15:50:39.338057044+02:00
|
||||
custom:
|
||||
Issue: "399"
|
||||
SchemaChange: No schema change
|
7
.changes/unreleased/Fixed-20250424-133943.yaml
Normal file
7
.changes/unreleased/Fixed-20250424-133943.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
kind: Fixed
|
||||
body: trying to prevent bug of typeerror in doc-history + improved display of document
|
||||
history
|
||||
time: 2025-04-24T13:39:43.878468232+02:00
|
||||
custom:
|
||||
Issue: "376"
|
||||
SchemaChange: No schema change
|
7
.changes/unreleased/Fixed-20250424-163746.yaml
Normal file
7
.changes/unreleased/Fixed-20250424-163746.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
kind: Fixed
|
||||
body: Display previous participation in acc course work even if the person has left
|
||||
the acc course
|
||||
time: 2025-04-24T16:37:46.970203594+02:00
|
||||
custom:
|
||||
Issue: "381"
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Fixed-20250505-102715.yaml
Normal file
6
.changes/unreleased/Fixed-20250505-102715.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Fixed
|
||||
body: Fix display of text in calendar events
|
||||
time: 2025-05-05T10:27:15.461493066+02:00
|
||||
custom:
|
||||
Issue: "372"
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Fixed-20250514-145339.yaml
Normal file
6
.changes/unreleased/Fixed-20250514-145339.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Fixed
|
||||
body: Add missing translation for user_group.no_user_groups
|
||||
time: 2025-05-14T14:53:39.53927329+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Fixed-20250520-140008.yaml
Normal file
6
.changes/unreleased/Fixed-20250520-140008.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Fixed
|
||||
body: Fix retrieve schema to form full tablename and construct sql statements correctly in Thirdparty merger.
|
||||
time: 2025-05-20T14:00:08.987229634+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Fixed-20250520-140433.yaml
Normal file
6
.changes/unreleased/Fixed-20250520-140433.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Fixed
|
||||
body: Fix add missing translation
|
||||
time: 2025-05-20T14:04:33.612140549+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/Fixed-20250520-164429.yaml
Normal file
6
.changes/unreleased/Fixed-20250520-164429.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: Fixed
|
||||
body: Fix the transfer of evaluations and documents during of accompanyingperiodwork
|
||||
time: 2025-05-20T16:44:29.093304653+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
@@ -1,6 +0,0 @@
|
||||
kind: Fixed
|
||||
body: adjust display logic for accompanying period dates, include closing date if period is closed.
|
||||
time: 2025-08-06T13:46:09.241584292+02:00
|
||||
custom:
|
||||
Issue: "382"
|
||||
SchemaChange: No schema change
|
@@ -1,6 +0,0 @@
|
||||
kind: Fixed
|
||||
body: add min and step attributes to integer field in DateIntervalType
|
||||
time: 2025-08-06T17:35:27.413787704+02:00
|
||||
custom:
|
||||
Issue: "384"
|
||||
SchemaChange: No schema change
|
6
.changes/unreleased/UX-20250423-172624.yaml
Normal file
6
.changes/unreleased/UX-20250423-172624.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
kind: UX
|
||||
body: Remove default filter in_progress for the page 'my tasks'; Allows for new tasks to be displayed upon opening of the page
|
||||
time: 2025-04-23T17:26:24.45777387+02:00
|
||||
custom:
|
||||
Issue: "374"
|
||||
SchemaChange: No schema change
|
@@ -1,6 +0,0 @@
|
||||
kind: UX
|
||||
body: Limit display of participations in event list
|
||||
time: 2025-07-22T13:26:37.500656935+02:00
|
||||
custom:
|
||||
Issue: ""
|
||||
SchemaChange: No schema change
|
@@ -1,22 +0,0 @@
|
||||
## v3.12.0 - 2025-06-30
|
||||
### Feature
|
||||
* ([#377](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/377)) Add the document file name to the document title when a user upload a document, unless there is already a document title.
|
||||
* Add desactivation date for social action and issue csv export
|
||||
* Add Emoji and Fullscreen feature to ckeditor configuration
|
||||
* ([#321](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/321)) Create editor which allow us to toggle between rich and simple text editor
|
||||
* Do not remove workflow which are automatically canceled after staling for more than 30 days
|
||||
### Fixed
|
||||
* ([#376](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/376)) trying to prevent bug of typeerror in doc-history + improved display of document history
|
||||
* ([#381](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/381)) Display previous participation in acc course work even if the person has left the acc course
|
||||
* ([#372](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/372)) Fix display of text in calendar events
|
||||
* Add missing translation for user_group.no_user_groups
|
||||
* Fix admin entity edit actions for event admin entities and activity reason (category) entities
|
||||
* ([#392](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/392)) Allow null and cast as string to setContent method for NewsItem
|
||||
|
||||
* ([#393](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/393)) Doc Generation: the "dump only" method send the document as an email attachment.
|
||||
### DX
|
||||
* ([#352](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/352)) Remove dead code for wopi-link module
|
||||
* Replace library node-sass by sass, and upgrade bootstrap to version 5.3 (yarn upgrade / install is required)
|
||||
### UX
|
||||
* ([#374](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/374)) Remove default filter in_progress for the page 'my tasks'; Allows for new tasks to be displayed upon opening of the page
|
||||
* Improve labeling of fields in person resource creation form
|
@@ -1,3 +0,0 @@
|
||||
## v3.12.1 - 2025-06-30
|
||||
### Fixed
|
||||
* Fix loading of the list of documents
|
@@ -1,74 +0,0 @@
|
||||
## v4.0.0 - 2025-07-08
|
||||
### Feature
|
||||
* ([#359](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/359)) Allow the merge of two accompanying period works
|
||||
### Fixed
|
||||
* ([#390](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/390)) Display the list of participant in the results, even if there is only one participant and that the search result display the requestor
|
||||
* Fix admin entity edit actions for event admin entities and activity reason (category) entities
|
||||
* Fix translations for social action fields in admin form: results, goals, evaluations
|
||||
### DX
|
||||
* Rewrite exports to run them asynchronously
|
||||
|
||||
**Schema Change**: Add columns or tables
|
||||
* Allow TranslatableMessage in flash messages
|
||||
### UX
|
||||
* Improve labeling of fields in person resource creation form
|
||||
|
||||
|
||||
**Release notes**
|
||||
|
||||
- Add new methods to serialize data using the rector rule
|
||||
- Remove all references to the Request in filters, aggregators, filters. Actually, the most frequent occurence is `$security->getUser()`.
|
||||
- Refactor manually the initializeQuery method
|
||||
- Remove the injection of ExportManager into the constructor of each export element:
|
||||
|
||||
```diff
|
||||
|
||||
- class MyFormatter implements FormatterInterface
|
||||
+ class MyFormatter implements FormatterInterface, \Chill\MainBundle\Export\ExportManagerAwareInterface
|
||||
{
|
||||
+ use \Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
|
||||
- public function __construct(private ExportManager $exportmanager) {}
|
||||
|
||||
public function MyMethod(): void
|
||||
{
|
||||
- $this->exportManager->getFilter('alias');
|
||||
+ $this->getExportManager()->getFilter('alias');
|
||||
}
|
||||
}
|
||||
```
|
||||
- configure messenger to handle export in a queue:
|
||||
|
||||
```diff
|
||||
# config/packages/messenger.yaml
|
||||
framework:
|
||||
messenger:
|
||||
routing:
|
||||
+ 'Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage': priority
|
||||
```
|
||||
|
||||
- add missing methods to exports, aggregators, filters, formatter:
|
||||
|
||||
```php
|
||||
public function normalizeFormData(array $formData): array;
|
||||
|
||||
public function denormalizeFormData(array $formData, int $fromVersion): array;
|
||||
```
|
||||
|
||||
There are rector rules to generate those methods:
|
||||
|
||||
- `Chill\Utils\Rector\Rector\ChillBundleAddNormalizationMethodsOnExportRector`
|
||||
|
||||
See:
|
||||
|
||||
```php
|
||||
// upgrade chill exports
|
||||
$rectorConfig->rules([\Chill\Utils\Rector\Rector\ChillBundleAddNormalizationMethodsOnExportRector::class]);
|
||||
```
|
||||
|
||||
This rule will create most of the work necessary, but some manuals changes are still necessary:
|
||||
|
||||
- we must set manually the correct repository for method `denormalizeDoctrineEntity`;
|
||||
- when the form data contains some entities, and the form type is not one of EntityType::class, PickUserDynamicType::class, PickUserLocationType::class, PickThirdpartyDynamicType::class, Select2CountryType::class, then we must handle the normalization manually (using the `\Chill\MainBundle\Export\ExportDataNormalizerTrait`)
|
||||
|
||||
|
@@ -1,4 +0,0 @@
|
||||
## v4.0.1 - 2025-07-08
|
||||
### Fixed
|
||||
* Fix package.json for compilation
|
||||
|
@@ -1,4 +0,0 @@
|
||||
## v4.0.2 - 2025-07-09
|
||||
### Fixed
|
||||
* Fix add missing translation
|
||||
* Fix the transfer of evaluations and documents during of accompanyingperiodwork
|
@@ -22,7 +22,7 @@ Chill is a comprehensive web application built as a set of Symfony bundles. It i
|
||||
- **Backend**: PHP 8.3+, Symfony 5.4
|
||||
- **Frontend**: JavaScript/TypeScript, Vue.js 3, Bootstrap 5
|
||||
- **Build Tools**: Webpack Encore, Yarn
|
||||
- **Database**: PostgreSQL with materialized views. We do not support other databases.
|
||||
- **Database**: PostgreSQL with materialized views
|
||||
- **Other Services**: Redis, AMQP (RabbitMQ), SMTP
|
||||
|
||||
## Project Structure
|
||||
@@ -149,93 +149,14 @@ Key configuration files:
|
||||
- `package.json`: JavaScript dependencies and scripts
|
||||
- `.env`: Default environment variables. Must usually not be updated: use `.env.local` instead.
|
||||
|
||||
### Database migrations
|
||||
|
||||
Each time a doctrine entity is created, we generate migration to adapt the database.
|
||||
|
||||
The migration are created using the command `symfony console doctrine:migrations:diff --no-interaction --namespace <namespace>`, where the namespace is the relevant namespace for migration. As this is a bash script, do not forget to quote the `\` (`\` must become `\\` in your command).
|
||||
|
||||
Each bundle has his own namespace for migration (always ask me to confirm that command, with a list of updated / created entities so that I can confirm you that it is ok):
|
||||
|
||||
- `Chill\Bundle\ActivityBundle` writes migrations to `Chill\Migrations\Activity`;
|
||||
- `Chill\Bundle\BudgetBundle` writes migrations to `Chill\Migrations\Budget`;
|
||||
- `Chill\Bundle\CustomFieldsBundle` writes migrations to `Chill\Migrations\CustomFields`;
|
||||
- `Chill\Bundle\DocGeneratorBundle` writes migrations to `Chill\Migrations\DocGenerator`;
|
||||
- `Chill\Bundle\DocStoreBundle` writes migrations to `Chill\Migrations\DocStore`;
|
||||
- `Chill\Bundle\EventBundle` writes migrations to `Chill\Migrations\Event`;
|
||||
- `Chill\Bundle\CalendarBundle` writes migrations to `Chill\Migrations\Calendar`;
|
||||
- `Chill\Bundle\FamilyMembersBundle` writes migrations to `Chill\Migrations\FamilyMembers`;
|
||||
- `Chill\Bundle\FranceTravailApiBundle` writes migrations to `Chill\Migrations\FranceTravailApi`;
|
||||
- `Chill\Bundle\JobBundle` writes migrations to `Chill\Migrations\Job`;
|
||||
- `Chill\Bundle\MainBundle` writes migrations to `Chill\Migrations\Main`;
|
||||
- `Chill\Bundle\PersonBundle` writes migrations to `Chill\Migrations\Person`;
|
||||
- `Chill\Bundle\ReportBundle` writes migrations to `Chill\Migrations\Report`;
|
||||
- `Chill\Bundle\TaskBundle` writes migrations to `Chill\Migrations\Task`;
|
||||
- `Chill\Bundle\ThirdPartyBundle` writes migrations to `Chill\Migrations\ThirdParty`;
|
||||
- `Chill\Bundle\TicketBundle` writes migrations to `Chill\Migrations\Ticket`;
|
||||
- `Chill\Bundle\WopiBundle` writes migrations to `Chill\Migrations\Wopi`;
|
||||
|
||||
Once created the, comment's classes should be removed and a description of the changes made to the entities should be added to the migrations, using the `getDescription` method. The migration should not be cleaned by any artificial intelligence, as modifying this migration is error prone.
|
||||
|
||||
### Guidelines related to code structure and requirements
|
||||
|
||||
#### Usage of clock
|
||||
|
||||
When we need to use a DateTime or DateTimeImmutable that need to express "now", we prefer the usage of
|
||||
`Symfony\Component\Clock\ClockInterface`, where possible. This is usually not possible in doctrine entities,
|
||||
where injection does not work when restoring an entity from database, but usually possible in services.
|
||||
|
||||
In test, we use `\Symfony\Component\Clock\MockClock` which is an implementation of `Symfony\Component\Clock\ClockInterface`
|
||||
where we have full and easy control of the date.
|
||||
|
||||
### Testing Information
|
||||
|
||||
The project uses PHPUnit for testing. Each bundle has its own test suite, and there's also a global test suite at the root level.
|
||||
|
||||
#### Use of mock in tests
|
||||
|
||||
##### General mocking
|
||||
|
||||
For creating mock, we prefer using prophecy (library phpspec/prophecy).
|
||||
|
||||
##### Useful helpers and tips that avoid create a mock
|
||||
|
||||
Some notable implementations that are tests helper, and avoid to create a mock:
|
||||
|
||||
- `\Psr\Log\NullLogger`, an implementation of `\Psr\Log\LoggerInterface`;
|
||||
- `\Symfony\Component\Clock\MockClock`, an implementation of `Symfony\Component\Clock\ClockInterface` (already mentioned above);
|
||||
- `\Symfony\Component\HttpClient\MockHttpClient`, an implementation of `\Symfony\Contracts\HttpClient\HttpClientInterface`;
|
||||
- When using `\Symfony\Component\Mailer\MailerInterface`, we can create the mock with "InMemoryTransport":
|
||||
|
||||
```php
|
||||
use Symfony\Component\Mailer\Transport\InMemoryTransport;
|
||||
use \Symfony\Component\Mailer\Mailer;
|
||||
|
||||
$transport = new InMemoryTransport();
|
||||
$mailer = new Mailer($transport);
|
||||
|
||||
// After sending:
|
||||
$messages = $transport->getSent(); // array of SentMessage
|
||||
```
|
||||
- When using `\Symfony\Contracts\EventDispatcher\EventDispatcherInterface`, we can use directly an instance of `\Symfony\Component\EventDispatcher\EventDispatcher`;
|
||||
|
||||
##### When we prefer not creating a mock
|
||||
|
||||
- When we use Doctrine Entities related to the project, we prefer not to use a mock: we instantiate them directly (unless it requires too much code to write);
|
||||
|
||||
##### Mocking final and readonly classes
|
||||
|
||||
Classes marked as final can't be mocked. To avoid that, either:
|
||||
|
||||
- we remove the `final` keyword from the class;
|
||||
- we extract an interface from the final class.
|
||||
|
||||
This must be a decision made by a human, not by an AI. Every AI task must abort with an explicit message in that case.
|
||||
|
||||
#### Running Tests
|
||||
|
||||
The tests are run from the project's root (not from the bundle's root).
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
vendor/bin/phpunit
|
||||
@@ -297,7 +218,7 @@ class TicketTest extends TestCase
|
||||
|
||||
#### Test Database
|
||||
|
||||
For tests that require a database, the project uses postgresql database filled by fixtures (usage of doctrine-fixtures). You can configure a different database for testing in the `.env.test` file.
|
||||
For tests that require a database, the project uses an in-memory SQLite database by default. You can configure a different database for testing in the `.env.test` file.
|
||||
|
||||
### Code Quality Tools
|
||||
|
||||
|
132
CHANGELOG.md
132
CHANGELOG.md
@@ -6,138 +6,6 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
|
||||
and is generated by [Changie](https://github.com/miniscruff/changie).
|
||||
|
||||
|
||||
## v4.0.2 - 2025-07-09
|
||||
### Fixed
|
||||
* Fix add missing translation
|
||||
* Fix the transfer of evaluations and documents during of accompanyingperiodwork
|
||||
|
||||
## v4.0.1 - 2025-07-08
|
||||
### Fixed
|
||||
* Fix package.json for compilation
|
||||
|
||||
|
||||
## v4.0.0 - 2025-07-08
|
||||
### Feature
|
||||
* ([#359](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/359)) Allow the merge of two accompanying period works
|
||||
### Fixed
|
||||
* ([#390](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/390)) Display the list of participant in the results, even if there is only one participant and that the search result display the requestor
|
||||
* Fix admin entity edit actions for event admin entities and activity reason (category) entities
|
||||
* Fix translations for social action fields in admin form: results, goals, evaluations
|
||||
### DX
|
||||
* Rewrite exports to run them asynchronously
|
||||
|
||||
**Schema Change**: Add columns or tables
|
||||
* Allow TranslatableMessage in flash messages
|
||||
### UX
|
||||
* Improve labeling of fields in person resource creation form
|
||||
|
||||
|
||||
**Release notes**
|
||||
|
||||
- Add new methods to serialize data using the rector rule
|
||||
- Remove all references to the Request in filters, aggregators, filters. Actually, the most frequent occurence is `$security->getUser()`.
|
||||
- Refactor manually the initializeQuery method
|
||||
- Remove the injection of ExportManager into the constructor of each export element:
|
||||
|
||||
```diff
|
||||
|
||||
- class MyFormatter implements FormatterInterface
|
||||
+ class MyFormatter implements FormatterInterface, \Chill\MainBundle\Export\ExportManagerAwareInterface
|
||||
{
|
||||
+ use \Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
|
||||
- public function __construct(private ExportManager $exportmanager) {}
|
||||
|
||||
public function MyMethod(): void
|
||||
{
|
||||
- $this->exportManager->getFilter('alias');
|
||||
+ $this->getExportManager()->getFilter('alias');
|
||||
}
|
||||
}
|
||||
```
|
||||
- configure messenger to handle export in a queue:
|
||||
|
||||
```diff
|
||||
# config/packages/messenger.yaml
|
||||
framework:
|
||||
messenger:
|
||||
routing:
|
||||
+ 'Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage': priority
|
||||
```
|
||||
|
||||
- add missing methods to exports, aggregators, filters, formatter:
|
||||
|
||||
```php
|
||||
public function normalizeFormData(array $formData): array;
|
||||
|
||||
public function denormalizeFormData(array $formData, int $fromVersion): array;
|
||||
```
|
||||
|
||||
There are rector rules to generate those methods:
|
||||
|
||||
- `Chill\Utils\Rector\Rector\ChillBundleAddNormalizationMethodsOnExportRector`
|
||||
|
||||
See:
|
||||
|
||||
```php
|
||||
// upgrade chill exports
|
||||
$rectorConfig->rules([\Chill\Utils\Rector\Rector\ChillBundleAddNormalizationMethodsOnExportRector::class]);
|
||||
```
|
||||
|
||||
This rule will create most of the work necessary, but some manuals changes are still necessary:
|
||||
|
||||
- we must set manually the correct repository for method `denormalizeDoctrineEntity`;
|
||||
- when the form data contains some entities, and the form type is not one of EntityType::class, PickUserDynamicType::class, PickUserLocationType::class, PickThirdpartyDynamicType::class, Select2CountryType::class, then we must handle the normalization manually (using the `\Chill\MainBundle\Export\ExportDataNormalizerTrait`)
|
||||
|
||||
|
||||
|
||||
## v3.12.1 - 2025-06-30
|
||||
### Fixed
|
||||
* Fix loading of the list of documents
|
||||
|
||||
## v3.12.0 - 2025-06-30
|
||||
### Feature
|
||||
* ([#377](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/377)) Add the document file name to the document title when a user upload a document, unless there is already a document title.
|
||||
* Add desactivation date for social action and issue csv export
|
||||
* Add Emoji and Fullscreen feature to ckeditor configuration
|
||||
* ([#321](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/321)) Create editor which allow us to toggle between rich and simple text editor
|
||||
* Do not remove workflow which are automatically canceled after staling for more than 30 days
|
||||
### Fixed
|
||||
* ([#376](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/376)) trying to prevent bug of typeerror in doc-history + improved display of document history
|
||||
* ([#381](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/381)) Display previous participation in acc course work even if the person has left the acc course
|
||||
* ([#372](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/372)) Fix display of text in calendar events
|
||||
* Add missing translation for user_group.no_user_groups
|
||||
* Fix admin entity edit actions for event admin entities and activity reason (category) entities
|
||||
* ([#392](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/392)) Allow null and cast as string to setContent method for NewsItem
|
||||
|
||||
* ([#393](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/393)) Doc Generation: the "dump only" method send the document as an email attachment.
|
||||
### DX
|
||||
* ([#352](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/352)) Remove dead code for wopi-link module
|
||||
* Replace library node-sass by sass, and upgrade bootstrap to version 5.3 (yarn upgrade / install is required)
|
||||
### UX
|
||||
* ([#374](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/374)) Remove default filter in_progress for the page 'my tasks'; Allows for new tasks to be displayed upon opening of the page
|
||||
* Improve labeling of fields in person resource creation form
|
||||
|
||||
## v3.11.0 - 2025-04-17
|
||||
### Feature
|
||||
* ([#365](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/365)) Add counters of actions and activities, with 2 boxes to (1) show the number of active actions on total actions and (2) show the number of activities in a accompanying period, and pills in menus for showing the number of active actions and the number of activities.
|
||||
* ([#364](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/364)) Added a second phone number "telephone2" to the thirdParty entity. Adapted twig templates and vuejs apps to handle this phone number
|
||||
|
||||
**Schema Change**: Add columns or tables
|
||||
* Signature: add a button to go directly to the signature zone, even if there is only one
|
||||
### Fixed
|
||||
* Fixed wrong translations in the on-the-fly for creation of thirdParty
|
||||
* Fixed update of phone number in on-the-fly edition of thirdParty
|
||||
* Fixed closing of modal when editing thirdParty in accompanying course works
|
||||
* Shorten the delay between two execution of AccompanyingPeriodStepChangeCronjob, to ensure at least one execution in a day
|
||||
* ([#102](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/102)) Fix display of title in document list
|
||||
* When cleaning the old stored object versions, do not throw an error if the stored object is not found on disk
|
||||
* Add consistent log prefix and key to logs when stale workflows are automatically canceled
|
||||
* ([#380](https://gitlab.com/Chill-Projet/chill-bundles/-/issues/380)) Remove the "not null" validation constraint on recently added properties on HouseholdComposition
|
||||
|
||||
### DX
|
||||
* Add new chill-col style for displaying title and aside in a flex table
|
||||
|
||||
## v3.10.3 - 2025-03-18
|
||||
### DX
|
||||
* Eslint fixes
|
||||
|
@@ -62,10 +62,8 @@ framework:
|
||||
'Chill\MainBundle\Workflow\Messenger\PostSignatureStateChangeMessage': priority
|
||||
'Chill\MainBundle\Workflow\Messenger\PostPublicViewMessage': async
|
||||
'Chill\MainBundle\Service\Workflow\CancelStaleWorkflowMessage': async
|
||||
'Chill\MainBundle\Notification\Email\NotificationEmailMessages\SendImmediateNotificationEmailMessage': async
|
||||
'Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage': priority
|
||||
'Chill\MainBundle\Export\Messenger\RemoveExportGenerationMessage': async
|
||||
'Chill\MainBundle\Notification\Email\NotificationEmailMessages\ScheduleDailyNotificationDigestMessage': async
|
||||
# end of routes added by chill-bundles recipes
|
||||
# Route your messages to the transports
|
||||
# 'App\Message\YourMessage': async
|
||||
|
@@ -2154,6 +2154,11 @@ parameters:
|
||||
count: 1
|
||||
path: src/Bundle/ChillMainBundle/Export/Formatter/SpreadSheetFormatter.php
|
||||
|
||||
-
|
||||
message: "#^Instanceof between string and DateTimeInterface will always evaluate to false\\.$#"
|
||||
count: 1
|
||||
path: src/Bundle/ChillMainBundle/Export/Formatter/SpreadsheetListFormatter.php
|
||||
|
||||
-
|
||||
message: "#^PHPDoc tag @var for property Chill\\\\MainBundle\\\\Export\\\\Helper\\\\ExportAddressHelper\\:\\:\\$unitNamesKeysCache contains unresolvable type\\.$#"
|
||||
count: 1
|
||||
|
@@ -37,6 +37,9 @@ return static function (RectorConfig $rectorConfig): void {
|
||||
$rectorConfig->rule(Rector\TypeDeclaration\Rector\Class_\MergeDateTimePropertyTypeDeclarationRector::class);
|
||||
$rectorConfig->rule(Rector\TypeDeclaration\Rector\ClassMethod\AddReturnTypeDeclarationBasedOnParentClassMethodRector::class);
|
||||
|
||||
// upgrade chill exports
|
||||
$rectorConfig->rules([\Chill\Utils\Rector\Rector\ChillBundleAddNormalizationMethodsOnExportRector::class]);
|
||||
|
||||
// part of the symfony 54 rules
|
||||
$rectorConfig->rule(\Rector\Symfony\Symfony53\Rector\StaticPropertyFetch\KernelTestCaseContainerPropertyDeprecationRector::class);
|
||||
$rectorConfig->rule(\Rector\Symfony\Symfony60\Rector\MethodCall\GetHelperControllerToServiceRector::class);
|
||||
|
@@ -48,6 +48,28 @@ class ActivityReasonCategoryController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a form to edit an existing ActivityReasonCategory entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreasoncategory/{id}/edit', name: 'chill_activity_activityreasoncategory_edit')]
|
||||
public function editAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(ActivityReasonCategory::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find ActivityReasonCategory entity.');
|
||||
}
|
||||
|
||||
$editForm = $this->createEditForm($entity);
|
||||
|
||||
return $this->render('@ChillActivity/ActivityReasonCategory/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all ActivityReasonCategory entities.
|
||||
*/
|
||||
@@ -78,10 +100,29 @@ class ActivityReasonCategoryController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and displays a ActivityReasonCategory entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreasoncategory/{id}/show', name: 'chill_activity_activityreasoncategory_show')]
|
||||
public function showAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(ActivityReasonCategory::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find ActivityReasonCategory entity.');
|
||||
}
|
||||
|
||||
return $this->render('@ChillActivity/ActivityReasonCategory/show.html.twig', [
|
||||
'entity' => $entity,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an existing ActivityReasonCategory entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreasoncategory/{id}/update', name: 'chill_activity_activityreasoncategory_update')]
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreasoncategory/{id}/update', name: 'chill_activity_activityreasoncategory_update', methods: ['POST', 'PUT'])]
|
||||
public function updateAction(Request $request, mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
@@ -98,7 +139,7 @@ class ActivityReasonCategoryController extends AbstractController
|
||||
if ($editForm->isSubmitted() && $editForm->isValid()) {
|
||||
$em->flush();
|
||||
|
||||
return $this->redirectToRoute('chill_activity_activityreasoncategory', ['id' => $id]);
|
||||
return $this->redirectToRoute('chill_activity_activityreasoncategory_edit', ['id' => $id]);
|
||||
}
|
||||
|
||||
return $this->render('@ChillActivity/ActivityReasonCategory/edit.html.twig', [
|
||||
@@ -137,7 +178,7 @@ class ActivityReasonCategoryController extends AbstractController
|
||||
{
|
||||
$form = $this->createForm(ActivityReasonCategoryType::class, $entity, [
|
||||
'action' => $this->generateUrl('chill_activity_activityreasoncategory_update', ['id' => $entity->getId()]),
|
||||
'method' => 'POST',
|
||||
'method' => 'PUT',
|
||||
]);
|
||||
|
||||
$form->add('submit', SubmitType::class, ['label' => 'Update']);
|
||||
|
@@ -17,6 +17,7 @@ use Chill\ActivityBundle\Repository\ActivityReasonRepository;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
/**
|
||||
* ActivityReason controller.
|
||||
@@ -49,6 +50,28 @@ class ActivityReasonController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a form to edit an existing ActivityReason entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreason/{id}/edit', name: 'chill_activity_activityreason_edit')]
|
||||
public function editAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(ActivityReason::class)->find($id);
|
||||
|
||||
if (null === $entity) {
|
||||
throw new NotFoundHttpException('Unable to find ActivityReason entity.');
|
||||
}
|
||||
|
||||
$editForm = $this->createEditForm($entity);
|
||||
|
||||
return $this->render('@ChillActivity/ActivityReason/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all ActivityReason entities.
|
||||
*/
|
||||
@@ -79,10 +102,29 @@ class ActivityReasonController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and displays a ActivityReason entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreason/{id}/show', name: 'chill_activity_activityreason_show')]
|
||||
public function showAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(ActivityReason::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find ActivityReason entity.');
|
||||
}
|
||||
|
||||
return $this->render('@ChillActivity/ActivityReason/show.html.twig', [
|
||||
'entity' => $entity,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an existing ActivityReason entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreason/{id}/update', name: 'chill_activity_activityreason_update')]
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/activityreason/{id}/update', name: 'chill_activity_activityreason_update', methods: ['POST', 'PUT'])]
|
||||
public function updateAction(Request $request, mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
@@ -138,7 +180,7 @@ class ActivityReasonController extends AbstractController
|
||||
{
|
||||
$form = $this->createForm(ActivityReasonType::class, $entity, [
|
||||
'action' => $this->generateUrl('chill_activity_activityreason_update', ['id' => $entity->getId()]),
|
||||
'method' => 'POST',
|
||||
'method' => 'PUT',
|
||||
]);
|
||||
|
||||
$form->add('submit', SubmitType::class, ['label' => 'Update']);
|
||||
|
@@ -2,7 +2,7 @@ import "es6-promise/auto";
|
||||
import { createStore } from "vuex";
|
||||
import { postLocation } from "./api";
|
||||
import prepareLocations from "./store.locations.js";
|
||||
import { fetchResults, makeFetch } from "ChillMainAssets/lib/api/apiMethods";
|
||||
import {fetchResults, makeFetch} from "ChillMainAssets/lib/api/apiMethods";
|
||||
|
||||
const debug = process.env.NODE_ENV !== "production";
|
||||
//console.log('window.activity', window.activity);
|
||||
@@ -369,7 +369,7 @@ const store = createStore({
|
||||
// console.log('works', works);
|
||||
commit("setAccompanyingPeriodWorks", works);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch works:", error);
|
||||
console.error('Failed to fetch works:', error);
|
||||
}
|
||||
},
|
||||
getWhoAmI({ commit }) {
|
||||
|
@@ -3,7 +3,7 @@
|
||||
{% block admin_content %}
|
||||
<h1>{{ 'ActivityReason list'|trans }}</h1>
|
||||
|
||||
<table class="table table-bordered border-dark align-middle">
|
||||
<table class="records_list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ 'Name'|trans }}</th>
|
||||
@@ -29,7 +29,10 @@
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ path('chill_activity_activityreason_update', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
<a href="{{ path('chill_activity_activityreason_show', { 'id': entity.id }) }}" class="btn btn-show" title="{{ 'show'|trans }}"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_activity_activityreason_edit', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
|
@@ -3,7 +3,7 @@
|
||||
{% block admin_content %}
|
||||
<h1>{{ 'ActivityReasonCategory list'|trans }}</h1>
|
||||
|
||||
<table class="table table-bordered border-dark align-middle">
|
||||
<table class="records_list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ 'Name'|trans }}</th>
|
||||
@@ -23,7 +23,10 @@
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ path('chill_activity_activityreasoncategory_update', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
<a href="{{ path('chill_activity_activityreasoncategory_show', { 'id': entity.id }) }}" class="btn btn-show" title="{{ 'show'|trans }}"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_activity_activityreasoncategory_edit', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
|
@@ -22,52 +22,6 @@ use Symfony\Component\Security\Core\Role\Role;
|
||||
*/
|
||||
final class ActivityControllerTest extends WebTestCase
|
||||
{
|
||||
/**
|
||||
* @dataProvider getSecuredPagesUnauthenticated
|
||||
*/
|
||||
public function testAccessIsDeniedForUnauthenticated(mixed $url)
|
||||
{
|
||||
$client = $this->createClient();
|
||||
|
||||
$client->request('GET', $url);
|
||||
|
||||
$this->assertEquals(302, $client->getResponse()->getStatusCode());
|
||||
$this->assertTrue(
|
||||
$client->getResponse()->isRedirect('http://localhost/login'),
|
||||
sprintf('the page "%s" does not redirect to http://localhost/login', $url)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a client unauthenticated and.
|
||||
*/
|
||||
public function getSecuredPagesUnauthenticated()
|
||||
{
|
||||
self::bootKernel();
|
||||
$person = $this->getPersonFromFixtures();
|
||||
$activities = $this->getActivitiesForPerson($person);
|
||||
|
||||
return [
|
||||
[sprintf('fr/person/%d/activity/', $person->getId())],
|
||||
[sprintf('fr/person/%d/activity/new', $person->getId())],
|
||||
[sprintf('fr/person/%d/activity/%d/show', $person->getId(), $activities[0]->getId())],
|
||||
[sprintf('fr/person/%d/activity/%d/edit', $person->getId(), $activities[0]->getId())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getSecuredPagesAuthenticated
|
||||
*
|
||||
* @param type $client
|
||||
* @param type $url
|
||||
*/
|
||||
public function testAccessIsDeniedForUnauthorized($client, $url)
|
||||
{
|
||||
$client->request('GET', $url);
|
||||
|
||||
$this->assertEquals(403, $client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public function getSecuredPagesAuthenticated()
|
||||
{
|
||||
self::bootKernel();
|
||||
@@ -101,6 +55,52 @@ final class ActivityControllerTest extends WebTestCase
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide a client unauthenticated and.
|
||||
*/
|
||||
public function getSecuredPagesUnauthenticated()
|
||||
{
|
||||
self::bootKernel();
|
||||
$person = $this->getPersonFromFixtures();
|
||||
$activities = $this->getActivitiesForPerson($person);
|
||||
|
||||
return [
|
||||
[sprintf('fr/person/%d/activity/', $person->getId())],
|
||||
[sprintf('fr/person/%d/activity/new', $person->getId())],
|
||||
[sprintf('fr/person/%d/activity/%d/show', $person->getId(), $activities[0]->getId())],
|
||||
[sprintf('fr/person/%d/activity/%d/edit', $person->getId(), $activities[0]->getId())],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getSecuredPagesUnauthenticated
|
||||
*/
|
||||
public function testAccessIsDeniedForUnauthenticated(mixed $url)
|
||||
{
|
||||
$client = $this->createClient();
|
||||
|
||||
$client->request('GET', $url);
|
||||
|
||||
$this->assertEquals(302, $client->getResponse()->getStatusCode());
|
||||
$this->assertTrue(
|
||||
$client->getResponse()->isRedirect('http://localhost/login'),
|
||||
sprintf('the page "%s" does not redirect to http://localhost/login', $url)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getSecuredPagesAuthenticated
|
||||
*
|
||||
* @param type $client
|
||||
* @param type $url
|
||||
*/
|
||||
public function testAccessIsDeniedForUnauthorized($client, $url)
|
||||
{
|
||||
$client->request('GET', $url);
|
||||
|
||||
$this->assertEquals(403, $client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public function testCompleteScenario()
|
||||
{
|
||||
// Create a new client to browse the application
|
||||
|
@@ -137,64 +137,6 @@ class ActivityACLAwareRepositoryTest extends KernelTestCase
|
||||
self::assertIsArray($actual);
|
||||
}
|
||||
|
||||
public function provideDataFindByAccompanyingPeriod(): iterable
|
||||
{
|
||||
$this->setUp();
|
||||
|
||||
if (null === $period = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('a')
|
||||
->from(AccompanyingPeriod::class, 'a')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getSingleResult()) {
|
||||
throw new \RuntimeException('no period found');
|
||||
}
|
||||
|
||||
if ([] === $types = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('t')
|
||||
->from(ActivityType::class, 't')
|
||||
->setMaxResults(2)
|
||||
->getQuery()
|
||||
->getResult()) {
|
||||
throw new \RuntimeException('no types');
|
||||
}
|
||||
|
||||
if ([] === $jobs = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('j')
|
||||
->from(UserJob::class, 'j')
|
||||
->setMaxResults(2)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
) {
|
||||
$job = new UserJob();
|
||||
$job->setLabel(['fr' => 'test']);
|
||||
$this->entityManager->persist($job);
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
if (null === $user = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('u')
|
||||
->from(User::class, 'u')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getSingleResult()
|
||||
) {
|
||||
throw new \RuntimeException('no user found');
|
||||
}
|
||||
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], []];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['my_activities' => true]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['types' => $types]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['jobs' => $jobs]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago')]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['before' => new \DateTimeImmutable('1 year ago')]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago'), 'before' => new \DateTimeImmutable('1 month ago')]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideDataFindByPerson
|
||||
*/
|
||||
@@ -349,4 +291,62 @@ class ActivityACLAwareRepositoryTest extends KernelTestCase
|
||||
yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['before' => new \DateTimeImmutable('1 year ago')]];
|
||||
yield [$person, $user, $centers, $scopes, ActivityVoter::SEE, 0, 5, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago'), 'before' => new \DateTimeImmutable('1 month ago')]];
|
||||
}
|
||||
|
||||
public function provideDataFindByAccompanyingPeriod(): iterable
|
||||
{
|
||||
$this->setUp();
|
||||
|
||||
if (null === $period = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('a')
|
||||
->from(AccompanyingPeriod::class, 'a')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getSingleResult()) {
|
||||
throw new \RuntimeException('no period found');
|
||||
}
|
||||
|
||||
if ([] === $types = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('t')
|
||||
->from(ActivityType::class, 't')
|
||||
->setMaxResults(2)
|
||||
->getQuery()
|
||||
->getResult()) {
|
||||
throw new \RuntimeException('no types');
|
||||
}
|
||||
|
||||
if ([] === $jobs = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('j')
|
||||
->from(UserJob::class, 'j')
|
||||
->setMaxResults(2)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
) {
|
||||
$job = new UserJob();
|
||||
$job->setLabel(['fr' => 'test']);
|
||||
$this->entityManager->persist($job);
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
if (null === $user = $this->entityManager
|
||||
->createQueryBuilder()
|
||||
->select('u')
|
||||
->from(User::class, 'u')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getSingleResult()
|
||||
) {
|
||||
throw new \RuntimeException('no user found');
|
||||
}
|
||||
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], []];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['my_activities' => true]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['types' => $types]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['jobs' => $jobs]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago')]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['before' => new \DateTimeImmutable('1 year ago')]];
|
||||
yield [$period, $user, ActivityVoter::SEE, 0, 10, ['date' => 'DESC'], ['after' => new \DateTimeImmutable('1 year ago'), 'before' => new \DateTimeImmutable('1 month ago')]];
|
||||
}
|
||||
}
|
||||
|
@@ -57,46 +57,6 @@ final class ActivityVoterTest extends KernelTestCase
|
||||
$this->prophet = new \Prophecy\Prophet();
|
||||
}
|
||||
|
||||
public function testNullUser()
|
||||
{
|
||||
$token = $this->prepareToken();
|
||||
$center = $this->prepareCenter(1, 'center');
|
||||
$person = $this->preparePerson($center);
|
||||
$scope = $this->prepareScope(1, 'default');
|
||||
$activity = $this->prepareActivity($scope, $person);
|
||||
|
||||
$this->assertEquals(
|
||||
VoterInterface::ACCESS_DENIED,
|
||||
$this->voter->vote($token, $activity, ['CHILL_ACTIVITY_SEE']),
|
||||
'assert that a null user is not allowed to see'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProvider_testVoteAction
|
||||
*
|
||||
* @param type $expectedResult
|
||||
* @param string $attribute
|
||||
* @param string $message
|
||||
*/
|
||||
public function testVoteAction(
|
||||
$expectedResult,
|
||||
User $user,
|
||||
Scope $scope,
|
||||
Center $center,
|
||||
$attribute,
|
||||
$message,
|
||||
) {
|
||||
$token = $this->prepareToken($user);
|
||||
$activity = $this->prepareActivity($scope, $this->preparePerson($center));
|
||||
|
||||
$this->assertEquals(
|
||||
$expectedResult,
|
||||
$this->voter->vote($token, $activity, [$attribute]),
|
||||
$message
|
||||
);
|
||||
}
|
||||
|
||||
public function dataProvider_testVoteAction()
|
||||
{
|
||||
$centerA = $this->prepareCenter(1, 'center A');
|
||||
@@ -150,6 +110,46 @@ final class ActivityVoterTest extends KernelTestCase
|
||||
];
|
||||
}
|
||||
|
||||
public function testNullUser()
|
||||
{
|
||||
$token = $this->prepareToken();
|
||||
$center = $this->prepareCenter(1, 'center');
|
||||
$person = $this->preparePerson($center);
|
||||
$scope = $this->prepareScope(1, 'default');
|
||||
$activity = $this->prepareActivity($scope, $person);
|
||||
|
||||
$this->assertEquals(
|
||||
VoterInterface::ACCESS_DENIED,
|
||||
$this->voter->vote($token, $activity, ['CHILL_ACTIVITY_SEE']),
|
||||
'assert that a null user is not allowed to see'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProvider_testVoteAction
|
||||
*
|
||||
* @param type $expectedResult
|
||||
* @param string $attribute
|
||||
* @param string $message
|
||||
*/
|
||||
public function testVoteAction(
|
||||
$expectedResult,
|
||||
User $user,
|
||||
Scope $scope,
|
||||
Center $center,
|
||||
$attribute,
|
||||
$message,
|
||||
) {
|
||||
$token = $this->prepareToken($user);
|
||||
$activity = $this->prepareActivity($scope, $this->preparePerson($center));
|
||||
|
||||
$this->assertEquals(
|
||||
$expectedResult,
|
||||
$this->voter->vote($token, $activity, [$attribute]),
|
||||
$message
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare a token interface with correct rights.
|
||||
*
|
||||
|
@@ -30,18 +30,6 @@ final class AsideActivityControllerTest extends WebTestCase
|
||||
self::ensureKernelShutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateAsideActivityId
|
||||
*/
|
||||
public function testEditWithoutUsers(int $asideActivityId)
|
||||
{
|
||||
self::ensureKernelShutdown();
|
||||
$client = $this->getClientAuthenticated();
|
||||
$client->request('GET', "/fr/asideactivity/{$asideActivityId}/edit");
|
||||
|
||||
$this->assertEquals(200, $client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public static function generateAsideActivityId(): iterable
|
||||
{
|
||||
self::bootKernel();
|
||||
@@ -70,6 +58,18 @@ final class AsideActivityControllerTest extends WebTestCase
|
||||
self::ensureKernelShutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateAsideActivityId
|
||||
*/
|
||||
public function testEditWithoutUsers(int $asideActivityId)
|
||||
{
|
||||
self::ensureKernelShutdown();
|
||||
$client = $this->getClientAuthenticated();
|
||||
$client->request('GET', "/fr/asideactivity/{$asideActivityId}/edit");
|
||||
|
||||
$this->assertEquals(200, $client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public function testIndexWithoutUsers()
|
||||
{
|
||||
self::ensureKernelShutdown();
|
||||
|
@@ -24,11 +24,7 @@ use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
class CalendarForShortMessageProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CalendarRepository $calendarRepository,
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly RangeGeneratorInterface $rangeGenerator,
|
||||
) {}
|
||||
public function __construct(private readonly CalendarRepository $calendarRepository, private readonly EntityManagerInterface $em, private readonly RangeGeneratorInterface $rangeGenerator) {}
|
||||
|
||||
/**
|
||||
* Generate calendars instance.
|
||||
|
@@ -42,32 +42,6 @@ final class CalendarControllerTest extends WebTestCase
|
||||
self::ensureKernelShutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideAccompanyingPeriod
|
||||
*/
|
||||
public function testList(int $accompanyingPeriodId)
|
||||
{
|
||||
$this->client->request(
|
||||
Request::METHOD_GET,
|
||||
sprintf('/fr/calendar/calendar/by-period/%d', $accompanyingPeriodId)
|
||||
);
|
||||
|
||||
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideAccompanyingPeriod
|
||||
*/
|
||||
public function testNew(int $accompanyingPeriodId)
|
||||
{
|
||||
$this->client->request(
|
||||
Request::METHOD_GET,
|
||||
sprintf('/fr/calendar/calendar/new?accompanying_period_id=%d', $accompanyingPeriodId)
|
||||
);
|
||||
|
||||
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
public static function provideAccompanyingPeriod(): iterable
|
||||
{
|
||||
self::bootKernel();
|
||||
@@ -108,4 +82,30 @@ final class CalendarControllerTest extends WebTestCase
|
||||
|
||||
self::ensureKernelShutdown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideAccompanyingPeriod
|
||||
*/
|
||||
public function testList(int $accompanyingPeriodId)
|
||||
{
|
||||
$this->client->request(
|
||||
Request::METHOD_GET,
|
||||
sprintf('/fr/calendar/calendar/by-period/%d', $accompanyingPeriodId)
|
||||
);
|
||||
|
||||
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideAccompanyingPeriod
|
||||
*/
|
||||
public function testNew(int $accompanyingPeriodId)
|
||||
{
|
||||
$this->client->request(
|
||||
Request::METHOD_GET,
|
||||
sprintf('/fr/calendar/calendar/new?accompanying_period_id=%d', $accompanyingPeriodId)
|
||||
);
|
||||
|
||||
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
|
||||
}
|
||||
}
|
||||
|
@@ -45,6 +45,20 @@ class MSUserAbsenceReaderTest extends TestCase
|
||||
self::assertEquals($expected, $absenceReader->isUserAbsent($user), $message);
|
||||
}
|
||||
|
||||
public function testIsUserAbsentWithoutRemoteId(): void
|
||||
{
|
||||
$user = new User();
|
||||
$client = new MockHttpClient();
|
||||
|
||||
$mapUser = $this->prophesize(MapCalendarToUser::class);
|
||||
$mapUser->getUserId($user)->willReturn(null);
|
||||
$clock = new MockClock(new \DateTimeImmutable('2023-07-07T12:00:00'));
|
||||
|
||||
$absenceReader = new MSUserAbsenceReader($client, $mapUser->reveal(), $clock);
|
||||
|
||||
self::assertNull($absenceReader->isUserAbsent($user), 'when no user found, absence should be null');
|
||||
}
|
||||
|
||||
public static function provideDataTestUserAbsence(): iterable
|
||||
{
|
||||
// contains data that was retrieved from microsoft graph api on 2023-07-06
|
||||
@@ -159,18 +173,4 @@ class MSUserAbsenceReaderTest extends TestCase
|
||||
'User is absent: absence is always enabled',
|
||||
];
|
||||
}
|
||||
|
||||
public function testIsUserAbsentWithoutRemoteId(): void
|
||||
{
|
||||
$user = new User();
|
||||
$client = new MockHttpClient();
|
||||
|
||||
$mapUser = $this->prophesize(MapCalendarToUser::class);
|
||||
$mapUser->getUserId($user)->willReturn(null);
|
||||
$clock = new MockClock(new \DateTimeImmutable('2023-07-07T12:00:00'));
|
||||
|
||||
$absenceReader = new MSUserAbsenceReader($client, $mapUser->reveal(), $clock);
|
||||
|
||||
self::assertNull($absenceReader->isUserAbsent($user), 'when no user found, absence should be null');
|
||||
}
|
||||
}
|
||||
|
@@ -21,6 +21,7 @@ namespace Chill\CalendarBundle\Tests\Service\ShortMessageNotification;
|
||||
use Chill\CalendarBundle\Entity\Calendar;
|
||||
use Chill\CalendarBundle\Repository\CalendarRepository;
|
||||
use Chill\CalendarBundle\Service\ShortMessageNotification\CalendarForShortMessageProvider;
|
||||
use Chill\CalendarBundle\Service\ShortMessageNotification\DefaultRangeGenerator;
|
||||
use Chill\CalendarBundle\Service\ShortMessageNotification\RangeGeneratorInterface;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
@@ -81,16 +82,10 @@ final class CalendarForShortMessageProviderTest extends TestCase
|
||||
$em = $this->prophesize(EntityManagerInterface::class);
|
||||
$em->clear()->shouldBeCalled();
|
||||
|
||||
$calendarRangeGenerator = $this->prophesize(RangeGeneratorInterface::class);
|
||||
$calendarRangeGenerator->generateRange(Argument::any())->willReturn([
|
||||
'startDate' => new \DateTimeImmutable('yesterday'),
|
||||
'endDate' => new \DateTimeImmutable('now'),
|
||||
]);
|
||||
|
||||
$provider = new CalendarForShortMessageProvider(
|
||||
$calendarRepository->reveal(),
|
||||
$em->reveal(),
|
||||
$calendarRangeGenerator->reveal(),
|
||||
new DefaultRangeGenerator()
|
||||
);
|
||||
|
||||
$calendars = iterator_to_array($provider->getCalendars(new \DateTimeImmutable('now')));
|
||||
@@ -108,32 +103,26 @@ final class CalendarForShortMessageProviderTest extends TestCase
|
||||
Argument::type(\DateTimeImmutable::class),
|
||||
Argument::type('int'),
|
||||
Argument::exact(0)
|
||||
)->will(static fn ($args) => array_fill(0, 10, new Calendar()))->shouldBeCalledTimes(1);
|
||||
)->will(static fn ($args) => array_fill(0, 1, new Calendar()))->shouldBeCalledTimes(1);
|
||||
$calendarRepository->findByNotificationAvailable(
|
||||
Argument::type(\DateTimeImmutable::class),
|
||||
Argument::type(\DateTimeImmutable::class),
|
||||
Argument::type('int'),
|
||||
Argument::exact(10)
|
||||
Argument::not(0)
|
||||
)->will(static fn ($args) => [])->shouldBeCalledTimes(1);
|
||||
|
||||
$em = $this->prophesize(EntityManagerInterface::class);
|
||||
$em->clear()->shouldBeCalled();
|
||||
|
||||
$calendarRangeGenerator = $this->prophesize(RangeGeneratorInterface::class);
|
||||
$calendarRangeGenerator->generateRange(Argument::any())->willReturn([
|
||||
'startDate' => new \DateTimeImmutable('yesterday'),
|
||||
'endDate' => new \DateTimeImmutable('now'),
|
||||
]);
|
||||
|
||||
$provider = new CalendarForShortMessageProvider(
|
||||
$calendarRepository->reveal(),
|
||||
$em->reveal(),
|
||||
$calendarRangeGenerator->reveal(),
|
||||
new DefaultRangeGenerator()
|
||||
);
|
||||
|
||||
$calendars = iterator_to_array($provider->getCalendars(new \DateTimeImmutable('now')));
|
||||
|
||||
$this->assertEquals(10, \count($calendars));
|
||||
$this->assertEquals(1, \count($calendars));
|
||||
$this->assertContainsOnly(Calendar::class, $calendars);
|
||||
}
|
||||
}
|
||||
|
@@ -28,24 +28,6 @@ use PHPUnit\Framework\TestCase;
|
||||
*/
|
||||
final class DefaultRangeGeneratorTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @dataProvider generateData
|
||||
*/
|
||||
public function testGenerateRange(\DateTimeImmutable $date, ?\DateTimeImmutable $startDate, ?\DateTimeImmutable $endDate)
|
||||
{
|
||||
$generator = new DefaultRangeGenerator();
|
||||
|
||||
['startDate' => $actualStartDate, 'endDate' => $actualEndDate] = $generator->generateRange($date);
|
||||
|
||||
if (null === $startDate) {
|
||||
$this->assertNull($actualStartDate);
|
||||
$this->assertNull($actualEndDate);
|
||||
} else {
|
||||
$this->assertEquals($startDate->format(\DateTimeImmutable::ATOM), $actualStartDate->format(\DateTimeImmutable::ATOM));
|
||||
$this->assertEquals($endDate->format(\DateTimeImmutable::ATOM), $actualEndDate->format(\DateTimeImmutable::ATOM));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* * Lundi => Envoi des rdv du mardi et mercredi.
|
||||
* * Mardi => Envoi des rdv du jeudi.
|
||||
@@ -97,4 +79,22 @@ final class DefaultRangeGeneratorTest extends TestCase
|
||||
null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateData
|
||||
*/
|
||||
public function testGenerateRange(\DateTimeImmutable $date, ?\DateTimeImmutable $startDate, ?\DateTimeImmutable $endDate)
|
||||
{
|
||||
$generator = new DefaultRangeGenerator();
|
||||
|
||||
['startDate' => $actualStartDate, 'endDate' => $actualEndDate] = $generator->generateRange($date);
|
||||
|
||||
if (null === $startDate) {
|
||||
$this->assertNull($actualStartDate);
|
||||
$this->assertNull($actualEndDate);
|
||||
} else {
|
||||
$this->assertEquals($startDate->format(\DateTimeImmutable::ATOM), $actualStartDate->format(\DateTimeImmutable::ATOM));
|
||||
$this->assertEquals($endDate->format(\DateTimeImmutable::ATOM), $actualEndDate->format(\DateTimeImmutable::ATOM));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -49,6 +49,80 @@ final class CustomFieldsChoiceTest extends KernelTestCase
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* provide empty data in different possible representations.
|
||||
* Those data are supposed to be deserialized.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function emptyDataProvider()
|
||||
{
|
||||
return [
|
||||
// 0
|
||||
[
|
||||
// signle
|
||||
'',
|
||||
],
|
||||
// 1
|
||||
[
|
||||
// single
|
||||
null,
|
||||
],
|
||||
// 2
|
||||
[
|
||||
// signle with allow other
|
||||
['_other' => 'something', '_choices' => ''],
|
||||
],
|
||||
// 3
|
||||
[
|
||||
// multiple
|
||||
[],
|
||||
],
|
||||
// 4
|
||||
[
|
||||
// multiple with allow other
|
||||
['_other' => 'something', '_choices' => []],
|
||||
],
|
||||
// 5
|
||||
[
|
||||
// multiple with allow other
|
||||
['_other' => '', '_choices' => []],
|
||||
],
|
||||
// 6
|
||||
[
|
||||
// empty
|
||||
['_other' => null, '_choices' => null],
|
||||
],
|
||||
// 7
|
||||
[
|
||||
// empty
|
||||
[null],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function serializedRepresentationDataProvider()
|
||||
{
|
||||
return [
|
||||
[
|
||||
// multiple => false, allow_other => false
|
||||
'my-value',
|
||||
],
|
||||
[
|
||||
// multiple => true, allow_ther => false
|
||||
['my-value'],
|
||||
],
|
||||
[
|
||||
// multiple => false, allow_other => true, current value not in other
|
||||
['_other' => '', '_choices' => 'my-value'],
|
||||
],
|
||||
[
|
||||
// multiple => true, allow_other => true, current value not in other
|
||||
['_other' => '', '_choices' => ['my-value']],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if the representation of the data is deserialized to an array text
|
||||
* with an "allow_other" field.
|
||||
@@ -338,58 +412,6 @@ final class CustomFieldsChoiceTest extends KernelTestCase
|
||||
$this->assertTrue($isEmpty);
|
||||
}
|
||||
|
||||
/**
|
||||
* provide empty data in different possible representations.
|
||||
* Those data are supposed to be deserialized.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function emptyDataProvider()
|
||||
{
|
||||
return [
|
||||
// 0
|
||||
[
|
||||
// signle
|
||||
'',
|
||||
],
|
||||
// 1
|
||||
[
|
||||
// single
|
||||
null,
|
||||
],
|
||||
// 2
|
||||
[
|
||||
// signle with allow other
|
||||
['_other' => 'something', '_choices' => ''],
|
||||
],
|
||||
// 3
|
||||
[
|
||||
// multiple
|
||||
[],
|
||||
],
|
||||
// 4
|
||||
[
|
||||
// multiple with allow other
|
||||
['_other' => 'something', '_choices' => []],
|
||||
],
|
||||
// 5
|
||||
[
|
||||
// multiple with allow other
|
||||
['_other' => '', '_choices' => []],
|
||||
],
|
||||
// 6
|
||||
[
|
||||
// empty
|
||||
['_other' => null, '_choices' => null],
|
||||
],
|
||||
// 7
|
||||
[
|
||||
// empty
|
||||
[null],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
// ///////////////////////////////////////
|
||||
//
|
||||
// test function isEmptyValue
|
||||
@@ -413,28 +435,6 @@ final class CustomFieldsChoiceTest extends KernelTestCase
|
||||
$this->assertFalse($isEmpty);
|
||||
}
|
||||
|
||||
public static function serializedRepresentationDataProvider()
|
||||
{
|
||||
return [
|
||||
[
|
||||
// multiple => false, allow_other => false
|
||||
'my-value',
|
||||
],
|
||||
[
|
||||
// multiple => true, allow_ther => false
|
||||
['my-value'],
|
||||
],
|
||||
[
|
||||
// multiple => false, allow_other => true, current value not in other
|
||||
['_other' => '', '_choices' => 'my-value'],
|
||||
],
|
||||
[
|
||||
// multiple => true, allow_other => true, current value not in other
|
||||
['_other' => '', '_choices' => ['my-value']],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $options
|
||||
*
|
||||
|
@@ -58,7 +58,6 @@
|
||||
|
||||
<script>
|
||||
import { buildLink } from "ChillDocGeneratorAssets/lib/document-generator";
|
||||
import { localizeString } from "ChillMainAssets/lib/localizationHelper/localizationHelper";
|
||||
|
||||
export default {
|
||||
name: "PickTemplate",
|
||||
@@ -114,9 +113,6 @@ export default {
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
localizeString(str) {
|
||||
return localizeString(str);
|
||||
},
|
||||
clickGenerate(event, link) {
|
||||
if (!this.preventDefaultMoveToGenerate) {
|
||||
window.location.assign(link);
|
||||
|
@@ -1,5 +1,7 @@
|
||||
{{ 'docgen.data_dump_email.Dear'|trans }}
|
||||
|
||||
{{ 'docgen.data_dump_email.data_dump_ready_and_attached'|trans }}
|
||||
{{ 'docgen.data_dump_email.data_dump_ready_and_link'|trans }}
|
||||
|
||||
{{ 'docgen.data_dump_email.filename'|trans({filename: filename}) }}
|
||||
{{ link }}
|
||||
|
||||
{{ 'docgen.data_dump_email.link_valid_until'|trans({validity: validity}) }}
|
||||
|
@@ -11,13 +11,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace Chill\DocGeneratorBundle\Service\Messenger;
|
||||
|
||||
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepositoryInterface;
|
||||
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepository;
|
||||
use Chill\DocGeneratorBundle\Service\Generator\Generator;
|
||||
use Chill\DocGeneratorBundle\Service\Generator\GeneratorException;
|
||||
use Chill\DocGeneratorBundle\Service\Generator\GeneratorInterface;
|
||||
use Chill\DocStoreBundle\AsyncUpload\TempUrlGeneratorInterface;
|
||||
use Chill\DocStoreBundle\Entity\StoredObject;
|
||||
use Chill\DocStoreBundle\Exception\StoredObjectManagerException;
|
||||
use Chill\DocStoreBundle\Repository\StoredObjectRepositoryInterface;
|
||||
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
|
||||
use Chill\DocStoreBundle\Repository\StoredObjectRepository;
|
||||
use Chill\MainBundle\Repository\UserRepositoryInterface;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
@@ -37,15 +37,15 @@ class RequestGenerationHandler implements MessageHandlerInterface
|
||||
private const LOG_PREFIX = '[docgen message handler] ';
|
||||
|
||||
public function __construct(
|
||||
private readonly DocGeneratorTemplateRepositoryInterface $docGeneratorTemplateRepository,
|
||||
private readonly DocGeneratorTemplateRepository $docGeneratorTemplateRepository,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly GeneratorInterface $generator,
|
||||
private readonly Generator $generator,
|
||||
private readonly LoggerInterface $logger,
|
||||
private readonly StoredObjectRepositoryInterface $storedObjectRepository,
|
||||
private readonly StoredObjectRepository $storedObjectRepository,
|
||||
private readonly UserRepositoryInterface $userRepository,
|
||||
private readonly MailerInterface $mailer,
|
||||
private readonly TempUrlGeneratorInterface $tempUrlGenerator,
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly StoredObjectManagerInterface $storedObjectManager,
|
||||
) {}
|
||||
|
||||
public function __invoke(RequestGenerationMessage $message)
|
||||
@@ -90,7 +90,7 @@ class RequestGenerationHandler implements MessageHandlerInterface
|
||||
|
||||
$this->sendDataDump($destinationStoredObject, $message);
|
||||
} else {
|
||||
$this->generator->generateDocFromTemplate(
|
||||
$destinationStoredObject = $this->generator->generateDocFromTemplate(
|
||||
$template,
|
||||
$message->getEntityId(),
|
||||
$message->getContextGenerationData(),
|
||||
@@ -122,20 +122,19 @@ class RequestGenerationHandler implements MessageHandlerInterface
|
||||
|
||||
private function sendDataDump(StoredObject $destinationStoredObject, RequestGenerationMessage $message): void
|
||||
{
|
||||
// Get the content of the document
|
||||
$content = $this->storedObjectManager->read($destinationStoredObject);
|
||||
$filename = $destinationStoredObject->getFilename();
|
||||
$contentType = $destinationStoredObject->getType();
|
||||
$url = $this->tempUrlGenerator->generate('GET', $destinationStoredObject->getFilename(), 3600);
|
||||
$parts = [];
|
||||
parse_str(parse_url($url->url)['query'], $parts);
|
||||
$validity = \DateTimeImmutable::createFromFormat('U', $parts['temp_url_expires']);
|
||||
|
||||
// Create the email with the document as an attachment
|
||||
$email = (new TemplatedEmail())
|
||||
->to($message->getSendResultToEmail())
|
||||
->textTemplate('@ChillDocGenerator/Email/send_data_dump_to_admin.txt.twig')
|
||||
->context([
|
||||
'filename' => $filename,
|
||||
'link' => $url->url,
|
||||
'validity' => $validity,
|
||||
])
|
||||
->subject($this->translator->trans('docgen.data_dump_email.subject'))
|
||||
->attach($content, $filename, $contentType);
|
||||
->subject($this->translator->trans('docgen.data_dump_email.subject'));
|
||||
|
||||
$this->mailer->send($email);
|
||||
}
|
||||
|
@@ -1,132 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\DocGeneratorBundle\Tests\Service\Messenger;
|
||||
|
||||
use Chill\DocGeneratorBundle\Entity\DocGeneratorTemplate;
|
||||
use Chill\DocGeneratorBundle\Repository\DocGeneratorTemplateRepositoryInterface;
|
||||
use Chill\DocGeneratorBundle\Service\Generator\GeneratorInterface;
|
||||
use Chill\DocGeneratorBundle\Service\Messenger\RequestGenerationHandler;
|
||||
use Chill\DocGeneratorBundle\Service\Messenger\RequestGenerationMessage;
|
||||
use Chill\DocStoreBundle\Entity\StoredObject;
|
||||
use Chill\DocStoreBundle\Repository\StoredObjectRepositoryInterface;
|
||||
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
|
||||
use Chill\MainBundle\Entity\User;
|
||||
use Chill\MainBundle\Repository\UserRepositoryInterface;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\ORM\Query;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Prophecy\Argument;
|
||||
use Prophecy\PhpUnit\ProphecyTrait;
|
||||
use Psr\Log\NullLogger;
|
||||
use Symfony\Component\Mailer\MailerInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* @coversNothing
|
||||
*/
|
||||
class RequestGenerationHandlerTest extends TestCase
|
||||
{
|
||||
use ProphecyTrait;
|
||||
|
||||
public function testGenerationHappyScenario(): void
|
||||
{
|
||||
// Create entities
|
||||
$template = new DocGeneratorTemplate();
|
||||
$this->setPrivateProperty($template, 'id', 1);
|
||||
|
||||
$storedObject = new StoredObject();
|
||||
$this->setPrivateProperty($storedObject, 'id', 2);
|
||||
|
||||
$creator = new User();
|
||||
$creator->setEmail('test@example.com');
|
||||
$this->setPrivateProperty($creator, 'id', 3);
|
||||
|
||||
$docGeneratorTemplateRepository = $this->prophesize(DocGeneratorTemplateRepositoryInterface::class);
|
||||
$docGeneratorTemplateRepository->find(1)->willReturn($template);
|
||||
|
||||
$storedObjectRepository = $this->prophesize(StoredObjectRepositoryInterface::class);
|
||||
$storedObjectRepository->find(2)->willReturn($storedObject);
|
||||
|
||||
$userRepository = $this->prophesize(UserRepositoryInterface::class);
|
||||
$userRepository->find(3)->willReturn($creator);
|
||||
|
||||
// Create a mock for the Query object
|
||||
$query = $this->prophesize(Query::class);
|
||||
$query->setParameter('id', 2)->willReturn($query->reveal());
|
||||
$query->execute()->shouldBeCalled();
|
||||
|
||||
// Create a mock for the EntityManager
|
||||
$entityManager = $this->prophesize(EntityManagerInterface::class);
|
||||
$entityManager->createQuery(Argument::containingString('UPDATE'))->willReturn($query->reveal());
|
||||
$entityManager->flush()->shouldBeCalled();
|
||||
|
||||
$generator = $this->prophesize(GeneratorInterface::class);
|
||||
$generator->generateDocFromTemplate(
|
||||
$template,
|
||||
123, // entityId
|
||||
['key' => 'value'], // contextGenerationData
|
||||
$storedObject,
|
||||
$creator
|
||||
)
|
||||
->willReturn($storedObject)->shouldBeCalled();
|
||||
|
||||
$logger = new NullLogger();
|
||||
|
||||
$mailer = $this->prophesize(MailerInterface::class);
|
||||
|
||||
$translator = $this->prophesize(TranslatorInterface::class);
|
||||
|
||||
$storedObjectManager = $this->prophesize(StoredObjectManagerInterface::class);
|
||||
|
||||
// Create handler
|
||||
$handler = new RequestGenerationHandler(
|
||||
$docGeneratorTemplateRepository->reveal(),
|
||||
$entityManager->reveal(),
|
||||
$generator->reveal(),
|
||||
$logger,
|
||||
$storedObjectRepository->reveal(),
|
||||
$userRepository->reveal(),
|
||||
$mailer->reveal(),
|
||||
$translator->reveal(),
|
||||
$storedObjectManager->reveal()
|
||||
);
|
||||
|
||||
// Create message
|
||||
$message = new RequestGenerationMessage(
|
||||
$creator,
|
||||
$template,
|
||||
123, // entityId
|
||||
$storedObject,
|
||||
['key' => 'value'], // contextGenerationData
|
||||
false, // isTest
|
||||
null, // sendResultToEmail
|
||||
false // dumpOnly
|
||||
);
|
||||
|
||||
// Invoke handler
|
||||
$handler->__invoke($message);
|
||||
|
||||
// Assertions
|
||||
// The assertions are handled by the shouldBeCalled() expectations on the mocks
|
||||
$this->assertTrue(true); // Just to have an assertion in the test
|
||||
}
|
||||
|
||||
private function setPrivateProperty(object $object, string $propertyName, $value): void
|
||||
{
|
||||
$reflection = new \ReflectionClass($object);
|
||||
$property = $reflection->getProperty($propertyName);
|
||||
$property->setAccessible(true);
|
||||
$property->setValue($object, $value);
|
||||
}
|
||||
}
|
@@ -31,36 +31,6 @@ final class DocGenEncoderTest extends TestCase
|
||||
$this->encoder = new DocGenEncoder();
|
||||
}
|
||||
|
||||
public function testEmbeddedLoopsThrowsException()
|
||||
{
|
||||
$this->expectException(UnexpectedValueException::class);
|
||||
|
||||
$data = [
|
||||
'data' => [
|
||||
['item' => 'one'],
|
||||
[
|
||||
'embedded' => [
|
||||
[
|
||||
['subitem' => 'two'],
|
||||
['subitem' => 'three'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->encoder->encode($data, 'docgen');
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateEncodeData
|
||||
*/
|
||||
public function testEncode(mixed $expected, mixed $data, string $msg)
|
||||
{
|
||||
$generated = $this->encoder->encode($data, 'docgen');
|
||||
$this->assertEquals($expected, $generated, $msg);
|
||||
}
|
||||
|
||||
public static function generateEncodeData()
|
||||
{
|
||||
yield [['tests' => 'ok'], ['tests' => 'ok'], 'A simple test with a simple array'];
|
||||
@@ -123,4 +93,34 @@ final class DocGenEncoderTest extends TestCase
|
||||
'a longer list, with near real data inside and embedded associative arrays',
|
||||
];
|
||||
}
|
||||
|
||||
public function testEmbeddedLoopsThrowsException()
|
||||
{
|
||||
$this->expectException(UnexpectedValueException::class);
|
||||
|
||||
$data = [
|
||||
'data' => [
|
||||
['item' => 'one'],
|
||||
[
|
||||
'embedded' => [
|
||||
[
|
||||
['subitem' => 'two'],
|
||||
['subitem' => 'three'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$this->encoder->encode($data, 'docgen');
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateEncodeData
|
||||
*/
|
||||
public function testEncode(mixed $expected, mixed $data, string $msg)
|
||||
{
|
||||
$generated = $this->encoder->encode($data, 'docgen');
|
||||
$this->assertEquals($expected, $generated, $msg);
|
||||
}
|
||||
}
|
||||
|
@@ -1,2 +1,4 @@
|
||||
docgen:
|
||||
# No ICU messages needed for data_dump_email anymore
|
||||
data_dump_email:
|
||||
link_valid_until: >-
|
||||
Ce lien est valide jusqu'au {validity, date, full}, {validity, time, medium}
|
||||
|
@@ -34,10 +34,8 @@ docgen:
|
||||
data_dump_email:
|
||||
subject: Contenu des données de génération de document disponible
|
||||
Dear: Cher
|
||||
data_dump_ready_and_attached: >-
|
||||
Le contenu des données est disponible. Vous le trouverez en pièce jointe à cet email.
|
||||
filename: >-
|
||||
Nom du fichier: %filename%
|
||||
data_dump_ready_and_link: >-
|
||||
Le contenu des données est disponible. Vous pouvez le télécharger à l'aide du lien suivant:
|
||||
|
||||
|
||||
|
||||
|
@@ -85,69 +85,6 @@ class TempUrlLocalStorageGeneratorTest extends TestCase
|
||||
self::assertEquals($expected, $urlGenerator->validateSignature($signature, $method, $objectName, $expiration), $message);
|
||||
}
|
||||
|
||||
public static function generateValidateSignatureData(): iterable
|
||||
{
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
true,
|
||||
'Valid signature, not expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('HEAD', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'HEAD',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
true,
|
||||
'Valid signature, not expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180).'A',
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Invalid signature',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration + 1)),
|
||||
false,
|
||||
'Signature expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name.'____',
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Invalid object name',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('POST', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'POST',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Wrong method',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateValidateSignaturePostData
|
||||
*/
|
||||
@@ -227,6 +164,69 @@ class TempUrlLocalStorageGeneratorTest extends TestCase
|
||||
];
|
||||
}
|
||||
|
||||
public static function generateValidateSignatureData(): iterable
|
||||
{
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
true,
|
||||
'Valid signature, not expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('HEAD', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'HEAD',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
true,
|
||||
'Valid signature, not expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180).'A',
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Invalid signature',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration + 1)),
|
||||
false,
|
||||
'Signature expired',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('GET', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'GET',
|
||||
$object_name.'____',
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Invalid object name',
|
||||
];
|
||||
|
||||
yield [
|
||||
TempUrlLocalStorageGeneratorTest::expectedSignature('POST', $object_name = 'testABC', $expiration = 1734307200 + 180),
|
||||
'POST',
|
||||
$object_name,
|
||||
$expiration,
|
||||
\DateTimeImmutable::createFromFormat('U', (string) ($expiration - 10)),
|
||||
false,
|
||||
'Wrong method',
|
||||
];
|
||||
}
|
||||
|
||||
private function buildGenerator(?UrlGeneratorInterface $urlGenerator = null, ?ClockInterface $clock = null): TempUrlLocalStorageGenerator
|
||||
{
|
||||
return new TempUrlLocalStorageGenerator(
|
||||
|
@@ -31,20 +31,6 @@ use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
*/
|
||||
final class StoredObjectManagerTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @dataProvider getDataProviderForRead
|
||||
*/
|
||||
public function testRead(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null)
|
||||
{
|
||||
if (null !== $exceptionClass) {
|
||||
$this->expectException($exceptionClass);
|
||||
}
|
||||
|
||||
$storedObjectManager = $this->getSubject($storedObject, $encodedContent);
|
||||
|
||||
self::assertEquals($clearContent, $storedObjectManager->read($storedObject));
|
||||
}
|
||||
|
||||
public static function getDataProviderForRead(): \Generator
|
||||
{
|
||||
/* HAPPY SCENARIO */
|
||||
@@ -110,40 +96,6 @@ final class StoredObjectManagerTest extends TestCase
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getDataProviderForWrite
|
||||
*/
|
||||
public function testWrite(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null, ?int $errorCode = null)
|
||||
{
|
||||
if (null !== $exceptionClass) {
|
||||
$this->expectException($exceptionClass);
|
||||
}
|
||||
|
||||
$previousVersion = $storedObject->getCurrentVersion();
|
||||
$previousFilename = $previousVersion->getFilename();
|
||||
|
||||
$client = new MockHttpClient(function ($method, $url, $options) use ($encodedContent, $previousFilename, $errorCode) {
|
||||
self::assertEquals('PUT', $method);
|
||||
self::assertStringStartsWith('https://example.com/', $url);
|
||||
self::assertStringNotContainsString($previousFilename, $url, 'test that the PUT operation is not performed on the same file');
|
||||
self::assertArrayHasKey('body', $options);
|
||||
self::assertEquals($encodedContent, $options['body']);
|
||||
|
||||
if (-1 === $errorCode) {
|
||||
throw new TransportException();
|
||||
}
|
||||
|
||||
return new MockResponse('', ['http_code' => $errorCode ?? 201]);
|
||||
});
|
||||
|
||||
$storedObjectManager = new StoredObjectManager($client, $this->getTempUrlGenerator($storedObject));
|
||||
|
||||
$newVersion = $storedObjectManager->write($storedObject, $clearContent);
|
||||
|
||||
self::assertNotSame($previousVersion, $newVersion);
|
||||
self::assertSame($storedObject->getCurrentVersion(), $newVersion);
|
||||
}
|
||||
|
||||
public static function getDataProviderForWrite(): \Generator
|
||||
{
|
||||
/* HAPPY SCENARIO */
|
||||
@@ -198,6 +150,54 @@ final class StoredObjectManagerTest extends TestCase
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getDataProviderForRead
|
||||
*/
|
||||
public function testRead(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null)
|
||||
{
|
||||
if (null !== $exceptionClass) {
|
||||
$this->expectException($exceptionClass);
|
||||
}
|
||||
|
||||
$storedObjectManager = $this->getSubject($storedObject, $encodedContent);
|
||||
|
||||
self::assertEquals($clearContent, $storedObjectManager->read($storedObject));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider getDataProviderForWrite
|
||||
*/
|
||||
public function testWrite(StoredObject $storedObject, string $encodedContent, string $clearContent, ?string $exceptionClass = null, ?int $errorCode = null)
|
||||
{
|
||||
if (null !== $exceptionClass) {
|
||||
$this->expectException($exceptionClass);
|
||||
}
|
||||
|
||||
$previousVersion = $storedObject->getCurrentVersion();
|
||||
$previousFilename = $previousVersion->getFilename();
|
||||
|
||||
$client = new MockHttpClient(function ($method, $url, $options) use ($encodedContent, $previousFilename, $errorCode) {
|
||||
self::assertEquals('PUT', $method);
|
||||
self::assertStringStartsWith('https://example.com/', $url);
|
||||
self::assertStringNotContainsString($previousFilename, $url, 'test that the PUT operation is not performed on the same file');
|
||||
self::assertArrayHasKey('body', $options);
|
||||
self::assertEquals($encodedContent, $options['body']);
|
||||
|
||||
if (-1 === $errorCode) {
|
||||
throw new TransportException();
|
||||
}
|
||||
|
||||
return new MockResponse('', ['http_code' => $errorCode ?? 201]);
|
||||
});
|
||||
|
||||
$storedObjectManager = new StoredObjectManager($client, $this->getTempUrlGenerator($storedObject));
|
||||
|
||||
$newVersion = $storedObjectManager->write($storedObject, $clearContent);
|
||||
|
||||
self::assertNotSame($previousVersion, $newVersion);
|
||||
self::assertSame($storedObject->getCurrentVersion(), $newVersion);
|
||||
}
|
||||
|
||||
public function testDelete(): void
|
||||
{
|
||||
$storedObject = new StoredObject();
|
||||
|
@@ -82,38 +82,6 @@ class TempUrlOpenstackGeneratorTest extends KernelTestCase
|
||||
self::assertEquals($expected, $signedUrl);
|
||||
}
|
||||
|
||||
public static function dataProviderGenerate(): iterable
|
||||
{
|
||||
$now = \DateTimeImmutable::createFromFormat('U', '1702041743');
|
||||
$expireDelay = 1800;
|
||||
$baseUrls = [
|
||||
'https://objectstore.example/v1/my_account/container/',
|
||||
'https://objectstore.example/v1/my_account/container',
|
||||
];
|
||||
$objectName = 'object';
|
||||
$method = 'GET';
|
||||
$key = 'MYKEY';
|
||||
|
||||
$signedUrl = new SignedUrl(
|
||||
'GET',
|
||||
'https://objectstore.example/v1/my_account/container/object?temp_url_sig=0aeef353a5f6e22d125c76c6ad8c644a59b222ba1b13eaeb56bf3d04e28b081d11dfcb36601ab3aa7b623d79e1ef03017071bbc842fb7b34afec2baff895bf80&temp_url_expires=1702043543',
|
||||
\DateTimeImmutable::createFromFormat('U', '1702043543'),
|
||||
$objectName
|
||||
);
|
||||
|
||||
foreach ($baseUrls as $baseUrl) {
|
||||
yield [
|
||||
$baseUrl,
|
||||
$now,
|
||||
$key,
|
||||
$method,
|
||||
$objectName,
|
||||
$expireDelay,
|
||||
$signedUrl,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider dataProviderGeneratePost
|
||||
*/
|
||||
@@ -157,6 +125,38 @@ class TempUrlOpenstackGeneratorTest extends KernelTestCase
|
||||
self::assertGreaterThanOrEqual(20, strlen($signedUrl->prefix));
|
||||
}
|
||||
|
||||
public static function dataProviderGenerate(): iterable
|
||||
{
|
||||
$now = \DateTimeImmutable::createFromFormat('U', '1702041743');
|
||||
$expireDelay = 1800;
|
||||
$baseUrls = [
|
||||
'https://objectstore.example/v1/my_account/container/',
|
||||
'https://objectstore.example/v1/my_account/container',
|
||||
];
|
||||
$objectName = 'object';
|
||||
$method = 'GET';
|
||||
$key = 'MYKEY';
|
||||
|
||||
$signedUrl = new SignedUrl(
|
||||
'GET',
|
||||
'https://objectstore.example/v1/my_account/container/object?temp_url_sig=0aeef353a5f6e22d125c76c6ad8c644a59b222ba1b13eaeb56bf3d04e28b081d11dfcb36601ab3aa7b623d79e1ef03017071bbc842fb7b34afec2baff895bf80&temp_url_expires=1702043543',
|
||||
\DateTimeImmutable::createFromFormat('U', '1702043543'),
|
||||
$objectName
|
||||
);
|
||||
|
||||
foreach ($baseUrls as $baseUrl) {
|
||||
yield [
|
||||
$baseUrl,
|
||||
$now,
|
||||
$key,
|
||||
$method,
|
||||
$objectName,
|
||||
$expireDelay,
|
||||
$signedUrl,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function dataProviderGeneratePost(): iterable
|
||||
{
|
||||
$now = \DateTimeImmutable::createFromFormat('U', '1702041743');
|
||||
|
@@ -61,55 +61,6 @@ class StoredObjectContentToLocalStorageControllerTest extends TestCase
|
||||
$controller->contentOperate($request);
|
||||
}
|
||||
|
||||
public static function generateOperateContentWithExceptionDataProvider(): iterable
|
||||
{
|
||||
yield [
|
||||
new Request(['object_name' => '', 'sig' => '', 'exp' => 0]),
|
||||
BadRequestHttpException::class,
|
||||
'Object name parameter is missing',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '', 'exp' => 0]),
|
||||
BadRequestHttpException::class,
|
||||
'Expiration is not set or equal to zero',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
BadRequestHttpException::class,
|
||||
'Signature is not set or is a blank string',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '1234', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
AccessDeniedHttpException::class,
|
||||
'Invalid signature',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '1234', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
NotFoundHttpException::class,
|
||||
'Object does not exists on disk',
|
||||
false,
|
||||
'',
|
||||
true,
|
||||
];
|
||||
}
|
||||
|
||||
public function testOperateContentGetHappyScenario(): void
|
||||
{
|
||||
$objectName = 'testABC';
|
||||
@@ -335,4 +286,53 @@ class StoredObjectContentToLocalStorageControllerTest extends TestCase
|
||||
'Filename does not start with signed prefix',
|
||||
];
|
||||
}
|
||||
|
||||
public static function generateOperateContentWithExceptionDataProvider(): iterable
|
||||
{
|
||||
yield [
|
||||
new Request(['object_name' => '', 'sig' => '', 'exp' => 0]),
|
||||
BadRequestHttpException::class,
|
||||
'Object name parameter is missing',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '', 'exp' => 0]),
|
||||
BadRequestHttpException::class,
|
||||
'Expiration is not set or equal to zero',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
BadRequestHttpException::class,
|
||||
'Signature is not set or is a blank string',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '1234', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
AccessDeniedHttpException::class,
|
||||
'Invalid signature',
|
||||
false,
|
||||
'',
|
||||
false,
|
||||
];
|
||||
|
||||
|
||||
yield [
|
||||
new Request(['object_name' => 'testABC', 'sig' => '1234', 'exp' => (new \DateTimeImmutable())->getTimestamp()]),
|
||||
NotFoundHttpException::class,
|
||||
'Object does not exists on disk',
|
||||
false,
|
||||
'',
|
||||
true,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
@@ -136,6 +136,63 @@ class WebdavControllerTest extends KernelTestCase
|
||||
self::assertXmlStringEqualsXmlString($expectedXmlResponse, $response->getContent(), $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateDataPropfindDirectory
|
||||
*/
|
||||
public function testPropfindDirectory(string $requestContent, int $expectedStatusCode, string $expectedXmlResponse, string $message): void
|
||||
{
|
||||
$controller = $this->buildController();
|
||||
|
||||
$request = new Request([], [], [], [], [], [], $requestContent);
|
||||
$request->setMethod('PROPFIND');
|
||||
$request->headers->add(['Depth' => '0']);
|
||||
$response = $controller->propfindDirectory($this->buildDocument(), '1234', $request);
|
||||
|
||||
self::assertEquals($expectedStatusCode, $response->getStatusCode());
|
||||
self::assertContains('content-type', $response->headers->keys());
|
||||
self::assertStringContainsString('text/xml', $response->headers->get('content-type'));
|
||||
self::assertTrue((new \DOMDocument())->loadXML($response->getContent()), $message.' test that the xml response is a valid xml');
|
||||
self::assertXmlStringEqualsXmlString($expectedXmlResponse, $response->getContent(), $message);
|
||||
}
|
||||
|
||||
public function testHeadDocument(): void
|
||||
{
|
||||
$controller = $this->buildController();
|
||||
$response = $controller->headDocument($this->buildDocument());
|
||||
|
||||
self::assertEquals(200, $response->getStatusCode());
|
||||
self::assertContains('content-length', $response->headers->keys());
|
||||
self::assertContains('content-type', $response->headers->keys());
|
||||
self::assertContains('etag', $response->headers->keys());
|
||||
self::assertEquals('ab56b4d92b40713acc5af89985d4b786', $response->headers->get('etag'));
|
||||
self::assertEquals('application/vnd.oasis.opendocument.text', $response->headers->get('content-type'));
|
||||
self::assertEquals(5, $response->headers->get('content-length'));
|
||||
}
|
||||
|
||||
public function testPutDocument(): void
|
||||
{
|
||||
$document = $this->buildDocument();
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$storedObjectManager = $this->createMock(StoredObjectManagerInterface::class);
|
||||
|
||||
// entity manager must be flushed
|
||||
$entityManager->expects($this->once())
|
||||
->method('flush');
|
||||
|
||||
// object must be written by StoredObjectManager
|
||||
$storedObjectManager->expects($this->once())
|
||||
->method('write')
|
||||
->with($this->identicalTo($document), $this->identicalTo('1234'));
|
||||
|
||||
$controller = $this->buildController($entityManager, $storedObjectManager);
|
||||
|
||||
$request = new Request(content: '1234');
|
||||
$response = $controller->putDocument($document, $request);
|
||||
|
||||
self::assertEquals(204, $response->getStatusCode());
|
||||
self::assertEquals('', $response->getContent());
|
||||
}
|
||||
|
||||
public static function generateDataPropfindDocument(): iterable
|
||||
{
|
||||
$content =
|
||||
@@ -290,25 +347,6 @@ class WebdavControllerTest extends KernelTestCase
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider generateDataPropfindDirectory
|
||||
*/
|
||||
public function testPropfindDirectory(string $requestContent, int $expectedStatusCode, string $expectedXmlResponse, string $message): void
|
||||
{
|
||||
$controller = $this->buildController();
|
||||
|
||||
$request = new Request([], [], [], [], [], [], $requestContent);
|
||||
$request->setMethod('PROPFIND');
|
||||
$request->headers->add(['Depth' => '0']);
|
||||
$response = $controller->propfindDirectory($this->buildDocument(), '1234', $request);
|
||||
|
||||
self::assertEquals($expectedStatusCode, $response->getStatusCode());
|
||||
self::assertContains('content-type', $response->headers->keys());
|
||||
self::assertStringContainsString('text/xml', $response->headers->get('content-type'));
|
||||
self::assertTrue((new \DOMDocument())->loadXML($response->getContent()), $message.' test that the xml response is a valid xml');
|
||||
self::assertXmlStringEqualsXmlString($expectedXmlResponse, $response->getContent(), $message);
|
||||
}
|
||||
|
||||
public static function generateDataPropfindDirectory(): iterable
|
||||
{
|
||||
yield [
|
||||
@@ -376,44 +414,6 @@ class WebdavControllerTest extends KernelTestCase
|
||||
'test creatableContentsInfo',
|
||||
];
|
||||
}
|
||||
|
||||
public function testHeadDocument(): void
|
||||
{
|
||||
$controller = $this->buildController();
|
||||
$response = $controller->headDocument($this->buildDocument());
|
||||
|
||||
self::assertEquals(200, $response->getStatusCode());
|
||||
self::assertContains('content-length', $response->headers->keys());
|
||||
self::assertContains('content-type', $response->headers->keys());
|
||||
self::assertContains('etag', $response->headers->keys());
|
||||
self::assertEquals('ab56b4d92b40713acc5af89985d4b786', $response->headers->get('etag'));
|
||||
self::assertEquals('application/vnd.oasis.opendocument.text', $response->headers->get('content-type'));
|
||||
self::assertEquals(5, $response->headers->get('content-length'));
|
||||
}
|
||||
|
||||
public function testPutDocument(): void
|
||||
{
|
||||
$document = $this->buildDocument();
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$storedObjectManager = $this->createMock(StoredObjectManagerInterface::class);
|
||||
|
||||
// entity manager must be flushed
|
||||
$entityManager->expects($this->once())
|
||||
->method('flush');
|
||||
|
||||
// object must be written by StoredObjectManager
|
||||
$storedObjectManager->expects($this->once())
|
||||
->method('write')
|
||||
->with($this->identicalTo($document), $this->identicalTo('1234'));
|
||||
|
||||
$controller = $this->buildController($entityManager, $storedObjectManager);
|
||||
|
||||
$request = new Request(content: '1234');
|
||||
$response = $controller->putDocument($document, $request);
|
||||
|
||||
self::assertEquals(204, $response->getStatusCode());
|
||||
self::assertEquals('', $response->getContent());
|
||||
}
|
||||
}
|
||||
|
||||
class MockedStoredObjectManager implements StoredObjectManagerInterface
|
||||
|
@@ -87,16 +87,6 @@ class PersonDocumentACLAwareRepositoryTest extends KernelTestCase
|
||||
self::assertIsInt($nb, 'test that the query could be executed');
|
||||
}
|
||||
|
||||
public static function provideDataBuildFetchQueryForPerson(): iterable
|
||||
{
|
||||
yield [null, null, null];
|
||||
yield [new \DateTimeImmutable('1 year ago'), null, null];
|
||||
yield [null, new \DateTimeImmutable('1 year ago'), null];
|
||||
yield [new \DateTimeImmutable('2 years ago'), new \DateTimeImmutable('1 year ago'), null];
|
||||
yield [null, null, 'test'];
|
||||
yield [new \DateTimeImmutable('2 years ago'), new \DateTimeImmutable('1 year ago'), 'test'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider provideDateForFetchQueryForAccompanyingPeriod
|
||||
*/
|
||||
@@ -152,4 +142,14 @@ class PersonDocumentACLAwareRepositoryTest extends KernelTestCase
|
||||
yield [$period, null, null, 'test'];
|
||||
yield [$period, new \DateTimeImmutable('2 years ago'), new \DateTimeImmutable('1 year ago'), 'test'];
|
||||
}
|
||||
|
||||
public static function provideDataBuildFetchQueryForPerson(): iterable
|
||||
{
|
||||
yield [null, null, null];
|
||||
yield [new \DateTimeImmutable('1 year ago'), null, null];
|
||||
yield [null, new \DateTimeImmutable('1 year ago'), null];
|
||||
yield [new \DateTimeImmutable('2 years ago'), new \DateTimeImmutable('1 year ago'), null];
|
||||
yield [null, null, 'test'];
|
||||
yield [new \DateTimeImmutable('2 years ago'), new \DateTimeImmutable('1 year ago'), 'test'];
|
||||
}
|
||||
}
|
||||
|
@@ -50,6 +50,19 @@ class StoredObjectVoterTest extends TestCase
|
||||
self::assertEquals($expected, $voter->vote($token, $subject, [$attribute]));
|
||||
}
|
||||
|
||||
private function buildStoredObjectVoter(bool $supportsIsCalled, bool $supports, bool $voteOnAttribute): StoredObjectVoterInterface
|
||||
{
|
||||
$storedObjectVoter = $this->createMock(StoredObjectVoterInterface::class);
|
||||
$storedObjectVoter->expects($supportsIsCalled ? $this->once() : $this->never())->method('supports')
|
||||
->with(self::isInstanceOf(StoredObjectRoleEnum::class), $this->isInstanceOf(StoredObject::class))
|
||||
->willReturn($supports);
|
||||
$storedObjectVoter->expects($supportsIsCalled && $supports ? $this->once() : $this->never())->method('voteOnAttribute')
|
||||
->with(self::isInstanceOf(StoredObjectRoleEnum::class), $this->isInstanceOf(StoredObject::class), $this->isInstanceOf(TokenInterface::class))
|
||||
->willReturn($voteOnAttribute);
|
||||
|
||||
return $storedObjectVoter;
|
||||
}
|
||||
|
||||
public static function provideDataVote(): iterable
|
||||
{
|
||||
yield [
|
||||
@@ -107,17 +120,4 @@ class StoredObjectVoterTest extends TestCase
|
||||
VoterInterface::ACCESS_GRANTED,
|
||||
];
|
||||
}
|
||||
|
||||
private function buildStoredObjectVoter(bool $supportsIsCalled, bool $supports, bool $voteOnAttribute): StoredObjectVoterInterface
|
||||
{
|
||||
$storedObjectVoter = $this->createMock(StoredObjectVoterInterface::class);
|
||||
$storedObjectVoter->expects($supportsIsCalled ? $this->once() : $this->never())->method('supports')
|
||||
->with(self::isInstanceOf(StoredObjectRoleEnum::class), $this->isInstanceOf(StoredObject::class))
|
||||
->willReturn($supports);
|
||||
$storedObjectVoter->expects($supportsIsCalled && $supports ? $this->once() : $this->never())->method('voteOnAttribute')
|
||||
->with(self::isInstanceOf(StoredObjectRoleEnum::class), $this->isInstanceOf(StoredObject::class), $this->isInstanceOf(TokenInterface::class))
|
||||
->willReturn($voteOnAttribute);
|
||||
|
||||
return $storedObjectVoter;
|
||||
}
|
||||
}
|
||||
|
@@ -40,29 +40,6 @@ class RemoveOldVersionCronJobTest extends KernelTestCase
|
||||
self::assertEquals($expected, $cronJob->canRun($cronJobExecution));
|
||||
}
|
||||
|
||||
public static function buildTestCanRunData(): iterable
|
||||
{
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-31 00:00:00', new \DateTimeZone('+00:00'))),
|
||||
true,
|
||||
];
|
||||
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-30 23:59:59', new \DateTimeZone('+00:00'))),
|
||||
true,
|
||||
];
|
||||
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-31 00:00:01', new \DateTimeZone('+00:00'))),
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
null,
|
||||
true,
|
||||
];
|
||||
}
|
||||
|
||||
public function testRun(): void
|
||||
{
|
||||
// we create a clock in the future. This led us a chance to having stored object to delete
|
||||
@@ -86,6 +63,29 @@ class RemoveOldVersionCronJobTest extends KernelTestCase
|
||||
self::assertIsInt($results['last-deleted-stored-object-version-id']);
|
||||
}
|
||||
|
||||
public static function buildTestCanRunData(): iterable
|
||||
{
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-31 00:00:00', new \DateTimeZone('+00:00'))),
|
||||
true,
|
||||
];
|
||||
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-30 23:59:59', new \DateTimeZone('+00:00'))),
|
||||
true,
|
||||
];
|
||||
|
||||
yield [
|
||||
(new CronJobExecution('last-deleted-stored-object-version-id'))->setLastEnd(new \DateTimeImmutable('2023-12-31 00:00:01', new \DateTimeZone('+00:00'))),
|
||||
false,
|
||||
];
|
||||
|
||||
yield [
|
||||
null,
|
||||
true,
|
||||
];
|
||||
}
|
||||
|
||||
private function buildMessageBus(bool $expectDistpatchAtLeastOnce = false): MessageBusInterface
|
||||
{
|
||||
$messageBus = $this->createMock(MessageBusInterface::class);
|
||||
|
@@ -48,6 +48,30 @@ class EventTypeController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a EventType entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/event_type/{id}/delete', name: 'chill_eventtype_admin_delete', methods: ['POST', 'DELETE'])]
|
||||
public function deleteAction(Request $request, mixed $id)
|
||||
{
|
||||
$form = $this->createDeleteForm($id);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$em = $this->managerRegistry->getManager();
|
||||
$entity = $em->getRepository(EventType::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find EventType entity.');
|
||||
}
|
||||
|
||||
$em->remove($entity);
|
||||
$em->flush();
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('chill_eventtype_admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a form to edit an existing EventType entity.
|
||||
*/
|
||||
@@ -63,10 +87,12 @@ class EventTypeController extends AbstractController
|
||||
}
|
||||
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/EventType/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -100,6 +126,28 @@ class EventTypeController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and displays a EventType entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/event_type/{id}/show', name: 'chill_eventtype_admin_show')]
|
||||
public function showAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(EventType::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find EventType entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/EventType/show.html.twig', [
|
||||
'entity' => $entity,
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an existing EventType entity.
|
||||
*/
|
||||
@@ -114,6 +162,7 @@ class EventTypeController extends AbstractController
|
||||
throw $this->createNotFoundException('Unable to find EventType entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$editForm->handleRequest($request);
|
||||
|
||||
@@ -126,6 +175,7 @@ class EventTypeController extends AbstractController
|
||||
return $this->render('@ChillEvent/EventType/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -148,6 +198,22 @@ class EventTypeController extends AbstractController
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to delete a EventType entity by id.
|
||||
*
|
||||
* @return \Symfony\Component\Form\FormInterface The form
|
||||
*/
|
||||
private function createDeleteForm(mixed $id)
|
||||
{
|
||||
return $this->createFormBuilder()
|
||||
->setAction($this->generateUrl(
|
||||
'chill_eventtype_admin_delete',
|
||||
['id' => $id]
|
||||
))
|
||||
->add('submit', SubmitType::class, ['label' => 'Delete'])
|
||||
->getForm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to edit a EventType entity.
|
||||
*
|
||||
@@ -162,7 +228,7 @@ class EventTypeController extends AbstractController
|
||||
'chill_eventtype_admin_update',
|
||||
['id' => $entity->getId()]
|
||||
),
|
||||
'method' => 'POST',
|
||||
'method' => 'PUT',
|
||||
]);
|
||||
|
||||
$form->add('submit', SubmitType::class, ['label' => 'Update']);
|
||||
|
@@ -48,6 +48,30 @@ class RoleController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a Role entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/role/{id}/delete', name: 'chill_event_admin_role_delete', methods: ['POST', 'DELETE'])]
|
||||
public function deleteAction(Request $request, mixed $id)
|
||||
{
|
||||
$form = $this->createDeleteForm($id);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$em = $this->managerRegistry->getManager();
|
||||
$entity = $em->getRepository(Role::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find Role entity.');
|
||||
}
|
||||
|
||||
$em->remove($entity);
|
||||
$em->flush();
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('chill_event_admin_role');
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a form to edit an existing Role entity.
|
||||
*/
|
||||
@@ -63,10 +87,12 @@ class RoleController extends AbstractController
|
||||
}
|
||||
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/Role/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -100,6 +126,28 @@ class RoleController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and displays a Role entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/role/{id}/show', name: 'chill_event_admin_role_show')]
|
||||
public function showAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(Role::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find Role entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/Role/show.html.twig', [
|
||||
'entity' => $entity,
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an existing Role entity.
|
||||
*/
|
||||
@@ -114,6 +162,7 @@ class RoleController extends AbstractController
|
||||
throw $this->createNotFoundException('Unable to find Role entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$editForm->handleRequest($request);
|
||||
|
||||
@@ -126,6 +175,7 @@ class RoleController extends AbstractController
|
||||
return $this->render('@ChillEvent/Role/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -148,6 +198,20 @@ class RoleController extends AbstractController
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to delete a Role entity by id.
|
||||
*
|
||||
* @return \Symfony\Component\Form\FormInterface The form
|
||||
*/
|
||||
private function createDeleteForm(mixed $id)
|
||||
{
|
||||
return $this->createFormBuilder()
|
||||
->setAction($this->generateUrl('chill_event_admin_role_delete', ['id' => $id]))
|
||||
->setMethod('DELETE')
|
||||
->add('submit', SubmitType::class, ['label' => 'Delete'])
|
||||
->getForm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to edit a Role entity.
|
||||
*
|
||||
@@ -162,7 +226,7 @@ class RoleController extends AbstractController
|
||||
'chill_event_admin_role_update',
|
||||
['id' => $entity->getId()]
|
||||
),
|
||||
'method' => 'POST',
|
||||
'method' => 'PUT',
|
||||
]);
|
||||
|
||||
$form->add('submit', SubmitType::class, ['label' => 'Update']);
|
||||
|
@@ -48,6 +48,30 @@ class StatusController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a Status entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/status/{id}/delete', name: 'chill_event_admin_status_delete', methods: ['POST', 'DELETE'])]
|
||||
public function deleteAction(Request $request, mixed $id)
|
||||
{
|
||||
$form = $this->createDeleteForm($id);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$em = $this->managerRegistry->getManager();
|
||||
$entity = $em->getRepository(Status::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find Status entity.');
|
||||
}
|
||||
|
||||
$em->remove($entity);
|
||||
$em->flush();
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('chill_event_admin_status');
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a form to edit an existing Status entity.
|
||||
*/
|
||||
@@ -63,10 +87,12 @@ class StatusController extends AbstractController
|
||||
}
|
||||
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/Status/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -100,6 +126,28 @@ class StatusController extends AbstractController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and displays a Status entity.
|
||||
*/
|
||||
#[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/admin/event/status/{id}/show', name: 'chill_event_admin_status_show')]
|
||||
public function showAction(mixed $id)
|
||||
{
|
||||
$em = $this->managerRegistry->getManager();
|
||||
|
||||
$entity = $em->getRepository(Status::class)->find($id);
|
||||
|
||||
if (!$entity) {
|
||||
throw $this->createNotFoundException('Unable to find Status entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
|
||||
return $this->render('@ChillEvent/Status/show.html.twig', [
|
||||
'entity' => $entity,
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits an existing Status entity.
|
||||
*/
|
||||
@@ -114,6 +162,7 @@ class StatusController extends AbstractController
|
||||
throw $this->createNotFoundException('Unable to find Status entity.');
|
||||
}
|
||||
|
||||
$deleteForm = $this->createDeleteForm($id);
|
||||
$editForm = $this->createEditForm($entity);
|
||||
$editForm->handleRequest($request);
|
||||
|
||||
@@ -126,6 +175,7 @@ class StatusController extends AbstractController
|
||||
return $this->render('@ChillEvent/Status/edit.html.twig', [
|
||||
'entity' => $entity,
|
||||
'edit_form' => $editForm->createView(),
|
||||
'delete_form' => $deleteForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -148,6 +198,19 @@ class StatusController extends AbstractController
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to delete a Status entity by id.
|
||||
*
|
||||
* @return \Symfony\Component\Form\FormInterface The form
|
||||
*/
|
||||
private function createDeleteForm(mixed $id)
|
||||
{
|
||||
return $this->createFormBuilder()
|
||||
->setAction($this->generateUrl('chill_event_admin_status_delete', ['id' => $id]))
|
||||
->add('submit', SubmitType::class, ['label' => 'Delete'])
|
||||
->getForm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form to edit a Status entity.
|
||||
*
|
||||
@@ -159,7 +222,7 @@ class StatusController extends AbstractController
|
||||
{
|
||||
$form = $this->createForm(StatusType::class, $entity, [
|
||||
'action' => $this->generateUrl('chill_event_admin_status_update', ['id' => $entity->getId()]),
|
||||
'method' => 'POST',
|
||||
'method' => 'PUT',
|
||||
]);
|
||||
|
||||
$form->add('submit', SubmitType::class, ['label' => 'Update']);
|
||||
|
@@ -54,14 +54,14 @@ block js %}
|
||||
{% if e.participations|length > 0 %}
|
||||
<div class="item-row separator">
|
||||
<strong>{{ "Participations" | trans }} : </strong>
|
||||
{% for part in e.participations|slice(0, 5) %} {% include
|
||||
{% for part in e.participations|slice(0, 20) %} {% include
|
||||
'@ChillMain/OnTheFly/_insert_vue_onthefly.html.twig' with {
|
||||
targetEntity: { name: 'person', id: part.person.id }, action:
|
||||
'show', displayBadge: true, buttonText:
|
||||
part.person|chill_entity_render_string, isDead:
|
||||
part.person.deathdate is not null } %} {% endfor %}
|
||||
{% if e.participations|length > 5 %}
|
||||
{{ 'events.and_other_count_participants'|trans({'count': e.participations|length - 5}) }}
|
||||
part.person.deathdate is not null } %} {% endfor %} {% if
|
||||
e.participations|length > 20 %}
|
||||
{{ 'events.and_other_count_participants'|trans({'count': e.participations|length - 20}) }}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
@@ -8,7 +8,7 @@
|
||||
{{ form_row(edit_form.name) }}
|
||||
{{ form_row(edit_form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_eventtype_admin') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
|
@@ -16,11 +16,14 @@
|
||||
<tbody>
|
||||
{% for entity in entities %}
|
||||
<tr>
|
||||
<td>{{ entity.id }}</a></td>
|
||||
<td><a href="{{ path('chill_eventtype_admin_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>
|
||||
<td>{{ entity.name|localize_translatable_string }}</td>
|
||||
<td><i class="fa {% if entity.active %}fa-check-square-o{% else %}fa-square-o{% endif %}"></i></td>
|
||||
<td>{{ entity.active }}</td>
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ path('chill_eventtype_admin_show', { 'id': entity.id }) }}" class="btn btn-show" title="{{ 'show'|trans }}"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_eventtype_admin_edit', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
</li>
|
||||
|
@@ -8,7 +8,7 @@
|
||||
{{ form_row(form.name) }}
|
||||
{{ form_row(form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_eventtype_admin') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
|
@@ -21,12 +21,17 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_eventtype_admin') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_eventtype_admin_edit', { 'id': entity.id }) }}" class="btn btn-edit">{{ 'Edit'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ form_start(delete_form) }}
|
||||
{{ form_row(delete_form.submit, { 'attr': { 'class' : 'btn btn-delete' }}) }}
|
||||
{{ form_end(delete_form) }}
|
||||
</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
@@ -8,12 +8,12 @@
|
||||
{{ form_row(edit_form.type) }}
|
||||
{{ form_row(edit_form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_role') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ form_row(edit_form.submit, { 'attr': { 'class' : 'btn btn-update' }}) }}
|
||||
{{ form_row(edit_form.submit, { 'attr': { 'class' : 'btn btn-edit' }}) }}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
@@ -17,12 +17,15 @@
|
||||
<tbody>
|
||||
{% for entity in entities %}
|
||||
<tr>
|
||||
<td>{{ entity.id }}</a></td>
|
||||
<td><a href="{{ path('chill_event_admin_role_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>
|
||||
<td>{{ entity.name|localize_translatable_string }}</td>
|
||||
<td>{{ entity.type.name|localize_translatable_string }}</td>
|
||||
<td><i class="fa {% if entity.active %}fa-check-square-o{% else %}fa-square-o{% endif %}"></i></td>
|
||||
<td>{{ entity.active }}</td>
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_role_show', { 'id': entity.id }) }}" class="btn btn-show" title="{{ 'show'|trans }}"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_role_edit', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
</li>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
{{ form_row(form.type) }}
|
||||
{{ form_row(form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_role') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
|
@@ -25,12 +25,17 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_role') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_role_edit', { 'id': entity.id }) }}" class="btn btn-edit">{{ 'Edit'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ form_start(delete_form) }}
|
||||
{{ form_row(delete_form.submit, { 'attr': { 'class' : 'btn btn-delete' }}) }}
|
||||
{{ form_end(delete_form) }}
|
||||
</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
@@ -9,7 +9,7 @@
|
||||
{{ form_row(edit_form.type) }}
|
||||
{{ form_row(edit_form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_status') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
|
@@ -17,12 +17,15 @@
|
||||
<tbody>
|
||||
{% for entity in entities %}
|
||||
<tr>
|
||||
<td>{{ entity.id }}</a></td>
|
||||
<td><a href="{{ path('chill_event_admin_status_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>
|
||||
<td>{{ entity.name|localize_translatable_string }}</td>
|
||||
<td>{{ entity.type.name|localize_translatable_string }}</td>
|
||||
<td><i class="fa {% if entity.active %}fa-check-square-o{% else %}fa-square-o{% endif %}"></i></td>
|
||||
<td>{{ entity.active }}</td>
|
||||
<td>
|
||||
<ul class="record_actions">
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_status_show', { 'id': entity.id }) }}" class="btn btn-show" title="{{ 'show'|trans }}"></a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_status_edit', { 'id': entity.id }) }}" class="btn btn-edit" title="{{ 'edit'|trans }}"></a>
|
||||
</li>
|
||||
|
@@ -9,7 +9,7 @@
|
||||
{{ form_row(form.type) }}
|
||||
{{ form_row(form.active) }}
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_status') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
|
@@ -25,12 +25,17 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<ul class="record_actions sticky-form-buttons">
|
||||
<ul class="record_actions">
|
||||
<li class="cancel">
|
||||
<a href="{{ path('chill_event_admin_status') }}" class="btn btn-cancel">{{ 'Back to the list'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="{{ path('chill_event_admin_status_edit', { 'id': entity.id }) }}" class="btn btn-edit">{{ 'Edit'|trans }}</a>
|
||||
</li>
|
||||
<li>
|
||||
{{ form_start(delete_form) }}
|
||||
{{ form_row(delete_form.submit, { 'attr': { 'class' : 'btn btn-delete' }}) }}
|
||||
{{ form_end(delete_form) }}
|
||||
</li>
|
||||
</ul>
|
||||
{% endblock %}
|
||||
|
@@ -20,7 +20,6 @@ use Chill\MainBundle\DependencyInjection\CompilerPass\SearchableServicesCompiler
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\TimelineCompilerClass;
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\WidgetsCompilerPass;
|
||||
use Chill\MainBundle\DependencyInjection\ConfigConsistencyCompilerPass;
|
||||
use Chill\MainBundle\Notification\FlagProviders\NotificationFlagProviderInterface;
|
||||
use Chill\MainBundle\Notification\NotificationHandlerInterface;
|
||||
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
|
||||
use Chill\MainBundle\Search\SearchApiInterface;
|
||||
@@ -62,8 +61,6 @@ class ChillMainBundle extends Bundle
|
||||
->addTag('chill_main.entity_info_provider');
|
||||
$container->registerForAutoconfiguration(ProvideRoleInterface::class)
|
||||
->addTag('chill_main.provide_role');
|
||||
$container->registerForAutoconfiguration(NotificationFlagProviderInterface::class)
|
||||
->addTag('chill_main.notification_flag_provider');
|
||||
|
||||
$container->addCompilerPass(new SearchableServicesCompilerPass(), \Symfony\Component\DependencyInjection\Compiler\PassConfig::TYPE_BEFORE_OPTIMIZATION, 0);
|
||||
$container->addCompilerPass(new ConfigConsistencyCompilerPass(), \Symfony\Component\DependencyInjection\Compiler\PassConfig::TYPE_BEFORE_OPTIMIZATION, 0);
|
||||
|
@@ -149,7 +149,7 @@ class ExportController extends AbstractController
|
||||
->createNamedBuilder(
|
||||
'',
|
||||
FormType::class,
|
||||
'centers' === $step ? ['centers' => $defaultFormData] : $defaultFormData,
|
||||
$defaultFormData,
|
||||
[
|
||||
'method' => $isGenerate ? Request::METHOD_GET : Request::METHOD_POST,
|
||||
'csrf_protection' => !$isGenerate,
|
||||
@@ -352,7 +352,7 @@ class ExportController extends AbstractController
|
||||
$formCenters->submit($dataCenters);
|
||||
$dataAsCollection = $formCenters->getData()['centers'];
|
||||
$centers = $dataAsCollection['centers'];
|
||||
$regroupments = $dataAsCollection['regroupments'] ?? [];
|
||||
$regroupments = $dataAsCollection['regroupments'];
|
||||
$dataCenters = [
|
||||
'centers' => $centers instanceof Collection ? $centers->toArray() : $centers,
|
||||
'regroupments' => $regroupments instanceof Collection ? $regroupments->toArray() : $regroupments,
|
||||
@@ -377,7 +377,7 @@ class ExportController extends AbstractController
|
||||
}
|
||||
|
||||
return [
|
||||
'centers' => ['centers' => $dataCenters['centers'], 'regroupments' => $dataCenters['regroupments']],
|
||||
'centers' => ['centers' => $dataCenters['centers'], 'regroupments' => $dataCenters['regroupments'] ?? []],
|
||||
'export' => $dataExport['export']['export'] ?? [],
|
||||
'filters' => $dataExport['export']['filters'] ?? [],
|
||||
'aggregators' => $dataExport['export']['aggregators'] ?? [],
|
||||
@@ -404,12 +404,7 @@ class ExportController extends AbstractController
|
||||
/** @var ExportManager $exportManager */
|
||||
$exportManager = $this->exportManager;
|
||||
|
||||
$form = $this->createCreateFormExport(
|
||||
$alias,
|
||||
'centers',
|
||||
$this->exportFormHelper->getDefaultData('centers', $export, []),
|
||||
$savedExport
|
||||
);
|
||||
$form = $this->createCreateFormExport($alias, 'centers', [], $savedExport);
|
||||
|
||||
if (Request::METHOD_POST === $request->getMethod()) {
|
||||
$form->handleRequest($request);
|
||||
|
@@ -16,7 +16,6 @@ use Chill\MainBundle\Entity\NotificationComment;
|
||||
use Chill\MainBundle\Form\NotificationCommentType;
|
||||
use Chill\MainBundle\Form\NotificationType;
|
||||
use Chill\MainBundle\Notification\Exception\NotificationHandlerNotFound;
|
||||
use Chill\MainBundle\Notification\FlagProviders\NotificationByUserFlagProvider;
|
||||
use Chill\MainBundle\Notification\NotificationHandlerManager;
|
||||
use Chill\MainBundle\Pagination\PaginatorFactory;
|
||||
use Chill\MainBundle\Repository\NotificationRepository;
|
||||
@@ -58,8 +57,7 @@ class NotificationController extends AbstractController
|
||||
$notification
|
||||
->setRelatedEntityClass($request->query->get('entityClass'))
|
||||
->setRelatedEntityId($request->query->getInt('entityId'))
|
||||
->setSender($this->security->getUser())
|
||||
->setType(NotificationByUserFlagProvider::FLAG);
|
||||
->setSender($this->security->getUser());
|
||||
|
||||
$tos = $request->query->all('tos');
|
||||
|
||||
|
@@ -11,11 +11,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace Chill\MainBundle\Controller;
|
||||
|
||||
use Chill\MainBundle\Form\UserProfileType;
|
||||
use Chill\MainBundle\Form\UserPhonenumberType;
|
||||
use Chill\MainBundle\Security\ChillSecurity;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
|
||||
@@ -38,19 +41,16 @@ final class UserProfileController extends AbstractController
|
||||
}
|
||||
|
||||
$user = $this->security->getUser();
|
||||
$editForm = $this->createForm(UserProfileType::class, $user);
|
||||
|
||||
$editForm->get('notificationFlags')->setData($user->getNotificationFlags());
|
||||
|
||||
$editForm = $this->createPhonenumberEditForm($user);
|
||||
$editForm->handleRequest($request);
|
||||
|
||||
if ($editForm->isSubmitted() && $editForm->isValid()) {
|
||||
$notificationFlagsData = $editForm->get('notificationFlags')->getData();
|
||||
$user->setNotificationFlags($notificationFlagsData);
|
||||
$phonenumber = $editForm->get('phonenumber')->getData();
|
||||
|
||||
$em = $this->managerRegistry->getManager();
|
||||
$em->flush();
|
||||
$this->addFlash('success', $this->translator->trans('user.profile.Profile successfully updated!'));
|
||||
$user->setPhonenumber($phonenumber);
|
||||
|
||||
$this->managerRegistry->getManager()->flush();
|
||||
$this->addFlash('success', $this->translator->trans('user.profile.Phonenumber successfully updated!'));
|
||||
|
||||
return $this->redirectToRoute('chill_main_user_profile');
|
||||
}
|
||||
@@ -60,4 +60,13 @@ final class UserProfileController extends AbstractController
|
||||
'form' => $editForm->createView(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function createPhonenumberEditForm(UserInterface $user): FormInterface
|
||||
{
|
||||
return $this->createForm(
|
||||
UserPhonenumberType::class,
|
||||
$user,
|
||||
)
|
||||
->add('submit', SubmitType::class, ['label' => $this->translator->trans('Save')]);
|
||||
}
|
||||
}
|
||||
|
@@ -11,10 +11,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Chill\MainBundle\DataFixtures\ORM;
|
||||
|
||||
use Chill\MainBundle\Entity\Center;
|
||||
use Chill\MainBundle\Entity\GroupCenter;
|
||||
use Chill\MainBundle\Entity\PermissionsGroup;
|
||||
use Chill\MainBundle\Entity\RoleScope;
|
||||
use Chill\MainBundle\Entity\User;
|
||||
use Doctrine\Common\DataFixtures\AbstractFixture;
|
||||
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
|
||||
@@ -65,15 +62,6 @@ class LoadUsers extends AbstractFixture implements ContainerAwareInterface, Orde
|
||||
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
$roleScope = new RoleScope();
|
||||
$roleScope->setRole('CHILL_MAIN_COMPOSE_EXPORT');
|
||||
$permissionGroup = new PermissionsGroup();
|
||||
$permissionGroup->setName('export');
|
||||
$permissionGroup->addRoleScope($roleScope);
|
||||
|
||||
$manager->persist($roleScope);
|
||||
$manager->persist($permissionGroup);
|
||||
|
||||
foreach (self::$refs as $username => $params) {
|
||||
$user = new User();
|
||||
|
||||
@@ -93,14 +81,7 @@ class LoadUsers extends AbstractFixture implements ContainerAwareInterface, Orde
|
||||
->setEmail(sprintf('%s@chill.social', \str_replace(' ', '', (string) $username)));
|
||||
|
||||
foreach ($params['groupCenterRefs'] as $groupCenterRef) {
|
||||
$user->addGroupCenter($gc = $this->getReference($groupCenterRef, GroupCenter::class));
|
||||
|
||||
$exportGroupCenter = new GroupCenter();
|
||||
$exportGroupCenter->setPermissionsGroup($permissionGroup);
|
||||
$exportGroupCenter->setCenter($gc->getCenter());
|
||||
$manager->persist($exportGroupCenter);
|
||||
|
||||
$user->addGroupCenter($exportGroupCenter);
|
||||
$user->addGroupCenter($this->getReference($groupCenterRef, GroupCenter::class));
|
||||
}
|
||||
|
||||
echo 'Creating user '.$username."... \n";
|
||||
|
@@ -70,9 +70,9 @@ class NewsItem implements TrackCreationInterface, TrackUpdateInterface
|
||||
return $this->content;
|
||||
}
|
||||
|
||||
public function setContent(?string $content): void
|
||||
public function setContent(string $content): void
|
||||
{
|
||||
$this->content = (string) $content;
|
||||
$this->content = $content;
|
||||
}
|
||||
|
||||
public function getStartDate(): ?\DateTimeImmutable
|
||||
|
@@ -14,7 +14,6 @@ namespace Chill\MainBundle\Entity;
|
||||
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
@@ -22,10 +21,10 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
#[ORM\Entity]
|
||||
#[ORM\HasLifecycleCallbacks]
|
||||
#[ORM\Table(name: 'chill_main_notification')]
|
||||
#[ORM\Index(columns: ['relatedentityclass', 'relatedentityid'], name: 'chill_main_notification_related_entity_idx')]
|
||||
#[ORM\Index(name: 'chill_main_notification_related_entity_idx', columns: ['relatedentityclass', 'relatedentityid'])]
|
||||
class Notification implements TrackUpdateInterface
|
||||
{
|
||||
#[ORM\Column(type: Types::TEXT, nullable: false)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, nullable: false)]
|
||||
private string $accessKey;
|
||||
|
||||
private array $addedAddresses = [];
|
||||
@@ -37,19 +36,12 @@ class Notification implements TrackUpdateInterface
|
||||
#[ORM\JoinTable(name: 'chill_main_notification_addresses_user')]
|
||||
private Collection $addressees;
|
||||
|
||||
/**
|
||||
* @var Collection<int, UserGroup>
|
||||
*/
|
||||
#[ORM\ManyToMany(targetEntity: UserGroup::class)]
|
||||
#[ORM\JoinTable(name: 'chill_main_notification_addressee_user_group')]
|
||||
private Collection $addresseeUserGroups;
|
||||
|
||||
/**
|
||||
* a list of destinee which will receive notifications.
|
||||
*
|
||||
* @var array|string[]
|
||||
*/
|
||||
#[ORM\Column(type: Types::JSON, options: ['default' => '[]', 'jsonb' => true])]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::JSON, options: ['default' => '[]', 'jsonb' => true])]
|
||||
private array $addressesEmails = [];
|
||||
|
||||
/**
|
||||
@@ -68,21 +60,21 @@ class Notification implements TrackUpdateInterface
|
||||
#[ORM\OrderBy(['createdAt' => \Doctrine\Common\Collections\Criteria::ASC])]
|
||||
private Collection $comments;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::DATETIME_IMMUTABLE)]
|
||||
private \DateTimeImmutable $date;
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: Types::INTEGER)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: Types::TEXT)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT)]
|
||||
private string $message = '';
|
||||
|
||||
#[ORM\Column(type: Types::STRING, length: 255)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::STRING, length: 255)]
|
||||
private string $relatedEntityClass = '';
|
||||
|
||||
#[ORM\Column(type: Types::INTEGER)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::INTEGER)]
|
||||
private int $relatedEntityId;
|
||||
|
||||
private array $removedAddresses = [];
|
||||
@@ -92,7 +84,7 @@ class Notification implements TrackUpdateInterface
|
||||
private ?User $sender = null;
|
||||
|
||||
#[Assert\NotBlank(message: 'notification.Title must be defined')]
|
||||
#[ORM\Column(type: Types::TEXT, options: ['default' => ''])]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::TEXT, options: ['default' => ''])]
|
||||
private string $title = '';
|
||||
|
||||
/**
|
||||
@@ -102,46 +94,31 @@ class Notification implements TrackUpdateInterface
|
||||
#[ORM\JoinTable(name: 'chill_main_notification_addresses_unread')]
|
||||
private Collection $unreadBy;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE)]
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::DATETIME_IMMUTABLE)]
|
||||
private ?\DateTimeImmutable $updatedAt = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: User::class)]
|
||||
private ?User $updatedBy = null;
|
||||
|
||||
#[ORM\Column(name: 'type', type: Types::STRING, nullable: true)]
|
||||
private string $type = '';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->addressees = new ArrayCollection();
|
||||
$this->addresseeUserGroups = new ArrayCollection();
|
||||
$this->unreadBy = new ArrayCollection();
|
||||
$this->comments = new ArrayCollection();
|
||||
$this->setDate(new \DateTimeImmutable());
|
||||
$this->accessKey = bin2hex(openssl_random_pseudo_bytes(24));
|
||||
}
|
||||
|
||||
public function addAddressee(User|UserGroup $addressee): self
|
||||
public function addAddressee(User $addressee): self
|
||||
{
|
||||
if ($addressee instanceof User) {
|
||||
if (!$this->addressees->contains($addressee)) {
|
||||
$this->addressees->add($addressee);
|
||||
$this->addressees[] = $addressee;
|
||||
$this->addedAddresses[] = $addressee;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (!$this->addresseeUserGroups->contains($addressee)) {
|
||||
$this->addresseeUserGroups->add($addressee);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
public function addAddressesEmail(string $email)
|
||||
{
|
||||
if (!\in_array($email, $this->addressesEmails, true)) {
|
||||
@@ -175,23 +152,13 @@ class Notification implements TrackUpdateInterface
|
||||
#[Assert\Callback]
|
||||
public function assertCountAddresses(ExecutionContextInterface $context, $payload): void
|
||||
{
|
||||
if (0 === (\count($this->getAddresseeUserGroups()) + \count($this->getAddressees()))) {
|
||||
if (0 === (\count($this->getAddressesEmails()) + \count($this->getAddressees()))) {
|
||||
$context->buildViolation('notification.At least one addressee')
|
||||
->atPath('addressees')
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
|
||||
public function getAddresseeUserGroups(): Collection
|
||||
{
|
||||
return $this->addresseeUserGroups;
|
||||
}
|
||||
|
||||
public function setAddresseeUserGroups(Collection $addresseeUserGroups): void
|
||||
{
|
||||
$this->addresseeUserGroups = $addresseeUserGroups;
|
||||
}
|
||||
|
||||
public function getAccessKey(): string
|
||||
{
|
||||
return $this->accessKey;
|
||||
@@ -215,23 +182,6 @@ class Notification implements TrackUpdateInterface
|
||||
return $this->addressees;
|
||||
}
|
||||
|
||||
public function getAllAddressees(): array
|
||||
{
|
||||
$allUsers = [];
|
||||
|
||||
foreach ($this->getAddressees() as $user) {
|
||||
$allUsers[$user->getId()] = $user;
|
||||
}
|
||||
|
||||
foreach ($this->getAddresseeUserGroups() as $userGroup) {
|
||||
foreach ($userGroup->getUsers() as $user) {
|
||||
$allUsers[$user->getId()] = $user;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($allUsers);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|string[]
|
||||
*/
|
||||
@@ -353,17 +303,11 @@ class Notification implements TrackUpdateInterface
|
||||
$this->addressesOnLoad = null;
|
||||
}
|
||||
|
||||
public function removeAddressee(User|UserGroup $addressee): self
|
||||
public function removeAddressee(User $addressee): self
|
||||
{
|
||||
if ($addressee instanceof User) {
|
||||
if ($this->addressees->contains($addressee)) {
|
||||
$this->addressees->removeElement($addressee);
|
||||
|
||||
return $this;
|
||||
if ($this->addressees->removeElement($addressee)) {
|
||||
$this->removedAddresses[] = $addressee;
|
||||
}
|
||||
}
|
||||
|
||||
$this->addresseeUserGroups->removeElement($addressee);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -434,7 +378,7 @@ class Notification implements TrackUpdateInterface
|
||||
|
||||
public function setUpdatedAt(\DateTimeInterface $datetime): self
|
||||
{
|
||||
$this->updatedAt = \DateTimeImmutable::createFromInterface($datetime);
|
||||
$this->updatedAt = $datetime;
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -445,16 +389,4 @@ class Notification implements TrackUpdateInterface
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setType(string $type): self
|
||||
{
|
||||
$this->type = $type;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
}
|
||||
|
@@ -176,14 +176,6 @@ class SavedExport implements TrackCreationInterface, TrackUpdateInterface
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if shared with at least one user or one group.
|
||||
*/
|
||||
public function isShared(): bool
|
||||
{
|
||||
return $this->sharedWithUsers->count() > 0 || $this->sharedWithGroups->count() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the user is shared with either directly or through a group.
|
||||
*
|
||||
|
@@ -34,9 +34,6 @@ use Chill\MainBundle\Validation\Constraint\PhonenumberConstraint;
|
||||
#[ORM\Table(name: 'users')]
|
||||
class User implements UserInterface, \Stringable, PasswordAuthenticatedUserInterface
|
||||
{
|
||||
public const NOTIF_FLAG_IMMEDIATE_EMAIL = 'immediate-email';
|
||||
public const NOTIF_FLAG_DAILY_DIGEST = 'daily-digest';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\Column(name: 'id', type: \Doctrine\DBAL\Types\Types::INTEGER)]
|
||||
#[ORM\GeneratedValue(strategy: 'AUTO')]
|
||||
@@ -119,12 +116,6 @@ class User implements UserInterface, \Stringable, PasswordAuthenticatedUserInter
|
||||
#[PhonenumberConstraint]
|
||||
private ?PhoneNumber $phonenumber = null;
|
||||
|
||||
/**
|
||||
* @var array<string, list<string>>
|
||||
*/
|
||||
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::JSON, nullable: false, options: ['default' => '[]', 'jsonb' => true])]
|
||||
private array $notificationFlags = [];
|
||||
|
||||
/**
|
||||
* User constructor.
|
||||
*/
|
||||
@@ -622,57 +613,4 @@ class User implements UserInterface, \Stringable, PasswordAuthenticatedUserInter
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current object is an instance of User.
|
||||
*
|
||||
* @return bool returns true if the current object is an instance of User, false otherwise
|
||||
*/
|
||||
public function isUser(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getNotificationFlags(): array
|
||||
{
|
||||
return $this->notificationFlags;
|
||||
}
|
||||
|
||||
public function setNotificationFlags(array $notificationFlags)
|
||||
{
|
||||
$this->notificationFlags = $notificationFlags;
|
||||
}
|
||||
|
||||
public function getNotificationFlagData(string $flag): array
|
||||
{
|
||||
return $this->notificationFlags[$flag] ?? [];
|
||||
}
|
||||
|
||||
public function setNotificationFlagData(string $flag, array $data): void
|
||||
{
|
||||
$this->notificationFlags[$flag] = $data;
|
||||
}
|
||||
|
||||
public function isNotificationSendImmediately(string $type): bool
|
||||
{
|
||||
if ([] === $this->getNotificationFlagData($type) || in_array(User::NOTIF_FLAG_IMMEDIATE_EMAIL, $this->getNotificationFlagData($type), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isNotificationDailyDigest(string $type): bool
|
||||
{
|
||||
if (in_array(User::NOTIF_FLAG_DAILY_DIGEST, $this->getNotificationFlagData($type), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getLocale(): string
|
||||
{
|
||||
return 'fr';
|
||||
}
|
||||
}
|
||||
|
@@ -147,12 +147,12 @@ final readonly class ExportFormHelper
|
||||
*/
|
||||
public function getPickedCenters(array $data): array
|
||||
{
|
||||
if (!array_key_exists('centers', $data)) {
|
||||
if (!array_key_exists('centers', $data) || !array_key_exists('regroupments', $data)) {
|
||||
throw new \RuntimeException('array has not the expected shape');
|
||||
}
|
||||
|
||||
$centers = $data['centers'] instanceof Collection ? $data['centers']->toArray() : $data['centers'];
|
||||
$regroupments = ($data['regroupments'] ?? []) instanceof Collection ? $data['regroupments']->toArray() : ($data['regroupments'] ?? []);
|
||||
$regroupments = $data['regroupments'] instanceof Collection ? $data['regroupments']->toArray() : $data['regroupments'];
|
||||
|
||||
return $this->centerRegroupementResolver->resolveCenters($regroupments, $centers);
|
||||
}
|
||||
|
@@ -144,9 +144,11 @@ class ExportManager
|
||||
/**
|
||||
* @param string $alias
|
||||
*
|
||||
* @return AggregatorInterface
|
||||
*
|
||||
* @throws \RuntimeException if the aggregator is not known
|
||||
*/
|
||||
public function getAggregator($alias): AggregatorInterface
|
||||
public function getAggregator($alias)
|
||||
{
|
||||
if (null === $aggregator = $this->aggregators[$alias] ?? null) {
|
||||
throw new \RuntimeException("The aggregator with alias {$alias} is not known.");
|
||||
|
241
src/Bundle/ChillMainBundle/Export/Formatter/CSVListFormatter.php
Normal file
241
src/Bundle/ChillMainBundle/Export/Formatter/CSVListFormatter.php
Normal file
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Export\Formatter;
|
||||
|
||||
use Chill\MainBundle\Export\ExportGenerationContext;
|
||||
use Chill\MainBundle\Export\ExportManagerAwareInterface;
|
||||
use Chill\MainBundle\Export\FormatterInterface;
|
||||
use Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Contracts\Translation\TranslatableInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use function count;
|
||||
|
||||
// command to get the report with curl : curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
|
||||
|
||||
/**
|
||||
* Create a CSV List for the export.
|
||||
*/
|
||||
class CSVListFormatter implements FormatterInterface, ExportManagerAwareInterface
|
||||
{
|
||||
use ExportManagerAwareTrait;
|
||||
|
||||
protected $exportAlias;
|
||||
|
||||
protected $exportData;
|
||||
|
||||
|
||||
protected $formatterData;
|
||||
|
||||
/**
|
||||
* This variable cache the labels internally.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $labelsCache;
|
||||
|
||||
protected $result;
|
||||
|
||||
/**
|
||||
* @var TranslatorInterface
|
||||
*/
|
||||
protected $translator;
|
||||
|
||||
public function __construct(TranslatorInterface $translatorInterface)
|
||||
{
|
||||
$this->translator = $translatorInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* build a form, which will be used to collect data required for the execution
|
||||
* of this formatter.
|
||||
*
|
||||
* @uses appendAggregatorForm
|
||||
*
|
||||
* @param type $exportAlias
|
||||
*/
|
||||
public function buildForm(
|
||||
FormBuilderInterface $builder,
|
||||
$exportAlias,
|
||||
array $aggregatorAliases,
|
||||
): void {
|
||||
$builder->add('numerotation', ChoiceType::class, [
|
||||
'choices' => [
|
||||
'yes' => true,
|
||||
'no' => false,
|
||||
],
|
||||
'expanded' => true,
|
||||
'multiple' => false,
|
||||
'label' => 'Add a number on first column',
|
||||
]);
|
||||
}
|
||||
|
||||
public function getNormalizationVersion(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function normalizeFormData(array $formData): array
|
||||
{
|
||||
return ['numerotation' => $formData['numerotation']];
|
||||
}
|
||||
|
||||
public function denormalizeFormData(array $formData, int $fromVersion): array
|
||||
{
|
||||
return ['numerotation' => $formData['numerotation']];
|
||||
}
|
||||
|
||||
public function getFormDefaultData(array $aggregatorAliases): array
|
||||
{
|
||||
return ['numerotation' => true];
|
||||
}
|
||||
|
||||
public function getName(): string|TranslatableInterface
|
||||
{
|
||||
return 'CSV vertical list';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a response from the data collected on differents ExportElementInterface.
|
||||
*
|
||||
* @param mixed[] $result The result, as given by the ExportInterface
|
||||
* @param mixed[] $formatterData collected from the current form
|
||||
* @param string $exportAlias the id of the current export
|
||||
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
|
||||
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
|
||||
*
|
||||
* @return Response The response to be shown
|
||||
*/
|
||||
public function getResponse(
|
||||
$result,
|
||||
$formatterData,
|
||||
$exportAlias,
|
||||
array $exportData,
|
||||
array $filtersData,
|
||||
array $aggregatorsData,
|
||||
ExportGenerationContext $context,
|
||||
) {
|
||||
$this->result = $result;
|
||||
$this->exportAlias = $exportAlias;
|
||||
$this->exportData = $exportData;
|
||||
$this->formatterData = $formatterData;
|
||||
|
||||
$output = fopen('php://output', 'wb');
|
||||
|
||||
$this->prepareHeaders($output);
|
||||
|
||||
$i = 1;
|
||||
|
||||
foreach ($result as $row) {
|
||||
$line = [];
|
||||
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$line[] = $i;
|
||||
}
|
||||
|
||||
foreach ($row as $key => $value) {
|
||||
$line[] = $this->getLabel($key, $value);
|
||||
}
|
||||
|
||||
fputcsv($output, $line);
|
||||
|
||||
++$i;
|
||||
}
|
||||
|
||||
$csvContent = stream_get_contents($output);
|
||||
fclose($output);
|
||||
|
||||
$response = new Response();
|
||||
$response->setStatusCode(200);
|
||||
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
|
||||
// $response->headers->set('Content-Disposition','attachment; filename="export.csv"');
|
||||
|
||||
$response->setContent($csvContent);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return FormatterInterface::TYPE_LIST;
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the label corresponding to the given key and value.
|
||||
*
|
||||
* @param string $key
|
||||
* @param string $value
|
||||
*
|
||||
* @throws \LogicException if the label is not found
|
||||
*/
|
||||
protected function getLabel($key, $value)
|
||||
{
|
||||
if (null === $this->labelsCache) {
|
||||
$this->prepareCacheLabels();
|
||||
}
|
||||
|
||||
if (!\array_key_exists($key, $this->labelsCache)) {
|
||||
throw new \OutOfBoundsException(sprintf('The key "%s" is not present in the list of keys handled by this query. Check your `getKeys` and `getLabels` methods. Available keys are %s.', $key, \implode(', ', \array_keys($this->labelsCache))));
|
||||
}
|
||||
|
||||
return $this->labelsCache[$key]($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the label cache which will be used by getLabel. This function
|
||||
* should be called only once in the generation lifecycle.
|
||||
*/
|
||||
protected function prepareCacheLabels()
|
||||
{
|
||||
$export = $this->getExportManager()->getExport($this->exportAlias);
|
||||
$keys = $export->getQueryKeys($this->exportData);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
// get an array with all values for this key if possible
|
||||
$values = \array_map(static fn ($v) => $v[$key], $this->result);
|
||||
// store the label in the labelsCache property
|
||||
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add the headers to the csv file.
|
||||
*
|
||||
* @param resource $output
|
||||
*/
|
||||
protected function prepareHeaders($output)
|
||||
{
|
||||
$keys = $this->getExportManager()->getExport($this->exportAlias)->getQueryKeys($this->exportData);
|
||||
// we want to keep the order of the first row. So we will iterate on the first row of the results
|
||||
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
|
||||
$header_line = [];
|
||||
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$header_line[] = $this->translator->trans('Number');
|
||||
}
|
||||
|
||||
foreach ($first_row as $key => $value) {
|
||||
$content = $this->getLabel($key, '_header');
|
||||
if ($content instanceof TranslatableInterface) {
|
||||
$header_line[] = $content->trans($this->translator, $this->translator->getLocale());
|
||||
} else {
|
||||
$header_line[] = $this->translator->trans($this->getLabel($key, '_header'));
|
||||
}
|
||||
}
|
||||
|
||||
if (\count($header_line) > 0) {
|
||||
fputcsv($output, $header_line);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Export\Formatter;
|
||||
|
||||
use Chill\MainBundle\Export\ExportGenerationContext;
|
||||
use Chill\MainBundle\Export\ExportManagerAwareInterface;
|
||||
use Chill\MainBundle\Export\FormatterInterface;
|
||||
use Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/**
|
||||
* Create a CSV List for the export where the header are printed on the
|
||||
* first column, and the result goes from left to right.
|
||||
*/
|
||||
class CSVPivotedListFormatter implements FormatterInterface, ExportManagerAwareInterface
|
||||
{
|
||||
use ExportManagerAwareTrait;
|
||||
|
||||
protected $exportAlias;
|
||||
|
||||
protected $exportData;
|
||||
|
||||
protected $formatterData;
|
||||
|
||||
/**
|
||||
* This variable cache the labels internally.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $labelsCache;
|
||||
|
||||
protected $result;
|
||||
|
||||
/**
|
||||
* @var TranslatorInterface
|
||||
*/
|
||||
protected $translator;
|
||||
|
||||
public function __construct(TranslatorInterface $translatorInterface)
|
||||
{
|
||||
$this->translator = $translatorInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* build a form, which will be used to collect data required for the execution
|
||||
* of this formatter.
|
||||
*
|
||||
* @uses appendAggregatorForm
|
||||
*
|
||||
* @param type $exportAlias
|
||||
*/
|
||||
public function buildForm(
|
||||
FormBuilderInterface $builder,
|
||||
$exportAlias,
|
||||
array $aggregatorAliases,
|
||||
): void {
|
||||
$builder->add('numerotation', ChoiceType::class, [
|
||||
'choices' => [
|
||||
'yes' => true,
|
||||
'no' => false,
|
||||
],
|
||||
'expanded' => true,
|
||||
'multiple' => false,
|
||||
'label' => 'Add a number on first column',
|
||||
'data' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public function getNormalizationVersion(): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public function normalizeFormData(array $formData): array
|
||||
{
|
||||
return ['numerotation' => $formData['numerotation']];
|
||||
}
|
||||
|
||||
public function denormalizeFormData(array $formData, int $fromVersion): array
|
||||
{
|
||||
return ['numerotation' => $formData['numerotation']];
|
||||
}
|
||||
|
||||
public function getFormDefaultData(array $aggregatorAliases): array
|
||||
{
|
||||
return ['numerotation' => true];
|
||||
}
|
||||
|
||||
public function getName(): string|\Symfony\Contracts\Translation\TranslatableInterface
|
||||
{
|
||||
return 'CSV horizontal list';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a response from the data collected on differents ExportElementInterface.
|
||||
*
|
||||
* @param mixed[] $result The result, as given by the ExportInterface
|
||||
* @param mixed[] $formatterData collected from the current form
|
||||
* @param string $exportAlias the id of the current export
|
||||
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
|
||||
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
|
||||
*
|
||||
* @return Response The response to be shown
|
||||
*/
|
||||
public function getResponse(
|
||||
$result,
|
||||
$formatterData,
|
||||
$exportAlias,
|
||||
array $exportData,
|
||||
array $filtersData,
|
||||
array $aggregatorsData,
|
||||
ExportGenerationContext $context,
|
||||
) {
|
||||
$this->result = $result;
|
||||
$this->exportAlias = $exportAlias;
|
||||
$this->exportData = $exportData;
|
||||
$this->formatterData = $formatterData;
|
||||
|
||||
$output = fopen('php://output', 'wb');
|
||||
|
||||
$i = 1;
|
||||
$lines = [];
|
||||
$this->prepareHeaders($lines);
|
||||
|
||||
foreach ($result as $row) {
|
||||
$j = 0;
|
||||
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$lines[$j][] = $i;
|
||||
++$j;
|
||||
}
|
||||
|
||||
foreach ($row as $key => $value) {
|
||||
$lines[$j][] = $this->getLabel($key, $value);
|
||||
++$j;
|
||||
}
|
||||
++$i;
|
||||
}
|
||||
|
||||
// adding the lines to the csv output
|
||||
foreach ($lines as $line) {
|
||||
fputcsv($output, $line);
|
||||
}
|
||||
|
||||
$csvContent = stream_get_contents($output);
|
||||
fclose($output);
|
||||
|
||||
$response = new Response();
|
||||
$response->setStatusCode(200);
|
||||
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
|
||||
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
|
||||
|
||||
$response->setContent($csvContent);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return FormatterInterface::TYPE_LIST;
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the label corresponding to the given key and value.
|
||||
*
|
||||
* @param string $key
|
||||
* @param string $value
|
||||
*
|
||||
* @throws \LogicException if the label is not found
|
||||
*/
|
||||
protected function getLabel($key, $value)
|
||||
{
|
||||
if (null === $this->labelsCache) {
|
||||
$this->prepareCacheLabels();
|
||||
}
|
||||
|
||||
return $this->labelsCache[$key]($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the label cache which will be used by getLabel. This function
|
||||
* should be called only once in the generation lifecycle.
|
||||
*/
|
||||
protected function prepareCacheLabels()
|
||||
{
|
||||
$export = $this->getExportManager()->getExport($this->exportAlias);
|
||||
$keys = $export->getQueryKeys($this->exportData);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
// get an array with all values for this key if possible
|
||||
$values = \array_map(static fn ($v) => $v[$key], $this->result);
|
||||
// store the label in the labelsCache property
|
||||
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add the headers to lines array.
|
||||
*
|
||||
* @param array $lines the lines where the header will be added
|
||||
*/
|
||||
protected function prepareHeaders(array &$lines)
|
||||
{
|
||||
$keys = $this->exportManager->getExport($this->exportAlias)->getQueryKeys($this->exportData);
|
||||
// we want to keep the order of the first row. So we will iterate on the first row of the results
|
||||
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
|
||||
$header_line = [];
|
||||
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$lines[] = [$this->translator->trans('Number')];
|
||||
}
|
||||
|
||||
foreach ($first_row as $key => $value) {
|
||||
$lines[] = [$this->getLabel($key, '_header')];
|
||||
}
|
||||
}
|
||||
}
|
@@ -12,25 +12,110 @@ declare(strict_types=1);
|
||||
namespace Chill\MainBundle\Export\Formatter;
|
||||
|
||||
use Chill\MainBundle\Export\ExportGenerationContext;
|
||||
use Chill\MainBundle\Export\ExportInterface;
|
||||
use Chill\MainBundle\Export\ExportManagerAwareInterface;
|
||||
use Chill\MainBundle\Export\FormattedExportGeneration;
|
||||
use Chill\MainBundle\Export\FormatterInterface;
|
||||
use Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\FormType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Contracts\Translation\TranslatableInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwareInterface
|
||||
class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwareInterface
|
||||
{
|
||||
use ExportManagerAwareTrait;
|
||||
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
/**
|
||||
* an array where keys are the aggregators aliases and
|
||||
* values are the data.
|
||||
*
|
||||
* replaced when `getResponse` is called.
|
||||
*/
|
||||
protected array $aggregatorsData;
|
||||
|
||||
/**
|
||||
* The export.
|
||||
*
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var \Chill\MainBundle\Export\ExportInterface
|
||||
*/
|
||||
protected $export;
|
||||
|
||||
|
||||
/**
|
||||
* array containing value of export form.
|
||||
*
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $exportData;
|
||||
|
||||
/**
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $filtersData;
|
||||
|
||||
/**
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $formatterData;
|
||||
|
||||
/**
|
||||
* The result, as returned by the export.
|
||||
*
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $result;
|
||||
|
||||
/**
|
||||
* replaced when `getResponse` is called.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
// protected $labels;
|
||||
|
||||
/**
|
||||
* temporary file to store spreadsheet.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $tempfile;
|
||||
|
||||
/**
|
||||
* @var TranslatorInterface
|
||||
*/
|
||||
protected $translator;
|
||||
|
||||
/**
|
||||
* cache for displayable result.
|
||||
*
|
||||
* This cache is reset when `getResponse` is called.
|
||||
*
|
||||
* The array's keys are the keys in the raw result, and
|
||||
* values are the callable which will transform the raw result to
|
||||
* displayable result.
|
||||
*/
|
||||
private ?array $cacheDisplayableResult = null;
|
||||
|
||||
/**
|
||||
* Whethe `cacheDisplayableResult` is initialized or not.
|
||||
*/
|
||||
private bool $cacheDisplayableResultIsInitialized = false;
|
||||
|
||||
public function __construct(TranslatorInterface $translatorInterface)
|
||||
{
|
||||
$this->translator = $translatorInterface;
|
||||
}
|
||||
|
||||
public function buildForm(
|
||||
FormBuilderInterface $builder,
|
||||
@@ -93,51 +178,6 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
return 'SpreadSheet (xlsx, ods)';
|
||||
}
|
||||
|
||||
public function generate(
|
||||
$result,
|
||||
$formatterData,
|
||||
string $exportAlias,
|
||||
array $exportData,
|
||||
array $filtersData,
|
||||
array $aggregatorsData,
|
||||
ExportGenerationContext $context,
|
||||
) {
|
||||
// Initialize local variables instead of class properties
|
||||
/** @var ExportInterface $export */
|
||||
$export = $this->getExportManager()->getExport($exportAlias);
|
||||
|
||||
// Initialize cache variables
|
||||
$cacheDisplayableResult = $this->initializeDisplayable($result, $export, $exportData, $aggregatorsData);
|
||||
|
||||
$tempfile = \tempnam(\sys_get_temp_dir(), '');
|
||||
|
||||
if (false === $tempfile) {
|
||||
throw new \RuntimeException('Unable to create temporary file');
|
||||
}
|
||||
|
||||
$this->generateContent(
|
||||
$context,
|
||||
$tempfile,
|
||||
$result,
|
||||
$formatterData,
|
||||
$export,
|
||||
$exportData,
|
||||
$filtersData,
|
||||
$aggregatorsData,
|
||||
$cacheDisplayableResult,
|
||||
);
|
||||
|
||||
$result = new FormattedExportGeneration(
|
||||
file_get_contents($tempfile),
|
||||
$this->getContentType($formatterData['format']),
|
||||
);
|
||||
|
||||
// remove the temp file from disk
|
||||
\unlink($tempfile);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getResponse(
|
||||
$result,
|
||||
$formatterData,
|
||||
@@ -147,10 +187,33 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
array $aggregatorsData,
|
||||
ExportGenerationContext $context,
|
||||
): Response {
|
||||
$formattedResult = $this->generate($result, $formatterData, $exportAlias, $exportData, $filtersData, $aggregatorsData, $context);
|
||||
// store all data when the process is initiated
|
||||
$this->result = $result;
|
||||
$this->formatterData = $formatterData;
|
||||
$this->export = $this->getExportManager()->getExport($exportAlias);
|
||||
$this->exportData = $exportData;
|
||||
$this->filtersData = $filtersData;
|
||||
$this->aggregatorsData = $aggregatorsData;
|
||||
|
||||
$response = new BinaryFileResponse($formattedResult->content);
|
||||
$response->headers->set('Content-Type', $formattedResult->contentType);
|
||||
// reset cache
|
||||
$this->cacheDisplayableResult = [];
|
||||
$this->cacheDisplayableResultIsInitialized = false;
|
||||
|
||||
$response = new Response();
|
||||
$response->headers->set(
|
||||
'Content-Type',
|
||||
$this->getContentType($this->formatterData['format'])
|
||||
);
|
||||
|
||||
$this->tempfile = \tempnam(\sys_get_temp_dir(), '');
|
||||
$this->generateContent($context);
|
||||
|
||||
$f = \fopen($this->tempfile, 'rb');
|
||||
$response->setContent(\stream_get_contents($f));
|
||||
fclose($f);
|
||||
|
||||
// remove the temp file from disk
|
||||
\unlink($this->tempfile);
|
||||
|
||||
return $response;
|
||||
}
|
||||
@@ -160,7 +223,7 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
return 'tabular';
|
||||
}
|
||||
|
||||
private function addContentTable(
|
||||
protected function addContentTable(
|
||||
Worksheet $worksheet,
|
||||
$sortedResults,
|
||||
$line,
|
||||
@@ -182,11 +245,11 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
*
|
||||
* @return int the line number after the last description
|
||||
*/
|
||||
private function addFiltersDescription(Worksheet &$worksheet, ExportGenerationContext $context, array $filtersData)
|
||||
protected function addFiltersDescription(Worksheet &$worksheet, ExportGenerationContext $context)
|
||||
{
|
||||
$line = 3;
|
||||
|
||||
foreach ($filtersData as $alias => $data) {
|
||||
foreach ($this->filtersData as $alias => $data) {
|
||||
$filter = $this->getExportManager()->getFilter($alias);
|
||||
$description = $filter->describeAction($data, $context);
|
||||
if (\is_array($description)) {
|
||||
@@ -211,22 +274,26 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
*
|
||||
* return the line number where the next content (i.e. result) should
|
||||
* be appended.
|
||||
*
|
||||
* @param int $line
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private function addHeaders(
|
||||
protected function addHeaders(
|
||||
Worksheet &$worksheet,
|
||||
array $globalKeys,
|
||||
int $line,
|
||||
array $cacheDisplayableResult = [],
|
||||
): int {
|
||||
$line,
|
||||
) {
|
||||
// get the displayable form of headers
|
||||
$displayables = [];
|
||||
|
||||
foreach ($globalKeys as $key) {
|
||||
$displayable = $this->getDisplayableResult($key, '_header', $cacheDisplayableResult);
|
||||
$displayable = $this->getDisplayableResult($key, '_header');
|
||||
|
||||
if ($displayable instanceof TranslatableInterface) {
|
||||
$displayables[] = $displayable->trans($this->translator, $this->translator->getLocale());
|
||||
} else {
|
||||
$displayables[] = $this->translator->trans($this->getDisplayableResult($key, '_header', $cacheDisplayableResult));
|
||||
$displayables[] = $this->translator->trans($this->getDisplayableResult($key, '_header'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,9 +311,9 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
* Add the title to the worksheet and merge the cell containing
|
||||
* the title.
|
||||
*/
|
||||
private function addTitleToWorkSheet(Worksheet &$worksheet, $export)
|
||||
protected function addTitleToWorkSheet(Worksheet &$worksheet)
|
||||
{
|
||||
$worksheet->setCellValue('A1', $this->getTitle($export));
|
||||
$worksheet->setCellValue('A1', $this->getTitle());
|
||||
$worksheet->mergeCells('A1:G1');
|
||||
}
|
||||
|
||||
@@ -255,14 +322,14 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
*
|
||||
* @return array where 1st member is spreadsheet, 2nd is worksheet
|
||||
*/
|
||||
private function createSpreadsheet($export)
|
||||
protected function createSpreadsheet()
|
||||
{
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
$worksheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
// setting the worksheet title and code name
|
||||
$worksheet
|
||||
->setTitle($this->getTitle($export))
|
||||
->setTitle($this->getTitle())
|
||||
->setCodeName('result');
|
||||
|
||||
return [$spreadsheet, $worksheet];
|
||||
@@ -271,38 +338,29 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
/**
|
||||
* Generate the content and write it to php://temp.
|
||||
*/
|
||||
private function generateContent(
|
||||
ExportGenerationContext $context,
|
||||
string $tempfile,
|
||||
$result,
|
||||
$formatterData,
|
||||
$export,
|
||||
array $exportData,
|
||||
array $filtersData,
|
||||
array $aggregatorsData,
|
||||
array $cacheDisplayableResult,
|
||||
) {
|
||||
[$spreadsheet, $worksheet] = $this->createSpreadsheet($export);
|
||||
protected function generateContent(ExportGenerationContext $context)
|
||||
{
|
||||
[$spreadsheet, $worksheet] = $this->createSpreadsheet();
|
||||
|
||||
$this->addTitleToWorkSheet($worksheet, $export);
|
||||
$line = $this->addFiltersDescription($worksheet, $context, $filtersData);
|
||||
$this->addTitleToWorkSheet($worksheet);
|
||||
$line = $this->addFiltersDescription($worksheet, $context);
|
||||
|
||||
// at this point, we are going to sort results for an easier manipulation
|
||||
// at this point, we are going to sort retsults for an easier manipulation
|
||||
[$sortedResult, $exportKeys, $aggregatorKeys, $globalKeys] =
|
||||
$this->sortResult($result, $export, $exportData, $aggregatorsData, $formatterData, $cacheDisplayableResult);
|
||||
$this->sortResult();
|
||||
|
||||
$line = $this->addHeaders($worksheet, $globalKeys, $line, $cacheDisplayableResult);
|
||||
$line = $this->addHeaders($worksheet, $globalKeys, $line);
|
||||
|
||||
$this->addContentTable($worksheet, $sortedResult, $line);
|
||||
$line = $this->addContentTable($worksheet, $sortedResult, $line);
|
||||
|
||||
$writer = match ($formatterData['format']) {
|
||||
$writer = match ($this->formatterData['format']) {
|
||||
'ods' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Ods'),
|
||||
'xlsx' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'),
|
||||
'csv' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv'),
|
||||
default => throw new \LogicException(),
|
||||
};
|
||||
|
||||
$writer->save($tempfile);
|
||||
$writer->save($this->tempfile);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,7 +369,7 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
*
|
||||
* @return string[] an array containing the keys of aggregators
|
||||
*/
|
||||
private function getAggregatorKeysSorted(array $aggregatorsData, array $formatterData)
|
||||
protected function getAggregatorKeysSorted()
|
||||
{
|
||||
// empty array for aggregators keys
|
||||
$keys = [];
|
||||
@@ -319,7 +377,7 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
// during sorting
|
||||
$aggregatorKeyAssociation = [];
|
||||
|
||||
foreach ($aggregatorsData as $alias => $data) {
|
||||
foreach ($this->aggregatorsData as $alias => $data) {
|
||||
$aggregator = $this->exportManager->getAggregator($alias);
|
||||
$aggregatorsKeys = $aggregator->getQueryKeys($data);
|
||||
// append the keys from aggregator to the $keys existing array
|
||||
@@ -331,9 +389,9 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
}
|
||||
|
||||
// sort the result using the form
|
||||
usort($keys, function ($a, $b) use ($aggregatorKeyAssociation, $formatterData) {
|
||||
$A = $formatterData[$aggregatorKeyAssociation[$a]]['order'];
|
||||
$B = $formatterData[$aggregatorKeyAssociation[$b]]['order'];
|
||||
usort($keys, function ($a, $b) use ($aggregatorKeyAssociation) {
|
||||
$A = $this->formatterData[$aggregatorKeyAssociation[$a]]['order'];
|
||||
$B = $this->formatterData[$aggregatorKeyAssociation[$b]]['order'];
|
||||
|
||||
if ($A === $B) {
|
||||
return 0;
|
||||
@@ -349,7 +407,7 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
return $keys;
|
||||
}
|
||||
|
||||
private function getContentType($format)
|
||||
protected function getContentType($format)
|
||||
{
|
||||
switch ($format) {
|
||||
case 'csv':
|
||||
@@ -366,20 +424,23 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
|
||||
/**
|
||||
* Get the displayable result.
|
||||
*
|
||||
* @param string $key
|
||||
*/
|
||||
private function getDisplayableResult(
|
||||
string $key,
|
||||
mixed $value,
|
||||
array $cacheDisplayableResult,
|
||||
): string|TranslatableInterface|\DateTimeInterface|int|float|bool {
|
||||
$value ??= '';
|
||||
|
||||
return \call_user_func($cacheDisplayableResult[$key], $value);
|
||||
protected function getDisplayableResult($key, mixed $value)
|
||||
{
|
||||
if (false === $this->cacheDisplayableResultIsInitialized) {
|
||||
$this->initializeCache($key);
|
||||
}
|
||||
|
||||
private function getTitle($export): string
|
||||
$value ??= '';
|
||||
|
||||
return \call_user_func($this->cacheDisplayableResult[$key], $value);
|
||||
}
|
||||
|
||||
protected function getTitle(): string
|
||||
{
|
||||
$original = $export->getTitle();
|
||||
$original = $this->export->getTitle();
|
||||
|
||||
if ($original instanceof TranslatableInterface) {
|
||||
$title = $original->trans($this->translator, $this->translator->getLocale());
|
||||
@@ -394,13 +455,8 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
return $title;
|
||||
}
|
||||
|
||||
private function initializeDisplayable(
|
||||
$result,
|
||||
ExportInterface $export,
|
||||
array $exportData,
|
||||
array $aggregatorsData,
|
||||
): array {
|
||||
$cacheDisplayableResult = [];
|
||||
protected function initializeCache($key)
|
||||
{
|
||||
/*
|
||||
* this function follows the following steps :
|
||||
*
|
||||
@@ -413,11 +469,12 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
// 1. create an associative array with key and export / aggregator
|
||||
$keysExportElementAssociation = [];
|
||||
// keys for export
|
||||
foreach ($export->getQueryKeys($exportData) as $key) {
|
||||
$keysExportElementAssociation[$key] = [$export, $exportData];
|
||||
foreach ($this->export->getQueryKeys($this->exportData) as $key) {
|
||||
$keysExportElementAssociation[$key] = [$this->export,
|
||||
$this->exportData, ];
|
||||
}
|
||||
// keys for aggregator
|
||||
foreach ($aggregatorsData as $alias => $data) {
|
||||
foreach ($this->aggregatorsData as $alias => $data) {
|
||||
$aggregator = $this->getExportManager()->getAggregator($alias);
|
||||
|
||||
foreach ($aggregator->getQueryKeys($data) as $key) {
|
||||
@@ -430,7 +487,7 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
|
||||
$allValues = [];
|
||||
// store all the values in an array
|
||||
foreach ($result as $row) {
|
||||
foreach ($this->result as $row) {
|
||||
foreach ($keys as $key) {
|
||||
$allValues[$key][] = $row[$key];
|
||||
}
|
||||
@@ -441,14 +498,15 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
foreach ($keysExportElementAssociation as $key => [$element, $data]) {
|
||||
// handle the case when there is not results lines (query is empty)
|
||||
if ([] === $allValues) {
|
||||
$cacheDisplayableResult[$key] = $element->getLabels($key, ['_header'], $data);
|
||||
$this->cacheDisplayableResult[$key] = $element->getLabels($key, ['_header'], $data);
|
||||
} else {
|
||||
$cacheDisplayableResult[$key] =
|
||||
$this->cacheDisplayableResult[$key] =
|
||||
$element->getLabels($key, \array_unique($allValues[$key]), $data);
|
||||
}
|
||||
}
|
||||
|
||||
return $cacheDisplayableResult;
|
||||
// the cache is initialized !
|
||||
$this->cacheDisplayableResultIsInitialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -486,28 +544,23 @@ final class SpreadSheetFormatter implements FormatterInterface, ExportManagerAwa
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
private function sortResult(
|
||||
$result,
|
||||
ExportInterface $export,
|
||||
array $exportData,
|
||||
array $aggregatorsData,
|
||||
array $formatterData,
|
||||
array $cacheDisplayableResult,
|
||||
) {
|
||||
protected function sortResult()
|
||||
{
|
||||
// get the keys for each row
|
||||
$exportKeys = $export->getQueryKeys($exportData);
|
||||
$aggregatorKeys = $this->getAggregatorKeysSorted($aggregatorsData, $formatterData);
|
||||
$exportKeys = $this->export->getQueryKeys($this->exportData);
|
||||
$aggregatorKeys = $this->getAggregatorKeysSorted();
|
||||
|
||||
$globalKeys = \array_merge($aggregatorKeys, $exportKeys);
|
||||
|
||||
$sortedResult = \array_map(function ($row) use ($globalKeys, $cacheDisplayableResult) {
|
||||
$sortedResult = \array_map(function ($row) use ($globalKeys) {
|
||||
$newRow = [];
|
||||
|
||||
foreach ($globalKeys as $key) {
|
||||
$newRow[] = $this->getDisplayableResult($key, $row[$key], $cacheDisplayableResult);
|
||||
$newRow[] = $this->getDisplayableResult($key, $row[$key]);
|
||||
}
|
||||
|
||||
return $newRow;
|
||||
}, $result);
|
||||
}, $this->result);
|
||||
|
||||
\array_multisort($sortedResult);
|
||||
|
||||
|
@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Export\Formatter;
|
||||
|
||||
use Chill\MainBundle\Export\ExportGenerationContext;
|
||||
use Chill\MainBundle\Export\ExportManagerAwareInterface;
|
||||
use Chill\MainBundle\Export\FormattedExportGeneration;
|
||||
use Chill\MainBundle\Export\FormatterInterface;
|
||||
use Chill\MainBundle\Export\Helper\ExportManagerAwareTrait;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date;
|
||||
@@ -22,9 +21,7 @@ use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Contracts\Translation\TranslatableInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/**
|
||||
@@ -34,17 +31,42 @@ class SpreadsheetListFormatter implements FormatterInterface, ExportManagerAware
|
||||
{
|
||||
use ExportManagerAwareTrait;
|
||||
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
protected $exportAlias;
|
||||
|
||||
protected $exportData;
|
||||
|
||||
protected $formatterData;
|
||||
|
||||
/**
|
||||
* This variable cache the labels internally.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $labelsCache;
|
||||
|
||||
protected $result;
|
||||
|
||||
/**
|
||||
* @var TranslatorInterface
|
||||
*/
|
||||
protected $translator;
|
||||
|
||||
public function __construct(TranslatorInterface $translatorInterface)
|
||||
{
|
||||
$this->translator = $translatorInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* build a form, which will be used to collect data required for the execution
|
||||
* of this formatter.
|
||||
*
|
||||
* @uses appendAggregatorForm
|
||||
*
|
||||
* @param string $exportAlias
|
||||
*/
|
||||
public function buildForm(
|
||||
FormBuilderInterface $builder,
|
||||
string $exportAlias,
|
||||
$exportAlias,
|
||||
array $aggregatorAliases,
|
||||
): void {
|
||||
$builder
|
||||
@@ -86,96 +108,11 @@ class SpreadsheetListFormatter implements FormatterInterface, ExportManagerAware
|
||||
return ['numerotation' => true, 'format' => 'xlsx'];
|
||||
}
|
||||
|
||||
public function getName(): string|TranslatableInterface
|
||||
public function getName(): string|\Symfony\Contracts\Translation\TranslatableInterface
|
||||
{
|
||||
return 'Spreadsheet list formatter (.xlsx, .ods)';
|
||||
}
|
||||
|
||||
public function generate($result, $formatterData, string $exportAlias, array $exportData, array $filtersData, array $aggregatorsData, ExportGenerationContext $context): FormattedExportGeneration
|
||||
{
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$worksheet = $spreadsheet->getActiveSheet();
|
||||
$cacheLabels = $this->prepareCacheLabels($result, $exportAlias, $exportData);
|
||||
|
||||
$this->prepareHeaders($cacheLabels, $worksheet, $result, $formatterData, $exportAlias, $exportData);
|
||||
|
||||
$i = 1;
|
||||
|
||||
foreach ($result as $row) {
|
||||
if (true === $formatterData['numerotation']) {
|
||||
$worksheet->setCellValue('A'.($i + 1), (string) $i);
|
||||
}
|
||||
|
||||
$a = $formatterData['numerotation'] ? 'B' : 'A';
|
||||
|
||||
foreach ($row as $key => $value) {
|
||||
$row = $a.($i + 1);
|
||||
|
||||
$formattedValue = $this->getLabel($cacheLabels, $key, $value, $result, $exportAlias, $exportData);
|
||||
|
||||
if ($formattedValue instanceof \DateTimeInterface) {
|
||||
$worksheet->setCellValue($row, Date::PHPToExcel($formattedValue));
|
||||
|
||||
if ('000000' === $formattedValue->format('His')) {
|
||||
$worksheet->getStyle($row)
|
||||
->getNumberFormat()
|
||||
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
|
||||
} else {
|
||||
$worksheet->getStyle($row)
|
||||
->getNumberFormat()
|
||||
->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME);
|
||||
}
|
||||
} elseif ($formattedValue instanceof TranslatableInterface) {
|
||||
$worksheet->setCellValue($row, $formattedValue->trans($this->translator));
|
||||
} else {
|
||||
$worksheet->setCellValue($row, $formattedValue);
|
||||
}
|
||||
++$a;
|
||||
}
|
||||
|
||||
++$i;
|
||||
}
|
||||
|
||||
switch ($formatterData['format']) {
|
||||
case 'ods':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Ods');
|
||||
$contentType = 'application/vnd.oasis.opendocument.spreadsheet';
|
||||
|
||||
break;
|
||||
|
||||
case 'xlsx':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
|
||||
$contentType = 'application/vnd.openxmlformats-officedocument.'
|
||||
.'spreadsheetml.sheet';
|
||||
|
||||
break;
|
||||
|
||||
case 'csv':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv');
|
||||
$contentType = 'text/csv';
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// this should not happen
|
||||
// throw an exception to ensure that the error is catched
|
||||
throw new \OutOfBoundsException('The format '.$formatterData['format'].' is not supported');
|
||||
}
|
||||
|
||||
$tempfile = \tempnam(\sys_get_temp_dir(), '');
|
||||
$writer->save($tempfile);
|
||||
|
||||
$generated = new FormattedExportGeneration(
|
||||
file_get_contents($tempfile),
|
||||
$contentType,
|
||||
);
|
||||
|
||||
// remove the temp file from disk
|
||||
\unlink($tempfile);
|
||||
|
||||
return $generated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a response from the data collected on differents ExportElementInterface.
|
||||
*
|
||||
@@ -196,10 +133,89 @@ class SpreadsheetListFormatter implements FormatterInterface, ExportManagerAware
|
||||
array $aggregatorsData,
|
||||
ExportGenerationContext $context,
|
||||
) {
|
||||
$generated = $this->generate($result, $formatterData, $exportAlias, $exportData, $filtersData, $aggregatorsData, $context);
|
||||
$this->result = $result;
|
||||
$this->exportAlias = $exportAlias;
|
||||
$this->exportData = $exportData;
|
||||
$this->formatterData = $formatterData;
|
||||
|
||||
$response = new BinaryFileResponse($generated->content);
|
||||
$response->headers->set('Content-Type', $generated->contentType);
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$worksheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
$this->prepareHeaders($worksheet);
|
||||
|
||||
$i = 1;
|
||||
|
||||
foreach ($result as $row) {
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$worksheet->setCellValue('A'.($i + 1), (string) $i);
|
||||
}
|
||||
|
||||
$a = $this->formatterData['numerotation'] ? 'B' : 'A';
|
||||
|
||||
foreach ($row as $key => $value) {
|
||||
$row = $a.($i + 1);
|
||||
|
||||
$formattedValue = $this->getLabel($key, $value);
|
||||
|
||||
if ($formattedValue instanceof \DateTimeInterface) {
|
||||
$worksheet->setCellValue($row, Date::PHPToExcel($formattedValue));
|
||||
|
||||
if ('000000' === $formattedValue->format('His')) {
|
||||
$worksheet->getStyle($row)
|
||||
->getNumberFormat()
|
||||
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
|
||||
} else {
|
||||
$worksheet->getStyle($row)
|
||||
->getNumberFormat()
|
||||
->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME);
|
||||
}
|
||||
} else {
|
||||
$worksheet->setCellValue($row, $formattedValue);
|
||||
}
|
||||
++$a;
|
||||
}
|
||||
|
||||
++$i;
|
||||
}
|
||||
|
||||
switch ($this->formatterData['format']) {
|
||||
case 'ods':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Ods');
|
||||
$contentType = 'application/vnd.oasis.opendocument.spreadsheet';
|
||||
|
||||
break;
|
||||
|
||||
case 'xlsx':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
|
||||
$contentType = 'application/vnd.openxmlformats-officedocument.'
|
||||
.'spreadsheetml.sheet';
|
||||
|
||||
break;
|
||||
|
||||
case 'csv':
|
||||
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv');
|
||||
$contentType = 'text/csv';
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
// this should not happen
|
||||
// throw an exception to ensure that the error is catched
|
||||
throw new \OutOfBoundsException('The format '.$this->formatterData['format'].' is not supported');
|
||||
}
|
||||
|
||||
$response = new Response();
|
||||
$response->headers->set('content-type', $contentType);
|
||||
|
||||
$tempfile = \tempnam(\sys_get_temp_dir(), '');
|
||||
$writer->save($tempfile);
|
||||
|
||||
$f = \fopen($tempfile, 'rb');
|
||||
$response->setContent(\stream_get_contents($f));
|
||||
fclose($f);
|
||||
|
||||
// remove the temp file from disk
|
||||
\unlink($tempfile);
|
||||
|
||||
return $response;
|
||||
}
|
||||
@@ -212,29 +228,34 @@ class SpreadsheetListFormatter implements FormatterInterface, ExportManagerAware
|
||||
/**
|
||||
* Give the label corresponding to the given key and value.
|
||||
*
|
||||
* @return string|\DateTimeInterface|int|float|TranslatableInterface|null
|
||||
* @param string $key
|
||||
* @param string $value
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws \LogicException if the label is not found
|
||||
*/
|
||||
private function getLabel(array $labelsCache, $key, $value, array $result, string $exportAlias, array $exportData)
|
||||
protected function getLabel($key, $value)
|
||||
{
|
||||
if (!\array_key_exists($key, $labelsCache)) {
|
||||
throw new \OutOfBoundsException(sprintf('The key "%s" is not present in the list of keys handled by this query. Check your `getKeys` and `getLabels` methods. Available keys are %s.', $key, \implode(', ', \array_keys($labelsCache))));
|
||||
if (null === $this->labelsCache) {
|
||||
$this->prepareCacheLabels();
|
||||
}
|
||||
|
||||
return $labelsCache[$key]($value);
|
||||
if (!\array_key_exists($key, $this->labelsCache)) {
|
||||
throw new \OutOfBoundsException(sprintf('The key "%s" is not present in the list of keys handled by this query. Check your `getKeys` and `getLabels` methods. Available keys are %s.', $key, \implode(', ', \array_keys($this->labelsCache))));
|
||||
}
|
||||
|
||||
return $this->labelsCache[$key]($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the label cache which will be used by getLabel.
|
||||
*
|
||||
* @return array The labels cache
|
||||
* Prepare the label cache which will be used by getLabel. This function
|
||||
* should be called only once in the generation lifecycle.
|
||||
*/
|
||||
private function prepareCacheLabels(array $result, string $exportAlias, array $exportData): array
|
||||
protected function prepareCacheLabels()
|
||||
{
|
||||
$labelsCache = [];
|
||||
$export = $this->getExportManager()->getExport($exportAlias);
|
||||
$keys = $export->getQueryKeys($exportData);
|
||||
$export = $this->getExportManager()->getExport($this->exportAlias);
|
||||
$keys = $export->getQueryKeys($this->exportData);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
// get an array with all values for this key if possible
|
||||
@@ -244,31 +265,29 @@ class SpreadsheetListFormatter implements FormatterInterface, ExportManagerAware
|
||||
}
|
||||
|
||||
return $v[$key];
|
||||
}, $result);
|
||||
// store the label in the labelsCache
|
||||
$labelsCache[$key] = $export->getLabels($key, $values, $exportData);
|
||||
}, $this->result);
|
||||
// store the label in the labelsCache property
|
||||
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
|
||||
}
|
||||
|
||||
return $labelsCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* add the headers to the csv file.
|
||||
*/
|
||||
protected function prepareHeaders(array $labelsCache, Worksheet $worksheet, array $result, array $formatterData, string $exportAlias, array $exportData)
|
||||
protected function prepareHeaders(Worksheet $worksheet)
|
||||
{
|
||||
$keys = $this->getExportManager()->getExport($exportAlias)->getQueryKeys($exportData);
|
||||
$keys = $this->getExportManager()->getExport($this->exportAlias)->getQueryKeys($this->exportData);
|
||||
// we want to keep the order of the first row. So we will iterate on the first row of the results
|
||||
$first_row = \count($result) > 0 ? $result[0] : [];
|
||||
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
|
||||
$header_line = [];
|
||||
|
||||
if (true === $formatterData['numerotation']) {
|
||||
if (true === $this->formatterData['numerotation']) {
|
||||
$header_line[] = $this->translator->trans('Number');
|
||||
}
|
||||
|
||||
foreach ($first_row as $key => $value) {
|
||||
$header_line[] = $this->translator->trans(
|
||||
$this->getLabel($labelsCache, $key, '_header', $result, $exportAlias, $exportData)
|
||||
$this->getLabel($key, '_header')
|
||||
);
|
||||
}
|
||||
|
||||
|
@@ -20,7 +20,7 @@ use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
|
||||
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
|
||||
|
||||
#[AsMessageHandler]
|
||||
final readonly class RemoveExportGenerationMessageHandler implements MessageHandlerInterface
|
||||
class RemoveExportGenerationMessageHandler implements MessageHandlerInterface
|
||||
{
|
||||
private const LOG_PREFIX = '[RemoveExportGenerationMessageHandler] ';
|
||||
|
||||
|
@@ -1,75 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Form\DataMapper;
|
||||
|
||||
use Chill\MainBundle\Entity\User;
|
||||
use Symfony\Component\Form\DataMapperInterface;
|
||||
|
||||
final readonly class NotificationFlagDataMapper implements DataMapperInterface
|
||||
{
|
||||
public function __construct(private array $notificationFlagProviders) {}
|
||||
|
||||
public function mapDataToForms($viewData, $forms): void
|
||||
{
|
||||
if (null === $viewData) {
|
||||
$viewData = [];
|
||||
}
|
||||
|
||||
$formsArray = iterator_to_array($forms);
|
||||
|
||||
foreach ($this->notificationFlagProviders as $flagProvider) {
|
||||
$flag = $flagProvider->getFlag();
|
||||
|
||||
if (isset($formsArray[$flag])) {
|
||||
$flagForm = $formsArray[$flag];
|
||||
|
||||
$immediateEmailChecked = in_array(User::NOTIF_FLAG_IMMEDIATE_EMAIL, $viewData[$flag] ?? [], true)
|
||||
|| !array_key_exists($flag, $viewData);
|
||||
$dailyEmailChecked = in_array(User::NOTIF_FLAG_DAILY_DIGEST, $viewData[$flag] ?? [], true);
|
||||
|
||||
if ($flagForm->has('immediate_email')) {
|
||||
$flagForm->get('immediate_email')->setData($immediateEmailChecked);
|
||||
}
|
||||
if ($flagForm->has('daily_email')) {
|
||||
$flagForm->get('daily_email')->setData($dailyEmailChecked);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function mapFormsToData($forms, &$viewData): void
|
||||
{
|
||||
$formsArray = iterator_to_array($forms);
|
||||
$viewData = [];
|
||||
|
||||
foreach ($this->notificationFlagProviders as $flagProvider) {
|
||||
$flag = $flagProvider->getFlag();
|
||||
|
||||
if (isset($formsArray[$flag])) {
|
||||
$flagForm = $formsArray[$flag];
|
||||
$viewData[$flag] = [];
|
||||
|
||||
if (true === $flagForm['immediate_email']->getData()) {
|
||||
$viewData[$flag][] = User::NOTIF_FLAG_IMMEDIATE_EMAIL;
|
||||
}
|
||||
|
||||
if (true === $flagForm['daily_email']->getData()) {
|
||||
$viewData[$flag][] = User::NOTIF_FLAG_DAILY_DIGEST;
|
||||
}
|
||||
|
||||
if ([] === $viewData[$flag]) {
|
||||
$viewData[$flag][] = User::NOTIF_FLAG_IMMEDIATE_EMAIL;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -12,12 +12,17 @@ declare(strict_types=1);
|
||||
namespace Chill\MainBundle\Form;
|
||||
|
||||
use Chill\MainBundle\Entity\Notification;
|
||||
use Chill\MainBundle\Form\Type\ChillCollectionType;
|
||||
use Chill\MainBundle\Form\Type\ChillTextareaType;
|
||||
use Chill\MainBundle\Form\Type\PickUserGroupOrUserDynamicType;
|
||||
use Chill\MainBundle\Form\Type\PickUserDynamicType;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EmailType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Validator\Constraints\Email;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Component\Validator\Constraints\NotNull;
|
||||
|
||||
class NotificationType extends AbstractType
|
||||
{
|
||||
@@ -28,14 +33,29 @@ class NotificationType extends AbstractType
|
||||
'label' => 'Title',
|
||||
'required' => true,
|
||||
])
|
||||
->add('addressees', PickUserGroupOrUserDynamicType::class, [
|
||||
->add('addressees', PickUserDynamicType::class, [
|
||||
'multiple' => true,
|
||||
'label' => 'notification.Pick user or user group',
|
||||
'empty_data' => '[]',
|
||||
'required' => true,
|
||||
'required' => false,
|
||||
])
|
||||
->add('message', ChillTextareaType::class, [
|
||||
'required' => false,
|
||||
])
|
||||
->add('addressesEmails', ChillCollectionType::class, [
|
||||
'label' => 'notification.dest by email',
|
||||
'help' => 'notification.dest by email help',
|
||||
'by_reference' => false,
|
||||
'allow_add' => true,
|
||||
'allow_delete' => true,
|
||||
'entry_type' => EmailType::class,
|
||||
'button_add_label' => 'notification.Add an email',
|
||||
'button_remove_label' => 'notification.Remove an email',
|
||||
'empty_collection_explain' => 'notification.Any email',
|
||||
'entry_options' => [
|
||||
'constraints' => [
|
||||
new NotNull(), new NotBlank(), new Email(),
|
||||
],
|
||||
'label' => 'Email',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
|
@@ -55,10 +55,6 @@ class DateIntervalType extends AbstractType
|
||||
{
|
||||
$builder
|
||||
->add('n', IntegerType::class, [
|
||||
'attr' => [
|
||||
'min' => 0,
|
||||
'step' => 1,
|
||||
],
|
||||
'constraints' => [
|
||||
new GreaterThan([
|
||||
'value' => 0,
|
||||
|
@@ -1,63 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Form\Type;
|
||||
|
||||
use Chill\MainBundle\Form\DataMapper\NotificationFlagDataMapper;
|
||||
use Chill\MainBundle\Notification\NotificationFlagManager;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\FormType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
|
||||
class NotificationFlagsType extends AbstractType
|
||||
{
|
||||
private readonly array $notificationFlagProviders;
|
||||
|
||||
public function __construct(NotificationFlagManager $notificationFlagManager)
|
||||
{
|
||||
$this->notificationFlagProviders = $notificationFlagManager->getAllNotificationFlagProviders();
|
||||
}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder->setDataMapper(new NotificationFlagDataMapper($this->notificationFlagProviders));
|
||||
|
||||
foreach ($this->notificationFlagProviders as $flagProvider) {
|
||||
$flag = $flagProvider->getFlag();
|
||||
$builder->add($flag, FormType::class, [
|
||||
'label' => $flagProvider->getLabel(),
|
||||
'required' => false,
|
||||
]);
|
||||
|
||||
$builder->get($flag)
|
||||
->add('immediate_email', CheckboxType::class, [
|
||||
'label' => false,
|
||||
'required' => false,
|
||||
'mapped' => false,
|
||||
])
|
||||
->add('daily_email', CheckboxType::class, [
|
||||
'label' => false,
|
||||
'required' => false,
|
||||
'mapped' => false,
|
||||
])
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => null,
|
||||
]);
|
||||
}
|
||||
}
|
@@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Notification\Email;
|
||||
|
||||
use Chill\MainBundle\Cron\CronJobInterface;
|
||||
use Chill\MainBundle\Entity\CronJobExecution;
|
||||
use Chill\MainBundle\Notification\Email\NotificationEmailMessages\ScheduleDailyNotificationDigestMessage;
|
||||
use Doctrine\DBAL\Connection;
|
||||
use Doctrine\DBAL\Exception;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Clock\ClockInterface;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
|
||||
readonly class DailyNotificationDigestCronjob implements CronJobInterface
|
||||
{
|
||||
public function __construct(
|
||||
private ClockInterface $clock,
|
||||
private Connection $connection,
|
||||
private MessageBusInterface $messageBus,
|
||||
private LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
public function canRun(?CronJobExecution $cronJobExecution): bool
|
||||
{
|
||||
$now = $this->clock->now();
|
||||
|
||||
if (null !== $cronJobExecution && $now->sub(new \DateInterval('PT23H45M')) < $cronJobExecution->getLastStart()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Run between 6 and 9 AM
|
||||
return in_array((int) $now->format('H'), [6, 7, 8], true);
|
||||
}
|
||||
|
||||
public function getKey(): string
|
||||
{
|
||||
return 'daily-notification-digest';
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \DateInvalidOperationException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function run(array $lastExecutionData): ?array
|
||||
{
|
||||
$now = $this->clock->now();
|
||||
if (isset($lastExecutionData['last_execution'])) {
|
||||
$lastExecution = \DateTimeImmutable::createFromFormat(
|
||||
\DateTimeImmutable::ATOM,
|
||||
$lastExecutionData['last_execution']
|
||||
);
|
||||
} else {
|
||||
$lastExecution = $now->sub(new \DateInterval('P1D'));
|
||||
}
|
||||
|
||||
// Get distinct users who received notifications since the last execution
|
||||
$sql = <<<'SQL'
|
||||
SELECT DISTINCT cmnau.user_id
|
||||
FROM chill_main_notification cmn
|
||||
JOIN chill_main_notification_addresses_user cmnau ON cmnau.notification_id = cmn.id
|
||||
WHERE cmn.date >= :lastExecution AND cmn.date <= :now
|
||||
SQL;
|
||||
|
||||
$sqlStatement = $this->connection->prepare($sql);
|
||||
$sqlStatement->bindValue('lastExecution', $lastExecution->format(\DateTimeInterface::RFC3339));
|
||||
$sqlStatement->bindValue('now', $now->format(\DateTimeInterface::RFC3339));
|
||||
$result = $sqlStatement->executeQuery();
|
||||
|
||||
$count = 0;
|
||||
foreach ($result->fetchAllAssociative() as $row) {
|
||||
$userId = (int) $row['user_id'];
|
||||
|
||||
$message = new ScheduleDailyNotificationDigestMessage(
|
||||
$userId,
|
||||
$lastExecution,
|
||||
$now
|
||||
);
|
||||
|
||||
$this->messageBus->dispatch($message);
|
||||
++$count;
|
||||
}
|
||||
|
||||
$this->logger->info('[DailyNotificationDigestCronjob] Dispatched daily digest messages', [
|
||||
'user_count' => $count,
|
||||
'last_execution' => $lastExecution->format('Y-m-d-H:i:s.u e'),
|
||||
'current_time' => $now->format('Y-m-d-H:i:s.u e'),
|
||||
]);
|
||||
|
||||
return [
|
||||
'last_execution' => $now->format('Y-m-d-H:i:s.u e'),
|
||||
];
|
||||
}
|
||||
}
|
@@ -1,75 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Notification\Email\NotificationEmailHandlers;
|
||||
|
||||
use Chill\MainBundle\Notification\Email\NotificationEmailMessages\ScheduleDailyNotificationDigestMessage;
|
||||
use Chill\MainBundle\Notification\Email\NotificationMailer;
|
||||
use Chill\MainBundle\Repository\NotificationRepository;
|
||||
use Chill\MainBundle\Repository\UserRepository;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
||||
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
|
||||
|
||||
#[AsMessageHandler]
|
||||
readonly class ScheduleDailyNotificationDigestHandler
|
||||
{
|
||||
public function __construct(
|
||||
private NotificationRepository $notificationRepository,
|
||||
private UserRepository $userRepository,
|
||||
private NotificationMailer $notificationMailer,
|
||||
private LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws TransportExceptionInterface
|
||||
*/
|
||||
public function __invoke(ScheduleDailyNotificationDigestMessage $message): void
|
||||
{
|
||||
$userId = $message->getUserId();
|
||||
$lastExecutionDate = $message->getLastExecutionDateTime();
|
||||
$currentDate = $message->getCurrentDateTime();
|
||||
|
||||
$user = $this->userRepository->find($userId);
|
||||
if (null === $user) {
|
||||
$this->logger->warning('[ScheduleDailyNotificationDigestHandler] User not found', [
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('User with ID %s not found', $userId));
|
||||
}
|
||||
|
||||
// Get all notifications for this user between last execution and current date
|
||||
$notifications = $this->notificationRepository->findNotificationsForUserBetweenDates(
|
||||
$userId,
|
||||
$lastExecutionDate,
|
||||
$currentDate
|
||||
);
|
||||
|
||||
// Filter out notifications that should be sent in a daily digest
|
||||
$dailyNotifications = array_filter($notifications, fn ($notification) => $user->isNotificationDailyDigest($notification->getType()));
|
||||
|
||||
if ([] === $dailyNotifications) {
|
||||
$this->logger->info('[ScheduleDailyNotificationDigestHandler] No daily notifications found for user', [
|
||||
'user_id' => $userId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->notificationMailer->sendDailyDigest($user, $dailyNotifications);
|
||||
|
||||
$this->logger->info('[ScheduleDailyNotificationDigestHandler] Sent daily digest', [
|
||||
'user_id' => $userId,
|
||||
'notification_count' => count($dailyNotifications),
|
||||
]);
|
||||
}
|
||||
}
|
@@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* Chill is a software for social workers
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Chill\MainBundle\Notification\Email\NotificationEmailHandlers;
|
||||
|
||||
use Chill\MainBundle\Notification\Email\NotificationEmailMessages\SendImmediateNotificationEmailMessage;
|
||||
use Chill\MainBundle\Notification\Email\NotificationMailer;
|
||||
use Chill\MainBundle\Repository\NotificationRepository;
|
||||
use Chill\MainBundle\Repository\UserRepository;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
||||
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
|
||||
|
||||
#[AsMessageHandler]
|
||||
readonly class SendImmediateNotificationEmailHandler
|
||||
{
|
||||
public function __construct(
|
||||
private NotificationRepository $notificationRepository,
|
||||
private UserRepository $userRepository,
|
||||
private NotificationMailer $notificationMailer,
|
||||
private LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws TransportExceptionInterface
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function __invoke(SendImmediateNotificationEmailMessage $message): void
|
||||
{
|
||||
$notification = $this->notificationRepository->find($message->getNotificationId());
|
||||
$addressee = $this->userRepository->find($message->getAddresseeId());
|
||||
|
||||
if (null === $notification) {
|
||||
$this->logger->error('[SendImmediateNotificationEmailHandler] Notification not found', [
|
||||
'notification_id' => $message->getNotificationId(),
|
||||
]);
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('Notification with ID %s not found', $message->getNotificationId()));
|
||||
}
|
||||
|
||||
if (null === $addressee) {
|
||||
$this->logger->error('[SendImmediateNotificationEmailHandler] Addressee not found', [
|
||||
'addressee_id' => $message->getAddresseeId(),
|
||||
]);
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('User with ID %s not found', $message->getAddresseeId()));
|
||||
}
|
||||
|
||||
try {
|
||||
$this->notificationMailer->sendEmailToAddressee($notification, $addressee);
|
||||
} catch (\Exception $e) {
|
||||
$this->logger->error('[SendImmediateNotificationEmailHandler] Failed to send email', [
|
||||
'notification_id' => $message->getNotificationId(),
|
||||
'addressee_id' => $message->getAddresseeId(),
|
||||
'stacktrace' => $e->getTraceAsString(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user