import { formatDocNo } from '@sims/domain' import type { DB } from './db' export const TYPE_PREFIX: Record = { QUOTATION: 'QT', PROFORMA: 'PI', INVOICE: 'INV', RECEIPT: 'RCT', CREDIT_NOTE: 'CN', } export function nextDocNo(db: DB, docType: string, fy: string): string { const prefix = `${TYPE_PREFIX[docType]}/${fy.slice(2)}` db.prepare( `INSERT INTO doc_series (doc_type, fy, prefix, next_seq) VALUES (?, ?, ?, 1) ON CONFLICT (doc_type, fy) DO NOTHING`, ).run(docType, fy, prefix) const row = db.prepare(`SELECT prefix, next_seq FROM doc_series WHERE doc_type=? AND fy=?`) .get(docType, fy) as { prefix: string; next_seq: number } db.prepare(`UPDATE doc_series SET next_seq = next_seq + 1 WHERE doc_type=? AND fy=?`).run(docType, fy) return formatDocNo(row.prefix, row.next_seq, 4) } /** Mid-FY cutover (spec ยง4): continue after the last APEX-issued number. */ export function seedSeries(db: DB, docType: string, fy: string, lastUsedSeq: number): void { const prefix = `${TYPE_PREFIX[docType]}/${fy.slice(2)}` db.prepare( `INSERT INTO doc_series (doc_type, fy, prefix, next_seq) VALUES (?, ?, ?, ?) ON CONFLICT (doc_type, fy) DO UPDATE SET next_seq = excluded.next_seq`, ).run(docType, fy, prefix, lastUsedSeq + 1) }