Migrations :
- relance_tasks (uuid id, organization_id FK CASCADE [scope direct sans join], invoice_id FK CASCADE, plan_step_id FK RESTRICT, send_at, status ENUM scheduled/sent/cancelled/failed, sent_at, queue_job_id pour cancel via BullMQ.remove). Indexes (org,status), (invoice_id), (send_at).
- checkin_tasks (uuid id, org_id, invoice_id, send_at, token_hash unique [SHA-256 du HMAC, TTL 24h], status ENUM scheduled/sent/answered/expired, answer 'paid'|'still_pending'). Pas encore branché — flow check-in arrivera dans un commit séparé (cf. backend.md §13.3).
Schema rules : status enums + answer typés.
Models RelanceTask + CheckinTask avec belongsTo Invoice / PlanStep.
Service relance_scheduler.ts :
- scheduleRelancesForInvoice(invoice) : pour chaque step du plan, calcule sendAt = dueDate + offsetDays. Si sendAt < now (facture importée en retard), on programme à `now + 1min` plutôt que skip — l'utilisateur "rattrape" une dette de relance, l'envoi immédiat est cohérent. Crée la RelanceTask + enqueue BullMQ avec delay, retry 5x exponential, jobId = `relance:<taskId>` pour idempotency. Cancelle les tasks scheduled existantes avant de re-programmer (gestion changement de plan).
- cancelFutureRelances(invoiceId, trx) : appelé par mark-paid pour stopper la chaîne.
Service queue.ts :
- getQueue(name) singleton lazy par queue
- registerWorker(name, handler) avec concurrency 5, log failed/completed
- shutdownQueue() pour le terminating hook Adonis
start/queue.ts (preload) : registerWorker('relances', sendRelanceJob) seulement quand `app.getEnvironment() === 'web'` (pas en tests/REPL — pas de connexion Redis pendant Japa).
Job send_relance_job.ts :
- Idempotent : si task.status !== 'scheduled', no-op
- Hook critique : si invoice paid/cancelled entre-temps, task.status = cancelled
- Mise en demeure (step.requiresManualValidation) : on n'envoie PAS, on log un activity_event 'warning_drafted' (cf. CLAUDE.md → Principes : validation manuelle obligatoire)
- Sinon : sendRelanceEmail + task.status=sent + invoice.rubisEarned+1 + organizations.rubis_count+1 + activity_event 'relance_sent'. Si invoice.status='pending', passe en 'in_relance' (sortie de l'état silencieux).
Service mail_dispatcher.ts : sendRelanceEmail interpole step.subject/body via mini moteur Mustache-like (renderTemplate, services/template.ts) avec {{client.name}}/{{numero}}/{{amount}}/{{dueDate}}/{{signature}}, puis @adonisjs/mail.use(MAIL_DRIVER) → Mailpit en dev, Resend en prod. Texte brut V1.
Triggers branchés :
- InvoicesController.store : si planId, scheduleRelancesForInvoice après création
- ImportBatchesController.validateDraft : pareil
- InvoicesController.markPaid : cancelFutureRelances dans la même tx que le paiement
#jobs/* ajouté aux imports package.json. Adonisrc preload start/queue.ts.
Bruno : doc 05-Invoices/04 Create maj avec instructions pour tester l'envoi immédiat (dueDate dans le passé → relance à now+1min → email visible dans Mailpit http://localhost:8025).
65 lines
1.6 KiB
Plaintext
65 lines
1.6 KiB
Plaintext
meta {
|
|
name: 04 Create
|
|
type: http
|
|
seq: 4
|
|
}
|
|
|
|
post {
|
|
url: {{baseUrl}}/api/v1/invoices
|
|
body: json
|
|
auth: inherit
|
|
}
|
|
|
|
body:json {
|
|
{
|
|
"clientId": "{{clientId}}",
|
|
"clientName": "Boulangerie Martin SARL",
|
|
"numero": "F-2026-0042",
|
|
"amountTtcCents": 124000,
|
|
"issueDate": "2026-04-20T09:00:00.000Z",
|
|
"dueDate": "2026-05-20T09:00:00.000Z"
|
|
}
|
|
|
|
}
|
|
|
|
script:post-response {
|
|
if (res.getStatus() === 201) {
|
|
bru.setEnvVar("invoiceId", res.getBody().data.id);
|
|
}
|
|
}
|
|
|
|
tests {
|
|
test("201 Created", function () {
|
|
expect(res.getStatus()).to.equal(201);
|
|
});
|
|
test("invoiceId saved", function () {
|
|
expect(bru.getEnvVar("invoiceId")).to.not.be.empty;
|
|
});
|
|
test("rubisEarned = 1 (bonus saisie)", function () {
|
|
expect(res.getBody().data.rubisEarned).to.equal(1);
|
|
});
|
|
}
|
|
|
|
docs {
|
|
POST /api/v1/invoices
|
|
|
|
Saisie manuelle. Résolution client en 3 étapes :
|
|
1. `clientId` fourni → utilise tel quel
|
|
2. sinon match par nom (case-insensitive) sur les clients existants
|
|
3. sinon création à la volée — `clientEmail` REQUIS sinon 422
|
|
`client_email_required`
|
|
|
|
Bonus +1 rubis à la création (gamification).
|
|
|
|
Si `planId` est fourni : programme automatiquement les RelanceTasks
|
|
BullMQ pour chaque step du plan (sendAt = dueDate + offsetDays).
|
|
Les jobs scheduled sont visibles via :
|
|
`docker exec rubis-redis redis-cli zrange bull:relances:delayed 0 -1`
|
|
|
|
Pour tester l'envoi immédiat : passer une `dueDate` dans le passé →
|
|
la première RelanceTask est programmée à `now + 1min`. Mailpit
|
|
http://localhost:8025 affichera le mail capté ~1min plus tard.
|
|
|
|
Capture `invoiceId` dans l'env pour les requêtes suivantes.
|
|
}
|