import type { TransactionClientContract } from '@adonisjs/lucid/types/database' import Client from '#models/client' export type ResolveClientInput = { clientId?: string | null clientName: string clientEmail?: string | null } export type ResolveClientResult = | { client: Client; created: boolean } | { errorCode: 'client_email_required' } /** * Résolution client à la création de facture / validation d'import OCR. * * Priorité (mêmes règles côté API que côté MSW) : * 1. `clientId` fourni + existant dans l'org → utilise tel quel. * 2. Match par nom (case-insensitive) sur les clients de l'org. * 3. Création à la volée → `clientEmail` REQUIS, sinon * `{ errorCode: 'client_email_required' }`. * * Le contrôleur appelant transforme l'erreur en HTTP 422 avec le code stable. */ export async function resolveClient( organizationId: string, fields: ResolveClientInput, trx: TransactionClientContract ): Promise { if (fields.clientId) { const c = await Client.query({ client: trx }) .where('organization_id', organizationId) .where('id', fields.clientId) .first() if (c) return { client: c, created: false } } const matched = await Client.query({ client: trx }) .where('organization_id', organizationId) .whereILike('name', fields.clientName) .first() if (matched) return { client: matched, created: false } if (!fields.clientEmail) { return { errorCode: 'client_email_required' } } const created = await Client.create( { organizationId, name: fields.clientName, email: fields.clientEmail, phone: null, address: null, siret: null, notes: null, }, { client: trx } ) return { client: created, created: true } }