104 Commits

Author SHA1 Message Date
47be7d340b fix: formatter
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 13s
Format / formatting (pull_request) Successful in 7s
2025-05-14 09:06:52 +02:00
232d10b164 fix: formatter
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 43s
CI / build (push) Successful in 13s
Format / formatting (pull_request) Failing after 6s
2025-05-14 09:04:35 +02:00
bc7ce888ad fix: build
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 44s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Failing after 5s
2025-05-13 20:00:51 +02:00
ed67a3734a fix: fix build
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 12s
2025-05-13 19:56:03 +02:00
95eb154556 fix: eslint
Some checks failed
Format / formatting (push) Failing after 7s
Build / build (push) Successful in 43s
CI / build (push) Failing after 11s
2025-05-13 19:52:31 +02:00
19fef63b0e fix: merge
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 45s
CI / build (push) Failing after 11s
2025-05-11 21:18:38 +02:00
1fd95265ea fix: this is not gonna work in time, switching to mock mod for canvas so we can show what we supposed to have atleast (local canvas) and we can explain what is the problem (you can disable the mock by putting the var USE_MOCK to false in CanvasItem.vue but dont do it) 2025-05-11 21:17:09 +02:00
3ef2d8a198 fix: join or create
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 10s
2025-05-11 20:37:57 +02:00
6b49bbbe57 fix: handlers weren't used properly in the unauth code
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 10s
2025-05-10 23:35:30 +02:00
4c15cab607 fix: still working on the pending
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 12s
2025-05-10 23:16:08 +02:00
abfe92bc87 Merge: branch 'backend-test' into front_foundation
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 9s
2025-05-10 21:54:20 +02:00
85b4fe6a4c fix: finalize logic
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 10s
2025-05-10 21:48:41 +02:00
f2448a029f added two endpoints necessary for routing in project request phase
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
2025-05-10 20:39:45 +02:00
cef4daef15 feat: finalize2
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 13s
2025-05-10 18:10:39 +02:00
f5aba70017 feat: add finalise logic
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 12s
2025-05-10 17:59:05 +02:00
27adc81ddc fix: minor change
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 9s
2025-05-10 01:16:00 +02:00
48f14e8a04 Merge branch 'backend-test' into front_foundation
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 10s
2025-05-09 22:59:23 +02:00
d4533ea725 added an endpoint to see if useraccuont is pending or not
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 42s
CI / build (push) Successful in 11s
2025-05-09 21:23:35 +02:00
7fc06035c7 fix: unauth users redirection
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 10s
2025-05-09 18:47:37 +02:00
1b559f29b7 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation 2025-05-09 02:24:33 +02:00
63327bc312 fix: config stuff, do make keycloak first
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 10s
2025-05-09 00:40:41 +02:00
f0cef41e2b Merge branch 'main' of https://gitea.piair.dev/piair/MyINPulse into front_foundation 2025-05-08 18:46:27 +02:00
7f16cdc86f fix: commit before merge 2025-05-08 18:11:50 +02:00
72d6f49995 Merge remote-tracking branch 'origin/main' into front_foundation 2025-05-08 18:08:18 +02:00
695ec5d9b8 fix: merge depuis backend-test
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 7s
2025-05-08 16:32:06 +02:00
0abafb4f7f Merge remote-tracking branch 'origin/backend-test' into front_foundation 2025-05-08 16:30:44 +02:00
3cd63e78e9 fix: changement de makefile 2025-05-08 16:30:42 +02:00
255af7ee7f feat: final test in sharedApi passing, it took a while to find where the bug is getAppointments by project
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
2025-05-07 20:57:03 +02:00
3b308cfa6d fix: my bad 403 error codes are never thrown by src code, now is up to date
All checks were successful
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 39s
CI / build (push) Successful in 10s
2025-05-07 11:44:09 +02:00
d039105f0a Merge remote-tracking branch 'origin/backend-test' into front_foundation 2025-05-07 11:16:15 +02:00
0a15dbbf2d fix: merge errors 2025-05-07 11:16:12 +02:00
d1fce63ac5 Merge remote-tracking branch 'origin/main' into front_foundation 2025-05-07 11:09:51 +02:00
d9aaa225aa Merge pull request 'Fix 403 errors' (#12) from backend-test into main
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 11s
Reviewed-on: #12
Reviewed-by: adnane <adnane.alami@bordeaux-inp.fr>
Reviewed-by: omar <omar.el_alaoui_el_ismaili@bordeaux-inp.fr>
Reviewed-by: Theo <tlelez@enseirb-matmeca.fr>
Reviewed-by: anas <anas.maillal@bordeaux-inp.fr>
2025-05-07 11:08:57 +02:00
d31bf259dd Merge branch 'main' into backend-test
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 11s
Format / formatting (pull_request) Successful in 6s
2025-05-07 11:06:30 +02:00
43b40c9432 feat: just added 403 response
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 10s
Format / formatting (pull_request) Successful in 5s
2025-05-07 11:04:24 +02:00
e84f69c21a fix: unused imports
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
2025-05-07 11:02:08 +02:00
cc1fc9b45b fix: eslint
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 13s
2025-05-07 11:01:57 +02:00
c76e83f2bf feat: changed endpoints
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 8s
2025-05-07 11:00:15 +02:00
0d0ec255a5 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 8s
2025-05-07 10:53:09 +02:00
e0c43a5c95 fix: merge 2025-05-07 10:53:02 +02:00
1f0f9196c4 feat: fixed 403 errors
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 11s
2025-05-07 10:45:38 +02:00
40e577ef07 Merge pull request 'backend-test' (#10) from backend-test into main
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
Reviewed-on: #10
Reviewed-by: adnane <adnane.alami@bordeaux-inp.fr>
Reviewed-by: anas <anas.maillal@bordeaux-inp.fr>
Reviewed-by: omar <omar.el_alaoui_el_ismaili@bordeaux-inp.fr>
2025-05-07 10:43:30 +02:00
60302c44d2 "reverting the fix, last ditch was no good: last ditch effort with .env variables, using default variable to set db connection values"
Some checks failed
Format / formatting (push) Successful in 10s
Build / build (push) Successful in 49s
CI / build (push) Failing after 12s
This reverts commit a6e4f80a01.
2025-05-07 00:04:26 +02:00
a6e4f80a01 fix: last ditch effort with .env variables, using default variable to set db connection values
Some checks failed
Format / formatting (push) Successful in 7s
Build / build (push) Successful in 51s
CI / build (push) Failing after 13s
2025-05-06 23:57:03 +02:00
02bff19de0 fix: il ya encors un problem de config! des erreurs de type (Connection to localhost:5433 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections)
Some checks failed
Format / formatting (push) Successful in 7s
Build / build (push) Successful in 56s
CI / build (push) Failing after 25s
2025-05-06 23:31:01 +02:00
ae36549de9 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation 2025-05-06 22:38:28 +02:00
b1a4c874ec trying out config to see if this is where 403 responses are comming from
All checks were successful
Format / formatting (push) Successful in 15s
Build / build (push) Successful in 1m4s
CI / build (push) Successful in 39s
2025-05-06 21:17:52 +02:00
829baac85e apply prettier to adminappointment
All checks were successful
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 40s
CI / build (push) Successful in 13s
2025-05-05 20:36:09 +02:00
2e9d841709 utilisation des fonctions Apis/admin.ts pour mettre un raport a un appointmentid
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 9s
2025-05-05 20:32:09 +02:00
25235f418a fix: merging from the main 2025-05-04 20:23:19 +02:00
13845394e3 feat: added doc for endpoint make-admin
All checks were successful
Format / formatting (push) Successful in 25s
Build / build (push) Successful in 44s
CI / build (push) Successful in 13s
Format / formatting (pull_request) Successful in 6s
2025-05-04 20:15:03 +02:00
73aac1875a Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
All checks were successful
Format / formatting (push) Successful in 7s
Build / build (push) Successful in 42s
CI / build (push) Successful in 14s
Format / formatting (pull_request) Successful in 6s
2025-05-02 01:52:52 +02:00
c3ad092512 fix: api integration 2025-05-02 01:26:08 +02:00
f4589c6306 fix: bug on CORS discussed before
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 46s
CI / build (push) Successful in 13s
Format / formatting (pull_request) Successful in 6s
2025-05-01 21:03:23 +02:00
6004bce4e8 Merge branch 'main' into backend-test
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 42s
CI / build (push) Successful in 11s
2025-05-01 20:53:18 +02:00
0730275e75 feat: added create-account
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 44s
CI / build (push) Successful in 11s
2025-05-01 20:51:10 +02:00
4356a01e4a feat: adding delete button with the corresponding endpoint
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 44s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Successful in 6s
2025-05-01 19:23:21 +02:00
592331236e added endpoints to see all user without any auth for testing
Some checks failed
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 45s
CI / build (push) Failing after 12s
Format / formatting (pull_request) Successful in 7s
2025-05-01 17:45:49 +02:00
49e52e1826 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 49s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 5s
2025-05-01 17:37:45 +02:00
efcea7f680 fix: backend fix 'adding PUT ... to the file' 2025-05-01 17:37:40 +02:00
8154814805 fix: type errors 2025-05-01 17:35:04 +02:00
7d41da97de prettier api.ts
Some checks failed
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 1m43s
CI / build (push) Failing after 12s
Format / formatting (pull_request) Successful in 6s
2025-05-01 16:11:07 +02:00
35f314498f list des upcoming appointments prettier
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 1m0s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 6s
2025-05-01 16:05:46 +02:00
f46c3756f0 lister tout les upcoming appointmens
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 43s
CI / build (push) Failing after 11s
Format / formatting (pull_request) Successful in 6s
2025-05-01 15:26:05 +02:00
92696c3e16 fix/feat: Now the projectId is correctly fetched yet we cant test shit since the db is empty
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 12s
Format / formatting (pull_request) Successful in 6s
2025-04-29 23:18:26 +02:00
5130c00796 fix: adding toObject in ApiClasses
Some checks failed
Format / formatting (push) Successful in 7s
Build / build (push) Successful in 44s
CI / build (push) Failing after 12s
Format / formatting (pull_request) Successful in 6s
2025-04-29 22:15:20 +02:00
5183a088e7 fix: forgot to remove a pram in an endpoint in docs
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 45s
CI / build (push) Successful in 13s
2025-04-29 21:41:25 +02:00
8ec569e6ff fix: prettier
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 46s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Successful in 6s
2025-04-29 21:35:00 +02:00
b503cae235 fix: styling
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 1m33s
CI / build (push) Successful in 11s
2025-04-29 21:25:03 +02:00
fcf4e1c01d feat: added an endpoint for fething the project an entrepreneur is associated with
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 1m28s
CI / build (push) Successful in 11s
2025-04-29 21:22:13 +02:00
4f90da69f3 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 6s
2025-04-29 20:58:09 +02:00
0fe64fd844 fix: using the new admins functions for apis 2025-04-29 20:57:51 +02:00
eb302268ba fix: still having 403 bit fixed some bugs
Some checks failed
Format / formatting (push) Successful in 9s
Build / build (push) Successful in 42s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 6s
2025-04-29 20:19:24 +02:00
3f18304028 formatting works time in and time out, empty commit to fix
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 42s
CI / build (push) Successful in 11s
2025-04-29 19:31:28 +02:00
bbb4debcd8 fix: changed the data structure used in getAllSectionCells for processing the latest version of sectioneCells as it gave some exception (it doesn't like being iterated and modified at the same time)
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
2025-04-29 19:18:12 +02:00
6f7fc70c4c didn't use the correct function for seting ids, test fixed
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 16s
2025-04-29 18:50:25 +02:00
4044a95dd1 fix: added a logout button in the header
Some checks failed
Format / formatting (push) Successful in 8s
Build / build (push) Successful in 41s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 7s
2025-04-29 16:20:11 +02:00
aee8e8797c feat: added an initial in mermory database configuration for seting up front
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 43s
CI / build (push) Successful in 11s
Format / formatting (pull_request) Successful in 6s
2025-04-29 14:11:45 +02:00
3d57ecb01a fix: fixed some sectionCell fetching logic (previously wasn't grouping by idReference), found out that idRefrence in sectionCell is always being incremented at inserion still looking for a fix
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Successful in 11s
2025-04-29 13:59:05 +02:00
1f91ab72d8 This reverts commit cbef042e97. I was working on front and back and pushed stuff to the wrong end
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Successful in 5s
2025-04-29 13:00:58 +02:00
a4e13b0f0a Revert "forgot to comment out said test"
Some checks failed
Format / formatting (push) Failing after 5s
Build / build (push) Failing after 41s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Failing after 6s
This reverts commit b116771375.
2025-04-29 13:00:18 +02:00
b116771375 forgot to comment out said test
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 11s
Format / formatting (pull_request) Successful in 5s
2025-04-29 12:55:50 +02:00
cbef042e97 found that idReference Incrementing when it shoudn't still looking for a fix, and fixed some sectioncell fetching logic in SectionCellService.java
Some checks failed
Format / formatting (push) Failing after 6s
Build / build (push) Failing after 40s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Failing after 6s
2025-04-29 12:48:29 +02:00
63f6f16d83 fix: tiny bug
All checks were successful
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Successful in 5s
2025-04-29 11:39:02 +02:00
864bbbb9fd fix: eslint + prettier
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Failing after 12s
Format / formatting (pull_request) Successful in 6s
2025-04-29 11:32:30 +02:00
e890a03a48 feat: all Canvas endpoints implemented, just waiting for projectId to test
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 42s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 6s
2025-04-29 11:24:26 +02:00
351727f3d5 fix: prettier
All checks were successful
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 40s
CI / build (push) Successful in 12s
Format / formatting (pull_request) Successful in 6s
2025-04-29 00:42:59 +02:00
b5637e4552 fix: bugs fixed, we still have the 404 error
Some checks failed
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 40s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 6s
2025-04-29 00:40:30 +02:00
8024b8070b merge: enstrpenrue issuees
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 5s
2025-04-29 00:34:41 +02:00
008e003207 fix: conflict on Apis 2025-04-29 00:32:03 +02:00
820c979c94 fix: bugs
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 11s
Format / formatting (pull_request) Successful in 6s
2025-04-29 00:28:56 +02:00
2ebea35e5d fix: confits 2025-04-29 00:03:44 +02:00
c3dded1e05 fix:
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 8s
Format / formatting (pull_request) Successful in 6s
2025-04-29 00:00:39 +02:00
8b48a55bf0 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
Some checks failed
Format / formatting (push) Successful in 5s
Build / build (push) Successful in 40s
CI / build (push) Failing after 8s
Format / formatting (pull_request) Successful in 6s
2025-04-28 23:54:53 +02:00
32de0d6ca8 feat: function that tells if an authentified person is an admin 2025-04-28 23:54:38 +02:00
7534d0d9c6 feat: logout button
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 6s
2025-04-28 23:54:04 +02:00
a0cbd5e324 fix: fixing a small bug
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 41s
CI / build (push) Failing after 10s
Format / formatting (pull_request) Successful in 6s
2025-04-28 23:25:54 +02:00
09eeaacfa6 Merge branch 'front_foundation' of https://gitea.piair.dev/piair/MyINPulse into front_foundation
Some checks failed
Format / formatting (push) Successful in 6s
Build / build (push) Successful in 40s
CI / build (push) Failing after 9s
Format / formatting (pull_request) Successful in 6s
2025-04-28 23:08:59 +02:00
de09ab2891 fix: api service 2025-04-28 23:08:19 +02:00
b1df7421dc fix: commiting some minor changes before switching to front_foundation branch 2025-02-10 15:32:28 +01:00
7a03146bf8 fix: commiting minor changes before switching to front_foundation branch 2025-02-10 15:21:07 +01:00
f0a371dc52 Merge pull request 'main-revert' (#2) from main-revert into main
Reviewed-on: #2
2025-02-09 13:11:01 +01:00
ac19d33bdb Reapply "fix: fixed TS errors"
This reverts commit 3d4d5b90d1.
2025-02-09 13:05:28 +01:00
3d4d5b90d1 Revert "fix: fixed TS errors"
This reverts commit b5c9b40672.
2025-02-09 13:03:26 +01:00
61 changed files with 5321 additions and 1276 deletions

View File

@ -33,8 +33,6 @@ dev-front: clean vite keycloak
@cp config/frontdev.docker-compose.yaml docker-compose.yaml
@docker compose up -d --build
@cd ./front/MyINPulse-front/ && npm run dev
@echo "cd MyINPulse-back" && echo 'export $$(cat .env | xargs)'
@echo "./gradlew bootRun --args='--server.port=8081'"
prod: clean keycloak
@cp config/prod.env front/MyINPulse-front/.env
@ -45,7 +43,6 @@ prod: clean keycloak
dev-back: keycloak
@cp config/backdev.env front/MyINPulse-front/.env
@cp config/backdev.env .env

View File

@ -29,6 +29,8 @@ dependencies {
implementation 'org.postgresql:postgresql'
implementation group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13.3'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'com.h2database:h2'

View File

@ -31,7 +31,7 @@ public class WebSecurityCustomConfiguration {
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of(frontendUrl));
configuration.setAllowedMethods(Arrays.asList("GET", "OPTIONS"));
configuration.setAllowedMethods(Arrays.asList("GET", "OPTIONS", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(
Arrays.asList("authorization", "content-type", "x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
@ -56,12 +56,18 @@ public class WebSecurityCustomConfiguration {
http.authorizeHttpRequests(
authorize ->
authorize
.requestMatchers("/entrepreneur/**", "/shared/**")
.requestMatchers("/entrepreneur/**")
.access(hasRole("REALM_MyINPulse-entrepreneur"))
.requestMatchers("/admin/**", "/shared/**")
.requestMatchers("/admin/**")
.access(hasRole("REALM_MyINPulse-admin"))
.requestMatchers("/shared/**")
.hasAnyRole(
"REALM_MyINPulse-admin",
"REALM_MyINPulse-entrepreneur")
.requestMatchers("/unauth/**")
.authenticated())
.authenticated()
.anyRequest()
.denyAll())
.oauth2ResourceServer(
oauth2 ->
oauth2.jwt(

View File

@ -115,4 +115,15 @@ public class AdminApi {
public Iterable<User> validateEntrepreneurAcc() {
return this.adminApiService.getPendingUsers();
}
@PostMapping("/admin/create-account")
public void createAccount(@AuthenticationPrincipal Jwt principal) {
String userSurname = principal.getClaimAsString("userSurname");
String username = principal.getClaimAsString("preferred_username");
String primaryMail = principal.getClaimAsString("email");
String secondaryMail = principal.getClaimAsString("secondaryMail");
String phoneNumber = principal.getClaimAsString("phoneNumber");
this.adminApiService.createAccount(
userSurname, username, primaryMail, secondaryMail, phoneNumber);
}
}

View File

@ -5,6 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
@ -42,6 +43,19 @@ public class EntrepreneurApi {
sectionCellId, content, principal.getClaimAsString("email"));
}
/**
* Endpoint used to update a LC section.
*
* @return status code
*/
@GetMapping("/entrepreneur/projects")
public Iterable<Project> getEntrepreneurProjectId(
@PathVariable Long sectionCellId,
@RequestBody String content,
@AuthenticationPrincipal Jwt principal) {
return entrepreneurApiService.getProjectIdViaClaim(principal.getClaimAsString("email"));
}
/**
* TODO: checkReturn Type
*
@ -81,4 +95,22 @@ public class EntrepreneurApi {
@RequestBody Project project, @AuthenticationPrincipal Jwt principal) {
entrepreneurApiService.requestNewProject(project, principal.getClaimAsString("email"));
}
/*
* <p>Endpoint to check if project is has already been validated by an admin
*/
@GetMapping("/entrepreneur/projects/project-is-active")
public Boolean checkIfProjectValidated(@AuthenticationPrincipal Jwt principal) {
return entrepreneurApiService.checkIfEntrepreneurProjectActive(
principal.getClaimAsString("email"));
}
/*
* <p>Endpoint to check if a user requested a project (used when project is pending)
*/
@GetMapping("/entrepreneur/projects/has-pending-request")
public Boolean checkIfHasRequested(@AuthenticationPrincipal Jwt principal) {
return entrepreneurApiService.entrepreneurHasPendingRequestedProject(
principal.getClaimAsString("email"));
}
}

View File

@ -2,6 +2,7 @@ package enseirb.myinpulse.controller;
import enseirb.myinpulse.model.Entrepreneur;
import enseirb.myinpulse.service.EntrepreneurApiService;
import enseirb.myinpulse.service.UtilsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -14,13 +15,15 @@ import org.springframework.web.bind.annotation.*;
public class UnauthApi {
private final EntrepreneurApiService entrepreneurApiService;
private final UtilsService utilsService;
@Autowired
UnauthApi(EntrepreneurApiService entrepreneurApiService) {
UnauthApi(EntrepreneurApiService entrepreneurApiService, UtilsService utilsService) {
this.entrepreneurApiService = entrepreneurApiService;
this.utilsService = utilsService;
}
@GetMapping("/unauth/finalize")
@PostMapping("/unauth/finalize")
public void createAccount(@AuthenticationPrincipal Jwt principal) {
boolean sneeStatus;
if (principal.getClaimAsString("sneeStatus") != null) {
@ -46,6 +49,13 @@ public class UnauthApi {
course,
sneeStatus,
true);
entrepreneurApiService.createAccount(e);
}
@GetMapping("/unauth/check-if-not-pending")
public Boolean checkAccountStatus(@AuthenticationPrincipal Jwt principal) {
// Throws 404 if user not found
return utilsService.checkEntrepreneurNotPending(principal.getClaimAsString("email"));
}
}

View File

@ -15,4 +15,6 @@ public interface SectionCellRepository extends JpaRepository<SectionCell, Long>
Iterable<SectionCell> findByProjectSectionCellAndSectionIdAndModificationDateBefore(
Project project, long sectionId, LocalDateTime date);
Iterable<SectionCell> findByProjectSectionCell(Project project);
}

View File

@ -206,4 +206,19 @@ public class AdminApiService {
public Iterable<User> getPendingUsers() {
return this.userService.getPendingAccounts();
}
public void createAccount(
String username,
String userSurname,
String primaryMail,
String secondaryMail,
String phoneNumber) {
Administrator a =
new Administrator(username, userSurname, primaryMail, secondaryMail, phoneNumber);
this.administratorService.addAdministrator(a);
}
public Iterable<Administrator> getAllAdmins() {
return this.administratorService.allAdministrators();
}
}

View File

@ -1,10 +1,12 @@
package enseirb.myinpulse.service;
import static enseirb.myinpulse.model.ProjectDecisionValue.PENDING;
import static enseirb.myinpulse.model.ProjectDecisionValue.ACTIVE;
import enseirb.myinpulse.model.Entrepreneur;
import enseirb.myinpulse.model.Project;
import enseirb.myinpulse.model.SectionCell;
import enseirb.myinpulse.model.User;
import enseirb.myinpulse.service.database.*;
import org.apache.logging.log4j.LogManager;
@ -15,6 +17,8 @@ import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Service
public class EntrepreneurApiService {
@ -219,4 +223,62 @@ public class EntrepreneurApiService {
}
throw new ResponseStatusException(HttpStatus.CONFLICT, "User already exists in the system");
}
public Iterable<Project> getProjectIdViaClaim(String email) {
Long UserId = this.userService.getUserByEmail(email).getIdUser();
Entrepreneur entrepreneur = this.entrepreneurService.getEntrepreneurById(UserId);
List<Project> Project_List = new ArrayList<>();
Project_List.add(entrepreneur.getProjectParticipation());
return Project_List;
}
public Iterable<Entrepreneur> getAllEntrepreneurs() {
return entrepreneurService.getAllEntrepreneurs();
}
/**
* Checks if an entrepreneur with the given email has a project that is ACTIVE.
*
* @param email The email of the entrepreneur.
* @return true if the entrepreneur has an active project, false otherwise.
*/
public Boolean checkIfEntrepreneurProjectActive(String email) {
User user = this.userService.getUserByEmail(email);
if (user == null) {
return false;
}
Long userId = user.getIdUser();
Entrepreneur entrepreneur = this.entrepreneurService.getEntrepreneurById(userId);
if (entrepreneur == null) {
return false;
}
Project proposedProject = entrepreneur.getProjectProposed();
return proposedProject != null && proposedProject.getProjectStatus() == ACTIVE;
}
/**
* Checks if an entrepreneur with the given email has proposed a project.
*
* @param email The email of the entrepreneur.
* @return true if the entrepreneur has a proposed project, false otherwise.
*/
public Boolean entrepreneurHasPendingRequestedProject(String email) {
User user = this.userService.getUserByEmail(email);
if (user == null) {
return false;
}
Long userId = user.getIdUser();
Entrepreneur entrepreneur = this.entrepreneurService.getEntrepreneurById(userId);
if (entrepreneur == null) {
return false;
}
Project proposedProject = entrepreneur.getProjectProposed();
if (entrepreneur.getProjectProposed() == null) {
return false;
}
return proposedProject.getProjectStatus() == PENDING;
}
}

View File

@ -25,8 +25,11 @@ import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.Map;
import java.util.Set;
@Service
public class SharedApiService {
@ -79,7 +82,7 @@ public class SharedApiService {
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
Project project = this.projectService.getProjectById(projectId);
return this.sectionCellService.getSectionCellsByProjectAndSectionIdBeforeDate(
return this.sectionCellService.getLatestSectionCellsByIdReferenceBeforeDate(
project, sectionId, dateTime);
}
@ -95,31 +98,36 @@ public class SharedApiService {
}
Project project = this.projectService.getProjectById(projectId);
List<SectionCell> allSectionCells = new ArrayList<SectionCell>();
project.getListSectionCell()
Map<Long, SectionCell> latestSectionCellsMap =
new HashMap<>(); // List for the intermediate result
// Iterate through all SectionCells associated with the project
// This loop iterates over project.getListSectionCell() but does NOT modify it which causes
// ConcurrentModificationException.
// Modifications are done only on the latestSectionCellsMap (which is safe).
project.getListSectionCell() // <-- Iterating over the original list (read-only)
.forEach(
projectCell -> {
AtomicBoolean sameReferenceId =
new AtomicBoolean(false); // side effect lambdas
allSectionCells.forEach(
selectedCell -> {
if (projectCell
.getIdReference()
.equals(selectedCell.getIdReference())) {
sameReferenceId.set(true);
Long idReference = projectCell.getIdReference();
// Check if we have already seen a SectionCell with this idReference in
// our map
if (latestSectionCellsMap.containsKey(idReference)) {
SectionCell existingCell = latestSectionCellsMap.get(idReference);
// Compare modification dates. If the current cell is newer, replace
// the one in the map.
if (projectCell
.getModificationDate()
.isAfter(selectedCell.getModificationDate())) {
allSectionCells.remove(selectedCell);
allSectionCells.add(projectCell);
.isAfter(existingCell.getModificationDate())) {
latestSectionCellsMap.put(idReference, projectCell);
}
} else {
// If this is the first time we encounter this idReference, add the
// cell to the map.
latestSectionCellsMap.put(idReference, projectCell);
}
});
if (!sameReferenceId.get()) {
allSectionCells.add(projectCell);
}
});
return allSectionCells;
return new ArrayList<>(latestSectionCellsMap.values());
}
// TODO: test
@ -163,18 +171,26 @@ public class SharedApiService {
"User {} tried to check the appointments related to the project {}",
mail,
projectId);
Iterable<SectionCell> sectionCells =
this.sectionCellService.getSectionCellsByProject(
projectService.getProjectById(projectId),
2L); // sectionId useless in this function ?
List<Appointment> appointments = new ArrayList<Appointment>();
sectionCells.forEach(
Project project = projectService.getProjectById(projectId);
Iterable<SectionCell> sectionCellsIterable =
this.sectionCellService.getSectionCellsByProject(project);
// Use a Set to collect unique appointments
Set<Appointment> uniqueAppointments = new HashSet<>();
sectionCellsIterable.forEach(
sectionCell -> {
appointments.addAll(
List<Appointment> sectionAppointments =
this.sectionCellService.getAppointmentsBySectionCellId(
sectionCell.getIdSectionCell()));
sectionCell.getIdSectionCell());
// Add all appointments from this section cell to the Set
uniqueAppointments.addAll(sectionAppointments);
});
return appointments;
// Convert the Set back to a List for the return value
return new ArrayList<>(uniqueAppointments);
}
public void getPDFReport(long appointmentId, String mail)

View File

@ -72,4 +72,10 @@ public class UtilsService {
return false;
}
}
public Boolean checkEntrepreneurNotPending(String email) {
// Throws 404 if user not found
User user = userService.getUserByEmail(email);
return !user.isPending();
}
}

View File

@ -14,7 +14,10 @@ import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
@ -116,6 +119,18 @@ public class SectionCellService {
return this.sectionCellRepository.findByProjectSectionCellAndSectionId(project, sectionId);
}
public Iterable<SectionCell> getSectionCellsByProject(Project project) {
logger.info("Fetching SectionCells for Project ID: {}", project.getIdProject());
Iterable<SectionCell> sectionCells =
this.sectionCellRepository.findByProjectSectionCell(project);
List<SectionCell> sectionCellList = new ArrayList<>();
sectionCells.forEach(
cell -> {
sectionCellList.add(cell);
});
return sectionCellList;
}
public Long getProjectId(Long sectionCellId) {
SectionCell sectionCell = getSectionCellById(sectionCellId);
Project sectionProject = sectionCell.getProjectSectionCell();
@ -132,4 +147,37 @@ public class SectionCellService {
return sectionCellRepository.findByProjectSectionCellAndSectionIdAndModificationDateBefore(
project, sectionId, date);
}
public Iterable<SectionCell> getLatestSectionCellsByIdReferenceBeforeDate(
Project project, long sectionId, LocalDateTime date) {
// 1. Fetch ALL relevant SectionCells modified before the date
Iterable<SectionCell> allMatchingCells =
sectionCellRepository.findByProjectSectionCellAndSectionIdAndModificationDateBefore(
project, sectionId, date);
// 2. Find the latest for each idReference
Map<Long, SectionCell> latestCellsByIdReference = new HashMap<>();
for (SectionCell cell : allMatchingCells) {
Long idReference = cell.getIdReference();
// Check if we've seen this idReference before
if (latestCellsByIdReference.containsKey(idReference)) {
// If yes, compare modification dates
SectionCell existingLatest = latestCellsByIdReference.get(idReference);
// If the current cell is more recent, update the map
if (cell.getModificationDate().isAfter(existingLatest.getModificationDate())) {
latestCellsByIdReference.put(idReference, cell);
}
} else {
// If this is the first time we see this idReference, add it to the map
latestCellsByIdReference.put(idReference, cell);
}
}
// 3. Return the collection of the latest cells (the values from the map)
return latestCellsByIdReference.values();
}
}

View File

@ -1,6 +1,6 @@
spring.application.name=myinpulse
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:7080/realms/test/protocol/openid-connect/certs
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:7080/realms/test
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:7080/realms/${VITE_KEYCLOAK_REALM}/protocol/openid-connect/certs
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:7080/realms/${VITE_KEYCLOAK_REALM}
spring.datasource.url=jdbc:postgresql://${DATABASE_URL}/${BACKEND_DB}
spring.datasource.username=${BACKEND_USER}
spring.datasource.password=${BACKEND_PASSWORD}

View File

@ -0,0 +1,13 @@
spring.application.name=myinpulse
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:7080/realms/test/protocol/openid-connect/certs
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:7080/realms/test
logging.pattern.console=%d{yyyy-MMM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create

View File

@ -1,99 +0,0 @@
TRUNCATE project, user_inpulse, entrepreneur, administrator, section_cell, appointment, report, annotation CASCADE;
SELECT setval('annotation_id_annotation_seq', 1, false);
SELECT setval('appointment_id_appointment_seq', 1, false);
SELECT setval('make_appointment_id_make_appointment_seq', 1, false);
SELECT setval('project_id_project_seq', 1, false);
SELECT setval('report_id_report_seq', 1, false);
SELECT setval('section_cell_id_section_cell_seq', 1, false);
SELECT setval('user_inpulse_id_user_seq', 1, false);
INSERT INTO user_inpulse (user_surname, user_name, primary_mail, secondary_mail, phone_number)
VALUES ('Dupont', 'Dupond', 'super@mail.fr', 'super2@mail.fr', '06 45 72 45 98'),
('Martin', 'Matin', 'genial@mail.fr', 'genial2@mail.fr', '06 52 14 58 73'),
('Charvet', 'Lautre', 'mieux@tmail.fr', 'mieux2@tmail.fr', '07 49 82 16 35'),
('Leguez', 'Theo', 'bof@mesmails.fr', 'bof2@mesmails.fr', '+33 6 78 14 25 29'),
('Kia', 'Bi', 'special@mail.fr', 'special2@mail.fr', '07 65 31 38 95'),
('Ducaillou', 'Pierre', 'maildefou@xyz.fr', 'maildefou2@xyz.fr', '06 54 78 12 62'),
('Janine', 'Dave', 'janine@labri.fr', 'janine2@labri.fr', '06 87 12 45 95');
INSERT INTO administrator (id_administrator)
VALUES (7);
INSERT INTO project (project_name, logo, creation_date, project_status, id_administrator)
VALUES ('Eau du robinet', decode('013d7d16d7ad4fefb61bd95b765c8ceb', 'hex'), TO_DATE('01-OCT-2023', 'DD-MON-YYYY'),
'En cours', 7),
('Air oxygéné', decode('150647a0984e8f228cd14b54', 'hex'), TO_DATE('04-APR-2024', 'DD-MON-YYYY'), 'En cours', 7),
('Débat concours', decode('022024abd5486e245c145dda65116f', 'hex'), TO_DATE('22-NOV-2023', 'DD-MON-YYYY'),
'Suspendu', 7),
('HDeirbMI', decode('ab548d6c1d595a2975e6476f544d14c55a', 'hex'), TO_DATE('07-DEC-2024', 'DD-MON-YYYY'),
'Lancement', 7);
INSERT INTO entrepreneur (school, course, snee_status, id_entrepreneur, id_project_participation, id_project_proposed)
VALUES ('ENSEIRB-MATMECA', 'INFO', TRUE, 1, 4, 4),
('ENSC', 'Cognitique', TRUE, 2, 2, null),
('ENSEIRB-MATMECA', 'MATMECA', FALSE, 3, 3, 3),
('SupOptique', 'Classique', TRUE, 4, 1, 1),
('ENSEGID', 'Géoscience', FALSE, 5, 1, null),
('ENSMAC', 'Matériaux composites - Mécanique', FALSE, 6, 2, 2);
INSERT INTO section_cell (title, content_section_cell, modification_date, id_project)
VALUES ('Problème', 'les problèmes...', TO_TIMESTAMP('15-JAN-2025 09:30:20', 'DD-MON-YYYY, HH24:MI:SS'), 2),
('Segment de client', 'Le segment AB passant le client n°8 est de longueur 32mm.
Le segment BC a quant à lui un longueur de 28mm. Quelle la longueur du segment AC ?',
TO_TIMESTAMP('12-OCT-2022 17:47:38', 'DD-MON-YYYY, HH24:MI:SS'), 3),
('Proposition de valeur unique', '''Son prix est de 2594€'' ''Ah oui c''est unique en effet',
TO_TIMESTAMP('25-MAY-2024 11:12:04', 'DD-MON-YYYY, HH24:MI:SS'), 2),
('Solution', 'Un problème ? Une solution', TO_TIMESTAMP('08-FEB-2024 10:17:53', 'DD-MON-YYYY, HH24:MI:SS'), 1),
('Canaux', 'Ici nous avons la Seine, là-bas le Rhin, oh et plus loin le canal de Suez',
TO_TIMESTAMP('19-JUL-2023 19:22:45', 'DD-MON-YYYY, HH24:MI:SS'), 4),
('Sources de revenus', 'Y''en n''a pas on est pas payé. Enfin y''a du café quoi',
TO_TIMESTAMP('12-JAN-2025 11:40:26', 'DD-MON-YYYY, HH24:MI:SS'), 1),
('Structure des coûts', '''Ah oui là ça va faire au moins 1000€ par mois'', Eirbware',
TO_TIMESTAMP('06-FEB-2025 13:04:06', 'DD-MON-YYYY, HH24:MI:SS'), 3),
('Indicateurs clés', 'On apprend les clés comme des badges, ça se fait',
TO_TIMESTAMP('05-FEB-2025 12:42:38', 'DD-MON-YYYY, HH24:MI:SS'), 4),
('Avantages concurrentiel', 'On est meilleur', TO_TIMESTAMP('23-APR-2024 16:24:02', 'DD-MON-YYYY, HH24:MI:SS'),
2);
INSERT INTO appointment (appointment_date, appointment_time, appointment_duration, appointment_place,
appointment_subject)
VALUES (TO_DATE('24-DEC-2023', 'DD-MON-YYYY'), '00:00:00', '00:37:53', 'À la maison', 'Ouvrir les cadeaux'),
(TO_DATE('15-AUG-2024', 'DD-MON-YYYY'), '22:35:00', '00:12:36', 'Sur les quais ou dans un champ probablement',
'BOUM BOUM les feux d''artifices (on fête quoi déjà ?)'),
(TO_DATE('28-FEB-2023', 'DD-MON-YYYY'), '14:20:00', '00:20:00', 'Salle TD 15',
'Ah mince c''est pas une année bissextile !'),
(TO_DATE('23-JAN-2024', 'DD-MON-YYYY'), '12:56:27', '11:03:33', 'Là où le vent nous porte',
'Journée la plus importante de l''année'),
(TO_DATE('25-AUG-2025', 'DD-MON-YYYY'), '00:09:00', '01:00:00', 'Euh c''est par où l''amphi 56 ?',
'Rentrée scolaire (il fait trop froid c''est quoi ça on est en août)');
INSERT INTO report (report_content, id_appointment)
VALUES ('Ah oui ça c''est super, ah ouais j''aime bien, bien vu de penser à ça', 1),
('Bonne réunion', 3),
('Ouais, j''ai rien compris mais niquel on fait comme vous avez dit', 3),
('Non non ça va pas du tout ce que tu me proposes, faut tout refaire', 4),
('Réponse de la DSI : non', 2),
('Trop dommage qu''Apple ait sorti leur logiciel avant nous, on avait la même idée et tout on aurait tellement pu leur faire de la concurrence',
5);
INSERT INTO annotation (comment, id_administrator, id_section_cell)
VALUES ('faut changer ça hein', 7, 5),
('??? sérieusement, vous pensez que c''est une bonne idée ?', 7, 7),
('ok donc ça c''est votre business plan, bah glhf la team', 7, 2);

View File

@ -1,2 +0,0 @@
DROP TABLE IF EXISTS administrateurs, projets, utilisateurs, entrepreneurs, sections, rendez_vous, comptes_rendus, concerner CASCADE;
DROP TABLE IF EXISTS administrator, project, user_inpulse, entrepreneur, section_cell, appointment, make_appointment, report, annotation, concern CASCADE;

View File

@ -0,0 +1,92 @@
-- Initial Database State Script
-- Insert Administrators
INSERT INTO administrator (idAdministrator) VALUES
(1),
(2),
(3); -- Added more administrators
-- Insert User Inpulse (some pending)
INSERT INTO user_inpulse (idUser, userSurname, userName, primaryMail, secondaryMail, phoneNumber, pending) VALUES
(1, 'Doe', 'John', 'john.doe@example.com', NULL, '123-456-7890', FALSE),
(2, 'Smith', 'Jane', 'jane.smith@example.com', 'jane.s@altmail.com', '987-654-3210', FALSE),
(3, 'Williams', 'Peter', 'peter.w@example.com', NULL, NULL, TRUE), -- Pending user
(4, 'Jones', 'Mary', 'mary.j@example.com', NULL, '555-123-4567', FALSE),
(5, 'Brown', 'Michael', 'michael.b@example.com', 'mike.brown@work.com', '111-222-3333', FALSE),
(6, 'Garcia', 'Maria', 'maria.g@example.com', NULL, '444-555-6666', TRUE), -- Another pending user
(7, 'Miller', 'David', 'david.m@example.com', NULL, '777-888-9999', FALSE);
-- Insert Entrepreneurs
INSERT INTO entrepreneur (idEntrepreneur, school, course, sneeStatus, idProjectParticipation, idProjectProposed, idMakeAppointment) VALUES
(1, 'Business School A', 'MBA', TRUE, NULL, NULL, NULL),
(2, 'Tech University B', 'Computer Science', FALSE, NULL, NULL, NULL),
(3, 'Art Institute C', 'Graphic Design', TRUE, NULL, NULL, NULL),
(4, 'Science College D', 'Biology', FALSE, NULL, NULL, NULL),
(5, 'Engineering School E', 'Mechanical Engineering', TRUE, NULL, NULL, NULL); -- Added more entrepreneurs
-- Insert Projects
-- Main project
INSERT INTO project (IdProject, projectName, loga, creationDate, projectStatus, pending, idAdministrator, entrepreneurProposed) VALUES
(101, 'Innovative Startup Idea', NULL, '2023-10-26', 'In Progress', FALSE, 1, NULL),
(102, 'Pending Project Alpha', NULL, '2024-01-15', 'Planning', TRUE, 1, NULL), -- Pending project
(103, 'Pending Project Beta', NULL, '2024-02-20', 'Idea Stage', TRUE, NULL, 1), -- Another pending project, proposed by entrepreneur 1
(104, 'E-commerce Platform Development', NULL, '2024-03-10', 'Completed', FALSE, 2, NULL), -- Completed project
(105, 'Mobile App for Education', NULL, '2024-04-01', 'In Progress', FALSE, 3, NULL),
(106, 'Pending Research Proposal', NULL, '2024-04-25', 'Drafting', TRUE, NULL, 4); -- Pending project proposed by entrepreneur 4
-- Link Entrepreneurs to projects (Project Participation and Proposed)
-- Based on the current schema, we'll update the entrepreneur table directly.
-- This might need adjustment based on actual application logic if it's a many-to-many.
UPDATE entrepreneur SET idProjectParticipation = 101 WHERE idEntrepreneur IN (1, 2); -- Entrepreneurs 1 and 2 participate in Project 101
UPDATE entrepreneur SET idProjectParticipation = 104 WHERE idEntrepreneur = 3; -- Entrepreneur 3 participates in Project 104
UPDATE entrepreneur SET idProjectProposed = 103 WHERE idEntrepreneur = 1; -- Entrepreneur 1 proposed Project 103
UPDATE entrepreneur SET idProjectProposed = 106 WHERE idEntrepreneur = 4; -- Entrepreneur 4 proposed Project 106
-- Insert Section Cells for the main project (Project 101) and other projects
INSERT INTO section_cell (idSectionCell, IdReference, sectionid, contentSectionCell, modificationDate, idProject) VALUES
(1001, NULL, 1, 'Initial project description for Project 101.', '2023-10-26 10:00:00', 101),
(1002, 1001, 2, 'Market analysis summary for Project 101.', '2023-10-27 14:30:00', 101),
(1003, NULL, 3, 'Team member profiles for Project 101.', '2023-10-28 09:00:00', 101),
(1004, NULL, 1, 'Project brief for Project 104.', '2024-03-10 11:00:00', 104),
(1005, 1004, 2, 'Technical specifications for Project 104.', '2024-03-15 16:00:00', 104),
(1006, NULL, 1, 'Initial concept for Project 105.', '2024-04-01 09:30:00', 105);
-- Insert Appointments
INSERT INTO appointment (idAppointment, appointmentDate, appointmentTime, appointmentDuration, appointmentPlace, appointmentSubject) VALUES
(2001, '2023-11-05', '11:00:00', '01:00:00', 'Meeting Room A', 'Project 101 Kick-off Meeting'),
(2002, '2023-11-10', '14:00:00', '00:30:00', 'Online', 'Project 101 Follow-up Discussion'),
(2003, '2024-03-20', '10:00:00', '01:30:00', 'Client Office', 'Project 104 Final Review'),
(2004, '2024-04-10', '15:00:00', '00:45:00', 'Video Call', 'Project 105 Initial Sync'); -- Added more appointments
-- Insert Concerns (linking Appointments and Section Cells)
INSERT INTO concern (IdAppointment, idSectionCell) VALUES
(2001, 1001), -- Kick-off meeting concerns section 1001 (Project 101)
(2001, 1002), -- Kick-off meeting concerns section 1002 (Project 101)
(2002, 1002), -- Follow-up concerns section 1002 (Project 101)
(2003, 1004), -- Project 104 review concerns section 1004
(2003, 1005), -- Project 104 review concerns section 1005
(2004, 1006); -- Project 105 sync concerns section 1006
-- Insert Make Appointments (linking Appointments, Administrators, and Entrepreneurs)
INSERT INTO make_appointment (idMakeAppointment, idAppointment, idAdministrator, idEntrepreneur) VALUES
(3001, 2001, 1, 1), -- Admin 1 scheduled appointment 2001 with Entrepreneur 1
(3002, 2001, 1, 2), -- Admin 1 scheduled appointment 2001 with Entrepreneur 2
(3003, 2002, 1, 1), -- Admin 1 scheduled appointment 2002 with Entrepreneur 1
(3004, 2003, 2, 3), -- Admin 2 scheduled appointment 2003 with Entrepreneur 3
(3005, 2004, 3, 5); -- Admin 3 scheduled appointment 2004 with Entrepreneur 5
-- Insert Annotations (linking to Section Cells and Administrators)
INSERT INTO annotation (IdAnnotation, comment, idSectionCell, idAdministrator) VALUES
(4001, 'Needs more detail on market size.', 1002, 1),
(4002, 'Looks good.', 1001, 1),
(4003, 'Confirm technical requirements.', 1005, 2),
(4004, 'Initial thoughts on UI/UX.', 1006, 3); -- Added more annotations
-- Insert Reports (linking to Make Appointments)
INSERT INTO report (IdReport, reportContent, idMakeAppointment) VALUES
(5001, 'Discussed project scope and timelines for Project 101.', 3001),
(5002, 'Reviewed market analysis feedback for Project 101.', 3003),
(5003, 'Final sign-off on Project 104 deliverables.', 3004),
(5004, 'Discussed initial concepts for Project 105.', 3005); -- Added more reports
-- The project ID for the main project is 101.

View File

@ -8,9 +8,10 @@ import static org.mockito.Mockito.when;
import enseirb.myinpulse.model.*;
import enseirb.myinpulse.service.SharedApiService;
import enseirb.myinpulse.service.database.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import enseirb.myinpulse.service.UtilsService;
import com.itextpdf.text.DocumentException;
import org.junit.jupiter.api.BeforeAll; // Use BeforeAll for static setup
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; // Keep this import
@ -22,8 +23,6 @@ import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@ -123,20 +122,6 @@ public class SharedApiServiceTest {
when(mockUtilsService.isAllowedToCheckProject(eq(staticUnauthorizedMail), anyLong()))
.thenReturn(false); // Unauthorized entrepreneur NOT allowed for ANY project ID by
// default
// Add more specific mock setups here if needed for entrepreneur tests
// E.g., If you have a test specifically for an entrepreneur accessing THEIR project:
// Entrepreneur testEntrepreneur =
// entrepreneurService.addEntrepreneur(getTestEntrepreneur("specific_linked_entrepreneur"));
// Project linkedProject =
// projectService.addNewProject(getTestProject("specific_linked_project",
// staticAuthorizedAdmin));
// // Link testEntrepreneur to linkedProject in the database setup...
// when(mockUtilsService.isAllowedToCheckProject(eq(testEntrepreneur.getPrimaryMail()),
// eq(linkedProject.getIdProject()))).thenReturn(true);
// when(mockUtilsService.isAllowedToCheckProject(eq(testEntrepreneur.getPrimaryMail()),
// anyLong())).thenReturn(false); // Deny for other projects
}
// --- Helper Methods (Can remain non-static or static as needed) ---
@ -176,6 +161,17 @@ public class SharedApiServiceTest {
return sectionCell;
}
private static SectionCell getTestSectionCell(
Project project, Long sectionId, String content, LocalDateTime date, Long refrenceId) {
SectionCell sectionCell = new SectionCell();
sectionCell.setProjectSectionCell(project);
sectionCell.setSectionId(sectionId);
sectionCell.setContentSectionCell(content);
sectionCell.setModificationDate(date);
sectionCell.setIdReference(refrenceId);
return sectionCell;
}
private static Appointment getTestAppointment(
LocalDate date,
LocalTime time,
@ -307,6 +303,262 @@ public class SharedApiServiceTest {
assertEquals(HttpStatus.UNAUTHORIZED, exception.getStatusCode());
}
/*
* Tests retrieving section cells for a specific project and section ID before a given date
* when the user is authorized and matching cells exist.
* Verifies that only the correct cells are returned.
*/
@Test
// Commenting out failing test
void testGetSectionCells_Authorized_Found() {
Long targetSectionId = 1L;
// Set a date filter slightly in the future so our "latest before" cell is included
LocalDateTime dateFilter = LocalDateTime.now().plusMinutes(5);
// Creating versions of the SAME SectionCell (share the same idReference)
// the first version. This will get a GENERATED idReference.
SectionCell firstVersion =
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Content V1 (Oldest)",
LocalDateTime.now().minusDays(3) // Oldest date
);
sectionCellService.addNewSectionCell(firstVersion);
Long sharedIdReference = firstVersion.getIdReference();
assertNotNull(
sharedIdReference,
"idReference should be generated after saving the first version");
System.out.println("Generated sharedIdReference: " + sharedIdReference);
// Create subsequent versions and MANUALLY set the SAME idReference.
// These represent updates to the cell identified by sharedIdReference.
SectionCell middleVersion =
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Content V2 (Middle)",
LocalDateTime.now().minusDays(2), // Middle date, before filter
sharedIdReference);
middleVersion = sectionCellService.addNewSectionCell(middleVersion);
sectionCellService.updateSectionCellReferenceId(
middleVersion.getIdSectionCell(), sharedIdReference);
SectionCell latestBeforeFilter =
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Content V3 (Latest Before Filter)",
LocalDateTime.now().minusDays(1), // Latest date before filter
sharedIdReference);
latestBeforeFilter = sectionCellService.addNewSectionCell(latestBeforeFilter);
sectionCellService.updateSectionCellReferenceId(
latestBeforeFilter.getIdSectionCell(), sharedIdReference);
SectionCell futureVersion =
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Content V4 (Future - Should Be Excluded)",
LocalDateTime.now().plusDays(1), // Date is AFTER the filter
sharedIdReference);
futureVersion = sectionCellService.addNewSectionCell(futureVersion);
sectionCellService.updateSectionCellReferenceId(
futureVersion.getIdSectionCell(), sharedIdReference);
// --- Create other SectionCells that should NOT be included (different sectionId or
// project) ---
// Cell in a different section ID
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject,
99L, // Different sectionId
"Content in Different Section",
LocalDateTime.now()));
// Act
Iterable<SectionCell> result =
sharedApiService.getSectionCells(
staticAuthorizedProject.getIdProject(), // Use static project ID
targetSectionId,
dateFilter.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
staticAuthorizedMail); // Use static authorized mail
List<SectionCell> resultList = TestUtils.toList(result);
assertEquals(1, resultList.size());
// Verify that the returned cell is the 'latestBeforeFilter' cell
// Comparing by idSectionCell is a good way to verify the exact entity
assertEquals(
latestBeforeFilter.getIdSectionCell(),
resultList.get(0).getIdSectionCell(),
"The returned SectionCell should be the one with the latest modification date before the filter.");
// Also assert the idReference and content
assertEquals(
sharedIdReference,
resultList.get(0).getIdReference(),
"The returned cell should have the shared idReference.");
assertEquals(
"Content V3 (Latest Before Filter)",
resultList.get(0).getContentSectionCell(),
"The returned cell should have the correct content.");
}
/*
* Tests retrieving the most recent section cell for each unique idReference
* within a project when the user is authorized and cells exist.
* Verifies that only the latest version of each referenced cell is returned.
*/
// Tests getAllSectionCells
@Test
// Commenting out failing test - Removed this comment as we are fixing it
void testGetAllSectionCells_Authorized_FoundLatest() {
// Arrange: Create specific SectionCells for this test
// Define the idReference values we will use for grouping
Long refIdGroup1 = 101L;
Long refIdGroup2 = 102L;
Long refIdOtherProject = 103L;
// --- Create and Add Cells for Group 1 (refIdGroup1) ---
// Create the older cell for group 1
SectionCell tempOldCell1 =
getTestSectionCell(
staticAuthorizedProject, // Project
1L, // Section ID (assuming this groups by section within refId)
"Ref1 Old", // Name
LocalDateTime.now().minusDays(3), // Date (older)
null); // Pass null or let getTestSectionCell handle it, we'll set
// idReference later
final SectionCell oldCell1 =
sectionCellService.addNewSectionCell(tempOldCell1); // Add to DB
// Create the newer cell for group 1
SectionCell tempNewerCell1 =
getTestSectionCell(
staticAuthorizedProject, // Project
1L, // Section ID
"Ref1 Newer", // Name
LocalDateTime.now().minusDays(2), // Date (newer than oldCell1)
null); // Pass null
final SectionCell newerCell1 =
sectionCellService.addNewSectionCell(tempNewerCell1); // Add to DB
// Now, update the idReference for both cells in Group 1 to the desired value
sectionCellService.updateSectionCellReferenceId(oldCell1.getIdSectionCell(), refIdGroup1);
sectionCellService.updateSectionCellReferenceId(newerCell1.getIdSectionCell(), refIdGroup1);
// --- Create and Add Cells for Group 2 (refIdGroup2) ---
// Create the older cell for group 2
SectionCell tempOldCell2 =
getTestSectionCell(
staticAuthorizedProject, // Project
2L, // Section ID (different section)
"Ref2 Old", // Name
LocalDateTime.now().minusDays(1), // Date (older than newerCell2)
null); // Pass null
final SectionCell oldCell2 =
sectionCellService.addNewSectionCell(tempOldCell2); // Add to DB
// Create the newer cell for group 2
SectionCell tempNewerCell2 =
getTestSectionCell(
staticAuthorizedProject, // Project
2L, // Section ID
"Ref2 Newer", // Name
LocalDateTime.now(), // Date (latest)
null); // Pass null
final SectionCell newerCell2 =
sectionCellService.addNewSectionCell(tempNewerCell2); // Add to DB
// Now, update the idReference for both cells in Group 2 to the desired value
sectionCellService.updateSectionCellReferenceId(oldCell2.getIdSectionCell(), refIdGroup2);
sectionCellService.updateSectionCellReferenceId(newerCell2.getIdSectionCell(), refIdGroup2);
// --- Create and Add Cell for Other Project (refIdOtherProject) ---
Project otherProject =
projectService.addNewProject(
getTestProject(
"other_project_for_cell_test",
administratorService.addAdministrator(
getTestAdmin("other_admin_cell_test"))));
SectionCell tempOtherProjectCell =
getTestSectionCell(
otherProject, // DIFFERENT Project
1L, // Section ID
"Other Project Cell", // Name
LocalDateTime.now(), // Date
null); // Pass null
final SectionCell otherProjectCell =
sectionCellService.addNewSectionCell(tempOtherProjectCell); // Add to DB
// Now, update the idReference for the Other Project cell
sectionCellService.updateSectionCellReferenceId(
otherProjectCell.getIdSectionCell(), refIdOtherProject);
// Act
// Ensure the service call uses the correct project ID and mail
Iterable<SectionCell> result =
sharedApiService.getAllSectionCells(
staticAuthorizedProject.getIdProject(), // Use static project ID
staticAuthorizedMail); // Use static authorized mail
List<SectionCell> resultList = TestUtils.toList(result);
// Assert
// We expect 2 cells from the staticAuthorizedProject:
// - The latest one from refIdGroup1 (newerCell1)
// - The latest one from refIdGroup2 (newerCell2)
assertEquals(2, resultList.size());
// Assert that the result list contains the LATEST cell from each group within the correct
// project
assertTrue(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(newerCell1.getIdSectionCell())),
"Should contain the latest cell for Group 1"); // Add assertion message
assertTrue(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(newerCell2.getIdSectionCell())),
"Should contain the latest cell for Group 2"); // Add assertion message
// Assert that the result list does NOT contain the OLDER cells from the correct project
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(oldCell1.getIdSectionCell())),
"Should not contain the older cell for Group 1"); // Add assertion message
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(oldCell2.getIdSectionCell())),
"Should not contain the older cell for Group 2"); // Add assertion message
// Assert that the result list does NOT contain the cell from the other project
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(otherProjectCell.getIdSectionCell())),
"Should not contain cells from other projects"); // Add assertion message
}
/*
* _____ _ ____ _ ____ _ _ ____
* |_ _|__ ___| |_ / ___| ___| |_| _ \ _ __ ___ (_) ___ ___| |_| __ ) _ _
@ -459,6 +711,129 @@ public class SharedApiServiceTest {
assertEquals(HttpStatus.UNAUTHORIZED, exception.getStatusCode());
}
@PersistenceContext // Inject EntityManager
private EntityManager entityManager;
// Assume these static variables are defined elsewhere in your test class
// private static Project staticAuthorizedProject;
// private static String staticAuthorizedMail;
// private static Administrator staticAuthorizedAdmin;
// Assume getTestSectionCell, getTestProject, getTestAdmin, getTestAppointment, TestUtils.toList
// are defined elsewhere
@Test
void testGetAppointmentsByProjectId_Authorized_Found() {
// Arrange: Create specific SectionCells and Appointments for this test
SectionCell cell1 =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject, 1L, "Cell 1 Test", LocalDateTime.now()));
SectionCell cell2 =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject, 2L, "Cell 2 Test", LocalDateTime.now()));
Project otherProject =
projectService.addNewProject(
getTestProject(
"other_project_app_test",
administratorService.addAdministrator(
getTestAdmin("other_admin_app_test"))));
SectionCell otherProjectCell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
otherProject,
1L,
"Other Project Cell App Test",
LocalDateTime.now()));
// Create Appointments with SectionCells lists (Owning side)
Appointment app1 =
getTestAppointment(
LocalDate.now().plusDays(10),
LocalTime.NOON,
LocalTime.of(0, 30),
"Place 1 App Test",
"Subject 1 App Test",
List.of(cell1), // This links Appointment to SectionCell
null);
Appointment savedApp1 = appointmentService.addNewAppointment(app1);
Appointment app2 =
getTestAppointment(
LocalDate.now().plusDays(11),
LocalTime.NOON.plusHours(1),
LocalTime.of(1, 0),
"Place 2 App Test",
"Subject 2 App Test",
List.of(cell1, cell2), // This links Appointment to SectionCells
null);
Appointment savedApp2 = appointmentService.addNewAppointment(app2);
Appointment otherApp =
getTestAppointment(
LocalDate.now().plusDays(12),
LocalTime.MIDNIGHT,
LocalTime.of(0, 15),
"Other Place App Test",
"Other Subject App Test",
List.of(otherProjectCell), // This links Appointment to SectionCell
null);
Appointment savedOtherApp =
appointmentService.addNewAppointment(otherApp); // Capture saved entity
// --- IMPORTANT DEBUGGING STEPS ---
// Flush pending changes to the database (including join table inserts)
entityManager.flush();
// Clear the persistence context cache to ensure entities are loaded fresh from the database
entityManager.clear();
// --- END IMPORTANT DEBUGGING STEPS ---
// --- Add Debug Logging Here ---
// Re-fetch cells to see their state after saving Appointments and flushing/clearing cache
// These fetches should load from the database due to entityManager.clear()
SectionCell fetchedCell1_postPersist =
sectionCellService.getSectionCellById(cell1.getIdSectionCell());
SectionCell fetchedCell2_postPersist =
sectionCellService.getSectionCellById(cell2.getIdSectionCell());
SectionCell fetchedOtherCell_postPersist =
sectionCellService.getSectionCellById(otherProjectCell.getIdSectionCell());
// Access the lazy collections to see if they are populated from the DB
// This access should trigger lazy loading if the data is in the DB
List<Appointment> cell1Apps_postPersist =
fetchedCell1_postPersist.getAppointmentSectionCell();
List<Appointment> cell2Apps_postPersist =
fetchedCell2_postPersist.getAppointmentSectionCell();
List<Appointment> otherCellApps_postPersist =
fetchedOtherCell_postPersist.getAppointmentSectionCell();
// Ensure logging is enabled in SharedApiService and SectionCellService methods called below
Iterable<Appointment> result =
sharedApiService.getAppointmentsByProjectId(
staticAuthorizedProject.getIdProject(), // Use static project ID
staticAuthorizedMail); // Use static authorized mail
List<Appointment> resultList = TestUtils.toList(result);
// Assert
assertEquals(2, resultList.size());
assertTrue(
resultList.stream()
.anyMatch(a -> a.getIdAppointment().equals(savedApp1.getIdAppointment())));
assertTrue(
resultList.stream()
.anyMatch(a -> a.getIdAppointment().equals(savedApp2.getIdAppointment())));
assertFalse(
resultList.stream()
.anyMatch(
a ->
a.getIdAppointment()
.equals(savedOtherApp.getIdAppointment())));
}
/*
* Tests creating a new appointment request when the user is authorized
* for the project linked to the appointment's section cell.
@ -544,443 +919,4 @@ public class SharedApiServiceTest {
a.getIdAppointment()
.equals(createdAppointment.getIdAppointment())));
}
/*
* Tests creating a new appointment request when the user is not authorized
* for the project linked to the appointment's section cell.
* Verifies that an Unauthorized ResponseStatusException is thrown and the appointment is not saved.
*/
@Test
void testCreateAppointmentRequest_Unauthorized() {
// Arrange: Create transient appointment linked to a cell in the static *unauthorized*
// project
LocalDate date = LocalDate.parse("2026-01-01");
LocalTime time = LocalTime.parse("10:00:00");
LocalTime duration = LocalTime.parse("00:30:00");
String place = "Meeting Room";
String subject = "Discuss Project";
String reportContent = "Initial Report";
SectionCell linkedCell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticUnauthorizedProject,
1L,
"Related Section Content",
LocalDateTime.now()));
Report newReport = getTestReport(reportContent);
Appointment newAppointment =
getTestAppointment(
date, time, duration, place, subject, List.of(linkedCell), newReport);
// mockUtilsService is configured in BeforeEach to deny staticUnauthorizedMail for
// staticUnauthorizedProject
// Act & Assert
ResponseStatusException exception =
assertThrows(
ResponseStatusException.class,
() -> {
sharedApiService.createAppointmentRequest(
newAppointment,
staticUnauthorizedMail); // Unauthorized user mail
});
assertEquals(HttpStatus.UNAUTHORIZED, exception.getStatusCode());
}
/*
_____ _ _ _
| ___|_ _(_) | ___ __| |
| |_ / _` | | |/ _ \/ _` |
| _| (_| | | | __/ (_| |
|_| \__,_|_|_|\___|\__,_|
_____ _____ ____ _____
|_ _| ____/ ___|_ _|
| | | _| \___ \ | |
| | | |___ ___) || |
|_| |_____|____/ |_|
*/
/* these tests fail because of the use of mockito's eq(),
* and since thee instances are technically not the same as
* as the classes used to turn them into persistant data
* (for e.g id are set by DB) so I have to add some equal functions
* probably and look at peer tests to see what they have done but for now
* I pushed this half-human code.
*/
// --- Test Methods (Use static data from @BeforeAll where possible) ---
/*
* Tests retrieving section cells for a specific project and section ID before a given date
* when the user is authorized and matching cells exist.
* Verifies that only the correct cells are returned.
*/
/*@Test*/
// Commenting out failing test
void testGetSectionCells_Authorized_Found() {
// Arrange: Create specific SectionCells for this test scenario
Long targetSectionId = 1L;
LocalDateTime dateFilter = LocalDateTime.now().plusDays(1);
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Old Content",
LocalDateTime.now().minusDays(2)));
SectionCell recentCell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Recent Content",
LocalDateTime.now().minusDays(1)));
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject, 2L, "Other Section", LocalDateTime.now()));
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject,
targetSectionId,
"Future Content",
LocalDateTime.now().plusDays(2)));
// Act
Iterable<SectionCell> result =
sharedApiService.getSectionCells(
staticAuthorizedProject.getIdProject(), // Use static project ID
targetSectionId,
dateFilter.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
staticAuthorizedMail); // Use static authorized mail
List<SectionCell> resultList = TestUtils.toList(result);
// Assert
assertEquals(1, resultList.size());
assertEquals(recentCell.getIdSectionCell(), resultList.get(0).getIdSectionCell());
}
/*
* Tests retrieving the most recent section cell for each unique idReference
* within a project when the user is authorized and cells exist.
* Verifies that only the latest version of each referenced cell is returned.
*/
// Tests getAllSectionCells
/*@Test*/
// Commenting out failing test
void testGetAllSectionCells_Authorized_FoundLatest() {
// Arrange: Create specific SectionCells for this test
Long refId1 = 101L;
Long refId2 = 102L;
SectionCell tempOldCell1 =
getTestSectionCell(
staticAuthorizedProject, 1L, "Ref1 Old", LocalDateTime.now().minusDays(3));
tempOldCell1.setIdReference(refId1);
final SectionCell oldCell1 = sectionCellService.addNewSectionCell(tempOldCell1);
SectionCell tempNewerCell1 =
getTestSectionCell(
staticAuthorizedProject,
1L,
"Ref1 Newer",
LocalDateTime.now().minusDays(2));
tempNewerCell1.setIdReference(refId1);
final SectionCell newerCell1 = sectionCellService.addNewSectionCell(tempNewerCell1);
SectionCell tempOldCell2 =
getTestSectionCell(
staticAuthorizedProject, 2L, "Ref2 Old", LocalDateTime.now().minusDays(1));
tempOldCell2.setIdReference(refId2);
final SectionCell oldCell2 = sectionCellService.addNewSectionCell(tempOldCell2);
SectionCell tempNewerCell2 =
getTestSectionCell(staticAuthorizedProject, 2L, "Ref2 Newer", LocalDateTime.now());
tempNewerCell2.setIdReference(refId2);
final SectionCell newerCell2 = sectionCellService.addNewSectionCell(tempNewerCell2);
Project otherProject =
projectService.addNewProject(
getTestProject(
"other_project_for_cell_test",
administratorService.addAdministrator(
getTestAdmin("other_admin_cell_test"))));
SectionCell tempOtherProjectCell =
getTestSectionCell(otherProject, 1L, "Other Project Cell", LocalDateTime.now());
tempOtherProjectCell.setIdReference(103L);
final SectionCell otherProjectCell =
sectionCellService.addNewSectionCell(tempOtherProjectCell);
// Act
Iterable<SectionCell> result =
sharedApiService.getAllSectionCells(
staticAuthorizedProject.getIdProject(), // Use static project ID
staticAuthorizedMail); // Use static authorized mail
List<SectionCell> resultList = TestUtils.toList(result);
// Assert
assertEquals(2, resultList.size()); // Expect 2 cells (one per idReference)
assertTrue(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(newerCell1.getIdSectionCell())));
assertTrue(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(newerCell2.getIdSectionCell())));
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(oldCell1.getIdSectionCell())));
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(oldCell2.getIdSectionCell())));
assertFalse(
resultList.stream()
.anyMatch(
cell ->
cell.getIdSectionCell()
.equals(otherProjectCell.getIdSectionCell())));
}
/*
* Tests retrieving entrepreneurs linked to a project when the user is authorized
* and entrepreneurs are linked.
* Verifies that the correct entrepreneurs are returned.
*/
// Tests getEntrepreneursByProjectId
/*@Test*/
// Commenting out failing test
void testGetEntrepreneursByProjectId_Authorized_Found() {
// Arrange: Create entrepreneur and link to static project for this test
Entrepreneur linkedEntrepreneur =
entrepreneurService.addEntrepreneur(
getTestEntrepreneur("linked_entrepreneur_test"));
// Fetch the static project to update its list
Project projectToUpdate =
projectService.getProjectById(staticAuthorizedProject.getIdProject());
projectToUpdate.updateListEntrepreneurParticipation(linkedEntrepreneur);
projectService.addNewProject(projectToUpdate); // Save the updated project
Entrepreneur otherEntrepreneur =
entrepreneurService.addEntrepreneur(getTestEntrepreneur("other_entrepreneur_test"));
// Act
Iterable<Entrepreneur> result =
sharedApiService.getEntrepreneursByProjectId(
staticAuthorizedProject.getIdProject(), staticAuthorizedMail);
List<Entrepreneur> resultList = TestUtils.toList(result);
// Assert
assertEquals(1, resultList.size());
assertTrue(
resultList.stream()
.anyMatch(e -> e.getIdUser().equals(linkedEntrepreneur.getIdUser())));
assertFalse(
resultList.stream()
.anyMatch(e -> e.getIdUser().equals(otherEntrepreneur.getIdUser())));
}
/*
* Tests retrieving appointments linked to a project's section cells when the user is authorized
* and such appointments exist.
* Verifies that the correct appointments are returned.
*/
// Tests getAppointmentsByProjectId
/*@Test*/
// Commenting out failing test
void testGetAppointmentsByProjectId_Authorized_Found() {
// Arrange: Create specific SectionCells and Appointments for this test
SectionCell cell1 =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject, 1L, "Cell 1 Test", LocalDateTime.now()));
SectionCell cell2 =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject, 2L, "Cell 2 Test", LocalDateTime.now()));
Project otherProject =
projectService.addNewProject(
getTestProject(
"other_project_app_test",
administratorService.addAdministrator(
getTestAdmin("other_admin_app_test"))));
SectionCell otherProjectCell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
otherProject,
1L,
"Other Project Cell App Test",
LocalDateTime.now()));
Appointment app1 =
getTestAppointment(
LocalDate.now().plusDays(10),
LocalTime.NOON,
LocalTime.of(0, 30),
"Place 1 App Test",
"Subject 1 App Test",
List.of(cell1),
null);
Appointment savedApp1 = appointmentService.addNewAppointment(app1);
Appointment app2 =
getTestAppointment(
LocalDate.now().plusDays(11),
LocalTime.NOON.plusHours(1),
LocalTime.of(1, 0),
"Place 2 App Test",
"Subject 2 App Test",
List.of(cell1, cell2),
null);
Appointment savedApp2 = appointmentService.addNewAppointment(app2);
Appointment otherApp =
getTestAppointment(
LocalDate.now().plusDays(12),
LocalTime.MIDNIGHT,
LocalTime.of(0, 15),
"Other Place App Test",
"Other Subject App Test",
List.of(otherProjectCell),
null);
appointmentService.addNewAppointment(otherApp);
// Act
Iterable<Appointment> result =
sharedApiService.getAppointmentsByProjectId(
staticAuthorizedProject.getIdProject(), // Use static project ID
staticAuthorizedMail); // Use static authorized mail
List<Appointment> resultList = TestUtils.toList(result);
// Assert
assertEquals(2, resultList.size());
assertTrue(
resultList.stream()
.anyMatch(a -> a.getIdAppointment().equals(savedApp1.getIdAppointment())));
assertTrue(
resultList.stream()
.anyMatch(a -> a.getIdAppointment().equals(savedApp2.getIdAppointment())));
assertFalse(
resultList.stream()
.anyMatch(
a ->
a.getIdAppointment()
.equals(otherApp.getIdAppointment()))); // Ensure
// appointment from other project is not included
}
/*
* Tests generating a PDF report for an appointment when the user is authorized
* for the project linked to the appointment's section cell.
* Verifies that no authorization exception is thrown. (Note: File I/O is mocked).
*/
// Tests getPDFReport (Focus on authorization and data retrieval flow)
/*@Test*/
// Commenting out failing test
void testGetPDFReport_Authorized() throws DocumentException, URISyntaxException, IOException {
// Arrange: Create a specific appointment linked to the static authorized project
SectionCell cell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticAuthorizedProject,
1L,
"Cell for PDF Test",
LocalDateTime.now()));
Report report =
new Report(null, "PDF Report Content // Point 2 PDF Content"); // ID set by DB
Appointment appointment =
getTestAppointment(
LocalDate.now().plusDays(20),
LocalTime.of(14, 0),
LocalTime.of(0, 45),
"Salle PDF",
"PDF Subject",
List.of(cell),
report);
Appointment savedAppointment = appointmentService.addNewAppointment(appointment);
// Mock getAppointmentById to return the saved appointment for the service to use
when(appointmentService.getAppointmentById(eq(savedAppointment.getIdAppointment())))
.thenReturn(savedAppointment);
// mockUtilsService is configured in BeforeEach to allow staticAuthorizedMail for
// staticAuthorizedProject
// Act & Assert (Just assert no authorization exception is thrown)
assertDoesNotThrow(
() ->
sharedApiService.getPDFReport(
savedAppointment.getIdAppointment(), staticAuthorizedMail));
// Note: Actual PDF generation and file operations are not tested here,
// as that requires mocking external libraries and file system operations.
}
/*
* Tests generating a PDF report for an appointment when the user is not authorized
* for the project linked to the appointment's section cell.
* Verifies that an Unauthorized ResponseStatusException is thrown.
*/
/*@Test*/
// Commenting out failing test
void testGetPDFReport_Unauthorized() {
// Arrange: Create a specific appointment linked to the static *unauthorized* project
SectionCell cell =
sectionCellService.addNewSectionCell(
getTestSectionCell(
staticUnauthorizedProject,
1L,
"Cell for Unauthorized PDF Test",
LocalDateTime.now()));
Report report = new Report(null, "Unauthorized PDF Report Content");
Appointment appointment =
getTestAppointment(
LocalDate.now().plusDays(21),
LocalTime.of(15, 0),
LocalTime.of(0, 30),
"Salle Unauthorized PDF",
"Unauthorized PDF Subject",
List.of(cell),
report);
Appointment savedAppointment = appointmentService.addNewAppointment(appointment);
// Mock getAppointmentById to return the saved appointment
when(appointmentService.getAppointmentById(eq(savedAppointment.getIdAppointment())))
.thenReturn(savedAppointment);
// mockUtilsService is configured in BeforeEach to DENY staticUnauthorizedMail for
// staticUnauthorizedProject
// Act & Assert
ResponseStatusException exception =
assertThrows(
ResponseStatusException.class,
() -> {
sharedApiService.getPDFReport(
savedAppointment.getIdAppointment(),
staticUnauthorizedMail); // Unauthorized user mail
});
assertEquals(HttpStatus.UNAUTHORIZED, exception.getStatusCode());
}
}

View File

@ -16,7 +16,7 @@ BACKEND_PASSWORD=backend_db_user_password
DATABASE_URL=localhost:5433
VITE_KEYCLOAK_URL=http://localhost:7080
VITE_KEYCLOAK_CLIENT_ID=myinpulse-dev
VITE_KEYCLOAK_REALM=test
VITE_KEYCLOAK_CLIENT_ID=MyINPulse-vite
VITE_KEYCLOAK_REALM=MyINPulse
VITE_APP_URL=http://localhost:5173
VITE_BACKEND_URL=http://localhost:8081/

View File

@ -22,6 +22,8 @@ paths:
description: Bad Request - Invalid project data provided (e.g., missing required fields).
"401":
description: Unauthorized - Authentication required or invalid token.
"403":
description: Bad Token - Invalid Keycloack configuration.
post:
operationId: addProjectManually
@ -39,7 +41,7 @@ paths:
schema:
$ref: "./main.yaml#/components/schemas/project"
responses:
"201": # Use 201 Created for successful creation
"200": # Use 200 Created for successful creation
description: Created - Project added successfully. Returns the created project.
content:
application/json:
@ -49,6 +51,8 @@ paths:
description: Bad Request - Project already exists.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/projects/pending:
@ -71,6 +75,8 @@ paths:
$ref: "./main.yaml#/components/schemas/project" # Assuming pending projects use the same schema
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/request-join:
get:
@ -92,6 +98,8 @@ paths:
$ref: "./main.yaml#/components/schemas/joinRequest"
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/request-join/decision/{joinRequestId}:
post:
@ -122,6 +130,8 @@ paths:
description: Bad Request - Invalid input (e.g., missing decision).
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/projects/pending/decision:
@ -136,14 +146,6 @@ paths:
If rejected (isAccepted=false), the pending project data might be archived or deleted based on business logic.
security:
- MyINPulse: [MyINPulse-admin]
parameters:
- in: path
name: pendingProjectId # Corrected typo and name change
required: true
schema:
type: integer
description: The ID of the pending project to decide upon.
example: 7
requestBody:
required: true
description: Decision payload.
@ -152,12 +154,14 @@ paths:
schema:
$ref: './main.yaml#/components/schemas/projectDecision'
responses:
"204": # Use 204 No Content for successful action with no body
"200": # Use 200 No Content for successful action with no body
description: No Content - Decision processed successfully.
"400":
description: Bad Request - Invalid input (e.g., missing decision).
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/pending-accounts: # Path updated
@ -180,6 +184,8 @@ paths:
$ref: "./main.yaml#/components/schemas/user-entrepreneur"
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/admin/accounts/validate/{userId}:
post: # Changed to POST as it changes state
@ -199,11 +205,12 @@ paths:
description: The ID of the user account to validate.
example: 102
responses:
"204":
"200":
description: No Content - Account validated successfully.
"400":
description: Bad Request - Invalid user ID format.
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -225,6 +232,8 @@ paths:
type: array
items:
$ref: "./main.yaml#/components/schemas/appointment"
"403":
description: Bad Token - Invalid Keycloack configuration.
"404":
description: no appointments found.
"401":
@ -255,13 +264,15 @@ paths:
schema:
$ref: "./main.yaml#/components/schemas/report"
responses:
"201":
"200":
description: Created - Report created and linked successfully. Returns the created report.
content:
application/json:
schema: { $ref: "./main.yaml#/components/schemas/report" }
"400":
description: Bad Request - Invalid input (e.g., missing content, invalid appointment ID format).
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -296,6 +307,8 @@ paths:
schema: { $ref: "./main.yaml#/components/schemas/report" }
"400":
description: Bad Request - Invalid input (e.g., missing content).
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -318,10 +331,12 @@ paths:
description: The ID of the project to remove.
example: 12
responses:
"204":
"200":
description: No Content - Project removed successfully.
"400":
description: Bad Request - Invalid project ID format.
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -345,9 +360,28 @@ paths:
description: The ID of the user to grant admin rights.
example: 103
responses:
"204": # Use 204 No Content
"200": # Use 200 No Content
description: No Content - Admin rights granted successfully.
"400":
description: Bad Request - Invalid user ID format or user is already an admin.
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
/admin/create-account:
post:
summary: Creates Admin out Jwt Token
tags:
- Admin API
security:
- MyINPulse: [MyINPulse-admin]
description: Create an admin instance in the MyINPulse DB of the information provided from the authenticated user's keycloack token.
The information required in the token are `userSurname`, `username`, `primaryMail`, `secondaryMail`, `phoneNumber`.
responses:
"200":
description: No Content - Admin user created successfully.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.

View File

@ -21,12 +21,14 @@ paths:
schema:
$ref: "./main.yaml#/components/schemas/project"
responses:
"202":
"200":
description: Accepted - Project creation request received and is pending validation.
"400":
description: Bad Request - Invalid input (e.g., missing name).
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/entrepreneur/sectionCells: # Base path
post:
@ -46,12 +48,14 @@ paths:
schema:
$ref: "./main.yaml#/components/schemas/sectionCell"
responses:
"201":
"200":
description: Created - Section cell added successfully. Returns the created cell.
"400":
description: Bad Request - Invalid input (e.g., missing content or sectionId).
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/entrepreneur/sectionCells/{sectionCellId}:
put:
@ -84,6 +88,8 @@ paths:
description: Bad Request - Invalid input or ID mismatch.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
delete:
operationId: removeSectionCell
@ -102,7 +108,7 @@ paths:
description: The ID of the section cell to remove.
example: 509
responses:
"204":
"200":
description: No Content - Section cell removed successfully.
"400":
description: Bad Request - Invalid ID format.
@ -110,3 +116,82 @@ paths:
description: Bad Request - sectionCell not found.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/entrepreneur/projects:
get:
summary: gets the projectId of the project associated with the entrepreneur
description: returns a list of projectIds of the projects associated with the entrepreneur
tags:
- Entrepreneurs API
security:
- MyINPulse: [MyINPulse-entrepreneur]
parameters:
responses:
"200":
description: OK - Section cell updated successfully. Returns the updated cell.
content:
application/json:
schema:
type: array
items:
$ref: "./main.yaml#/components/schemas/project"
"404":
description: Bad Request - Invalid input or ID mismatch.
"401":
description: Unauthorized or identity not found
"403":
description: Bad Token - Invalid Keycloack configuration.
/entrepreneur/projects/project-is-active:
get:
summary: checks if the project associated with an entrepreneur is active
description: returns a boolean if the project associated with an entrepreneur has an active status
(i.e has been validated by an admin). The user should be routed to LeanCanvas. any other response code
should be treated as false
tags:
- Entrepreneurs API
security:
- MyINPulse: [MyINPulse-entrepreneur]
parameters:
responses:
"200":
description: OK - got the value successfully any other response code should be treated as false.
content:
application/json:
schema:
type: boolean
"404":
description: Bad Request - Invalid input or ID mismatch.
"401":
description: Unauthorized or identity not found
"403":
description: Bad Token - Invalid Keycloack configuration.
/entrepreneur/projects/has-pending-request:
get:
summary: checks if the user has a pending projectRequest
description: returns a boolean if the project associated with an entrepreneur has a pending status
(i.e has not yet been validated by an admin). The user should be routed to a page telling him that he should
wait for admin validation. any other response code should be treated as false.
tags:
- Entrepreneurs API
security:
- MyINPulse: [MyINPulse-entrepreneur]
parameters:
responses:
"200":
description: OK - got the value successfully any other response code should be treated as false.
content:
application/json:
schema:
type: boolean
"404":
description: Bad Request - Invalid input or ID mismatch.
"401":
description: Unauthorized or identity not found
"403":
description: Bad Token - Invalid Keycloack configuration.

View File

@ -79,6 +79,10 @@ paths:
$ref: "./unauthApi.yaml#/paths/~1unauth~1finalize"
/unauth/request-join/{projectId}:
$ref: "./unauthApi.yaml#/paths/~1unauth~1request-join~1{projectId}"
/unauth/request-admin-role:
$ref: "./unauthApi.yaml#/paths/~1unauth~1request-admin-role"
/unauth/check-if-not-pending:
$ref: "./unauthApi.yaml#/paths/~1unauth~1check-if-not-pending"
# _ ____ __ __ ___ _ _ _ ____ ___
# / \ | _ \| \/ |_ _| \ | | / \ | _ \_ _|
@ -108,6 +112,8 @@ paths:
$ref: "./adminApi.yaml#/paths/~1admin~1projects~1{projectId}"
/admin/make-admin/{userId}:
$ref: "./adminApi.yaml#/paths/~1admin~1make-admin~1{userId}"
/admin/create-account:
$ref: "./adminApi.yaml#/paths/~1admin~1create-account"
# ____ _ _ _ ____ ___
# / ___|| |__ __ _ _ __ ___ __| | / \ | _ \_ _|
@ -138,9 +144,16 @@ paths:
# / ___ \| __/| |
# /_/ \_\_| |___|
#
/entrepreneur/projects:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1projects"
/entrepreneur/projects/request:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1projects~1request"
/entrepreneur/sectionCells:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1sectionCells"
/entrepreneur/sectionCells/{sectionCellId}:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1sectionCells~1{sectionCellId}"
/entrepreneur/projects/project-is-active:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1projects~1project-is-active"
/entrepreneur/projects/has-pending-request:
$ref: "./entrepreneurApi.yaml#/paths/~1entrepreneur~1projects~1has-pending-request"

View File

@ -37,6 +37,8 @@ paths:
$ref: "./main.yaml#/components/schemas/sectionCell"
"400":
description: Bad Request - Invalid parameter format.
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -68,7 +70,7 @@ paths:
"401":
description: Unauthorized.
"403":
description: Forbidden - User does not have access to this project.
description: Bad Token - Invalid Keycloack configuration.
"404":
description: Not Found - Project not found.
@ -97,7 +99,7 @@ paths:
"401":
description: Unauthorized.
"403":
description: Forbidden - User does not have access to this project.
description: Bad Token - Invalid Keycloack configuration.
"404":
description: Not Found - Project not found.
@ -126,6 +128,8 @@ paths:
type: array
items:
$ref: "./main.yaml#/components/schemas/appointment"
"403":
description: Bad Token - Invalid Keycloack configuration.
"401":
description: Unauthorized.
@ -156,6 +160,8 @@ paths:
format: binary
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/shared/appointments/request:
@ -176,11 +182,12 @@ paths:
$ref: "./main.yaml#/components/schemas/appointment" # Assuming request uses same model structure
# Potentially add projectId or targetUserId here
responses:
"202": # Accepted seems appropriate for a request
"200": # Accepted seems appropriate for a request
description: Accepted - Appointment request submitted.
"400":
description: Bad Request - Invalid appointment details.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.

View File

@ -18,12 +18,14 @@ paths:
tags:
- Unauth API
responses:
"201":
"200":
description: Created - Account finalized and pending admin validation. Returns the user profile.
"400":
description: Bad Request - Problem processing the token or user data derived from it.
"401":
description: Unauthorized - Valid authentication token required.
"403":
description: Bad Token - Invalid Keycloack configuration.
/unauth/request-join/{projectId}:
post:
summary: Request to join an existing project
@ -39,7 +41,7 @@ paths:
description: The ID of the project to request joining.
example: 15
responses: # Moved responses block to correct level
"202":
"200":
description: Accepted - Join request submitted and pending approval.
"400":
description: Bad Request - Invalid project ID format
@ -47,16 +49,42 @@ paths:
description: Already member/request pending.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/unauth/request-admin-role:
post:
summary: Request to join an existing project
summary: Request to become an admin
description: Submits a request for the authenticated user (keycloack authenticated) to become an admin. Their role is then changed to admin in server and Keycloak. This requires approval from a project admin.
tags:
- Unauth API
responses:
"202":
"200":
description: Accepted - Become admin request submitted and pending approval.
"400":
description: Bad Request - Invalid project ID format or already member/request pending.
"401":
description: Unauthorized.
"403":
description: Bad Token - Invalid Keycloack configuration.
/unauth/check-if-not-pending:
get:
summary: Returns a boolean of whether the user's account is not pending
description: Returns a boolean with value `true` if the user's account is not pending and `false` if it is.
tags:
- Unauth API
responses:
"200":
description: Accepted - Become admin request submitted and pending approval.
content:
application/json:
schema:
type: boolean
"400":
description: Bad Request - Invalid project ID format or already member/request pending.
"401":
description: Unauthorized.
"404":
description: Bad Request - User not found in database.
"403":
description: Bad Token - Invalid Keycloack configuration.

View File

@ -63,6 +63,17 @@ class Appointment {
set appointmentSubject(value: string | undefined) {
this._appointmentSubject = value;
}
toObject() {
return {
idAppointment: this.idAppointment,
appointmentDate: this.appointmentDate,
appointmentTime: this.appointmentTime,
appointmentDuration: this.appointmentDuration,
appointmentPlace: this.appointmentPlace,
appointmentSubject: this.appointmentSubject,
};
}
}
export default Appointment;

View File

@ -27,6 +27,13 @@ class JoinRequest {
set entrepreneur(value: UserEntrepreneur | undefined) {
this._entrepreneur = value;
}
toObject() {
return {
idProject: this.idProject,
entrepreneur: this.entrepreneur,
};
}
}
export default JoinRequest;

View File

@ -13,6 +13,12 @@ class JoinRequestDecision {
set isAccepted(value: boolean | undefined) {
this._isAccepted = value;
}
toObject() {
return {
isAccepted: this._isAccepted,
};
}
}
export default JoinRequestDecision;

View File

@ -22,16 +22,16 @@ class Project {
this._idProject = value;
}
get projectName(): string | undefined {
return this._projectName;
get projectName(): string {
return this._projectName ?? "";
}
set projectName(value: string | undefined) {
this._projectName = value;
}
get creationDate(): string | undefined {
return this._creationDate;
get creationDate(): string {
return this._creationDate ?? "";
}
set creationDate(value: string | undefined) {
@ -67,6 +67,23 @@ class Project {
) {
this._status = value;
}
toObject() {
return {
idProject: this.idProject,
projectName: this.projectName,
creationDate: this.creationDate,
logo: this.logo,
status: this.status,
};
}
toCreatePayload() {
return {
projectName: this.projectName,
logo: this.logo,
};
}
}
export default Project;

View File

@ -33,6 +33,14 @@ class ProjectDecision {
set isAccepted(value: boolean | undefined) {
this._isAccepted = value;
}
toObject() {
return {
projectId: this._projectId,
adminId: this._adminId,
isAccepted: this._isAccepted,
};
}
}
export default ProjectDecision;

View File

@ -23,6 +23,13 @@ class Report {
set reportContent(value: string | undefined) {
this._reportContent = value;
}
toObject() {
return {
idReport: this._idReport,
reportContent: this._reportContent,
};
}
}
export default Report;

View File

@ -44,7 +44,7 @@ class SectionCell {
this._modificationDate = value;
}
toPlainObject() {
toObject() {
return {
idSectionCell: this._idSectionCell,
sectionId: this._sectionId,

View File

@ -62,6 +62,17 @@ class User {
set phoneNumber(value: string | undefined) {
this._phoneNumber = value;
}
toObject() {
return {
idUser: this._idUser,
userSurname: this._userSurname,
userName: this._userName,
primaryMail: this._primaryMail,
secondaryMail: this._secondaryMail,
phoneNumber: this._phoneNumber,
};
}
}
export default User;

View File

@ -5,6 +5,10 @@ class UserAdmin extends User {
constructor(data: Partial<UserAdmin> = {}) {
super(data);
}
get idUser(): number | undefined {
return super.idUser;
}
}
export default UserAdmin;

View File

@ -36,6 +36,15 @@ class UserEntrepreneur extends User {
set sneeStatus(value: boolean | undefined) {
this._sneeStatus = value;
}
toObject() {
return {
...super.toObject(),
school: this._school,
course: this._course,
sneeStatus: this._sneeStatus,
};
}
}
export default UserEntrepreneur;

View File

@ -12,24 +12,13 @@
/>
</div>
<div class="form-group">
<label for="creationDate">Date de création</label>
<input
id="creationDate"
v-model="project.creationDate"
type="text"
placeholder="JJ-MM-AAAA"
required
/>
</div>
<div class="form-group">
<label for="logo">Logo</label>
<input
id="logo"
v-model="project.logo"
type="text"
placeholder="(à discuter)"
placeholder="(Description)"
/>
</div>
@ -39,16 +28,17 @@
<script setup lang="ts">
import { ref } from "vue";
import { postApi } from "@/services/api.ts";
import Project from "@/ApiClasses/Project";
import { addProjectManually } from "@/services/Apis/Admin";
const project = ref({
projectName: "",
creationDate: "",
logo: "to be discussed not yet fixed",
});
const project = ref(new Project({}));
function submitProject() {
postApi("/admin/projects/add", project.value);
addProjectManually(
project.value.toCreatePayload(),
(res) => console.log("Success:", res.data),
(err) => console.error("Error:", err)
);
}
</script>

View File

@ -37,6 +37,11 @@
</template>
<script>
import {
createAppointmentReport,
updateAppointmentReport,
} from "@/services/Apis/Admin";
export default {
name: "AdminAppointmentsComponent",
data() {
@ -63,28 +68,21 @@ export default {
this.appointmentId--;
}
},
async submitReport() {
const reportData = {
reportContent: this.reportContent,
};
const url = `/admin/appointments/report/${this.appointmentId}`;
const method = this.isUpdate ? "PUT" : "POST";
try {
const response = await this.$axios({
method,
url,
data: reportData,
});
submitReport() {
const reportData = { content: this.reportContent };
const onSuccess = (response) => {
if (response.status === 201 || response.status === 200) {
this.responseMessage =
"Rapport " +
(this.isUpdate ? "mis à jour" : "créé") +
" avec succès.";
}
} catch (error) {
};
const onError = (error) => {
console.error(
"Erreur lors de l'envoi du rapport :",
error.response || error.message
);
if (error.response && error.response.status === 400) {
this.responseMessage =
"Requête invalide. Vérifiez les informations.";
@ -95,6 +93,22 @@ export default {
this.responseMessage =
"Une erreur est survenue. Veuillez réessayer.";
}
};
if (this.isUpdate) {
updateAppointmentReport(
this.appointmentId,
reportData,
onSuccess,
onError
);
} else {
createAppointmentReport(
this.appointmentId,
reportData,
onSuccess,
onError
);
}
},
},

View File

@ -0,0 +1,77 @@
<template>
<div class="entrepreneur-list">
<button @click="fetchEntrepreneurs">Afficher les entrepreneurs</button>
<ul v-if="entrepreneurs.length">
<li
v-for="entrepreneur in entrepreneurs"
:key="entrepreneur.idUser"
>
{{ entrepreneur.userName }} {{ entrepreneur.userSurname }} -
{{ entrepreneur.primaryMail }}
</li>
</ul>
<p v-else-if="loading">Chargement...</p>
<p v-else-if="errorMessage">{{ errorMessage }}</p>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import type { AxiosResponse, AxiosError } from "axios";
import { getAllEntrepreneurs } from "@/services/Apis/Unauth"; // ajuste ce chemin selon ton projet
// Types
interface Entrepreneur {
idUser: number;
userName: string;
userSurname: string;
primaryMail: string;
}
// Refs
const entrepreneurs = ref<Entrepreneur[]>([]);
const loading = ref(false);
const errorMessage = ref("");
// Méthode
function fetchEntrepreneurs() {
loading.value = true;
errorMessage.value = "";
getAllEntrepreneurs(
(response: AxiosResponse) => {
if (Array.isArray(response.data)) {
entrepreneurs.value = response.data;
} else {
console.error("Format inattendu :", response.data);
errorMessage.value = "Réponse inattendue du serveur.";
}
loading.value = false;
},
(error: AxiosError) => {
errorMessage.value = "Erreur lors du chargement des entrepreneurs.";
console.error(error);
loading.value = false;
}
);
}
</script>
<style scoped>
button {
margin-bottom: 1rem;
padding: 0.5rem 1rem;
font-size: 1rem;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 0.5rem;
}
</style>

View File

@ -0,0 +1,90 @@
<template>
<div class="appointment-list">
<h2>Liste des rendez-vous</h2>
<h3>de {{ store.user.username }}</h3>
<ul v-if="appointments.length">
<li v-for="appt in appointments" :key="appt.idAppointment">
<strong>Sujet :</strong> {{ appt.appointmentSubject }}<br />
<strong>Date :</strong> {{ appt.appointmentDate }}<br />
<strong>Heure :</strong> {{ appt.appointmentTime }}<br />
<strong>Durée :</strong> {{ appt.appointmentDuration }}<br />
<strong>Lieu :</strong> {{ appt.appointmentPlace }}
<hr />
</li>
</ul>
<p v-else>Aucun rendez-vous trouvé.</p>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { callApi } from "@/services/api";
import Appointment from "@/ApiClasses/Appointment";
import { store } from "@/main.ts";
// Define the interface for the API response
interface AppointmentResponse {
idAppointment: number;
appointmentSubject: string;
appointmentDate: string;
appointmentTime: string;
appointmentDuration: string;
appointmentPlace: string;
}
const appointments = ref<Appointment[]>([]);
function loadAppointments() {
if (!store.user) {
console.error(
"L'utilisateur n'est pas connecté ou les données utilisateur ne sont pas disponibles."
);
return;
}
//console.log("username :", store.user.username);
//console.log("token :", store.user.token);
callApi(
"/admin/appointments/upcoming",
(response) => {
appointments.value = response.data.map(
(item: AppointmentResponse) => new Appointment(item)
);
},
(error) => {
console.error(
"Erreur lors de la récupération des rendez-vous :",
error
);
}
);
}
onMounted(() => {
loadAppointments();
});
</script>
<style scoped>
.appointment-list {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background: #fdfdfd;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}
h2 {
font-size: 1.8rem;
margin-bottom: 20px;
color: #333;
border-bottom: 2px solid #ddd;
padding-bottom: 10px;
}
li {
margin-bottom: 15px;
line-height: 1.6;
}
</style>

View File

@ -1,5 +1,5 @@
<template>
<header>
<header class="header">
<a
href="https://www.bordeaux-inp.fr/fr/lincubateur-bordeaux-inpulse"
target="_blank"
@ -11,26 +11,54 @@
class="logo"
/>
</a>
<div class="header-actions">
<button class="logout" @click="store.logout">Logout</button>
</div>
</header>
</template>
<script lang="ts">
export default {
name: "HeaderComponent",
};
<script setup lang="ts">
import { store } from "@/main.ts";
</script>
<style scoped>
header img {
width: 100px;
}
@import "@/components/canvas/style-project.css";
header {
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 20px;
background-color: #fff;
border-bottom: 2px solid #ddd;
padding: 15px 30px;
background-color: #f9f9f9;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.logo {
height: 50px;
}
.header-actions {
display: flex;
align-items: center;
gap: 20px;
position: relative;
}
.logout {
background-color: #009cde;
color: white;
border: none;
padding: 10px 15px;
cursor: pointer;
font-size: 14px;
border-radius: 5px;
text-decoration: none;
transition: background-color 0.2s ease;
font-family: Arial, sans-serif;
}
.logout:hover {
background-color: #007bad;
}
</style>

View File

@ -1,9 +1,9 @@
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { jwtDecode } from "jwt-decode"; // i hope this doesn't break the code later
import { store } from "../main.ts";
import { callApi } from "@/services/api.ts";
import { checkPending } from "@/services/Apis/Unauth";
import Header from "@/components/HeaderComponent.vue";
const router = useRouter();
@ -13,7 +13,7 @@ type TokenPayload = {
};
};
const customRequest = ref("");
//const customRequest = ref("");
onMounted(() => {
if (store.authenticated && store.user.token) {
@ -23,23 +23,44 @@ onMounted(() => {
if (roles.includes("MyINPulse-admin")) {
router.push("/admin");
} else if (roles.includes("MyINPulse-entrepreneur")) {
router.push("/leanCanva");
return;
}
if (roles.includes("MyINPulse-entrepreneur")) {
router.push("/canvas");
return;
}
checkPending(
(response) => {
const isValidated = response.data === true;
if (
isValidated &&
roles.includes("MyINPulse-entrepreneur")
) {
router.push("/canvas");
//router.push("/JorCproject");
} else {
router.push("/JorCproject");
//router.push("/finalize");
}
},
(error) => {
if (error.response?.status === 403) {
router.push("/finalize");
} else {
console.error(
"Unexpected error during checkPending",
error
);
}
}
);
} catch (err) {
console.error("Failed to decode token", err);
}
}
});
/*
const loading = ref(false);
const callApiWithLoading = async (path: string) => {
loading.value = true;
await callApi(path);
loading.value = false;
};
*/
</script>
<template>
@ -47,7 +68,7 @@ const callApiWithLoading = async (path: string) => {
<error-wrapper></error-wrapper>
<div class="auth-container">
<div class="auth-card">
<h1>Bienvenue</h1>
<h1>Bienvenue à MyINPulse</h1>
<div
class="status"
@ -65,11 +86,12 @@ const callApiWithLoading = async (path: string) => {
<div class="actions">
<button @click="store.login">Login</button>
<button @click="store.logout">Logout</button>
<button @click="store.signup">Signup-admin</button>
<!--<button @click="store.signup">Signup-admin</button>
<button @click="store.signup">Signup-Entrepreneur</button>
<button @click="store.refreshUserToken">Refresh Token</button>
<button @click="store.refreshUserToken">Refresh Token</button>-->
</div>
<!--
<div v-if="store.authenticated" class="token-section">
<p><strong>Access Token:</strong></p>
<pre>{{ store.user.token }}</pre>
@ -93,7 +115,7 @@ const callApiWithLoading = async (path: string) => {
/>
<button @click="callApi(customRequest)">Call</button>
</div>
</div>
</div>-->
</div>
</div>
</template>

View File

@ -15,26 +15,29 @@
<script setup lang="ts">
import { defineProps } from "vue";
import { postApi } from "@/services/api";
import { addNewMessage, color } from "@/services/popupDisplayer";
import { decidePendingProject } from "@/services/Apis/Admin";
import ProjectDecision from "@/ApiClasses/ProjectDecision";
const props = defineProps<{
projectId?: number;
projectName: string;
creationDate: string;
adminId?: number;
}>();
const URI = "/admin/projects/pending/decision";
const sendDecision = (isAccepted: boolean) => {
const decision = new ProjectDecision({
projectId: props.projectId,
adminId: props.adminId,
isAccepted,
});
const sendDecision = (decision: "true" | "false") => {
postApi(
URI,
{
projectName: props.projectName,
decidePendingProject(
decision,
},
() => {
addNewMessage(
`Projet ${props.projectName} ${decision === "true" ? "accepté" : "refusé"}`,
`Projet ${props.projectName} ${isAccepted ? "accepté" : "refusé"}`,
color.Green
);
},
@ -45,8 +48,8 @@ const sendDecision = (decision: "true" | "false") => {
);
};
const acceptProject = () => sendDecision("true");
const refuseProject = () => sendDecision("false");
const acceptProject = () => sendDecision(true);
const refuseProject = () => sendDecision(false);
</script>
<style scoped>

View File

@ -0,0 +1,228 @@
<!-- <template>
<section class="pending-requests">
<h2>Comptes en attente</h2>
<ul v-if="pendingAccounts.length">
<li v-for="account in pendingAccounts" :key="account.userId">
{{ account.userName }} ({{ account.email }})
<button @click="validateAccount(account.userId)">Valider</button>
</li>
</ul>
<p v-else>Aucun compte en attente</p>
<h2>Demandes de participation aux projets</h2>
<ul v-if="joinRequests.length">
<li v-for="request in joinRequests" :key="request.joinRequestId">
{{ request.userName }} veut rejoindre le projet {{ request.projectName }}
<button @click="decideJoinRequest(request.joinRequestId, true)">Accepter</button>
<button @click="decideJoinRequest(request.joinRequestId, false)">Refuser</button>
</li>
</ul>
<p v-else>Aucune demande de participation</p>
</section>
</template> -->
<template>
<section class="section">
<h2>Comptes en attente</h2>
<div v-if="pendingAccounts.length">
<div
v-for="account in pendingAccounts"
:key="account.userId"
class="request-item"
>
<div class="request-info">
{{ account.userName }} ({{ account.email }})
</div>
<div class="request-buttons">
<button
class="accept"
@click="validateAccount(account.userId)"
>
Valider
</button>
</div>
</div>
</div>
<div v-else class="empty-message">Aucun compte en attente</div>
</section>
<section class="section">
<h2>Demandes de participation aux projets</h2>
<div v-if="joinRequests.length">
<div
v-for="request in joinRequests"
:key="request.joinRequestId"
class="request-item"
>
<div class="request-info">
{{ request.userName }} veut rejoindre le projet "{{
request.projectName
}}"
</div>
<div class="request-buttons">
<button
class="accept"
@click="decideJoinRequest(request.joinRequestId, true)"
>
Accepter
</button>
<button
class="reject"
@click="decideJoinRequest(request.joinRequestId, false)"
>
Refuser
</button>
</div>
</div>
</div>
<div v-else class="empty-message">Aucune demande de participation</div>
</section>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
getPendingAccounts,
validateUserAccount,
getPendingProjectJoinRequests,
decideProjectJoinRequest,
} from "@/services/Apis/Admin";
type PendingAccount = {
userId: number;
userName: string;
email: string;
};
type JoinRequest = {
joinRequestId: number;
userName: string;
projectName: string;
};
const pendingAccounts = ref<PendingAccount[]>([]);
const joinRequests = ref<JoinRequest[]>([]);
function fetchAccounts() {
getPendingAccounts(
(res) => (pendingAccounts.value = res.data),
(err) => {
console.error("Erreur lors du chargement des comptes", err);
}
);
}
function fetchJoinRequests() {
getPendingProjectJoinRequests(
(res) => (joinRequests.value = res.data),
(err) => {
console.error("Erreur lors du chargement des demandes", err);
}
);
}
function validateAccount(userId: number) {
validateUserAccount(userId, () => {
pendingAccounts.value = pendingAccounts.value.filter(
(a) => a.userId !== userId
);
});
}
function decideJoinRequest(joinRequestId: number, isAccepted: boolean) {
decideProjectJoinRequest(joinRequestId, { isAccepted }, () => {
joinRequests.value = joinRequests.value.filter(
(r) => r.joinRequestId !== joinRequestId
);
});
}
onMounted(() => {
fetchAccounts();
fetchJoinRequests();
});
</script>
<style>
.section {
background: #ffffff;
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
margin-bottom: 2rem;
}
.section h2 {
font-size: 1.4rem;
color: #2c3e50;
border-bottom: 2px solid #ddd;
padding-bottom: 0.5rem;
margin-bottom: 1rem;
}
.request-item {
display: flex;
justify-content: space-between;
align-items: center;
border: 1px solid #e0e0e0;
border-radius: 12px;
background: linear-gradient(to right, #f8f9fb, #ffffff);
padding: 1rem 1.25rem;
margin-bottom: 1rem;
transition: box-shadow 0.2s ease;
}
.request-item:hover {
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
}
.request-info {
flex: 1;
font-size: 1rem;
color: #333;
}
.request-buttons {
display: flex;
gap: 0.75rem;
}
.request-buttons button {
padding: 0.45rem 1rem;
font-size: 0.9rem;
border: none;
border-radius: 8px;
color: #fff;
font-weight: 500;
cursor: pointer;
transition:
background-color 0.2s ease,
transform 0.2s ease;
}
.request-buttons button:hover {
transform: translateY(-1px);
}
button.accept {
background-color: #4caf50;
}
button.accept:hover {
background-color: #3e8e41;
}
button.reject {
background-color: #e74c3c;
}
button.reject:hover {
background-color: #c0392b;
}
.empty-message {
font-style: italic;
color: #777;
padding: 1rem 0;
}
</style>

View File

@ -3,18 +3,20 @@
<div class="project-header">
<h2 @click="goToLink">{{ projectName }}</h2>
<div class="header-actions">
<div class="dropdown-wrapper">
<!-- Empêche la propagation du clic vers le parent -->
<div ref="dropdownRef" class="dropdown-wrapper">
<button class="contact-button" @click.stop="toggleDropdown">
Contact
</button>
<div v-if="isDropdownOpen" class="dropdown-menu">
<button @click.stop="contactAll">Contacter tous</button>
<div
v-if="entrepreneurEmails.length > 0"
class="contact-dropdown"
:class="{ 'dropdown-visible': isDropdownOpen }"
>
<button @click="contactAll">Contacter tous</button>
<button
v-for="(email, index) in entrepreneurEmails"
:key="index"
@click.stop="contactSingle(email)"
@click="contactSingle(email)"
>
{{ email }}
</button>
@ -37,9 +39,11 @@
<script setup lang="ts">
import { defineProps, ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { getProjectEntrepreneurs } from "@/services/Apis/Shared.ts";
import UserEntrepreneur from "@/ApiClasses/UserEntrepreneur.ts";
const IS_MOCK_MODE = true;
const IS_MOCK_MODE = false;
const dropdownRef = ref<HTMLElement | null>(null);
const props = defineProps<{
projectName: string;
@ -52,11 +56,97 @@ const router = useRouter();
const isDropdownOpen = ref(false);
const entrepreneurEmails = ref<string[]>([]);
const entrepreneurs = ref<UserEntrepreneur[]>([]);
const goToLink = () => {
if (props.projectLink) {
router.push(props.projectLink);
}
};
const toggleDropdown = () => {
isDropdownOpen.value = !isDropdownOpen.value;
};
const fetchMockEntrepreneurs = () => {
const mockData = [
{
userName: "Doe",
userSurname: "John",
primaryMail: "john.doe@example.com",
},
{
userName: "Smith",
userSurname: "Anna",
primaryMail: "anna.smith@example.com",
},
{
userName: "Mock",
userSurname: "User",
primaryMail: undefined,
},
];
entrepreneurs.value = mockData.map((item) => new UserEntrepreneur(item));
entrepreneurEmails.value = entrepreneurs.value
.map((e) => e.primaryMail)
.filter((mail): mail is string => !!mail);
console.log("Mock entrepreneurs chargés :", entrepreneurs.value);
};
const fetchEntrepreneurs = (projectId: number, useMock = false) => {
if (useMock) {
fetchMockEntrepreneurs();
} else {
getProjectEntrepreneurs(
projectId,
(response) => {
const rawData = response.data as Partial<UserEntrepreneur>[];
entrepreneurs.value = rawData.map(
(item) => new UserEntrepreneur(item)
);
entrepreneurEmails.value = entrepreneurs.value
.map((e) => e.primaryMail)
.filter((mail): mail is string => !!mail);
},
(error) => {
console.error(
"Erreur lors de la récupération des entrepreneurs :",
error
);
}
);
}
};
const contactAll = () => {
const allEmails = entrepreneurEmails.value.join(", ");
navigator.clipboard
.writeText(allEmails)
.then(() => {
alert("Tous les emails copiés dans le presse-papiers !");
window.open("https://partage.bordeaux-inp.fr/", "_blank");
})
.catch((err) => console.error("Erreur lors de la copie :", err));
};
const contactSingle = (email: string) => {
navigator.clipboard
.writeText(email)
.then(() => {
alert(`Adresse copiée : ${email}`);
window.open("https://partage.bordeaux-inp.fr/", "_blank");
})
.catch((err) => console.error("Erreur lors de la copie :", err));
};
// Pour fermer le dropdown si on clique ailleurs
const handleClickOutside = (event: MouseEvent) => {
const dropdown = document.querySelector(".dropdown-wrapper");
if (dropdown && !dropdown.contains(event.target as Node)) {
if (
isDropdownOpen.value &&
dropdownRef.value &&
!dropdownRef.value.contains(event.target as Node)
) {
isDropdownOpen.value = false;
}
};
@ -69,98 +159,6 @@ onMounted(() => {
onBeforeUnmount(() => {
document.removeEventListener("click", handleClickOutside);
});
const toggleDropdown = () => {
isDropdownOpen.value = !isDropdownOpen.value;
};
const goToLink = () => {
if (props.projectLink) {
router.push(props.projectLink);
}
};
const fetchEntrepreneurs = async (
projectId: number,
useMock = IS_MOCK_MODE
) => {
try {
const responseData: Entrepreneur[] = useMock
? await mockFetchEntrepreneurs(/*projectId*/)
: (
await axios.get(
`http://localhost:5000/shared/projects/entrepreneurs/${projectId}`
)
).data;
entrepreneurEmails.value = responseData.map(
(item: Entrepreneur) => item.primaryMail
);
} catch (error) {
console.error(
"Erreur lors de la récupération des entrepreneurs :",
error
);
}
};
type Entrepreneur = {
idUser: number;
userSurname: string;
userName: string;
primaryMail: string;
secondaryMail: string;
phoneNumber: string;
school: string;
course: string;
sneeStatus: boolean;
};
const mockFetchEntrepreneurs = async (/*projectId: number*/) => {
return new Promise<Entrepreneur[]>((resolve) => {
setTimeout(() => {
resolve([
{
idUser: 1,
userSurname: "Doe",
userName: "John",
primaryMail: "john.doe@example.com",
secondaryMail: "johndoe@backup.com",
phoneNumber: "612345678",
school: "ENSEIRB",
course: "Info",
sneeStatus: false,
},
{
idUser: 2,
userSurname: "Smith",
userName: "Jane",
primaryMail: "jane.smith@example.com",
secondaryMail: "janesmith@backup.com",
phoneNumber: "698765432",
school: "ENSEIRB",
course: "Info",
sneeStatus: true,
},
]);
}, 500);
});
};
const contactAll = () => {
const allEmails = entrepreneurEmails.value.join(", ");
navigator.clipboard.writeText(allEmails).then(() => {
alert("Tous les emails copiés dans le presse-papiers !");
window.open("https://partage.bordeaux-inp.fr/", "_blank");
});
};
const contactSingle = (email: string) => {
navigator.clipboard.writeText(email).then(() => {
alert(`Adresse copiée : ${email}`);
window.open("https://partage.bordeaux-inp.fr/", "_blank");
});
};
</script>
<style scoped>
@ -233,48 +231,76 @@ const contactSingle = (email: string) => {
line-height: 1.6;
}
button {
padding: 10px 15px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 30px;
background-color: #f9f9f9;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.dropdown-wrapper {
.logo {
height: 50px;
}
.header-actions {
display: flex;
align-items: center;
gap: 20px;
position: relative;
}
.dropdown-menu {
position: absolute;
top: 100%; /* juste en dessous du bouton */
right: 0;
background-color: white;
border: 1px solid #ccc;
padding: 0.5rem;
z-index: 1000;
display: flex;
flex-direction: column;
gap: 0.5rem;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 0.25rem;
min-width: 150px;
}
.dropdown-menu button {
text-align: left;
padding: 0.3rem 0.5rem;
background: none;
.contact-button,
.return-button {
background-color: #009cde;
color: white;
border: none;
padding: 10px 15px;
cursor: pointer;
transition: background-color 0.2s;
font-size: 14px;
border-radius: 5px;
text-decoration: none;
transition: background-color 0.2s ease;
font-family: Arial, sans-serif;
}
.dropdown-menu button:hover {
background-color: #f0f0f0;
.return-button:hover,
.contact-button:hover {
background-color: #007bad;
}
.contact-dropdown {
position: absolute;
top: 100%;
left: 0;
background-color: #000;
color: white;
box-shadow: 0px 4px 8px rgba(255, 255, 255, 0.2);
border-radius: 8px;
padding: 10px;
margin-top: 5px;
z-index: 1000;
min-width: 200px;
display: none;
}
.contact-dropdown button {
display: block;
width: 100%;
padding: 5px;
text-align: left;
border: none;
background: none;
cursor: pointer;
color: white;
}
.contact-dropdown button:hover {
background-color: #009cde;
}
.contact-dropdown.dropdown-visible {
display: block;
}
</style>

View File

@ -30,6 +30,18 @@
<template v-else>
<!-- Mode affichage -->
<template v-if="!isEditing[index]">
<template v-if="expanded">
<button
class="delete-button"
title="Supprimer"
@click.stop="
deleteSectionCell(desc.idSectionCell, index)
"
>
</button>
</template>
<div class="description">
<p class="m-0">{{ desc.contentSectionCell }}</p>
</div>
@ -87,7 +99,7 @@ import { ref, defineProps, onMounted } from "vue";
import { getSectionCellsByDate } from "@/services/Apis/Shared.ts";
import { addSectionCell } from "@/services/Apis/Entrepreneurs.ts";
import SectionCell from "@/ApiClasses/SectionCell";
import { removeSectionCell } from "@/services/Apis/Entrepreneurs.ts";
import type { AxiosResponse, AxiosError } from "axios";
const props = defineProps<{
@ -95,10 +107,10 @@ const props = defineProps<{
title: number;
titleText: string;
description: string;
isAdmin: number;
isAdmin: boolean;
}>();
const IS_MOCK_MODE = false;
const IS_MOCK_MODE = true;
const IS_ADMIN = props.isAdmin;
const expanded = ref(false);
@ -106,22 +118,6 @@ const currentDescriptions = ref<SectionCell[]>([]);
const editedDescriptions = ref<SectionCell[]>([]);
const isEditing = ref<boolean[]>([]);
function getCurrentFormattedDate(): string {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // +1 car janvier = 0
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
onMounted(() => {
fetchData(props.projectId, props.title, getCurrentFormattedDate(), IS_MOCK_MODE);
});
// Fonctions
const startEditing = (index: number) => {
isEditing.value[index] = true;
};
@ -137,10 +133,14 @@ const saveEdit = (index: number) => {
editedDescriptions.value[index].contentSectionCell;
isEditing.value[index] = false;
if (!IS_MOCK_MODE){
addSectionCell(currentDescriptions.value[index],
if (!IS_MOCK_MODE) {
addSectionCell(
currentDescriptions.value[index],
(response) => {
console.log("Modification enregistrée avec succès :", response.data);
console.log(
"Modification enregistrée avec succès :",
response.data
);
},
(error) => {
console.error("Erreur lors de l'enregistrement :", error);
@ -149,6 +149,36 @@ const saveEdit = (index: number) => {
}
};
const deleteSectionCell = (id: number | undefined, index: number): void => {
if (id === -1) {
window.confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");
console.error("Delete ignored");
return;
}
const confirmed = window.confirm(
"Êtes-vous sûr de vouloir supprimer cet élément ?"
);
if (!confirmed) return;
if (id === undefined) {
console.error("ID de la cellule non défini");
return;
}
removeSectionCell(
id,
() => {
currentDescriptions.value.splice(index, 1);
editedDescriptions.value.splice(index, 1);
isEditing.value.splice(index, 1);
},
(error: AxiosError) => {
console.error("Erreur lors de la suppression :", error);
}
);
};
const handleClick = () => {
if (expanded.value) {
@ -161,45 +191,89 @@ const handleClick = () => {
}
};
// fetchData
const handleFetchSuccess = (sectionCells: SectionCell[]) => {
currentDescriptions.value = sectionCells;
editedDescriptions.value = sectionCells.map(
(cell) => new SectionCell({
(cell) =>
new SectionCell({
idSectionCell: cell.idSectionCell,
sectionId: cell.sectionId,
contentSectionCell: cell.contentSectionCell,
modificationDate: cell.modificationDate, })
modificationDate: cell.modificationDate,
})
);
isEditing.value = Array(sectionCells.length).fill(false);
};
const handleFetchError = (error: unknown) => {
console.error("Erreur lors de la récupération des données :", error);
const errorCell = new SectionCell({
idSectionCell: -1,
sectionId: -1,
contentSectionCell: "Échec du chargement des données.",
modificationDate: new Date().toISOString(),
});
currentDescriptions.value = [errorCell];
editedDescriptions.value = [errorCell];
isEditing.value = [false];
};
const fetchData = async ( projectId: number, title: number, date: string, useMock = false ) => {
const fetchData = async (
projectId: number,
title: number,
date: string,
useMock = false
) => {
try {
if (useMock) {
const responseData = await mockFetch(projectId, title, date);
handleFetchSuccess(responseData);
} else {
if (projectId == -1) {
const errorCell = new SectionCell({
idSectionCell: -1,
sectionId: -1,
contentSectionCell: "Échec du chargement des données.",
modificationDate: new Date().toISOString(),
});
currentDescriptions.value = [errorCell];
editedDescriptions.value = [errorCell];
isEditing.value = [false];
console.error(
"No sections to show because no project was found."
);
return;
}
await new Promise<void>((resolve, reject) => {
getSectionCellsByDate( projectId, title, date,
getSectionCellsByDate(
projectId,
title,
date,
(response: AxiosResponse) => {
const data = response.data;
if (Array.isArray(data) && data.length > 0) {
const sectionCells = data.map((cellData) => new SectionCell({
const sectionCells = data.map(
(cellData) =>
new SectionCell({
idSectionCell: cellData.idSectionCell,
sectionId: cellData.sectionId,
contentSectionCell: cellData.contentSectionCell,
contentSectionCell:
cellData.contentSectionCell,
modificationDate:
cellData.modificationDate, })
cellData.modificationDate,
})
);
handleFetchSuccess(sectionCells);
} else {
console.warn( "Aucune donnée reçue ou format inattendu :", data);
console.warn(
"Aucune donnée reçue ou format inattendu :",
data
);
}
resolve();
@ -216,7 +290,11 @@ const fetchData = async ( projectId: number, title: number, date: string, useMoc
}
};
const mockFetch = async ( projectId: number, title: number, date: string ): Promise<SectionCell[]> => {
const mockFetch = async (
projectId: number,
title: number,
date: string
): Promise<SectionCell[]> => {
console.log(
`Mock fetch pour projectId: ${projectId}, title: ${title}, date: ${date}`
);
@ -267,19 +345,42 @@ const mockFetch = async ( projectId: number, title: number, date: string ): Prom
],
};
// On extrait les descriptions pour la section demandée
const section = leanCanvasData[title] || ["Aucune donnée disponible."];
// On crée des instances de SectionCell
const result = section.map(
(txt, index) => new SectionCell({ idSectionCell: index + 1, sectionId: title,
contentSectionCell: txt, modificationDate: date, })
(txt, index) =>
new SectionCell({
idSectionCell: index + 1,
sectionId: title,
contentSectionCell: txt,
modificationDate: date,
})
);
return new Promise<SectionCell[]>((resolve) => {
setTimeout(() => resolve(result), 500);
});
};
function getCurrentFormattedDate(): string {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0"); // +1 car janvier = 0
const day = String(now.getDate()).padStart(2, "0");
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
onMounted(() => {
fetchData(
props.projectId,
props.title,
getCurrentFormattedDate(),
IS_MOCK_MODE
);
});
</script>
<style scoped>
@ -302,7 +403,7 @@ const mockFetch = async ( projectId: number, title: number, date: string ): Prom
.tooltip-explain {
position: absolute;
bottom: 101%; /* au-dessus de la carte */
bottom: 101%;
left: 50%;
transform: translateX(-50%);
background-color: #333;
@ -561,12 +662,26 @@ const mockFetch = async ( projectId: number, title: number, date: string ): Prom
color: #444;
background-color: #f9f9f9;
padding: 7px;
border-left: 4px solid #0d6efd;
border-right: 4px solid #0d6efd;
border-radius: 6px;
margin-bottom: 20px;
margin-top: 20px;
line-height: 1.6;
font-family: "Segoe UI", sans-serif;
}
.delete-button {
position: absolute;
top: 5px;
right: 10px;
background: transparent;
border: none;
color: #a00;
font-size: 1.2rem;
cursor: pointer;
z-index: 10;
}
.section-bloc {
position: relative;
}
</style>

View File

@ -13,11 +13,15 @@
</a>
<div class="header-actions">
<button class="return-button" @click="store.logout">Logout</button>
<div v-if="props.isAdmin">
<div ref="dropdownRef" class="dropdown-wrapper">
<button class="contact-button" @click.stop="toggleDropdown">
Contact
</button>
<div
v-if="entrepreneurEmails.length > 0"
class="contact-dropdown"
:class="{ 'dropdown-visible': isDropdownOpen }"
>
@ -31,102 +35,87 @@
</button>
</div>
</div>
<RouterLink to="/" class="return-button">Retour</RouterLink>
</div>
</div>
</header>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import axios from "axios";
import { store } from "@/main.ts";
import { getProjectEntrepreneurs } from "@/services/Apis/Shared.ts";
import UserEntrepreneur from "@/ApiClasses/UserEntrepreneur.ts";
const IS_MOCK_MODE = true;
const dropdownRef = ref<HTMLElement | null>(null); // ref pour le dropdown
const dropdownRef = ref<HTMLElement | undefined>(undefined);
const props = defineProps<{
projectId: number;
isAdmin: boolean;
}>();
type Entrepreneur = {
idUser: number;
userSurname: string;
userName: string;
primaryMail: string;
secondaryMail: string;
phoneNumber: string;
school: string;
course: string;
sneeStatus: boolean;
};
const isDropdownOpen = ref(false);
const entrepreneurEmails = ref<string[]>([]);
const entrepreneurs = ref<UserEntrepreneur[]>([]);
const IS_MOCK_MODE = false;
const toggleDropdown = () => {
isDropdownOpen.value = !isDropdownOpen.value;
console.log("Dropdown toggled:", isDropdownOpen.value);
};
const fetchEntrepreneurs = async (
projectId: number,
useMock = IS_MOCK_MODE
) => {
try {
const responseData: Entrepreneur[] = useMock
? await mockFetchEntrepreneurs(projectId)
: (
await axios.get(
`http://localhost:5000/shared/projects/entrepreneurs/${projectId}`
)
).data;
const fetchMockEntrepreneurs = () => {
const mockData = [
{
userName: "Doe",
userSurname: "John",
primaryMail: "john.doe@example.com",
},
{
userName: "Smith",
userSurname: "Anna",
primaryMail: "anna.smith@example.com",
},
{
userName: "Mock",
userSurname: "User",
primaryMail: undefined,
},
];
if (responseData.length > 0) {
entrepreneurEmails.value = responseData.map(
(item: Entrepreneur) => item.primaryMail
);
entrepreneurs.value = mockData.map((item) => new UserEntrepreneur(item));
entrepreneurEmails.value = entrepreneurs.value
.map((e) => e.primaryMail)
.filter((mail): mail is string => !!mail);
console.log("Mock entrepreneurs chargés :", entrepreneurs.value);
};
const fetchEntrepreneurs = (projectId: number, useMock = false) => {
if (useMock) {
fetchMockEntrepreneurs();
} else {
console.warn("Aucun entrepreneur trouvé.");
if (projectId == -1) {
console.error("No contact to show because no project was found.");
return;
}
} catch (error) {
getProjectEntrepreneurs(
projectId,
(response) => {
const rawData = response.data as Partial<UserEntrepreneur>[];
entrepreneurs.value = rawData.map(
(item) => new UserEntrepreneur(item)
);
entrepreneurEmails.value = entrepreneurs.value
.map((e) => e.primaryMail)
.filter((mail): mail is string => !!mail);
},
(error) => {
console.error(
"Erreur lors de la récupération des entrepreneurs :",
error
);
}
};
// Fonction de simulation de l'API
const mockFetchEntrepreneurs = async (projectId: number) => {
console.log(`Mock fetch pour projectId: ${projectId}`);
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{
idUser: 1,
userSurname: "Doe",
userName: "John",
primaryMail: "john.doe@example.com",
secondaryMail: "johndoe@backup.com",
phoneNumber: "612345678",
school: "ENSEIRB",
course: "Info",
sneeStatus: false,
},
{
idUser: 2,
userSurname: "Smith",
userName: "Jane",
primaryMail: "jane.smith@example.com",
secondaryMail: "janesmith@backup.com",
phoneNumber: "698765432",
school: "ENSEIRB",
course: "Info",
sneeStatus: true,
},
]);
}, 500);
});
);
}
};
const contactAll = () => {
@ -137,9 +126,7 @@ const contactAll = () => {
alert("Tous les emails copiés dans le presse-papiers !");
window.open("https://partage.bordeaux-inp.fr/", "_blank");
})
.catch((err) => {
console.error("Erreur lors de la copie :", err);
});
.catch((err) => console.error("Erreur lors de la copie :", err));
};
const contactSingle = (email: string) => {
@ -149,12 +136,9 @@ const contactSingle = (email: string) => {
alert(`Adresse copiée : ${email}`);
window.open("https://partage.bordeaux-inp.fr/", "_blank");
})
.catch((err) => {
console.error("Erreur lors de la copie :", err);
});
.catch((err) => console.error("Erreur lors de la copie :", err));
};
// Cacher le menu si on clique en dehors
const handleClickOutside = (event: MouseEvent) => {
if (
isDropdownOpen.value &&
@ -166,7 +150,9 @@ const handleClickOutside = (event: MouseEvent) => {
};
onMounted(() => {
if (props.isAdmin) {
fetchEntrepreneurs(props.projectId, IS_MOCK_MODE);
}
document.addEventListener("click", handleClickOutside);
});
@ -182,7 +168,7 @@ onBeforeUnmount(() => {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 30px;
padding: 10px 20px;
background-color: #f9f9f9;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

View File

@ -6,7 +6,7 @@
:title="item.title"
:title-text="item.title_text"
:description="item.description"
:project-id="item.projectId"
:project-id="props.projectId"
:class="['canvas-item', item.class, 'card', 'shadow', 'p-3']"
:is-admin="props.isAdmin"
/>
@ -18,95 +18,66 @@ import { ref } from "vue";
import CanvasItem from "@/components/canvas/CanvasItem.vue";
const props = defineProps<{
isAdmin: number;
projectId: number;
isAdmin: boolean;
}>();
const items = ref([
{
projectId: 1,
title: 1,
title_text: "1. Problème",
description: "3 problèmes essentiels à résoudre pour le client",
class: "Probleme",
},
{
projectId: 1,
title: 2,
title_text: "2. Segments",
description: "Les segments de clientèle visés",
class: "Segments",
},
{
projectId: 1,
title: 3,
title_text: "3. Valeur",
description: "La proposition de valeur",
class: "Valeur",
},
{
projectId: 1,
title: 4,
title_text: "4. Solution",
description: "Les solutions proposées",
class: "Solution",
},
{
projectId: 1,
title: 5,
title_text: "5. Avantage",
description: "Les avantages concurrentiels",
class: "Avantage",
},
{
projectId: 1,
title: 6,
title_text: "6. Canaux",
description: "Les canaux de distribution",
class: "Canaux",
},
{
projectId: 1,
title: 7,
title_text: "7. Indicateurs",
description: "Les indicateurs clés de performance",
class: "Indicateurs",
},
{
projectId: 1,
title: 8,
title_text: "8. Coûts",
description: "Les coûts associés",
class: "Couts",
},
{
projectId: 1,
title: 9,
title_text: "9. Revenus",
description: "Les sources de revenus",
class: "Revenus",
},
]);
/*
onMounted(() => {
const bootstrapCss = document.createElement("link");
bootstrapCss.rel = "stylesheet";
bootstrapCss.href =
"https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css";
bootstrapCss.integrity =
"sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+Fpc+NC";
bootstrapCss.crossOrigin = "anonymous";
document.head.appendChild(bootstrapCss);
const bootstrapJs = document.createElement("script");
bootstrapJs.src =
"https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js";
bootstrapJs.integrity =
"sha384-mQ93S0EhrF4Z1nM+fTflmYf0DyzsY5j7F5H3WlClDD6H3WUJh6kxBkF3GDW8n1j6";
bootstrapJs.crossOrigin = "anonymous";
document.body.appendChild(bootstrapJs);
});
*/
</script>
<style scoped>
@ -119,10 +90,10 @@ onMounted(() => {
gap: 12px;
padding: 30px;
position: relative;
height: auto; /* autorise la hauteur à s'ajuster selon le contenu */
max-height: none; /* enlève la limite de hauteur */
height: auto;
max-height: none;
box-sizing: border-box;
overflow: visible; /* autorise le débordement visible */
overflow: visible;
}
@media (max-width: 768px) {
@ -169,7 +140,6 @@ onMounted(() => {
}
.canvas-item {
/*background-color: white;*/
border: 1px solid #dee2e6;
border-radius: 0.5rem;
}

View File

@ -40,6 +40,18 @@ const router = createRouter({
name: "JorCproject",
component: () => import("../views/JoinOrCreatProjectForEntrep.vue"),
},
{
path: "/finalize",
name: "finalize",
component: () => import("../views/FinalizeAccount.vue"),
},
{
path: "/pending-approval",
name: "PendingApproval",
component: () => import("@/views/PendingApproval.vue"),
},
],
});

View File

@ -1,7 +1,12 @@
import { type AxiosError, type AxiosResponse } from "axios";
import Project from "@/ApiClasses/Project";
import Report from "@/ApiClasses/Repport";
import { axiosInstance, defaultApiErrorHandler, defaultApiSuccessHandler } from "@/services/api"
import ProjectDecision from "@/ApiClasses/ProjectDecision";
//import UserAdmin from "@/ApiClasses/UserAdmin";
import {
axiosInstance,
defaultApiErrorHandler,
defaultApiSuccessHandler,
} from "@/services/api";
// Admin API
function getPendingAccounts(
@ -49,51 +54,50 @@ function validateUserAccount(
});
}
// function getPendingProjectJoinRequests( // Not yet implemented [cite: 3]
// onSuccessHandler?: (response: AxiosResponse) => void,
// onErrorHandler?: (error: AxiosError) => void
// ): void {
// axiosInstance
// .get("/admin/request-join")
// .then((response) => {
// if (onSuccessHandler) {
// onSuccessHandler(response);
// } else {
// defaultApiSuccessHandler(response);
// }
// })
// .catch((error: AxiosError) => {
// if (onErrorHandler) {
// onErrorHandler(error);
// } else {
// defaultApiErrorHandler(error);
// }
// });
// }
// function decideProjectJoinRequest( // Not yet implemented [cite: 3]
// joinRequestId: number,
// decision: { isAccepted: boolean },
// onSuccessHandler?: (response: AxiosResponse) => void,
// onErrorHandler?: (error: AxiosError) => void
// ): void {
// axiosInstance
// .post(`/admin/request-join/decision/${joinRequestId}`, decision)
// .then((response) => {
// if (onSuccessHandler) {
// onSuccessHandler(response);
// } else {
// defaultApiSuccessHandler(response);
// }
// })
// .catch((error: AxiosError) => {
// if (onErrorHandler) {
// onErrorHandler(error);
// } else {
// defaultApiErrorHandler(error);
// }
// });
// }
function getPendingProjectJoinRequests( // Not yet implemented
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/admin/request-join")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
function decideProjectJoinRequest( // Not yet implemented
joinRequestId: number,
decision: { isAccepted: boolean },
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.post(`/admin/request-join/decision/${joinRequestId}`, decision)
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
function getAdminProjects(
onSuccessHandler?: (response: AxiosResponse) => void,
@ -117,27 +121,20 @@ function getAdminProjects(
});
}
type ProjectCreatePayload = {
projectName: string;
logo?: string;
};
function addProjectManually(
projectDetails: Project, // Replace 'any' with a proper type for project details if available
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
payload: ProjectCreatePayload,
onSuccess?: (response: AxiosResponse) => void,
onError?: (error: AxiosError) => void
): void {
axiosInstance
.post("/admin/projects", projectDetails)
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
.post("/admin/projects", payload)
.then((response) => onSuccess?.(response))
.catch((error: AxiosError) => onError?.(error));
}
function getPendingProjects(
@ -163,13 +160,12 @@ function getPendingProjects(
}
function decidePendingProject(
pendingProjectId: number,
decision: { projectId: number; adminId: number; isAccepted: boolean }, // Replace 'any' with a proper type for project decision if available
decision: ProjectDecision,
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.post(`/admin/projects/pending/decision/${pendingProjectId}`, decision)
.post(`/admin/projects/pending/decision`, decision.toObject())
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
@ -302,13 +298,35 @@ function grantAdminRights(
});
}
function createAdmin(
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.post("/admin/create-account")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
export {
axiosInstance,
// requestJoinProject, // Not yet implemented [cite: 4]
//requestJoinProject, // Not yet implemented [cite: 4]
getPendingAccounts,
validateUserAccount,
// getPendingProjectJoinRequests, // Not yet implemented [cite: 3]
// decideProjectJoinRequest, // Not yet implemented [cite: 3]
getPendingProjectJoinRequests, // Not yet implemented [cite: 3]
decideProjectJoinRequest, // Not yet implemented [cite: 3]
getAdminProjects,
addProjectManually,
getPendingProjects,
@ -318,4 +336,5 @@ export {
getUpcomingAppointments,
removeProject,
grantAdminRights,
createAdmin,
};

View File

@ -1,45 +1,42 @@
import { type AxiosError, type AxiosResponse } from "axios";
import Project from "@/ApiClasses/Project";
import SectionCell from "@/ApiClasses/SectionCell";
import { axiosInstance, defaultApiErrorHandler, defaultApiSuccessHandler } from "@/services/api"
axiosInstance.interceptors.response.use(
(response) => response, // Directly return successful responses.
async (error) => {
const originalRequest = error.config;
if (
((error.response && error.response.status === 401) ||
error.code == "ERR_NETWORK") &&
!originalRequest._retry &&
store.authenticated
) {
originalRequest._retry = true; // Mark the request as retried to avoid infinite loops.
try {
await store.refreshUserToken();
// Update the authorization header with the new access token.
axiosInstance.defaults.headers.common["Authorization"] =
`Bearer ${store.user.token}`;
return axiosInstance(originalRequest); // Retry the original request with the new access token.
} catch (refreshError) {
// Handle refresh token errors by clearing stored tokens and redirecting to the login page.
console.error("Token refresh failed:", refreshError);
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
router.push("/login");
return Promise.reject(refreshError);
}
}
return Promise.reject(error); // For all other errors, return the error as is.
}
);
import {
axiosInstance,
defaultApiErrorHandler,
defaultApiSuccessHandler,
} from "@/services/api";
// Entrepreneurs API
function getEntrepreneurProjectId(
onSuccessHandler?: (response: AxiosResponse<number[]>) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/entrepreneur/projects")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
function requestProjectCreation(
projectDetails: Project, // Replace 'any' with a proper type for project details if available
projectDetails: Project,
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.post("/entrepreneur/projects/request", projectDetails)
.post("/entrepreneur/projects/request", projectDetails.toObject())
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
@ -62,7 +59,7 @@ function addSectionCell(
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.post("/entrepreneur/sectionCells", sectionCellDetails.toPlainObject()) // <-- Ici
.post("/entrepreneur/sectionCells", sectionCellDetails.toObject())
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
@ -81,7 +78,7 @@ function addSectionCell(
function modifySectionCell(
sectionCellId: number,
sectionCellDetails: SectionCell, // Replace 'any' with a proper type for section cell details if available
sectionCellDetails: SectionCell,
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
@ -126,9 +123,58 @@ function removeSectionCell(
});
}
// Checks if the entrepreneur has a pending project request
function checkPendingProjectRequest(
onSuccessHandler?: (response: AxiosResponse<boolean>) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/entrepreneur/projects/has-pending-request")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
// Checks if the entrepreneur has an active project
function checkIfProjectIsActive(
onSuccessHandler?: (response: AxiosResponse<boolean>) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/entrepreneur/projects/project-is-active")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
export {
getEntrepreneurProjectId,
requestProjectCreation,
addSectionCell,
modifySectionCell,
removeSectionCell,
checkPendingProjectRequest,
checkIfProjectIsActive,
};

View File

@ -1,7 +1,10 @@
import { type AxiosError, type AxiosResponse } from "axios";
import Appointment from "@/ApiClasses/Appointment";
import { axiosInstance, defaultApiErrorHandler, defaultApiSuccessHandler } from "@/services/api"
import {
axiosInstance,
defaultApiErrorHandler,
defaultApiSuccessHandler,
} from "@/services/api";
// Shared API
function getSectionCellsByDate(

View File

@ -1,7 +1,10 @@
import { type AxiosError, type AxiosResponse } from "axios";
import { axiosInstance, defaultApiErrorHandler, defaultApiSuccessHandler } from "@/services/api"
import {
axiosInstance,
defaultApiErrorHandler,
defaultApiSuccessHandler,
} from "@/services/api";
// Unauth API
function finalizeAccount(
@ -49,8 +52,52 @@ function finalizeAccount(
// });
// }
function getAllEntrepreneurs(
onSuccessHandler?: (response: AxiosResponse) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/unauth/getAllEntrepreneurs")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
function checkPending(
onSuccessHandler?: (response: AxiosResponse<boolean>) => void,
onErrorHandler?: (error: AxiosError) => void
): void {
axiosInstance
.get("/unauth/check-if-not-pending")
.then((response) => {
if (onSuccessHandler) {
onSuccessHandler(response);
} else {
defaultApiSuccessHandler(response);
}
})
.catch((error: AxiosError) => {
if (onErrorHandler) {
onErrorHandler(error);
} else {
defaultApiErrorHandler(error);
}
});
}
export {
finalizeAccount,
getAllEntrepreneurs,
checkPending,
// requestJoinProject, // Not yet implemented [cite: 4]
};

View File

@ -1,6 +1,7 @@
import axios, { type AxiosError, type AxiosResponse } from "axios";
import { store } from "@/main.ts";
import { addNewMessage, color } from "@/services/popupDisplayer.ts";
import router from "@/router/router";
const axiosInstance = axios.create({
baseURL: import.meta.env.VITE_BACKEND_URL,
@ -9,6 +10,19 @@ const axiosInstance = axios.create({
},
});
axiosInstance.interceptors.request.use(
(config) => {
const token = store.user?.token; // Récupérez le token depuis le store
if (token) {
config.headers["Authorization"] = `Bearer ${token}`; // Ajoutez le token dans l'en-tête
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
axiosInstance.interceptors.response.use(
(response) => response, // Directly return successful responses.
async (error) => {
@ -19,19 +33,17 @@ axiosInstance.interceptors.response.use(
!originalRequest._retry &&
store.authenticated
) {
originalRequest._retry = true; // Mark the request as retried to avoid infinite loops.
originalRequest._retry = true;
try {
await store.refreshUserToken();
// Update the authorization header with the new access token.
axiosInstance.defaults.headers.common["Authorization"] =
`Bearer ${store.user.token}`;
return axiosInstance(originalRequest); // Retry the original request with the new access token.
return axiosInstance(originalRequest);
} catch (refreshError) {
// Handle refresh token errors by clearing stored tokens and redirecting to the login page.
console.error("Token refresh failed:", refreshError);
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
window.location.href = "/login";
router.push("/login");
return Promise.reject(refreshError);
}
}
@ -41,7 +53,9 @@ axiosInstance.interceptors.response.use(
// TODO: spawn a error modal
function defaultApiErrorHandler(err: AxiosError) {
addNewMessage(err.message, color.Red);
const errorMessage =
(err.response?.data as { message?: string })?.message ?? err.message;
addNewMessage(errorMessage, color.Red);
}
function defaultApiSuccessHandler(response: AxiosResponse) {
@ -88,4 +102,13 @@ function deleteApi(
.catch(onErrorHandler ?? defaultApiErrorHandler);
}
export { axiosInstance, callApi, postApi, deleteApi };
//export { axiosInstance, callApi, postApi, deleteApi };
export {
axiosInstance,
defaultApiErrorHandler,
defaultApiSuccessHandler,
callApi,
postApi,
deleteApi,
};

View File

@ -0,0 +1,24 @@
import { jwtDecode } from "jwt-decode";
import { store } from "@/main";
type TokenPayload = {
realm_access?: {
roles?: string[];
};
};
function isAdmin(): boolean {
if (store.authenticated && store.user.token) {
const decoded = jwtDecode<TokenPayload>(store.user.token);
const roles = decoded.realm_access?.roles || [];
if (roles.includes("MyINPulse-admin")) {
return true;
} else {
return false;
}
} else {
return false;
}
}
export { isAdmin };

View File

@ -1,6 +1,7 @@
<template>
<Header />
<error-wrapper></error-wrapper>
<error-wrapper />
<div id="container">
<div id="main">
<h3>Projet en cours</h3>
@ -13,18 +14,18 @@
:project-id="0"
/>
<div id="main">
<h3>Projet en attente</h3>
<!-- <AllEntrep /> -->
<h3>Projet en attente</h3>
<PendingProjectComponent
v-for="(project, index) in pendingProjects"
:key="index"
:project-name="project.name"
:project-name="project.projectName"
:creation-date="project.creationDate"
/>
</div>
<AddProjectForm />
<PendingRequestsManager />
</div>
<Agenda :project-r-d-v="rendezVous" />
@ -32,79 +33,145 @@
</template>
<script setup lang="ts">
import { ref /*, onMounted*/ } from "vue";
//import { callApi } from "@/services/api";
import { ref, onMounted } from "vue";
import { getAdminProjects, getPendingProjects } from "@/services/Apis/Admin";
import { getProjectEntrepreneurs } from "@/services/Apis/Shared";
import { type AxiosError, type AxiosResponse } from "axios";
import Header from "../components/HeaderComponent.vue";
import Agenda from "../components/AgendaComponent.vue";
import ProjectComp from "../components/ProjectComponent.vue";
import PendingProjectComponent from "@/components/PendingProjectComponent.vue";
import AddProjectForm from "@/components/AddProjectForm.vue";
import PendingRequestsManager from "@/components/PendingRequestsManager.vue";
import { createAdmin } from "@/services/Apis/Admin";
import Project from "@/ApiClasses/Project";
import UserEntrepreneur from "@/ApiClasses/UserEntrepreneur";
//import UserAdmin from "@/ApiClasses/UserAdmin";
//import AllEntrep from "../components/AllEntrep.vue";
const projects = ref<
{
name: string;
link: string;
members: string[];
}[]
>([]);
//const PORT = "8081";
//const URI = `http://localhost:${PORT}`;
//const projects = ref<{ name: string; link: string; members: string[] }[]>([]);
/* const fetchProjects = () => {
callApi(
`${URI}/admin/projects`,
async (response) => {
console.log(response);
const projectList = response.data;
const projectPromises = projectList.map((project: any) => {
return new Promise(async (resolve) => {
callApi(
`${URI}/shared/projects/entrepreneurs/${project.idProject}`,
(memberResponse) => {
const members = memberResponse.data.map((m: any) => m.userName);
resolve({
name: project.projectName,
link: `/project/${project.idProject}`,
members,
});
},
() => {
// Error fetching members, still resolve with empty members
resolve({
name: project.projectName,
link: `/project/${project.idProject}`,
members: [],
});
}
);
});
});
projects.value = await Promise.all(projectPromises);
},
(error) => {
console.error("Error fetching projects:", error);
}
);
};
onMounted(fetchProjects);
*/
const projects = ref([
const fallbackProjects = [
{
name: "Projet Alpha",
link: "/canvas", // to test
link: "/canvas",
members: ["Alice", "Bob", "Charlie"],
},
{
name: "Projet Beta",
link: "./canvas", // to test
link: "./canvas",
members: ["David", "Eve", "Frank"],
},
]);
];
const pendingProjects = ref([
{ name: "l'eau", creationDate: "26-02-2024" },
{ name: "l'air", creationDate: "09-03-2023" },
]);
const createFirstAdmin = () => {
createAdmin(
(response) => {
console.log("Admin créé avec succès :", response.data);
},
(error) => {
console.error(
"Erreur lors de la création de l'admin :",
error.message
);
}
);
};
onMounted(createFirstAdmin);
const fetchProjects = () => {
getAdminProjects(
(response: AxiosResponse) => {
const projectList = response.data.map(
(p: Project) => new Project(p)
);
const projectPromises = projectList.map(
(project: Project) =>
new Promise<void>((resolve) => {
getProjectEntrepreneurs(
project.idProject!,
(memberResponse: AxiosResponse) => {
const members = memberResponse.data.map(
(m: UserEntrepreneur) =>
new UserEntrepreneur(m).userName ||
"Unknown"
);
projects.value.push({
name:
project.projectName ||
"Unnamed Project",
link: `/project/${project.idProject}`,
members,
});
resolve();
},
() => {
projects.value.push({
name:
project.projectName ||
"Unnamed Project",
link: `/project/${project.idProject}`,
members: [],
});
resolve();
}
);
})
);
Promise.all(projectPromises).catch(() => {
projects.value = fallbackProjects;
});
},
(error: AxiosError) => {
console.error("Error fetching admin projects:", error);
projects.value = fallbackProjects;
}
);
};
const pendingProjects = ref<Project[]>([]);
const mockPendingProjects = [
new Project({ projectName: "l'eau", creationDate: "26-02-2024" }),
new Project({ projectName: "l'air", creationDate: "09-03-2023" }),
];
onMounted(fetchProjects);
onMounted(() => {
getPendingProjects(
(response) => {
pendingProjects.value = response.data.map(
(p: Project) =>
new Project({
projectName: p.projectName,
creationDate: p.creationDate,
})
);
},
(error) => {
console.error(
"Failed to fetch pending projects, using mock:",
error
);
pendingProjects.value = mockPendingProjects.map(
(p) =>
new Project({
projectName: p.projectName,
creationDate: p.creationDate,
})
);
}
);
});
const rendezVous = ref([
{ projectName: "Projet Alpha", date: "2025-03-10", lieu: "P106" },
@ -153,7 +220,6 @@ button:hover {
background-color: #0056b3;
}
/* Add spacing between project sections */
#main > * + * {
margin-top: 2rem;
}

View File

@ -1,7 +1,7 @@
<template>
<div>
<header>
<HeaderCanvas :project-id="1" />
<HeaderCanvas :project-id="projectId" :is-admin="isAdmin_" />
</header>
</div>
<div>
@ -10,22 +10,22 @@
Cliquez sur un champ du tableau pour afficher son contenu en détail
ci-dessous.
</p>
<LeanCanvas :is-admin="isAdmin" />
<LeanCanvas :project-id="projectId" :is-admin="isAdmin_" />
<div class="info-box">
<p>
<p v-if="admin">
Responsable :
<strong>{{ admin.userName }} {{ admin.userSurname }}</strong
><br />
Contact :
<a href="mailto:{{ admin.primaryMail }}">{{
<a :href="`mailto:${admin.primaryMail}`">{{
admin.primaryMail
}}</a>
|
<a href="tel:{{ admin.phoneNumber }}">{{
<a :href="`tel:${admin.phoneNumber}`">{{
admin.phoneNumber
}}</a>
</p>
<div class="main"></div>
<p v-else>Chargement des informations du responsable...</p>
</div>
</div>
</template>
@ -33,69 +33,101 @@
<script setup lang="ts">
import HeaderCanvas from "../components/canvas/HeaderCanvas.vue";
import LeanCanvas from "../components/canvas/LeanCanvas.vue";
import { ref, onMounted /*, defineProps*/ } from "vue";
import { axiosInstance } from "@/services/api.ts";
import { ref, onMounted } from "vue";
import { isAdmin } from "@/services/tools.ts";
import { getProjectAdmin } from "@/services/Apis/Shared.ts";
import UserAdmin from "@/ApiClasses/UserAdmin.ts";
import type { AxiosResponse, AxiosError } from "axios";
import { getEntrepreneurProjectId } from "@/services/Apis/Entrepreneurs";
const IS_MOCK_MODE = true;
const IS_MOCK_MODE = false;
const isAdmin_ = isAdmin();
const admin = ref<UserAdmin | null>(null);
const projectId = ref<number>(-1);
/*
const props = defineProps<{
projectId: number;
token: TokenPayload;
}>();
is_admin = token.includes("MyINPulse-admin")
*/
const isAdmin = 0;
// Variables pour les informations de l'administrateur
const admin = ref({
idUser: 0,
userSurname: "",
userName: "",
primaryMail: "",
secondaryMail: "",
phoneNumber: "",
});
const mockAdminData = {
const mockAdminData = new UserAdmin({
idUser: 1,
userSurname: "ALAMI",
userName: "Adnane",
primaryMail: "mock.admin@example.com",
secondaryMail: "admin.backup@example.com",
phoneNumber: "0600000000",
};
});
// Fonction pour récupérer les données de l'administrateur
const fetchAdminData = async (projectId: number, useMock = IS_MOCK_MODE) => {
try {
if (useMock) {
console.log(
"Utilisation des données mockées pour l'administrateur"
function getProjectId(): Promise<number> {
return new Promise((resolve) => {
getEntrepreneurProjectId(
(response) => {
const projectIds = response.data;
if (!Array.isArray(projectIds) || projectIds.length === 0) {
console.warn("Aucun projet trouvé pour cet entrepreneur.");
resolve(-1);
return;
}
resolve(projectIds[0]);
},
(error) => {
console.error("Erreur API :", error);
resolve(-1);
}
);
});
}
async function fetchProjectId() {
try {
projectId.value = await getProjectId();
console.log("ProjectId :", projectId.value);
} catch (error) {
console.error("Erreur lors de la récupération du projet :", error);
}
}
const fetchAdminData = (projectId: number, useMock = IS_MOCK_MODE) => {
if (useMock) {
console.log("Utilisation des données mockées pour l'administrateur");
admin.value = mockAdminData;
return;
}
const response = await axiosInstance.get(
`/shared/projects/admin/${projectId}`
);
admin.value = response.data;
} catch (error) {
if (projectId === -1) {
admin.value = new UserAdmin({
idUser: 0,
userSurname: "Erreur",
userName: "Chargement",
primaryMail: "N/A",
secondaryMail: "N/A",
phoneNumber: "N/A",
});
return;
}
getProjectAdmin(
projectId,
(response: AxiosResponse) => {
admin.value = new UserAdmin(response.data);
},
(error: AxiosError) => {
console.error(
"Erreur lors de la récupération des données de l'administrateur :",
error
);
admin.value = new UserAdmin({
idUser: 0,
userSurname: "Erreur",
userName: "Chargement",
primaryMail: "N/A",
secondaryMail: "N/A",
phoneNumber: "N/A",
});
}
);
};
// Appeler la fonction fetch au montage du composant
onMounted(() => {
const projectId = 1;
fetchAdminData(projectId);
fetchProjectId();
fetchAdminData(projectId.value);
});
</script>

View File

@ -0,0 +1,81 @@
<template>
<Header />
<div class="finalize-page">
<div class="loader-container">
<button class="return-button" @click="store.logout">Logout</button>
<div class="spinner"></div>
<p>Finalisation du compte en cours...</p>
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted } from "vue";
//import { useRouter } from "vue-router";
import { finalizeAccount } from "@/services/Apis/Unauth";
import Header from "@/components/HeaderComponent.vue";
import { store } from "@/main.ts";
//const router = useRouter();
onMounted(() => {
finalizeAccount(
() => {
console.log("finalize sended");
},
(error) => {
console.error("Erreur lors de la finalisation :", error);
}
);
});
</script>
<style scoped>
.finalize-page {
display: flex;
justify-content: center;
align-items: center;
min-height: 80vh;
background-color: #f9fbfd;
}
.loader-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
color: #333;
font-size: 1.1rem;
font-style: italic;
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid #cfd8dc;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.return-button {
background-color: #009cde;
color: white;
border: none;
padding: 10px 15px;
cursor: pointer;
font-size: 14px;
border-radius: 5px;
text-decoration: none;
transition: background-color 0.2s ease;
font-family: Arial, sans-serif;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>

View File

@ -1,10 +1,12 @@
<template>
<Header />
<header class="header">
<img
src="@/components/icons/logo inpulse.png"
alt="INPulse Logo"
class="logo"
/>
<button class="return-button" @click="store.logout">Logout</button>
</header>
<div class="choix-projet">
@ -39,8 +41,18 @@
</template>
<script setup lang="ts">
import { ref } from "vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import Project from "@/ApiClasses/Project";
import Header from "../components/HeaderComponent.vue";
import { store } from "@/main.ts";
import {
requestProjectCreation,
checkIfProjectIsActive,
checkPendingProjectRequest,
} from "@/services/Apis/Entrepreneurs";
const router = useRouter();
const choix = ref<string | null>(null);
const nomProjet = ref("");
@ -53,8 +65,53 @@ const validerCreation = () => {
alert("Veuillez entrer un nom de projet.");
return;
}
const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, "0");
const dd = String(today.getDate()).padStart(2, "0");
const formattedDate = `${yyyy}-${mm}-${dd}`;
const nouveauProjet = new Project({
projectName: nomProjet.value.trim(),
creationDate: formattedDate,
status: "PENDING",
});
requestProjectCreation(
nouveauProjet,
(response) => {
console.log("Projet créé :", response.data);
alert(`Projet "${nomProjet.value}" créé avec succès !`);
},
(error) => {
console.error("Erreur lors de la création du projet :", error);
alert("Une erreur est survenue lors de la création du projet.");
}
);
};
onMounted(() => {
checkIfProjectIsActive(
(response) => {
if (response.data === true) {
router.push("/canvas");
}
},
() => {
checkPendingProjectRequest(
(response) => {
if (response.data === true) {
router.push("/pending-approval");
}
},
(error) => {
console.warn("No active or pending project:", error);
}
);
}
);
});
</script>
<style scoped>
@ -112,4 +169,17 @@ input {
.logo {
height: 50px;
}
.return-button {
background-color: #009cde;
color: white;
border: none;
padding: 10px 15px;
cursor: pointer;
font-size: 14px;
border-radius: 5px;
text-decoration: none;
transition: background-color 0.2s ease;
font-family: Arial, sans-serif;
}
</style>

View File

@ -0,0 +1,41 @@
<template>
<Header />
<div class="pending-container">
<h1>Projet en attente de validation</h1>
<p>
Votre demande de création de projet a bien été reçue.<br />
Un administrateur doit valider votre projet avant que vous puissiez
continuer.
</p>
</div>
</template>
<script setup lang="ts">
import Header from "@/components/HeaderComponent.vue";
</script>
<style scoped>
.pending-container {
max-width: 600px;
margin: 100px auto;
padding: 2rem;
text-align: center;
background-color: #fffdf8;
border: 1px solid #ececec;
border-radius: 12px;
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
font-family: "Inter", sans-serif;
}
h1 {
color: #f57c00;
font-size: 1.8rem;
margin-bottom: 1rem;
}
p {
font-size: 1.1rem;
color: #333;
margin-bottom: 1.5rem;
}
</style>

View File

@ -58,7 +58,7 @@ const USERID = ref("");
<tr>
<td>Get Pending Accounts</td>
<td>
<button @click="callApi('admin/get_pending_accounts')">
<button @click="callApi('/admin/pending-accounts')">
call
</button>
</td>

2638
keycloak/realm.json Normal file

File diff suppressed because it is too large Load Diff