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).
78 lines
2.4 KiB
TypeScript
78 lines
2.4 KiB
TypeScript
import { type SchemaRules } from '@adonisjs/lucid/types/schema_generator'
|
|
|
|
/**
|
|
* Override de types pour les colonnes que Lucid n'arrive pas à inférer
|
|
* depuis l'introspection PG (ex. ENUMs natifs et jsonb → tapés `any`).
|
|
*/
|
|
export default {
|
|
tables: {
|
|
plan_steps: {
|
|
columns: {
|
|
tone: {
|
|
tsType: "'amical' | 'courtois' | 'ferme' | 'mise_en_demeure'",
|
|
},
|
|
},
|
|
},
|
|
invoices: {
|
|
columns: {
|
|
status: {
|
|
tsType:
|
|
"'pending' | 'awaiting_user_confirmation' | 'in_relance' | 'paid' | 'litigation' | 'cancelled'",
|
|
},
|
|
},
|
|
},
|
|
activity_events: {
|
|
columns: {
|
|
kind: {
|
|
tsType:
|
|
"'relance_sent' | 'invoice_paid' | 'invoice_imported' | 'warning_drafted'",
|
|
},
|
|
meta: {
|
|
tsType:
|
|
"{ invoiceId?: string; clientId?: string; planStepOrder?: number; [k: string]: unknown }",
|
|
},
|
|
},
|
|
},
|
|
relance_tasks: {
|
|
columns: {
|
|
status: {
|
|
tsType: "'scheduled' | 'sent' | 'cancelled' | 'failed'",
|
|
},
|
|
},
|
|
},
|
|
checkin_tasks: {
|
|
columns: {
|
|
status: {
|
|
tsType: "'scheduled' | 'sent' | 'answered' | 'expired'",
|
|
},
|
|
answer: {
|
|
tsType: "'paid' | 'still_pending' | null",
|
|
},
|
|
},
|
|
},
|
|
import_drafts: {
|
|
columns: {
|
|
status: {
|
|
tsType: "'pending' | 'validated' | 'skipped'",
|
|
},
|
|
// jsonb des champs extraits par l'OCR. La forme est garantie par
|
|
// le validator Vine côté entrée et par le service côté seed.
|
|
extracted: {
|
|
tsType:
|
|
"{ clientId: string | null; clientName: string; clientEmail: string | null; numero: string; amountTtcCents: number; issueDate: string; dueDate: string; planId: string | null }",
|
|
},
|
|
edited: {
|
|
tsType:
|
|
"{ clientId: string | null; clientName: string; clientEmail: string | null; numero: string; amountTtcCents: number; issueDate: string; dueDate: string; planId: string | null }",
|
|
},
|
|
// Confiance par champ — 0..1. Partial parce que l'OCR n'a pas
|
|
// toujours toutes les confiances.
|
|
confidence: {
|
|
tsType:
|
|
"Partial<{ clientId: number; clientName: number; clientEmail: number; numero: number; amountTtcCents: number; issueDate: number; dueDate: number; planId: number }>",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
} satisfies SchemaRules
|