fix: registry number re-allocation on company change + extreme PDF large file support

- Registratura: re-allocate number when company/direction changes on update,
  recalculate old company's sequence counter from actual entries
- Extreme PDF: stream body to temp file instead of req.formData() to support large files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
AI Assistant
2026-03-11 14:05:13 +02:00
parent ed504bd1de
commit 1c51236c31
3 changed files with 118 additions and 13 deletions
@@ -252,6 +252,51 @@ export async function allocateSequenceNumber(
};
}
/**
* Recalculate a company's sequence counter to match actual entries in the DB.
* Called when an entry is reassigned away from a company, so the counter
* reflects the real max sequence instead of staying artificially high.
*/
export async function recalculateSequence(
company: CompanyId,
direction: RegistryDirection,
year?: number,
): Promise<void> {
const { prisma } = await import("@/core/storage/prisma");
const companyPrefix = REGISTRY_COMPANY_PREFIX[company];
const typeCode = DIRECTION_TYPE_CODE[direction];
const yr = year ?? new Date().getFullYear();
// Find the actual max sequence from entries in KeyValueStore
const pattern = `${companyPrefix}-${yr}-${typeCode}-%`;
const rows = await prisma.$queryRaw<Array<{ maxSeq: number | null }>>`
SELECT MAX(
CAST(SUBSTRING(value::text FROM ${`${companyPrefix}-${yr}-${typeCode}-(\\d{5})`}) AS INTEGER)
) AS "maxSeq"
FROM "KeyValueStore"
WHERE namespace = 'registratura'
AND key LIKE 'entry:%'
AND value::text LIKE ${`%"number":"${pattern}"%`}
`;
const actualMax = rows[0]?.maxSeq ?? 0;
// Reset the counter to the actual max (or delete if 0)
if (actualMax === 0) {
await prisma.$executeRaw`
DELETE FROM "RegistrySequence"
WHERE company = ${companyPrefix} AND year = ${yr} AND type = ${typeCode}
`;
} else {
await prisma.$executeRaw`
UPDATE "RegistrySequence"
SET "lastSeq" = ${actualMax}, "updatedAt" = NOW()
WHERE company = ${companyPrefix} AND year = ${yr} AND type = ${typeCode}
`;
}
}
// ── Number format detection + parsing ──
export interface ParsedRegistryNumber {