Migration invoices : uuid id, organization_id FK CASCADE, client_id FK RESTRICT (on n'efface pas les factures si l'utilisateur supprime un client par erreur — audit/comptable), plan_id FK SET NULL, numero, amount_ttc_cents (int, jamais float), issue_date, due_date, status ENUM PG natif (pending/awaiting_user_confirmation/in_relance/paid/litigation/cancelled), pdf_storage_key, notes, rubis_earned, paid_at. Indexes (org,status), (org,client_id), (org,due_date), unique (org,numero). Modèles : Invoice avec belongsTo Organization/Client/Plan. Client et Plan étendus avec hasMany Invoice maintenant que la table existe. Endpoints : - GET /invoices : filtres status/q/clientId/page, tri actionnable (awaiting_user_confirmation puis in_relance puis pending puis litigation puis paid puis cancelled), pagination simple 50/page (cursor-based en V2). - GET /invoices/counts : compteurs par statut pour les chips dashboard, requête agrégée groupBy. - GET /invoices/:id : détail enrichi avec client + plan préchargés + timeline composée par buildTimeline() (étapes du plan calées sur due_date, états past/current/future). - POST /invoices : saisie manuelle. Résolution client en 3 étapes (clientId → match par nom → création à la volée avec email REQUIS, sinon 422 client_email_required). Bonus +1 rubis à la création. - POST /invoices/:id/mark-paid : status=paid + paid_at + bonus +1 rubis (sur invoice + sur organization.rubis_count). Idempotent. L'ordre des routes /invoices/counts AVANT /invoices/:id est critique sinon `:id` matche "counts". Branche les vraies stats : - ClientStats : agrégation PG une seule requête (count, count actives, count en retard, paid_count, sum paid_cents, sum pending_cents, last_activity) avec FILTER clauses et casting enum::text. Plus de TODO/zéros. - PlansController : usageCount calculé pareil (factures actives référençant le plan). Skip pour l'instant (ImportBatch domain à venir) : POST /invoices/upload, GET /invoices/import-batch/*, validate/skip drafts.
150 lines
4.5 KiB
TypeScript
150 lines
4.5 KiB
TypeScript
import Plan from '#models/plan'
|
|
import PlanStep from '#models/plan_step'
|
|
import PlanTransformer from '#transformers/plan_transformer'
|
|
import { updatePlanValidator } from '#validators/plan'
|
|
import type { HttpContext } from '@adonisjs/core/http'
|
|
import { Exception } from '@adonisjs/core/exceptions'
|
|
import db from '@adonisjs/lucid/services/db'
|
|
|
|
const ACTIVE_INVOICE_STATUSES = "('pending','in_relance','awaiting_user_confirmation')"
|
|
|
|
function requireOrgId(auth: HttpContext['auth']): string {
|
|
const user = auth.getUserOrFail()
|
|
if (!user.organizationId) {
|
|
throw new Exception('Aucune organisation rattachée', { status: 404, code: 'not_found' })
|
|
}
|
|
return user.organizationId
|
|
}
|
|
|
|
function serializePlan(p: Plan) {
|
|
return new PlanTransformer(p).toObject()
|
|
}
|
|
|
|
/**
|
|
* Compte combien de factures actives (non payées, non annulées) référencent
|
|
* chaque plan d'une org. Utilisé pour enrichir la liste avec un badge "X
|
|
* factures utilisent ce plan" — utile avant édition pour signaler l'impact.
|
|
*/
|
|
async function bulkComputePlanUsage(
|
|
organizationId: string,
|
|
planIds: string[]
|
|
): Promise<Map<string, number>> {
|
|
const map = new Map<string, number>()
|
|
for (const id of planIds) map.set(id, 0)
|
|
|
|
if (planIds.length === 0) return map
|
|
|
|
const rows = await db
|
|
.from('invoices')
|
|
.where('organization_id', organizationId)
|
|
.whereIn('plan_id', planIds)
|
|
.whereRaw(`status::text in ${ACTIVE_INVOICE_STATUSES}`)
|
|
.select('plan_id')
|
|
.count('* as count')
|
|
.groupBy('plan_id')
|
|
|
|
for (const r of rows) {
|
|
map.set(r.plan_id, Number(r.count))
|
|
}
|
|
return map
|
|
}
|
|
|
|
export default class PlansController {
|
|
/**
|
|
* GET /plans — liste enrichie avec compteurs d'usage.
|
|
*/
|
|
async index({ auth, response }: HttpContext) {
|
|
const organizationId = requireOrgId(auth)
|
|
|
|
const plans = await Plan.query()
|
|
.where('organization_id', organizationId)
|
|
.preload('steps')
|
|
.orderBy('is_default', 'desc')
|
|
.orderBy('name', 'asc')
|
|
|
|
const usage = await bulkComputePlanUsage(
|
|
organizationId,
|
|
plans.map((p) => p.id)
|
|
)
|
|
|
|
const data = plans.map((p) => ({
|
|
...serializePlan(p),
|
|
usageCount: usage.get(p.id) ?? 0,
|
|
}))
|
|
|
|
return response.json({ data })
|
|
}
|
|
|
|
/**
|
|
* GET /plans/:slug — détail.
|
|
* Le SPA lookup par slug pour les plans pré-fournis (URL stable et
|
|
* lisible : /parametres/plans/standard-30j).
|
|
*/
|
|
async show({ auth, params, response }: HttpContext) {
|
|
const organizationId = requireOrgId(auth)
|
|
|
|
const plan = await Plan.query()
|
|
.where('organization_id', organizationId)
|
|
.where('slug', params.slug)
|
|
.preload('steps')
|
|
.first()
|
|
|
|
if (!plan) {
|
|
throw new Exception('Plan introuvable', { status: 404, code: 'not_found' })
|
|
}
|
|
|
|
const usage = await bulkComputePlanUsage(organizationId, [plan.id])
|
|
return response.json({
|
|
data: { ...serializePlan(plan), usageCount: usage.get(plan.id) ?? 0 },
|
|
})
|
|
}
|
|
|
|
/**
|
|
* PATCH /plans/:slug — édite nom, description et/ou recompose les étapes.
|
|
*
|
|
* Recomposition des steps : on ne fait pas de diff fin (id par id), on
|
|
* remplace tout le set en transaction. Plus simple, plus prévisible, et
|
|
* idiomatique côté UX (l'utilisateur a édité son plan dans son ensemble).
|
|
*/
|
|
async update({ auth, params, request, response }: HttpContext) {
|
|
const organizationId = requireOrgId(auth)
|
|
const payload = await request.validateUsing(updatePlanValidator)
|
|
|
|
const plan = await Plan.query()
|
|
.where('organization_id', organizationId)
|
|
.where('slug', params.slug)
|
|
.first()
|
|
|
|
if (!plan) {
|
|
throw new Exception('Plan introuvable', { status: 404, code: 'not_found' })
|
|
}
|
|
|
|
await db.transaction(async (trx) => {
|
|
plan.useTransaction(trx)
|
|
if (payload.name !== undefined) plan.name = payload.name
|
|
if (payload.description !== undefined) plan.description = payload.description
|
|
await plan.save()
|
|
|
|
if (payload.steps !== undefined) {
|
|
// Remplace tout le set
|
|
await PlanStep.query({ client: trx }).where('plan_id', plan.id).delete()
|
|
await PlanStep.createMany(
|
|
payload.steps.map((s) => ({
|
|
planId: plan.id,
|
|
order: s.order,
|
|
offsetDays: s.offsetDays,
|
|
tone: s.tone,
|
|
subject: s.subject,
|
|
body: s.body,
|
|
requiresManualValidation: s.requiresManualValidation,
|
|
})),
|
|
{ client: trx }
|
|
)
|
|
}
|
|
})
|
|
|
|
await plan.load('steps')
|
|
return response.json({ data: serializePlan(plan) })
|
|
}
|
|
}
|