fix: use only actual entries as source of truth for registry numbers
The previous fix still used MAX(actualMax, counterVal) which meant a stale counter (from entries deleted before the fix was deployed) would override the actual entry count. Changed to use ONLY actualMax + 1. The RegistrySequence counter is now just a cache that gets synced — it never overrides the actual entries count. Also added /api/registratura/debug-sequences endpoint: - GET: shows all counters vs actual entry max (for diagnostics) - POST: resets all counters to match actual entries (one-time fix) After deploy, call POST /api/registratura/debug-sequences to reset the stale counters, then delete the BTG-2026-OUT-00004 entry and recreate it — it will get 00001. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -261,19 +261,14 @@ export async function allocateSequenceNumber(
|
||||
`;
|
||||
const actualMax = maxRows[0]?.maxSeq ?? 0;
|
||||
|
||||
// 2. Also read the current counter as a safety net (should never be
|
||||
// higher than actualMax if everything is consistent, but we take
|
||||
// the MAX of both just in case).
|
||||
const counterRows = await tx.$queryRaw<Array<{ lastSeq: number }>>`
|
||||
SELECT "lastSeq" FROM "RegistrySequence"
|
||||
WHERE company = ${companyPrefix} AND year = ${yr} AND type = ${typeCode}
|
||||
`;
|
||||
const counterVal = counterRows[0]?.lastSeq ?? 0;
|
||||
// 2. Next sequence = actual entries max + 1.
|
||||
// Entries in KeyValueStore are the SOLE source of truth.
|
||||
// The RegistrySequence counter is only a cache — if it drifted
|
||||
// (e.g. entries were deleted before the recalculate fix), we
|
||||
// ignore it entirely and reset it to match reality.
|
||||
const nextSeq = actualMax + 1;
|
||||
|
||||
// 3. Next sequence = max(actual entries, counter) + 1
|
||||
const nextSeq = Math.max(actualMax, counterVal) + 1;
|
||||
|
||||
// 4. Upsert the counter to the new value
|
||||
// 3. Upsert the counter to the new value (keep it in sync)
|
||||
await tx.$executeRaw`
|
||||
INSERT INTO "RegistrySequence" (id, company, year, type, "lastSeq", "createdAt", "updatedAt")
|
||||
VALUES (gen_random_uuid()::text, ${companyPrefix}, ${yr}, ${typeCode}, ${nextSeq}, NOW(), NOW())
|
||||
|
||||
Reference in New Issue
Block a user