From 94d9428c43f2f698f428c682cae5473e0c7b1e05 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Fri, 17 Apr 2026 18:34:04 +0200 Subject: [PATCH 01/11] feat(backend): #28 templates email validation compte (Handlebars) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Templates .hbs parent principal, co-parent, AM + lien create-password - app_name / app_url / expéditeur via ConfigService (sendEmail) - validateUser: renouvelle token création MDP + envoi email si sans password - Dist: assets *.hbs (nest-cli) - Tests unitaires MailService (mock sendEmail) - Doc liste tickets #28 terminé Made-with: Cursor --- backend/nest-cli.json | 8 +- backend/package-lock.json | 199 ++++++++++++++++-- backend/package.json | 2 + backend/src/modules/mail/mail.service.spec.ts | 72 +++++++ backend/src/modules/mail/mail.service.ts | 68 ++++++ .../mail/templates/account-validated-am.hbs | 14 ++ .../account-validated-parent-coparent.hbs | 14 ++ .../account-validated-parent-primary.hbs | 14 ++ backend/src/routes/user/user.module.ts | 2 + backend/src/routes/user/user.service.ts | 56 ++++- docs/23_LISTE-TICKETS.md | 22 +- 11 files changed, 439 insertions(+), 32 deletions(-) create mode 100644 backend/src/modules/mail/mail.service.spec.ts create mode 100644 backend/src/modules/mail/templates/account-validated-am.hbs create mode 100644 backend/src/modules/mail/templates/account-validated-parent-coparent.hbs create mode 100644 backend/src/modules/mail/templates/account-validated-parent-primary.hbs diff --git a/backend/nest-cli.json b/backend/nest-cli.json index f9aa683..0830f40 100644 --- a/backend/nest-cli.json +++ b/backend/nest-cli.json @@ -3,6 +3,12 @@ "collection": "@nestjs/schematics", "sourceRoot": "src", "compilerOptions": { - "deleteOutDir": true + "deleteOutDir": true, + "assets": [ + { + "include": "**/*.hbs", + "watchAssets": true + } + ] } } diff --git a/backend/package-lock.json b/backend/package-lock.json index 3c2f567..a0827ca 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -22,8 +22,11 @@ "bcryptjs": "^3.0.2", "class-transformer": "^0.5.1", "class-validator": "^0.14.2", + "handlebars": "^4.7.8", "joi": "^18.0.0", "mapped-types": "^0.0.1", + "multer": "^1.4.5-lts.1", + "nodemailer": "^6.9.16", "passport-jwt": "^4.0.1", "pg": "^8.16.3", "reflect-metadata": "^0.2.2", @@ -39,8 +42,11 @@ "@nestjs/testing": "^11.0.1", "@types/bcrypt": "^6.0.0", "@types/express": "^5.0.0", + "@types/handlebars": "^4.1.0", "@types/jest": "^30.0.0", + "@types/multer": "^1.4.12", "@types/node": "^22.10.7", + "@types/nodemailer": "^6.4.16", "@types/passport-jwt": "^4.0.1", "@types/supertest": "^6.0.2", "eslint": "^9.18.0", @@ -2462,6 +2468,82 @@ "@nestjs/core": "^11.0.0" } }, + "node_modules/@nestjs/platform-express/node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/@nestjs/platform-express/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@nestjs/platform-express/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@nestjs/platform-express/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@nestjs/platform-express/node_modules/multer": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz", + "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "mkdirp": "^0.5.6", + "object-assign": "^4.1.1", + "type-is": "^1.6.18", + "xtend": "^4.0.2" + }, + "engines": { + "node": ">= 10.16.0" + } + }, + "node_modules/@nestjs/platform-express/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/@nestjs/schematics": { "version": "11.0.7", "resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.0.7.tgz", @@ -3613,6 +3695,17 @@ "@types/send": "*" } }, + "node_modules/@types/handlebars": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@types/handlebars/-/handlebars-4.1.0.tgz", + "integrity": "sha512-gq9YweFKNNB1uFK71eRqsd4niVkXrxHugqWFQkeLRJvGjnxsLr16bYtcsG4tOFwmYi0Bax+wCkbf1reUfdl4kA==", + "deprecated": "This is a stub types definition. handlebars provides its own type definitions, so you do not need this installed.", + "dev": true, + "license": "MIT", + "dependencies": { + "handlebars": "*" + } + }, "node_modules/@types/http-errors": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", @@ -3688,6 +3781,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/multer": { + "version": "1.4.13", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz", + "integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, "node_modules/@types/mysql": { "version": "2.15.27", "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.27.tgz", @@ -3706,6 +3809,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/nodemailer": { + "version": "6.4.23", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.23.tgz", + "integrity": "sha512-aFV3/NsYFLSx9mbb5gtirBSXJnAlrusoKNuPbxsASWc7vrKLmIrTQRpdcxNcSFL3VW2A2XpeLEavwb2qMi6nlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/passport": { "version": "1.0.17", "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.17.tgz", @@ -5578,20 +5691,56 @@ "license": "MIT" }, "node_modules/concat-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", - "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", "engines": [ - "node >= 6.0" + "node >= 0.8" ], "license": "MIT", "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", - "readable-stream": "^3.0.2", + "readable-stream": "^2.2.2", "typedarray": "^0.0.6" } }, + "node_modules/concat-stream/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/concat-stream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/concat-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/concat-stream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/consola": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", @@ -5658,7 +5807,6 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true, "license": "MIT" }, "node_modules/cors": { @@ -7004,7 +7152,6 @@ "version": "4.7.8", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz", "integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==", - "dev": true, "license": "MIT", "dependencies": { "minimist": "^1.2.5", @@ -7026,7 +7173,6 @@ "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -8889,21 +9035,22 @@ "license": "MIT" }, "node_modules/multer": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz", - "integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==", + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", "license": "MIT", "dependencies": { "append-field": "^1.0.0", - "busboy": "^1.6.0", - "concat-stream": "^2.0.0", - "mkdirp": "^0.5.6", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", "object-assign": "^4.1.1", - "type-is": "^1.6.18", - "xtend": "^4.0.2" + "type-is": "^1.6.4", + "xtend": "^4.0.0" }, "engines": { - "node": ">= 10.16.0" + "node": ">= 6.0.0" } }, "node_modules/multer/node_modules/media-typer": { @@ -8995,7 +9142,6 @@ "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true, "license": "MIT" }, "node_modules/node-abort-controller": { @@ -9049,6 +9195,15 @@ "dev": true, "license": "MIT" }, + "node_modules/nodemailer": { + "version": "6.10.1", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.10.1.tgz", + "integrity": "sha512-Z+iLaBGVaSjbIzQ4pX6XV41HrooLsQ10ZWPUehGmuantvzWoDVBnmsdUcOIDM1t+yPor5pDhVlDESgOMEGxhHA==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -9706,6 +9861,12 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -11534,7 +11695,6 @@ "version": "3.19.3", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", - "dev": true, "license": "BSD-2-Clause", "optional": true, "bin": { @@ -12013,7 +12173,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", - "dev": true, "license": "MIT" }, "node_modules/wrap-ansi": { diff --git a/backend/package.json b/backend/package.json index cb149bf..d5a1710 100644 --- a/backend/package.json +++ b/backend/package.json @@ -36,6 +36,7 @@ "bcryptjs": "^3.0.2", "class-transformer": "^0.5.1", "class-validator": "^0.14.2", + "handlebars": "^4.7.8", "joi": "^18.0.0", "mapped-types": "^0.0.1", "multer": "^1.4.5-lts.1", @@ -55,6 +56,7 @@ "@nestjs/testing": "^11.0.1", "@types/bcrypt": "^6.0.0", "@types/express": "^5.0.0", + "@types/handlebars": "^4.1.0", "@types/jest": "^30.0.0", "@types/multer": "^1.4.12", "@types/node": "^22.10.7", diff --git a/backend/src/modules/mail/mail.service.spec.ts b/backend/src/modules/mail/mail.service.spec.ts new file mode 100644 index 0000000..8f5cbe5 --- /dev/null +++ b/backend/src/modules/mail/mail.service.spec.ts @@ -0,0 +1,72 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { MailService, ValidationAccountEmailKind } from './mail.service'; +import { AppConfigService } from '../config/config.service'; + +describe('MailService (ticket #28)', () => { + let service: MailService; + let sendEmailSpy: jest.SpyInstance; + + const mockConfigGet = jest.fn((key: string, defaultValue?: unknown) => { + const values: Record = { + app_name: 'TestApp', + app_url: 'https://app.test/', + smtp_host: '127.0.0.1', + smtp_port: 1025, + smtp_secure: false, + smtp_auth_required: false, + smtp_user: '', + smtp_password: '', + email_from_name: 'Test', + email_from_address: 'noreply@test', + }; + if (key in values) return values[key]; + return defaultValue; + }); + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + MailService, + { + provide: AppConfigService, + useValue: { get: mockConfigGet }, + }, + ], + }).compile(); + + service = module.get(MailService); + sendEmailSpy = jest.spyOn(service, 'sendEmail').mockResolvedValue(undefined); + }); + + afterEach(() => { + sendEmailSpy.mockRestore(); + }); + + it.each<[ValidationAccountEmailKind, string]>([ + ['parent_primary', 'Compte validé'], + ['parent_coparent', 'Co-parent'], + ['am', 'Inscription validée'], + ])('sendValidatedAccountPasswordSetupEmail (%s) utilise Handlebars + lien token', async (kind, subjectPart) => { + const token = '11111111-2222-3333-4444-555555555555'; + await service.sendValidatedAccountPasswordSetupEmail( + { + email: 'user@test.fr', + prenom: 'Jean', + nom: 'Dupont', + token, + numeroDossier: '2025-000001', + }, + kind, + ); + + expect(sendEmailSpy).toHaveBeenCalledTimes(1); + const [, subject, html] = sendEmailSpy.mock.calls[0]; + expect(subject).toContain('TestApp'); + expect(subject).toContain(subjectPart); + expect(html).toContain('Jean'); + expect(html).toContain('Dupont'); + expect(html).toContain('2025-000001'); + expect(html).toContain(`https://app.test/create-password?token=${encodeURIComponent(token)}`); + }); +}); diff --git a/backend/src/modules/mail/mail.service.ts b/backend/src/modules/mail/mail.service.ts index 10f9fc9..aa39e3f 100644 --- a/backend/src/modules/mail/mail.service.ts +++ b/backend/src/modules/mail/mail.service.ts @@ -1,12 +1,80 @@ import { Injectable, Logger } from '@nestjs/common'; +import { readFileSync } from 'fs'; +import { join } from 'path'; +import * as Handlebars from 'handlebars'; import { AppConfigService } from '../config/config.service'; +/** Ticket #28 — quel template d'email envoyer après validation de compte */ +export type ValidationAccountEmailKind = 'parent_primary' | 'parent_coparent' | 'am'; + @Injectable() export class MailService { private readonly logger = new Logger(MailService.name); + /** Cache des templates Handlebars compilés (fichiers .hbs) */ + private readonly compiledTemplates = new Map(); + constructor(private readonly configService: AppConfigService) {} + private templateBasename(kind: ValidationAccountEmailKind): string { + const map: Record = { + parent_primary: 'account-validated-parent-primary', + parent_coparent: 'account-validated-parent-coparent', + am: 'account-validated-am', + }; + return map[kind]; + } + + private getCompiledTemplate(kind: ValidationAccountEmailKind): Handlebars.TemplateDelegate { + let compiled = this.compiledTemplates.get(kind); + if (!compiled) { + const filePath = join(__dirname, 'templates', `${this.templateBasename(kind)}.hbs`); + const source = readFileSync(filePath, 'utf8'); + compiled = Handlebars.compile(source); + this.compiledTemplates.set(kind, compiled); + } + return compiled; + } + + /** + * Email post-validation : lien création MDP (token existant ou régénéré côté appelant). + * Ticket #28 — app_name, app_url, expéditeur via ConfigService (sendEmail). + */ + async sendValidatedAccountPasswordSetupEmail( + recipient: { + email: string; + prenom: string; + nom: string; + token: string; + numeroDossier?: string | null; + }, + kind: ValidationAccountEmailKind, + ): Promise { + const appName = this.configService.get('app_name', "P'titsPas"); + const appUrl = (this.configService.get('app_url', 'https://app.ptits-pas.fr') || '').replace(/\/+$/, ''); + + const createPasswordUrl = `${appUrl}/create-password?token=${encodeURIComponent(recipient.token)}`; + + const data: Record = { + prenom: recipient.prenom || '', + nom: recipient.nom || '', + appName, + appUrl, + createPasswordUrl, + numeroDossier: recipient.numeroDossier || '', + }; + + const html = this.getCompiledTemplate(kind)(data) as string; + + const subjects: Record = { + parent_primary: `${appName} — Compte validé : créez votre mot de passe`, + parent_coparent: `${appName} — Co-parent : créez votre mot de passe`, + am: `${appName} — Inscription validée : créez votre mot de passe`, + }; + + await this.sendEmail(recipient.email, subjects[kind], html); + } + /** * Envoi d'un email générique * @param to Destinataire diff --git a/backend/src/modules/mail/templates/account-validated-am.hbs b/backend/src/modules/mail/templates/account-validated-am.hbs new file mode 100644 index 0000000..f79ffca --- /dev/null +++ b/backend/src/modules/mail/templates/account-validated-am.hbs @@ -0,0 +1,14 @@ +
+

Bonjour {{prenom}} {{nom}},

+

Votre demande d'inscription en tant qu'assistante maternelle sur {{appName}} a été validée.

+ {{#if numeroDossier}} +

Numéro de dossier : {{numeroDossier}}

+ {{/if}} +

Pour finaliser l'activation de votre compte, veuillez créer votre mot de passe en cliquant sur le bouton ci-dessous.

+ +

Si le bouton ne fonctionne pas, copiez ce lien dans votre navigateur :
{{{createPasswordUrl}}}

+
+

Cet email a été envoyé automatiquement par {{appName}}. Merci de ne pas y répondre.

+
diff --git a/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs b/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs new file mode 100644 index 0000000..e75c446 --- /dev/null +++ b/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs @@ -0,0 +1,14 @@ +
+

Bonjour {{prenom}} {{nom}},

+

Le dossier d'inscription sur {{appName}} auquel vous êtes rattaché·e en tant que co-parent a été validé.

+ {{#if numeroDossier}} +

Numéro de dossier : {{numeroDossier}}

+ {{/if}} +

Vous devez maintenant définir votre mot de passe pour accéder à l'application avec votre propre compte.

+ +

Si le bouton ne fonctionne pas, copiez ce lien dans votre navigateur :
{{{createPasswordUrl}}}

+
+

Cet email a été envoyé automatiquement par {{appName}}. Merci de ne pas y répondre.

+
diff --git a/backend/src/modules/mail/templates/account-validated-parent-primary.hbs b/backend/src/modules/mail/templates/account-validated-parent-primary.hbs new file mode 100644 index 0000000..3cdb68a --- /dev/null +++ b/backend/src/modules/mail/templates/account-validated-parent-primary.hbs @@ -0,0 +1,14 @@ +
+

Bonjour {{prenom}} {{nom}},

+

Votre demande d'inscription sur {{appName}} a été validée.

+ {{#if numeroDossier}} +

Numéro de dossier : {{numeroDossier}}

+ {{/if}} +

En tant que demandeur principal, vous devez maintenant définir votre mot de passe pour accéder à l'application.

+ +

Si le bouton ne fonctionne pas, copiez ce lien dans votre navigateur :
{{{createPasswordUrl}}}

+
+

Cet email a été envoyé automatiquement par {{appName}}. Merci de ne pas y répondre.

+
diff --git a/backend/src/routes/user/user.module.ts b/backend/src/routes/user/user.module.ts index 2924082..62598f8 100644 --- a/backend/src/routes/user/user.module.ts +++ b/backend/src/routes/user/user.module.ts @@ -11,6 +11,7 @@ import { AssistantesMaternellesModule } from '../assistantes_maternelles/assista import { Parents } from 'src/entities/parents.entity'; import { GestionnairesModule } from './gestionnaires/gestionnaires.module'; import { MailModule } from 'src/modules/mail/mail.module'; +import { AppConfigModule } from 'src/modules/config/config.module'; @Module({ imports: [TypeOrmModule.forFeature( @@ -24,6 +25,7 @@ import { MailModule } from 'src/modules/mail/mail.module'; AssistantesMaternellesModule, GestionnairesModule, MailModule, + AppConfigModule, ], controllers: [UserController], providers: [UserService], diff --git a/backend/src/routes/user/user.service.ts b/backend/src/routes/user/user.service.ts index 7e44081..2f3437e 100644 --- a/backend/src/routes/user/user.service.ts +++ b/backend/src/routes/user/user.service.ts @@ -9,7 +9,8 @@ import * as bcrypt from 'bcrypt'; import { StatutValidationType, Validation } from "src/entities/validations.entity"; import { Parents } from "src/entities/parents.entity"; import { AssistanteMaternelle } from "src/entities/assistantes_maternelles.entity"; -import { MailService } from "src/modules/mail/mail.service"; +import { MailService, ValidationAccountEmailKind } from "src/modules/mail/mail.service"; +import { AppConfigService } from "src/modules/config/config.service"; import * as crypto from 'crypto'; @Injectable() @@ -30,6 +31,8 @@ export class UserService { private readonly assistantesRepository: Repository, private readonly mailService: MailService, + + private readonly appConfigService: AppConfigService, ) { } async createUser(dto: CreateUserDto, currentUser?: Users): Promise { @@ -265,6 +268,57 @@ export class UserService { comment, }); await this.validationRepository.save(validation); + + // Ticket #28 — email création MDP (parents / AM), Handlebars + lien app_url + const roleCibleMdp = + savedUser.role === RoleType.PARENT || savedUser.role === RoleType.ASSISTANTE_MATERNELLE; + if (roleCibleMdp && !savedUser.password) { + try { + const joursExpiration = await this.appConfigService.get( + 'password_reset_token_expiry_days', + 7, + ); + if (!savedUser.token_creation_mdp) { + savedUser.token_creation_mdp = crypto.randomUUID(); + } + const exp = new Date(); + exp.setDate(exp.getDate() + joursExpiration); + savedUser.token_creation_mdp_expire_le = exp; + await this.usersRepository.save(savedUser); + + let kind: ValidationAccountEmailKind = 'am'; + if (savedUser.role === RoleType.ASSISTANTE_MATERNELLE) { + kind = 'am'; + } else if (savedUser.numero_dossier) { + const parentsDossier = await this.usersRepository.find({ + where: { numero_dossier: savedUser.numero_dossier, role: RoleType.PARENT }, + order: { cree_le: 'ASC' }, + }); + const premier = parentsDossier[0]; + kind = + premier && premier.id !== savedUser.id ? 'parent_coparent' : 'parent_primary'; + } else { + kind = 'parent_primary'; + } + + await this.mailService.sendValidatedAccountPasswordSetupEmail( + { + email: savedUser.email, + prenom: savedUser.prenom ?? '', + nom: savedUser.nom ?? '', + token: savedUser.token_creation_mdp, + numeroDossier: savedUser.numero_dossier, + }, + kind, + ); + } catch (err) { + this.logger.warn( + `Envoi email validation compte (#28) échoué pour ${savedUser.email}`, + err as Error, + ); + } + } + return savedUser; } diff --git a/docs/23_LISTE-TICKETS.md b/docs/23_LISTE-TICKETS.md index eee299d..934fb6a 100644 --- a/docs/23_LISTE-TICKETS.md +++ b/docs/23_LISTE-TICKETS.md @@ -591,22 +591,24 @@ Installer et configurer Nodemailer pour l'envoi d'emails. --- -### Ticket #28 : [Backend] Templates Email - Validation +### Ticket #28 : [Backend] Templates Email - Validation ✅ **Estimation** : 3h -**Labels** : `backend`, `p2`, `email` +**Labels** : `backend`, `p2`, `email` +**Statut** : ✅ TERMINÉ **Description** : Créer les templates d'emails pour la validation des comptes (avec lien création MDP). **Tâches** : -- [ ] Template Parent 1 (création MDP) -- [ ] URL app : Lire depuis `ConfigService.get('app_url')` -- [ ] Nom app : Lire depuis `ConfigService.get('app_name')` -- [ ] Expéditeur : Lire depuis ConfigService -- [ ] Template Parent 2 (co-parent création MDP) -- [ ] Template AM (création MDP) -- [ ] Intégration Handlebars -- [ ] Tests d'envoi +- [x] Template Parent 1 (création MDP) — `account-validated-parent-primary.hbs` +- [x] URL app : Lire depuis `ConfigService.get('app_url')` (lien `/create-password?token=…`) +- [x] Nom app : Lire depuis `ConfigService.get('app_name')` +- [x] Expéditeur : via `sendEmail` (email_from_name / email_from_address) +- [x] Template Parent 2 (co-parent création MDP) — `account-validated-parent-coparent.hbs` +- [x] Template AM (création MDP) — `account-validated-am.hbs` +- [x] Intégration Handlebars + copie `.hbs` dans `dist` (`nest-cli.json` assets) +- [x] Envoi déclenché dans `UserService.validateUser` (parent / AM sans mot de passe) + renouvellement expiration token +- [x] Tests unitaires (`mail.service.spec.ts`, mock `sendEmail`) **Référence** : [20_WORKFLOW-CREATION-COMPTE.md](./20_WORKFLOW-CREATION-COMPTE.md#étape-6--réception-de-la-notification) From 7590c95f06fb008a780d5980e4ec677631afa765 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Fri, 17 Apr 2026 18:37:47 +0200 Subject: [PATCH 02/11] refactor(mail): #28 un seul template email parent (principal + co-parent) Made-with: Cursor --- backend/src/modules/mail/mail.service.spec.ts | 3 +-- backend/src/modules/mail/mail.service.ts | 8 +++----- .../account-validated-parent-coparent.hbs | 14 -------------- ...-primary.hbs => account-validated-parent.hbs} | 4 ++-- backend/src/routes/user/user.service.ts | 16 ++-------------- docs/23_LISTE-TICKETS.md | 3 +-- 6 files changed, 9 insertions(+), 39 deletions(-) delete mode 100644 backend/src/modules/mail/templates/account-validated-parent-coparent.hbs rename backend/src/modules/mail/templates/{account-validated-parent-primary.hbs => account-validated-parent.hbs} (77%) diff --git a/backend/src/modules/mail/mail.service.spec.ts b/backend/src/modules/mail/mail.service.spec.ts index 8f5cbe5..03eb5b0 100644 --- a/backend/src/modules/mail/mail.service.spec.ts +++ b/backend/src/modules/mail/mail.service.spec.ts @@ -44,8 +44,7 @@ describe('MailService (ticket #28)', () => { }); it.each<[ValidationAccountEmailKind, string]>([ - ['parent_primary', 'Compte validé'], - ['parent_coparent', 'Co-parent'], + ['parent', 'Compte parent validé'], ['am', 'Inscription validée'], ])('sendValidatedAccountPasswordSetupEmail (%s) utilise Handlebars + lien token', async (kind, subjectPart) => { const token = '11111111-2222-3333-4444-555555555555'; diff --git a/backend/src/modules/mail/mail.service.ts b/backend/src/modules/mail/mail.service.ts index aa39e3f..79521c8 100644 --- a/backend/src/modules/mail/mail.service.ts +++ b/backend/src/modules/mail/mail.service.ts @@ -5,7 +5,7 @@ import * as Handlebars from 'handlebars'; import { AppConfigService } from '../config/config.service'; /** Ticket #28 — quel template d'email envoyer après validation de compte */ -export type ValidationAccountEmailKind = 'parent_primary' | 'parent_coparent' | 'am'; +export type ValidationAccountEmailKind = 'parent' | 'am'; @Injectable() export class MailService { @@ -18,8 +18,7 @@ export class MailService { private templateBasename(kind: ValidationAccountEmailKind): string { const map: Record = { - parent_primary: 'account-validated-parent-primary', - parent_coparent: 'account-validated-parent-coparent', + parent: 'account-validated-parent', am: 'account-validated-am', }; return map[kind]; @@ -67,8 +66,7 @@ export class MailService { const html = this.getCompiledTemplate(kind)(data) as string; const subjects: Record = { - parent_primary: `${appName} — Compte validé : créez votre mot de passe`, - parent_coparent: `${appName} — Co-parent : créez votre mot de passe`, + parent: `${appName} — Compte parent validé : créez votre mot de passe`, am: `${appName} — Inscription validée : créez votre mot de passe`, }; diff --git a/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs b/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs deleted file mode 100644 index e75c446..0000000 --- a/backend/src/modules/mail/templates/account-validated-parent-coparent.hbs +++ /dev/null @@ -1,14 +0,0 @@ -
-

Bonjour {{prenom}} {{nom}},

-

Le dossier d'inscription sur {{appName}} auquel vous êtes rattaché·e en tant que co-parent a été validé.

- {{#if numeroDossier}} -

Numéro de dossier : {{numeroDossier}}

- {{/if}} -

Vous devez maintenant définir votre mot de passe pour accéder à l'application avec votre propre compte.

- -

Si le bouton ne fonctionne pas, copiez ce lien dans votre navigateur :
{{{createPasswordUrl}}}

-
-

Cet email a été envoyé automatiquement par {{appName}}. Merci de ne pas y répondre.

-
diff --git a/backend/src/modules/mail/templates/account-validated-parent-primary.hbs b/backend/src/modules/mail/templates/account-validated-parent.hbs similarity index 77% rename from backend/src/modules/mail/templates/account-validated-parent-primary.hbs rename to backend/src/modules/mail/templates/account-validated-parent.hbs index 3cdb68a..78d82bc 100644 --- a/backend/src/modules/mail/templates/account-validated-parent-primary.hbs +++ b/backend/src/modules/mail/templates/account-validated-parent.hbs @@ -1,10 +1,10 @@

Bonjour {{prenom}} {{nom}},

-

Votre demande d'inscription sur {{appName}} a été validée.

+

Votre compte parent sur {{appName}} a été validé.

{{#if numeroDossier}}

Numéro de dossier : {{numeroDossier}}

{{/if}} -

En tant que demandeur principal, vous devez maintenant définir votre mot de passe pour accéder à l'application.

+

Pour accéder à l'application, veuillez définir votre mot de passe en cliquant sur le bouton ci-dessous.

diff --git a/backend/src/routes/user/user.service.ts b/backend/src/routes/user/user.service.ts index 2f3437e..9becd46 100644 --- a/backend/src/routes/user/user.service.ts +++ b/backend/src/routes/user/user.service.ts @@ -286,20 +286,8 @@ export class UserService { savedUser.token_creation_mdp_expire_le = exp; await this.usersRepository.save(savedUser); - let kind: ValidationAccountEmailKind = 'am'; - if (savedUser.role === RoleType.ASSISTANTE_MATERNELLE) { - kind = 'am'; - } else if (savedUser.numero_dossier) { - const parentsDossier = await this.usersRepository.find({ - where: { numero_dossier: savedUser.numero_dossier, role: RoleType.PARENT }, - order: { cree_le: 'ASC' }, - }); - const premier = parentsDossier[0]; - kind = - premier && premier.id !== savedUser.id ? 'parent_coparent' : 'parent_primary'; - } else { - kind = 'parent_primary'; - } + const kind: ValidationAccountEmailKind = + savedUser.role === RoleType.ASSISTANTE_MATERNELLE ? 'am' : 'parent'; await this.mailService.sendValidatedAccountPasswordSetupEmail( { diff --git a/docs/23_LISTE-TICKETS.md b/docs/23_LISTE-TICKETS.md index 934fb6a..a0996d0 100644 --- a/docs/23_LISTE-TICKETS.md +++ b/docs/23_LISTE-TICKETS.md @@ -600,11 +600,10 @@ Installer et configurer Nodemailer pour l'envoi d'emails. Créer les templates d'emails pour la validation des comptes (avec lien création MDP). **Tâches** : -- [x] Template Parent 1 (création MDP) — `account-validated-parent-primary.hbs` +- [x] Template **Parent** (création MDP, parent principal ou co-parent) — `account-validated-parent.hbs` - [x] URL app : Lire depuis `ConfigService.get('app_url')` (lien `/create-password?token=…`) - [x] Nom app : Lire depuis `ConfigService.get('app_name')` - [x] Expéditeur : via `sendEmail` (email_from_name / email_from_address) -- [x] Template Parent 2 (co-parent création MDP) — `account-validated-parent-coparent.hbs` - [x] Template AM (création MDP) — `account-validated-am.hbs` - [x] Intégration Handlebars + copie `.hbs` dans `dist` (`nest-cli.json` assets) - [x] Envoi déclenché dans `UserService.validateUser` (parent / AM sans mot de passe) + renouvellement expiration token From f2daab1325a42f9ba74e30abbb2b2679c9c85ae0 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Fri, 17 Apr 2026 18:49:44 +0200 Subject: [PATCH 03/11] =?UTF-8?q?fix(db):=20validations=20=E2=80=94=20colo?= =?UTF-8?q?nnes=20commentaire=20et=20valide=5Fpar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - BDD.sql alignée sur l’entité TypeORM - Patch SQL pour bases existantes + README patches Made-with: Cursor --- database/BDD.sql | 2 ++ .../2026-04-17-validations-commentaire-valide-par.sql | 8 ++++++++ database/patches/README.md | 9 +++++++++ 3 files changed, 19 insertions(+) create mode 100644 database/patches/2026-04-17-validations-commentaire-valide-par.sql create mode 100644 database/patches/README.md diff --git a/database/BDD.sql b/database/BDD.sql index 3cd7e3a..e577b46 100644 --- a/database/BDD.sql +++ b/database/BDD.sql @@ -274,6 +274,8 @@ CREATE TABLE validations ( id_utilisateur UUID REFERENCES utilisateurs(id), type VARCHAR(50), statut statut_validation_type DEFAULT 'en_attente', + commentaire TEXT, + valide_par UUID REFERENCES utilisateurs(id), cree_le TIMESTAMPTZ DEFAULT now(), modifie_le TIMESTAMPTZ DEFAULT now() ); diff --git a/database/patches/2026-04-17-validations-commentaire-valide-par.sql b/database/patches/2026-04-17-validations-commentaire-valide-par.sql new file mode 100644 index 0000000..2e06263 --- /dev/null +++ b/database/patches/2026-04-17-validations-commentaire-valide-par.sql @@ -0,0 +1,8 @@ +-- Alignement schéma validations ↔ entité TypeORM (ticket validation IHM / #28) +-- À exécuter sur les bases déjà créées sans ces colonnes. + +ALTER TABLE validations + ADD COLUMN IF NOT EXISTS commentaire TEXT; + +ALTER TABLE validations + ADD COLUMN IF NOT EXISTS valide_par UUID REFERENCES utilisateurs(id); diff --git a/database/patches/README.md b/database/patches/README.md new file mode 100644 index 0000000..dbcc5b6 --- /dev/null +++ b/database/patches/README.md @@ -0,0 +1,9 @@ +# Correctifs SQL (hors init `BDD.sql`) + +Scripts à appliquer **manuellement** sur les bases déjà créées (ex. `psql` ou client SQL), dans l’ordre des dates si plusieurs fichiers. + +| Fichier | Objet | +|---------|--------| +| `2026-04-17-validations-commentaire-valide-par.sql` | Ajoute `commentaire` et `valide_par` sur `validations` (requis par l’API / TypeORM). | + +Les nouvelles installs via `BDD.sql` à jour incluent déjà ces colonnes. From fc86181a73dbe774006ac3ec75799b2a1ff32d0a Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Fri, 17 Apr 2026 18:57:34 +0200 Subject: [PATCH 04/11] fix(frontend): CGU/PDF compatible Flutter 3.19 + pdfx 2.6 (build web Docker) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Color.withOpacity à la place de withValues - PdfViewPinch sans API absente (documentProgress, minScale) Made-with: Cursor --- .../cgu_privacy_validation_dialog.dart | 111 +++--------------- 1 file changed, 14 insertions(+), 97 deletions(-) diff --git a/frontend/lib/widgets/cgu_privacy_validation_dialog.dart b/frontend/lib/widgets/cgu_privacy_validation_dialog.dart index 73b9ac2..78bb722 100644 --- a/frontend/lib/widgets/cgu_privacy_validation_dialog.dart +++ b/frontend/lib/widgets/cgu_privacy_validation_dialog.dart @@ -137,7 +137,7 @@ class _CguPrivacyValidationDialogState extends State child: Material( color: _ModaleCouleur.ivoire, elevation: 6, - shadowColor: _ModaleCouleur.encre.withValues(alpha: 0.12), + shadowColor: _ModaleCouleur.encre.withOpacity(0.12), child: SizedBox( width: dialogW, height: dialogH, @@ -179,9 +179,7 @@ class _CguPrivacyValidationDialogState extends State color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all( - color: _ModaleCouleur.turquoiseFonce.withValues( - alpha: 0.35, - ), + color: _ModaleCouleur.turquoiseFonce.withOpacity(0.35), ), ), child: ClipRRect( @@ -200,7 +198,7 @@ class _CguPrivacyValidationDialogState extends State 'Document non disponible.', style: GoogleFonts.merienda( color: _ModaleCouleur.encre - .withValues(alpha: 0.75), + .withOpacity(0.75), ), ), ), @@ -221,9 +219,9 @@ class _CguPrivacyValidationDialogState extends State backgroundColor: _ModaleCouleur.turquoiseFonce, foregroundColor: Colors.white, disabledBackgroundColor: - _ModaleCouleur.mentheClair.withValues(alpha: 0.7), + _ModaleCouleur.mentheClair.withOpacity(0.7), disabledForegroundColor: - _ModaleCouleur.encre.withValues(alpha: 0.45), + _ModaleCouleur.encre.withOpacity(0.45), padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 14, @@ -286,7 +284,7 @@ class _CguPrivacyValidationDialogState extends State tooltip: 'Fermer', icon: Icon( Icons.close, - color: _ModaleCouleur.encre.withValues(alpha: 0.55), + color: _ModaleCouleur.encre.withOpacity(0.55), ), onPressed: () => Navigator.of(context).pop(false), ), @@ -311,7 +309,7 @@ class _CguPrivacyValidationDialogState extends State ? _ModaleCouleur.turquoise : _ModaleCouleur.mentheTresClair, side: BorderSide( - color: _ModaleCouleur.turquoiseFonce.withValues(alpha: 0.55), + color: _ModaleCouleur.turquoiseFonce.withOpacity(0.55), width: 1.5, ), padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 10), @@ -327,10 +325,8 @@ class _CguPrivacyValidationDialogState extends State } } -/// [PdfViewPinch] s’appuie sur un [InteractiveViewer], sans vrai [Scrollable] : -/// barre verticale reliée à [PdfControllerPinch.documentProgress] pour que le -/// « chariot » reste visible (surtout sur le web où la barre OS est souvent -/// masquée). +/// [PdfViewPinch] pour le web / mobile (Flutter 3.19 + pdfx 2.6 : pas de +/// `documentProgress` / `minScale` comme sur les versions plus récentes). class _PdfPaneWithScrollbar extends StatefulWidget { const _PdfPaneWithScrollbar({ super.key, @@ -344,106 +340,27 @@ class _PdfPaneWithScrollbar extends StatefulWidget { } class _PdfPaneWithScrollbarState extends State<_PdfPaneWithScrollbar> { - static const double _barW = 14; - static const double _thumbW = 9; - static const double _minThumbH = 44; - late final PdfControllerPinch _ctrl; @override void initState() { super.initState(); _ctrl = PdfControllerPinch(document: widget.documentFuture); - _ctrl.addListener(_onCtrl); - } - - void _onCtrl() { - // [PdfViewPinch] met à jour documentProgress dans son propre listener : - // replanifier pour lire la valeur après ce tour de notifications. - Future.microtask(() { - if (mounted) setState(() {}); - }); } @override void dispose() { - _ctrl.removeListener(_onCtrl); _ctrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - final raw = _ctrl.documentProgress; - final safeP = (!raw.isFinite || raw.isNaN) ? 0.0 : raw.clamp(0.0, 1.0); - - return Stack( - clipBehavior: Clip.hardEdge, - fit: StackFit.expand, - children: [ - Padding( - padding: const EdgeInsets.only(right: _barW), - child: PdfViewPinch( - padding: 10, - scrollDirection: Axis.vertical, - minScale: 1, - maxScale: 4, - controller: _ctrl, - backgroundDecoration: const BoxDecoration(color: Colors.white), - ), - ), - Positioned( - top: 6, - right: 1, - bottom: 6, - width: _barW, - child: LayoutBuilder( - builder: (context, c) { - final trackH = c.maxHeight; - final thumbH = (trackH * 0.2).clamp(_minThumbH, trackH * 0.5); - final maxTop = (trackH - thumbH).clamp(0.0, double.infinity); - final top = safeP * maxTop; - - return Semantics( - label: 'Position dans le document', - child: Stack( - children: [ - Positioned.fill( - child: DecoratedBox( - decoration: BoxDecoration( - color: _ModaleCouleur.turquoise.withValues( - alpha: 0.35, - ), - borderRadius: BorderRadius.circular(8), - ), - ), - ), - Positioned( - top: top, - left: (_barW - _thumbW) / 2, - child: Container( - width: _thumbW, - height: thumbH, - decoration: BoxDecoration( - color: _ModaleCouleur.turquoiseFonce, - borderRadius: BorderRadius.circular(_thumbW / 2), - boxShadow: const [ - BoxShadow( - color: Color(0x40000000), - blurRadius: 3, - offset: Offset(0, 1), - ), - ], - ), - ), - ), - ], - ), - ); - }, - ), - ), - ], + return PdfViewPinch( + padding: 10, + scrollDirection: Axis.vertical, + controller: _ctrl, + backgroundDecoration: const BoxDecoration(color: Colors.white), ); } } From 2c746ceff3ff0301e182fe373089649c3239a280 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Wed, 22 Apr 2026 18:48:17 +0200 Subject: [PATCH 05/11] =?UTF-8?q?fix(front,db,ci):=20d=C3=A9ploiement=20we?= =?UTF-8?q?b,=20API=20m=C3=AAme=20origine,=20Flutter=203.29,=20sch=C3=A9ma?= =?UTF-8?q?=20validations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Frontend (prod web): - Image builder Flutter 3.29.3 (Dockerfile + workflow CI alignés) - web/index.html: bootstrap Flutter 3.29 (flutter_bootstrap.js), scripts pdf.js conservés - Dockerfile: rm html avant COPY pour éviter l’index « Welcome to nginx » - nginx: server_name _ pour Traefik - env: sur le web, API = Uri.base.origin si pas de API_BASE_URL (évite mixed content http/https) - auth: message d’erreur réseau avec type/détail si non-Exception - CGU/PDF: commentaire sans mention Flutter 3.19 obsolète - pubspec.lock: résolution dépendances Flutter 3.29 Base de données & doc: - BDD.sql: validations.commentaire, valide_par, FK ON DELETE SET NULL + commentaire - patch 2026-04-17: valide_par avec ON DELETE SET NULL - patch 2026-04-18: FK validations en SET NULL sur bases existantes - seed: statut validation « valide » (enum) - FK_POLICIES.md: valide_par - doc workflow: Flutter 3.29.3 Made-with: Cursor --- database/BDD.sql | 8 +- database/docs/FK_POLICIES.md | 4 +- ...-17-validations-commentaire-valide-par.sql | 2 +- ...4-18-validations-fk-on-delete-set-null.sql | 13 +++ database/patches/README.md | 3 +- database/seed/02_seed.sql | 2 +- docs/20_WORKFLOW-CREATION-COMPTE.md | 2 +- frontend/.github/workflows/flutter-check.yml | 2 +- frontend/Dockerfile | 6 +- frontend/lib/config/env.dart | 32 ++++--- frontend/lib/services/auth_service.dart | 5 +- .../cgu_privacy_validation_dialog.dart | 4 +- frontend/nginx.conf | 3 +- frontend/pubspec.lock | 88 +++++++++---------- frontend/web/index.html | 32 +------ 15 files changed, 110 insertions(+), 96 deletions(-) create mode 100644 database/patches/2026-04-18-validations-fk-on-delete-set-null.sql diff --git a/database/BDD.sql b/database/BDD.sql index e577b46..da1a210 100644 --- a/database/BDD.sql +++ b/database/BDD.sql @@ -269,13 +269,17 @@ CREATE TABLE notifications ( -- ========================================================== -- Table : validations -- ========================================================== +-- Historique des décisions (validation / refus / suspension de compte). +-- Colonnes commentaire + valide_par : requises par l’API Nest (TypeORM). +-- FK en ON DELETE SET NULL : conserver la ligne si l’utilisateur référencé +-- est supprimé (voir database/docs/FK_POLICIES.md). CREATE TABLE validations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - id_utilisateur UUID REFERENCES utilisateurs(id), + id_utilisateur UUID REFERENCES utilisateurs(id) ON DELETE SET NULL, type VARCHAR(50), statut statut_validation_type DEFAULT 'en_attente', commentaire TEXT, - valide_par UUID REFERENCES utilisateurs(id), + valide_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL, cree_le TIMESTAMPTZ DEFAULT now(), modifie_le TIMESTAMPTZ DEFAULT now() ); diff --git a/database/docs/FK_POLICIES.md b/database/docs/FK_POLICIES.md index 3be63b3..d4686b1 100644 --- a/database/docs/FK_POLICIES.md +++ b/database/docs/FK_POLICIES.md @@ -47,6 +47,7 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo | **uploads(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Fichier reste référencé sans l’auteur | | **notifications(id_utilisateur)** → `utilisateurs(id)` | **CASCADE** | Notifications propres à l’utilisateur | | **validations(id_utilisateur)** → `utilisateurs(id)` | **SET NULL** | Garder l’historique de décision | +| **validations(valide_par)** → `utilisateurs(id)` | **SET NULL** | Décideur supprimé : la ligne reste | > **ON UPDATE** : **NO ACTION** partout (les UUID ne changent pas). @@ -84,7 +85,8 @@ Documenter, de façon unique et partagée, les règles de suppression/mise à jo - `signalements_bugs.id_utilisateur` → **SET NULL** - `uploads.id_utilisateur` → **SET NULL** - `notifications.id_utilisateur` → **CASCADE** -- `validations.id_utilisateur` → **SET NULL** +- `validations.id_utilisateur` → **SET NULL** +- `validations.valide_par` → **SET NULL** --- diff --git a/database/patches/2026-04-17-validations-commentaire-valide-par.sql b/database/patches/2026-04-17-validations-commentaire-valide-par.sql index 2e06263..55615ef 100644 --- a/database/patches/2026-04-17-validations-commentaire-valide-par.sql +++ b/database/patches/2026-04-17-validations-commentaire-valide-par.sql @@ -5,4 +5,4 @@ ALTER TABLE validations ADD COLUMN IF NOT EXISTS commentaire TEXT; ALTER TABLE validations - ADD COLUMN IF NOT EXISTS valide_par UUID REFERENCES utilisateurs(id); + ADD COLUMN IF NOT EXISTS valide_par UUID REFERENCES utilisateurs(id) ON DELETE SET NULL; diff --git a/database/patches/2026-04-18-validations-fk-on-delete-set-null.sql b/database/patches/2026-04-18-validations-fk-on-delete-set-null.sql new file mode 100644 index 0000000..58882fe --- /dev/null +++ b/database/patches/2026-04-18-validations-fk-on-delete-set-null.sql @@ -0,0 +1,13 @@ +-- Alignement FK validations ↔ BDD.sql / FK_POLICIES (ON DELETE SET NULL). +-- À exécuter sur les bases créées avant la mise à jour du 2026-04-18. +-- Noms de contraintes par défaut PostgreSQL : {table}_{colonne}_fkey. + +ALTER TABLE validations DROP CONSTRAINT IF EXISTS validations_id_utilisateur_fkey; +ALTER TABLE validations + ADD CONSTRAINT validations_id_utilisateur_fkey + FOREIGN KEY (id_utilisateur) REFERENCES utilisateurs(id) ON DELETE SET NULL; + +ALTER TABLE validations DROP CONSTRAINT IF EXISTS validations_valide_par_fkey; +ALTER TABLE validations + ADD CONSTRAINT validations_valide_par_fkey + FOREIGN KEY (valide_par) REFERENCES utilisateurs(id) ON DELETE SET NULL; diff --git a/database/patches/README.md b/database/patches/README.md index dbcc5b6..4bc8ad7 100644 --- a/database/patches/README.md +++ b/database/patches/README.md @@ -5,5 +5,6 @@ Scripts à appliquer **manuellement** sur les bases déjà créées (ex. `psql` | Fichier | Objet | |---------|--------| | `2026-04-17-validations-commentaire-valide-par.sql` | Ajoute `commentaire` et `valide_par` sur `validations` (requis par l’API / TypeORM). | +| `2026-04-18-validations-fk-on-delete-set-null.sql` | Passe les FK `id_utilisateur` et `valide_par` en **ON DELETE SET NULL** (comme `BDD.sql` à jour). | -Les nouvelles installs via `BDD.sql` à jour incluent déjà ces colonnes. +Les nouvelles installs via `BDD.sql` à jour incluent déjà ces colonnes et ces politiques de suppression. diff --git a/database/seed/02_seed.sql b/database/seed/02_seed.sql index 0cda26f..a0a109c 100644 --- a/database/seed/02_seed.sql +++ b/database/seed/02_seed.sql @@ -212,7 +212,7 @@ INSERT INTO validations (id, id_utilisateur, statut, commentaire, cree_le) VALUES ( 'v0000000-0000-0000-0000-000000000001', '66666666-6666-6666-6666-666666666666', - 'accepte', + 'valide', 'Dossier AM vérifié par gestionnaire.', NOW() ) diff --git a/docs/20_WORKFLOW-CREATION-COMPTE.md b/docs/20_WORKFLOW-CREATION-COMPTE.md index df2ddc8..64add56 100644 --- a/docs/20_WORKFLOW-CREATION-COMPTE.md +++ b/docs/20_WORKFLOW-CREATION-COMPTE.md @@ -1528,7 +1528,7 @@ sequenceDiagram ### Architecture Frontend -**Framework** : Flutter 3.19.0 +**Framework** : Flutter 3.29.3 **Langage** : Dart 3.x **State Management** : Provider / Riverpod **HTTP Client** : Dio / http diff --git a/frontend/.github/workflows/flutter-check.yml b/frontend/.github/workflows/flutter-check.yml index b7b9f8f..3165a2e 100644 --- a/frontend/.github/workflows/flutter-check.yml +++ b/frontend/.github/workflows/flutter-check.yml @@ -18,7 +18,7 @@ jobs: - name: 💡 Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: '3.19.0' # ou celle que tu utilises + flutter-version: '3.29.3' channel: stable - name: 📦 Install dependencies diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 7aaab71..c975aa2 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,5 +1,5 @@ # Stage builder -FROM ghcr.io/cirruslabs/flutter:3.19.0 AS builder +FROM ghcr.io/cirruslabs/flutter:3.29.3 AS builder WORKDIR /app COPY pubspec.* ./ RUN flutter pub get @@ -8,6 +8,10 @@ RUN flutter build web --release # Stage production FROM nginx:alpine +# Image nginx:alpine contient déjà index.html « Welcome to nginx ». +# Un merge de dossiers sans nettoyage peut laisser ce fichier si le build +# Flutter n’écrase pas tous les fichiers → SPA invisible. On vide d’abord. +RUN rm -rf /usr/share/nginx/html/* COPY nginx.conf /etc/nginx/conf.d/default.conf COPY --from=builder /app/build/web /usr/share/nginx/html diff --git a/frontend/lib/config/env.dart b/frontend/lib/config/env.dart index fb9c0e1..a44aa29 100644 --- a/frontend/lib/config/env.dart +++ b/frontend/lib/config/env.dart @@ -1,14 +1,24 @@ +import 'package:flutter/foundation.dart' show kIsWeb; + class Env { - // Base URL de l'API, surchargeable à la compilation via --dart-define=API_BASE_URL - static const String apiBaseUrl = String.fromEnvironment( - 'API_BASE_URL', - defaultValue: 'https://app.ptits-pas.fr', - ); + /// Base URL de l’API (sans `/api/v1`). + /// + /// - **Web prod** : par défaut on utilise [Uri.base.origin] (même schéma + hôte que la page), + /// ce qui évite les blocages « mixed content » (ex. page en `http://` vs API en `https://`) + /// et les builds où `--dart-define=API_BASE_URL` ne serait pas passé. + /// - **Web dev** : surcharger avec `--dart-define=API_BASE_URL=http://localhost:3000` (ou l’URL du back). + /// - **Mobile** : défaut `https://app.ptits-pas.fr` ou `API_BASE_URL` en `--dart-define`. + static String get apiBaseUrl { + const fromEnv = String.fromEnvironment('API_BASE_URL'); + if (fromEnv.isNotEmpty) { + return fromEnv; + } + if (kIsWeb) { + return Uri.base.origin; + } + return 'https://app.ptits-pas.fr'; + } - // Construit une URL vers l'API v1 à partir d'un chemin (commençant par '/') - static String apiV1(String path) => '$apiBaseUrl/api/v1$path'; + /// Construit une URL vers l'API v1 à partir d'un chemin (commençant par '/') + static String apiV1(String path) => '${apiBaseUrl}/api/v1$path'; } - - - - diff --git a/frontend/lib/services/auth_service.dart b/frontend/lib/services/auth_service.dart index 77f9587..629329b 100644 --- a/frontend/lib/services/auth_service.dart +++ b/frontend/lib/services/auth_service.dart @@ -69,7 +69,10 @@ class AuthService { } } catch (e) { if (e is Exception) rethrow; - throw Exception('Erreur réseau: impossible de se connecter au serveur'); + // Erreurs non-Exception (ex. certains cas côté web) : afficher le détail pour le diagnostic + throw Exception( + 'Erreur réseau: impossible de se connecter au serveur (${e.runtimeType}: $e)', + ); } } diff --git a/frontend/lib/widgets/cgu_privacy_validation_dialog.dart b/frontend/lib/widgets/cgu_privacy_validation_dialog.dart index 78bb722..dde2625 100644 --- a/frontend/lib/widgets/cgu_privacy_validation_dialog.dart +++ b/frontend/lib/widgets/cgu_privacy_validation_dialog.dart @@ -325,8 +325,8 @@ class _CguPrivacyValidationDialogState extends State } } -/// [PdfViewPinch] pour le web / mobile (Flutter 3.19 + pdfx 2.6 : pas de -/// `documentProgress` / `minScale` comme sur les versions plus récentes). +/// [PdfViewPinch] pour le web / mobile avec `pdfx` 2.6 (pas de +/// `documentProgress` / `minScale` dans cette API). class _PdfPaneWithScrollbar extends StatefulWidget { const _PdfPaneWithScrollbar({ super.key, diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 29d7e49..8b1ceed 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -1,6 +1,7 @@ server { listen 80; - server_name ynov.ptits-pas.fr; + # Host réel fourni par Traefik (app.ptits-pas.fr, etc.) + server_name _; location / { root /usr/share/nginx/html; diff --git a/frontend/pubspec.lock b/frontend/pubspec.lock index be25dd5..752a6b7 100644 --- a/frontend/pubspec.lock +++ b/frontend/pubspec.lock @@ -5,42 +5,42 @@ packages: dependency: transitive description: name: async - sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 url: "https://pub.dev" source: hosted - version: "2.11.0" + version: "2.12.0" boolean_selector: dependency: transitive description: name: boolean_selector - sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" characters: dependency: transitive description: name: characters - sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.4.0" clock: dependency: transitive description: name: clock - sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" collection: dependency: transitive description: name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.1" cross_file: dependency: transitive description: @@ -85,10 +85,10 @@ packages: dependency: transitive description: name: fake_async - sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "1.3.2" ffi: dependency: transitive description: @@ -281,10 +281,10 @@ packages: dependency: transitive description: name: intl - sha256: "3bc132a9dbce73a7e4a21a17d06e1878839ffbf975568bc875c60537824b0c4d" + sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf url: "https://pub.dev" source: hosted - version: "0.18.1" + version: "0.19.0" js: dependency: "direct main" description: @@ -297,26 +297,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec url: "https://pub.dev" source: hosted - version: "10.0.0" + version: "10.0.8" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.9" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "3.0.1" lints: dependency: transitive description: @@ -337,26 +337,26 @@ packages: dependency: transitive description: name: matcher - sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 url: "https://pub.dev" source: hosted - version: "0.12.16+1" + version: "0.12.17" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.16.0" mime: dependency: transitive description: @@ -377,10 +377,10 @@ packages: dependency: transitive description: name: path - sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" url: "https://pub.dev" source: hosted - version: "1.9.0" + version: "1.9.1" path_provider: dependency: transitive description: @@ -529,39 +529,39 @@ packages: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_span: dependency: transitive description: name: source_span - sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.10.1" stack_trace: dependency: transitive description: name: stack_trace - sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" url: "https://pub.dev" source: hosted - version: "1.11.1" + version: "1.12.1" stream_channel: dependency: transitive description: name: stream_channel - sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.4" string_scanner: dependency: transitive description: name: string_scanner - sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.4.1" synchronized: dependency: transitive description: @@ -574,18 +574,18 @@ packages: dependency: transitive description: name: term_glyph - sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.2.2" test_api: dependency: transitive description: name: test_api - sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.7.4" typed_data: dependency: transitive description: @@ -686,10 +686,10 @@ packages: dependency: transitive description: name: vm_service - sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" url: "https://pub.dev" source: hosted - version: "13.0.0" + version: "14.3.1" web: dependency: transitive description: @@ -723,5 +723,5 @@ packages: source: hosted version: "1.1.0" sdks: - dart: ">=3.3.0 <4.0.0" + dart: ">=3.7.0-0 <4.0.0" flutter: ">=3.19.0" diff --git a/frontend/web/index.html b/frontend/web/index.html index da896cd..4525c6f 100644 --- a/frontend/web/index.html +++ b/frontend/web/index.html @@ -32,21 +32,9 @@ P'titsPas - - - - - - - + - + + From a140db8e9d2f94ec3668ff3a5397932227bb0f0e Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Wed, 22 Apr 2026 19:00:11 +0200 Subject: [PATCH 06/11] =?UTF-8?q?fix(front):=20validation=20dossier=20fami?= =?UTF-8?q?lle=20=E2=80=94=20accepter=20HTTP=20201=20(Nest=20POST)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NestJS renvoie 201 Created sur POST /parents/:id/valider-dossier. Le client ne gérait que 200 : la validation et l’envoi d’e-mails étaient déjà effectués mais l’UI affichait une erreur après lecture du corps (liste JSON). Made-with: Cursor --- frontend/lib/services/user_service.dart | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/lib/services/user_service.dart b/frontend/lib/services/user_service.dart index 4db19ed..eb67a67 100644 --- a/frontend/lib/services/user_service.dart +++ b/frontend/lib/services/user_service.dart @@ -222,7 +222,10 @@ class UserService { headers: await _headers(), body: jsonEncode(comment != null ? {'comment': comment} : {}), ); - if (response.statusCode != 200) { + // NestJS renvoie souvent 201 Created sur un POST même avec corps JSON — le front ne doit pas traiter ça comme une erreur + // (sinon validation + emails déjà faits côté serveur mais SnackBar rouge côté UI). + final ok = response.statusCode == 200 || response.statusCode == 201; + if (!ok) { try { final err = jsonDecode(response.body); throw Exception(_errMessage(err is Map ? err['message'] : err)); From 29cbbb1d08da72c2711114176c20254b2e9d9ea5 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Thu, 23 Apr 2026 11:49:31 +0200 Subject: [PATCH 07/11] feat(auth): align verify-token with #118 invalid-link behavior Treat missing token on GET /auth/verify-token as the same neutral invalid/expired/used response (404), matching ticket #118 expectations for /create-password flows. Made-with: Cursor --- backend/src/routes/auth/auth.service.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/src/routes/auth/auth.service.ts b/backend/src/routes/auth/auth.service.ts index bced215..506c22c 100644 --- a/backend/src/routes/auth/auth.service.ts +++ b/backend/src/routes/auth/auth.service.ts @@ -140,7 +140,9 @@ export class AuthService { async verifyCreatePasswordToken(token: string) { const cleanedToken = token?.trim(); if (!cleanedToken) { - throw new BadRequestException('Token manquant'); + // #118: côté front, un token absent doit être traité comme lien invalide/expiré. + // On renvoie donc la même réponse neutre 404 que pour les autres cas invalides. + throw new NotFoundException('Token invalide, expiré, ou déjà utilisé.'); } const user = await this.usersRepo.findOne({ From 3716dfe61156fa15bae220f80e54a45308da31e4 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Thu, 23 Apr 2026 11:53:34 +0200 Subject: [PATCH 08/11] test(auth): couvrir verify-token/create-password pour le ticket #118 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ajoute des tests unitaires sur le flux API de création de mot de passe: forwarding verify-token, rejet confirmation mismatch et validation du comportement lien invalide/expiré côté service. Made-with: Cursor --- .../src/routes/auth/auth.controller.spec.ts | 55 +++++++++++++++++++ backend/src/routes/auth/auth.service.spec.ts | 50 ++++++++++++++++- 2 files changed, 103 insertions(+), 2 deletions(-) diff --git a/backend/src/routes/auth/auth.controller.spec.ts b/backend/src/routes/auth/auth.controller.spec.ts index 27a31e6..e1b11aa 100644 --- a/backend/src/routes/auth/auth.controller.spec.ts +++ b/backend/src/routes/auth/auth.controller.spec.ts @@ -1,12 +1,24 @@ +import { BadRequestException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { AuthController } from './auth.controller'; +import { AuthService } from './auth.service'; +import { UserService } from '../user/user.service'; describe('AuthController', () => { let controller: AuthController; + const authServiceMock = { + verifyCreatePasswordToken: jest.fn(), + createPasswordWithToken: jest.fn(), + }; beforeEach(async () => { + jest.clearAllMocks(); const module: TestingModule = await Test.createTestingModule({ controllers: [AuthController], + providers: [ + { provide: AuthService, useValue: authServiceMock }, + { provide: UserService, useValue: {} }, + ], }).compile(); controller = module.get(AuthController); @@ -15,4 +27,47 @@ describe('AuthController', () => { it('should be defined', () => { expect(controller).toBeDefined(); }); + + it('forwards token verification to auth service', async () => { + authServiceMock.verifyCreatePasswordToken.mockResolvedValue({ + valid: true, + message: 'Token valide', + }); + + await expect(controller.verifyCreatePasswordToken('tok-123')).resolves.toEqual({ + valid: true, + message: 'Token valide', + }); + expect(authServiceMock.verifyCreatePasswordToken).toHaveBeenCalledWith('tok-123'); + }); + + it('rejects create-password when confirmation mismatches', async () => { + await expect( + controller.createPassword({ + token: 'tok-123', + password: 'Password1', + password_confirmation: 'Password2', + }), + ).rejects.toThrow(BadRequestException); + expect(authServiceMock.createPasswordWithToken).not.toHaveBeenCalled(); + }); + + it('calls auth service when create-password payload is valid', async () => { + authServiceMock.createPasswordWithToken.mockResolvedValue({ + message: 'Mot de passe créé avec succès. Vous pouvez maintenant vous connecter.', + userId: 'user-1', + }); + + await expect( + controller.createPassword({ + token: 'tok-123', + password: 'Password1', + password_confirmation: 'Password1', + }), + ).resolves.toEqual({ + message: 'Mot de passe créé avec succès. Vous pouvez maintenant vous connecter.', + userId: 'user-1', + }); + expect(authServiceMock.createPasswordWithToken).toHaveBeenCalledWith('tok-123', 'Password1'); + }); }); diff --git a/backend/src/routes/auth/auth.service.spec.ts b/backend/src/routes/auth/auth.service.spec.ts index 800ab66..03812b4 100644 --- a/backend/src/routes/auth/auth.service.spec.ts +++ b/backend/src/routes/auth/auth.service.spec.ts @@ -1,12 +1,41 @@ +import { NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; +import { JwtService } from '@nestjs/jwt'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { ConfigService } from '@nestjs/config'; import { AuthService } from './auth.service'; +import { UserService } from '../user/user.service'; +import { AppConfigService } from 'src/modules/config/config.service'; +import { MailService } from 'src/modules/mail/mail.service'; +import { NumeroDossierService } from 'src/modules/numero-dossier/numero-dossier.service'; +import { Parents } from 'src/entities/parents.entity'; +import { Users } from 'src/entities/users.entity'; +import { Children } from 'src/entities/children.entity'; +import { AssistanteMaternelle } from 'src/entities/assistantes_maternelles.entity'; -describe('AuthService', () => { +describe('AuthService (#118 create-password API)', () => { let service: AuthService; + const usersRepoMock = { + findOne: jest.fn(), + createQueryBuilder: jest.fn(), + }; beforeEach(async () => { + jest.clearAllMocks(); const module: TestingModule = await Test.createTestingModule({ - providers: [AuthService], + providers: [ + AuthService, + { provide: UserService, useValue: {} }, + { provide: JwtService, useValue: {} }, + { provide: ConfigService, useValue: { get: jest.fn() } }, + { provide: AppConfigService, useValue: {} }, + { provide: MailService, useValue: {} }, + { provide: NumeroDossierService, useValue: {} }, + { provide: getRepositoryToken(Parents), useValue: {} }, + { provide: getRepositoryToken(Users), useValue: usersRepoMock }, + { provide: getRepositoryToken(Children), useValue: {} }, + { provide: getRepositoryToken(AssistanteMaternelle), useValue: {} }, + ], }).compile(); service = module.get(AuthService); @@ -15,4 +44,21 @@ describe('AuthService', () => { it('should be defined', () => { expect(service).toBeDefined(); }); + + it('returns 404-like error when verify token is missing', async () => { + await expect(service.verifyCreatePasswordToken('')).rejects.toThrow(NotFoundException); + }); + + it('returns valid=true when token exists and is not expired', async () => { + usersRepoMock.findOne.mockResolvedValue({ + id: 'u1', + password: null, + token_creation_mdp_expire_le: new Date(Date.now() + 60_000), + }); + + await expect(service.verifyCreatePasswordToken('tok-123')).resolves.toEqual({ + valid: true, + message: 'Token valide', + }); + }); }); From 29623f33b9fd8dfaba310e625177b961d3fdcc25 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Thu, 23 Apr 2026 11:58:10 +0200 Subject: [PATCH 09/11] =?UTF-8?q?feat(front):=20impl=C3=A9menter=20la=20pa?= =?UTF-8?q?ge=20create-password=20du=20ticket=20#118?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ajoute le flux frontend de création initiale du mot de passe via token email (route /create-password, vérification de token et soumission /auth/create-password), avec redirection login en succès et gestion neutre des liens invalides/expirés. Made-with: Cursor --- frontend/lib/config/app_router.dart | 6 + .../screens/auth/create_password_screen.dart | 244 ++++++++++++++++++ frontend/lib/screens/auth/login_screen.dart | 4 +- frontend/lib/services/api/api_config.dart | 2 + frontend/lib/services/auth_service.dart | 55 ++++ 5 files changed, 309 insertions(+), 2 deletions(-) create mode 100644 frontend/lib/screens/auth/create_password_screen.dart diff --git a/frontend/lib/config/app_router.dart b/frontend/lib/config/app_router.dart index 074262f..8db296c 100644 --- a/frontend/lib/config/app_router.dart +++ b/frontend/lib/config/app_router.dart @@ -18,6 +18,7 @@ import '../screens/auth/am_register_step1_screen.dart'; import '../screens/auth/am_register_step2_screen.dart'; import '../screens/auth/am_register_step3_screen.dart'; import '../screens/auth/am_register_step4_screen.dart'; +import '../screens/auth/create_password_screen.dart'; import '../screens/home/home_screen.dart'; import '../screens/administrateurs/admin_dashboardScreen.dart'; import '../screens/gestionnaire/gestionnaire_dashboard_screen.dart'; @@ -49,6 +50,11 @@ class AppRouter { path: '/register-choice', builder: (BuildContext context, GoRouterState state) => const RegisterChoiceScreen(), ), + GoRoute( + path: '/create-password', + builder: (BuildContext context, GoRouterState state) => + CreatePasswordScreen(token: state.uri.queryParameters['token']), + ), GoRoute( path: '/home', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), diff --git a/frontend/lib/screens/auth/create_password_screen.dart b/frontend/lib/screens/auth/create_password_screen.dart new file mode 100644 index 0000000..f9fe096 --- /dev/null +++ b/frontend/lib/screens/auth/create_password_screen.dart @@ -0,0 +1,244 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:google_fonts/google_fonts.dart'; + +import '../../services/auth_service.dart'; +import '../../widgets/image_button.dart'; + +class CreatePasswordScreen extends StatefulWidget { + final String? token; + + const CreatePasswordScreen({super.key, this.token}); + + @override + State createState() => _CreatePasswordScreenState(); +} + +class _CreatePasswordScreenState extends State { + final _formKey = GlobalKey(); + final _passwordCtrl = TextEditingController(); + final _confirmCtrl = TextEditingController(); + + bool _checkingToken = true; + bool _submitting = false; + bool _tokenValid = false; + String? _message; + + String get _token => (widget.token ?? '').trim(); + + @override + void initState() { + super.initState(); + _checkToken(); + } + + @override + void dispose() { + _passwordCtrl.dispose(); + _confirmCtrl.dispose(); + super.dispose(); + } + + bool _isStrongPassword(String v) { + if (v.length < 8) return false; + final hasUpper = RegExp(r'[A-Z]').hasMatch(v); + final hasDigit = RegExp(r'\d').hasMatch(v); + return hasUpper && hasDigit; + } + + String? _validatePassword(String? value) { + final v = value ?? ''; + if (v.isEmpty) return 'Veuillez saisir un mot de passe.'; + if (!_isStrongPassword(v)) { + return 'Minimum 8 caractères, avec au moins 1 majuscule et 1 chiffre.'; + } + return null; + } + + String? _validateConfirmation(String? value) { + final v = value ?? ''; + if (v.isEmpty) return 'Veuillez confirmer le mot de passe.'; + if (v != _passwordCtrl.text) return 'Les mots de passe ne correspondent pas.'; + return null; + } + + Future _checkToken() async { + if (_token.isEmpty) { + setState(() { + _checkingToken = false; + _tokenValid = false; + }); + return; + } + try { + final ok = await AuthService.verifyCreatePasswordToken(_token); + if (!mounted) return; + setState(() { + _checkingToken = false; + _tokenValid = ok; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _checkingToken = false; + _tokenValid = false; + _message = e.toString().replaceAll('Exception: ', ''); + }); + } + } + + Future _submit() async { + if (_submitting || !_tokenValid) return; + if (!(_formKey.currentState?.validate() ?? false)) return; + setState(() { + _submitting = true; + _message = null; + }); + try { + await AuthService.createPasswordWithToken( + token: _token, + password: _passwordCtrl.text, + passwordConfirmation: _confirmCtrl.text, + ); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Mot de passe créé avec succès. Vous pouvez vous connecter.', + style: GoogleFonts.merienda(), + ), + ), + ); + context.go('/login'); + } catch (e) { + if (!mounted) return; + setState(() { + _submitting = false; + _message = e.toString().replaceAll('Exception: ', ''); + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + decoration: const BoxDecoration( + image: DecorationImage( + image: AssetImage('assets/images/paper2.png'), + fit: BoxFit.cover, + repeat: ImageRepeat.repeat, + ), + ), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Card( + color: const Color(0xF4FFFFFF), + margin: const EdgeInsets.all(24), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Padding( + padding: const EdgeInsets.all(24), + child: _checkingToken + ? const Center(child: CircularProgressIndicator()) + : _tokenValid + ? _buildForm() + : _buildInvalidToken(), + ), + ), + ), + ), + ), + ); + } + + Widget _buildForm() { + return Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'Créer votre mot de passe', + style: GoogleFonts.merienda(fontSize: 28, fontWeight: FontWeight.w700), + textAlign: TextAlign.center, + ), + const SizedBox(height: 18), + TextFormField( + controller: _passwordCtrl, + obscureText: true, + validator: _validatePassword, + decoration: const InputDecoration( + labelText: 'Nouveau mot de passe', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 14), + TextFormField( + controller: _confirmCtrl, + obscureText: true, + validator: _validateConfirmation, + decoration: const InputDecoration( + labelText: 'Confirmer le mot de passe', + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 10), + Text( + 'Le mot de passe doit contenir au moins 8 caractères, dont 1 majuscule et 1 chiffre.', + style: GoogleFonts.merienda(fontSize: 12, color: Colors.black54), + ), + if (_message != null) ...[ + const SizedBox(height: 12), + Text( + _message!, + style: GoogleFonts.merienda(color: Colors.red.shade700), + ), + ], + const SizedBox(height: 16), + _submitting + ? const Center(child: CircularProgressIndicator()) + : ImageButton( + bg: 'assets/images/bg_green.png', + width: double.infinity, + height: 44, + text: 'Valider', + textColor: const Color(0xFF2D6A4F), + onPressed: _submit, + ), + ], + ), + ); + } + + Widget _buildInvalidToken() { + final msg = _message ?? 'Lien invalide ou expiré.'; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'Création du mot de passe', + style: GoogleFonts.merienda(fontSize: 28, fontWeight: FontWeight.w700), + textAlign: TextAlign.center, + ), + const SizedBox(height: 20), + Text( + msg, + style: GoogleFonts.merienda(fontSize: 16), + textAlign: TextAlign.center, + ), + const SizedBox(height: 20), + ImageButton( + bg: 'assets/images/bg_green.png', + width: double.infinity, + height: 44, + text: 'Retour à la connexion', + textColor: const Color(0xFF2D6A4F), + onPressed: () => context.go('/login'), + ), + ], + ); + } +} diff --git a/frontend/lib/screens/auth/login_screen.dart b/frontend/lib/screens/auth/login_screen.dart index 16ee6d9..4ad0b22 100644 --- a/frontend/lib/screens/auth/login_screen.dart +++ b/frontend/lib/screens/auth/login_screen.dart @@ -355,7 +355,7 @@ class _LoginPageState extends State { Center( child: TextButton( onPressed: () { - // TODO: Implémenter la logique de récupération de mot de passe + context.go('/create-password'); }, child: Text( 'Mot de passe oublié ?', @@ -618,7 +618,7 @@ class _LoginPageState extends State { ), const SizedBox(height: 12), TextButton( - onPressed: () {/* TODO */}, + onPressed: () => context.go('/create-password'), child: Text( 'Mot de passe oublié ?', style: GoogleFonts.merienda( diff --git a/frontend/lib/services/api/api_config.dart b/frontend/lib/services/api/api_config.dart index b3fe61d..34c88a2 100644 --- a/frontend/lib/services/api/api_config.dart +++ b/frontend/lib/services/api/api_config.dart @@ -44,6 +44,8 @@ class ApiConfig { static const String refreshToken = '/auth/refresh'; static const String authMe = '/auth/me'; static const String changePasswordRequired = '/auth/change-password-required'; + static const String verifyCreatePasswordToken = '/auth/verify-token'; + static const String createPassword = '/auth/create-password'; // Users endpoints static const String users = '/users'; diff --git a/frontend/lib/services/auth_service.dart b/frontend/lib/services/auth_service.dart index 629329b..321d2c4 100644 --- a/frontend/lib/services/auth_service.dart +++ b/frontend/lib/services/auth_service.dart @@ -131,6 +131,61 @@ class AuthService { } } + /// Vérifie qu'un token de création de mot de passe est encore valide. + /// Retourne `true` si l'API renvoie 200 ; `false` si 404. + static Future verifyCreatePasswordToken(String token) async { + final cleaned = token.trim(); + if (cleaned.isEmpty) return false; + try { + final uri = Uri.parse( + '${ApiConfig.baseUrl}${ApiConfig.verifyCreatePasswordToken}?token=${Uri.encodeQueryComponent(cleaned)}', + ); + final response = await http.get(uri, headers: ApiConfig.headers); + if (response.statusCode == 200) return true; + if (response.statusCode == 404) return false; + final decoded = _tryDecodeJsonMap(response.body); + throw Exception(_extractErrorMessage(decoded, response.statusCode)); + } on http.ClientException { + throw Exception( + 'Connexion à ${ApiConfig.baseUrl} impossible. Vérifiez votre réseau puis réessayez.', + ); + } + } + + /// Crée le mot de passe initial via token email. + static Future createPasswordWithToken({ + required String token, + required String password, + required String passwordConfirmation, + }) async { + final cleaned = token.trim(); + if (cleaned.isEmpty) { + throw Exception('Lien invalide ou expiré.'); + } + late final http.Response response; + try { + response = await http.post( + Uri.parse('${ApiConfig.baseUrl}${ApiConfig.createPassword}'), + headers: ApiConfig.headers, + body: jsonEncode({ + 'token': cleaned, + 'password': password, + 'password_confirmation': passwordConfirmation, + }), + ); + } on http.ClientException { + throw Exception( + 'Connexion à ${ApiConfig.baseUrl} impossible. Vérifiez votre réseau puis réessayez.', + ); + } + + if (response.statusCode == 200 || response.statusCode == 201) { + return; + } + final decoded = _tryDecodeJsonMap(response.body); + throw Exception(_extractErrorMessage(decoded, response.statusCode)); + } + /// Déconnexion de l'utilisateur static Future logout() async { await TokenService.clearAll(); From e887562a1c89b65c5d4e8b7775d0deb9e639bae1 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Thu, 23 Apr 2026 12:09:46 +0200 Subject: [PATCH 10/11] fix(front): activer path URL strategy pour create-password (#118) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Active usePathUrlStrategy pour que les deep links web /create-password?token=... soient correctement résolus sans redirection implicite vers #login, et déclare flutter_web_plugins côté front. Made-with: Cursor --- frontend/lib/main.dart | 3 +++ frontend/pubspec.lock | 2 +- frontend/pubspec.yaml | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart index 4478ce1..2a60d50 100644 --- a/frontend/lib/main.dart +++ b/frontend/lib/main.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter_web_plugins/url_strategy.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; // Import pour la localisation // import 'package:provider/provider.dart'; // Supprimer Provider @@ -7,6 +8,8 @@ import 'config/app_router.dart'; // <-- Importer le bon routeur (GoRouter) // import 'theme/theme_provider.dart'; // Supprimer ThemeProvider void main() { + // Permet les URLs web propres (/create-password?token=...) sans hash. + usePathUrlStrategy(); runApp(const MyApp()); // Exécution simple } diff --git a/frontend/pubspec.lock b/frontend/pubspec.lock index 752a6b7..09ded02 100644 --- a/frontend/pubspec.lock +++ b/frontend/pubspec.lock @@ -177,7 +177,7 @@ packages: source: sdk version: "0.0.0" flutter_web_plugins: - dependency: transitive + dependency: "direct main" description: flutter source: sdk version: "0.0.0" diff --git a/frontend/pubspec.yaml b/frontend/pubspec.yaml index d9f9b57..0f2e0aa 100644 --- a/frontend/pubspec.yaml +++ b/frontend/pubspec.yaml @@ -9,6 +9,8 @@ environment: dependencies: flutter: sdk: flutter + flutter_web_plugins: + sdk: flutter flutter_localizations: sdk: flutter provider: ^6.1.1 From e2188fbc87d9b69f5d1e82077fcf8feccea7a637 Mon Sep 17 00:00:00 2001 From: Julien Martin Date: Thu, 23 Apr 2026 16:48:13 +0200 Subject: [PATCH 11/11] =?UTF-8?q?docs(#127):=20liste=20tickets=20+=20issue?= =?UTF-8?q?=20Gitea=20mot=20de=20passe=20oubli=C3=A9;=20chmod=20create-git?= =?UTF-8?q?ea-issue.sh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Made-with: Cursor --- docs/23_LISTE-TICKETS.md | 44 ++++++++++++++++++++++++++++++----- scripts/create-gitea-issue.sh | 0 2 files changed, 38 insertions(+), 6 deletions(-) mode change 100644 => 100755 scripts/create-gitea-issue.sh diff --git a/docs/23_LISTE-TICKETS.md b/docs/23_LISTE-TICKETS.md index a0996d0..8a4118f 100644 --- a/docs/23_LISTE-TICKETS.md +++ b/docs/23_LISTE-TICKETS.md @@ -1,15 +1,15 @@ # 🎫 Liste Complète des Tickets - Projet P'titsPas -**Version** : 1.7 -**Date** : 25 Mars 2026 +**Version** : 1.9 +**Date** : 23 Avril 2026 **Auteur** : Équipe PtitsPas -**Estimation totale** : ~208h +**Estimation totale** : ~220h --- ## 🔗 Liste des tickets Gitea -**Les numéros de section dans ce document = numéros d’issues Gitea.** Ticket #14 dans le doc = issue Gitea #14, etc. Source : dépôt `jmartin/petitspas` (état au 25 mars 2026 ; #106, #107, #109, #119 fermés via API). +**Les numéros de section dans ce document = numéros d’issues Gitea** (ticket #14 = issue Gitea #14, etc.). Le **numéro d’une nouvelle issue** n’est pas choisi dans ce fichier : il est **attribué par Gitea** (champ `number` dans la réponse JSON du `POST` création d’issue, ou affiché dans l’UI après création). Procédure : [**26_GITEA-API.md**](./26_GITEA-API.md) (§ 2 authentification, § 3.2 issues). Source dépôt : `jmartin/petitspas` (état au 25 mars 2026 ; #106, #107, #109, #119 fermés via API). | Gitea # | Titre (dépôt) | Statut | |--------|----------------|--------| @@ -102,6 +102,7 @@ | 117 | Évolution du cahier des charges | Ouvert | | 119 | Endpoint unifié GET /dossiers/:numeroDossier (AM ou famille) | ✅ Fermé | | 120 | [Full-stack] Inscription AM — photo, API et UX alignés sur les parents (suite #91) | ✅ Fermé | +| 127 | [Full-stack] Mot de passe oublié — flux complet (demande, e-mail, réinitialisation) | Ouvert | *Gitea #1 et #2 = anciens tickets de test (fermés). Liste complète : https://git.ptits-pas.fr/jmartin/petitspas/issues* @@ -118,11 +119,11 @@ | **P0** | 7 tickets | ~5h | Amendements BDD (BLOQUANT) | | **P1** | 7 tickets | ~22h | Configuration système (BLOQUANT) | | **P2** | 18 tickets | ~50h | Backend métier | -| **P3** | 22 tickets | ~71h | Frontend | +| **P3** | 23 tickets | ~83h | Frontend | | **P4** | 4 tickets | ~24h | Tests & Documentation | | **CRITIQUES** | 6 tickets | ~13h | Upload, Logs, Infra, CDC | | **JURIDIQUE** | 1 ticket | ~8h | Rédaction CGU/Privacy | -| **TOTAL** | **65 tickets** | **~184h** | | +| **TOTAL** | **66 tickets** | **~220h** | | --- @@ -913,6 +914,37 @@ Créer l'écran de création de mot de passe (lien reçu par email). --- +### Ticket #127 : [Full-stack] Mot de passe oublié — flux complet (demande, e-mail, réinitialisation) +**Issue Gitea** : https://git.ptits-pas.fr/jmartin/petitspas/issues/127 (créée le 2026-04-23 via API, voir [26_GITEA-API.md](./26_GITEA-API.md)). + +**Estimation** : 12h +**Labels** : `full-stack`, `p2`, `p3`, `auth`, `security`, `cdc` + +**Description** : +Couvrir **tout** le parcours « Mot de passe oublié » : distinct du flux **création** de mot de passe post-inscription (#24 / #43 / `GET verify-token` + `POST create-password`). Aujourd’hui, le lien sur l’écran de connexion (`frontend/lib/screens/auth/login_screen.dart`) envoie vers `/create-password`, ce qui est incorrect pour un utilisateur déjà enregistré qui a oublié son mot de passe. + +**Tâches — Backend** : +- [ ] Analyse : réutiliser `password_reset_token` / `password_reset_expires` (et config type `password_reset_token_expiry_days`) **ou** introduire des champs / flux séparés si le même couple token/expiry sert encore à l’inscription — documenter le choix +- [ ] `POST` (ex.) `/api/v1/auth/forgot-password` : body `{ "email" }` ; toujours réponse **neutre** (ex. 204 ou message identique que l’e-mail existe ou non) pour limiter l’énumération +- [ ] Génération token, persistance, expiration ; invalidation après usage ou rotation +- [ ] Envoi e-mail via MailService (template Handlebars dédié « réinitialisation ») +- [ ] `POST` (ex.) `/api/v1/auth/reset-password` : `{ "token", "password", "password_confirmation" }` — règles de complexité alignées sur `create-password` / changement MDP +- [ ] Rate limiting / throttling par IP et/ou par e-mail +- [ ] Tests unitaires / intégration ; entrées OpenAPI + +**Tâches — Frontend** : +- [ ] Écran ou bottom sheet « Saisir votre e-mail » + appel forgot-password + message générique de confirmation +- [ ] Route dédiée « nouveau mot de passe » (ex. `/reset-password?token=`) **distincte** de `/create-password` ; vérification token si endpoint dédié +- [ ] Corriger le `onPressed` du lien « Mot de passe oublié ? » sur le login : ne plus naviguer vers `/create-password` pour ce cas +- [ ] Gestion erreurs (token expiré / invalide) avec libellés neutres + +**Tâches — transverses** : +- [ ] Mise à jour doc CDC / évolutions si besoin ; E2E ou scénario de test manuel référencé + +**Synchronisation doc** : pour toute **nouvelle** issue à l’avenir, le numéro vient de la réponse Gitea (§ 3.2 [26_GITEA-API.md](./26_GITEA-API.md)) ou du script `bash ./scripts/create-gitea-issue.sh "Titre" "Corps"`. + +--- + ### Ticket #44 : [Frontend] Dashboard Gestionnaire - Structure ✅ **Estimation** : 2h **Labels** : `frontend`, `p3`, `gestionnaire` diff --git a/scripts/create-gitea-issue.sh b/scripts/create-gitea-issue.sh old mode 100644 new mode 100755