feat(cf-order): wire session userId + surface DB-only cols in Prisma
Follow-up to the 2026-05-20 schema-drift ALTER. Now that the DB
accepts the create() call, also do the cleanup:
1. PRISMA SCHEMA — added the four DB-only columns that were
previously raw-SQL only. CfExtract now declares:
userId String? // Authentik sub of orderer
type String? @default("epay") // 'epay' | 'admin'
pdfData Bytes? // legacy inline PDF
adminOrderedBy String? // ops who placed for someone
Plus two new indices: @@index([userId]) and the composite
@@index([userId, nrCadastral]) so per-user "my orders" lookups
don't scan. Prisma client regenerated; type-check clean.
2. SESSION → USER ID PROPAGATION — /api/ancpi/order now reads the
NextAuth session at request time and stamps the userId onto each
parcel before enqueue:
const session = await getAuthSession();
const userId = session?.user.id ?? session?.user.email;
const stampedParcels = parcels.map(p => ({ ...p, userId: p.userId ?? userId }));
Body-supplied userId still wins (admin/cron paths can override).
3. ENQUEUEORDER PATH — CfExtractCreateInput gained an optional
userId field. epay-queue.ts's tx.cfExtract.create({}) now sets:
userId: input.userId, // (undefined → NULL, allowed post-patch)
type: "epay", // explicit; DB also has default but
// setting it makes the column visible
// in Prisma RETURNING reads.
After this commit, new orders carry the orderer's identity. Existing
NULL-userId rows from before this fix stay as-is (DB allows NULL).
Future RLS work on architots_postgres (if it survives Faza H) can
key off this column.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
+79
-69
@@ -23,23 +23,23 @@ model KeyValueStore {
|
|||||||
|
|
||||||
model GisSyncRule {
|
model GisSyncRule {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
siruta String? /// Set = UAT-specific rule
|
siruta String? /// Set = UAT-specific rule
|
||||||
county String? /// Set = county-wide default rule
|
county String? /// Set = county-wide default rule
|
||||||
frequency String /// "3x-daily"|"daily"|"weekly"|"monthly"|"manual"
|
frequency String /// "3x-daily"|"daily"|"weekly"|"monthly"|"manual"
|
||||||
syncTerenuri Boolean @default(true)
|
syncTerenuri Boolean @default(true)
|
||||||
syncCladiri Boolean @default(true)
|
syncCladiri Boolean @default(true)
|
||||||
syncNoGeom Boolean @default(false)
|
syncNoGeom Boolean @default(false)
|
||||||
syncEnrich Boolean @default(false)
|
syncEnrich Boolean @default(false)
|
||||||
priority Int @default(5) /// 1=highest, 10=lowest
|
priority Int @default(5) /// 1=highest, 10=lowest
|
||||||
enabled Boolean @default(true)
|
enabled Boolean @default(true)
|
||||||
allowedHoursStart Int? /// null = no restriction, e.g. 1 for 01:00
|
allowedHoursStart Int? /// null = no restriction, e.g. 1 for 01:00
|
||||||
allowedHoursEnd Int? /// e.g. 5 for 05:00
|
allowedHoursEnd Int? /// e.g. 5 for 05:00
|
||||||
allowedDays String? /// e.g. "1,2,3,4,5" for weekdays, null = all days
|
allowedDays String? /// e.g. "1,2,3,4,5" for weekdays, null = all days
|
||||||
lastSyncAt DateTime?
|
lastSyncAt DateTime?
|
||||||
lastSyncStatus String? /// "done"|"error"
|
lastSyncStatus String? /// "done"|"error"
|
||||||
lastSyncError String?
|
lastSyncError String?
|
||||||
nextDueAt DateTime?
|
nextDueAt DateTime?
|
||||||
label String? /// Human-readable note
|
label String? /// Human-readable note
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@ -52,25 +52,25 @@ model GisSyncRule {
|
|||||||
// ─── GIS: eTerra ParcelSync ────────────────────────────────────────
|
// ─── GIS: eTerra ParcelSync ────────────────────────────────────────
|
||||||
|
|
||||||
model GisFeature {
|
model GisFeature {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
layerId String // e.g. TERENURI_ACTIVE, CLADIRI_ACTIVE
|
layerId String // e.g. TERENURI_ACTIVE, CLADIRI_ACTIVE
|
||||||
siruta String
|
siruta String
|
||||||
objectId Int // eTerra OBJECTID (unique per layer); negative for no-geometry parcels (= -immovablePk)
|
objectId Int // eTerra OBJECTID (unique per layer); negative for no-geometry parcels (= -immovablePk)
|
||||||
inspireId String?
|
inspireId String?
|
||||||
cadastralRef String? // NATIONAL_CADASTRAL_REFERENCE
|
cadastralRef String? // NATIONAL_CADASTRAL_REFERENCE
|
||||||
areaValue Float?
|
areaValue Float?
|
||||||
isActive Boolean @default(true)
|
isActive Boolean @default(true)
|
||||||
attributes Json // all raw eTerra attributes
|
attributes Json // all raw eTerra attributes
|
||||||
geometry Json? // GeoJSON geometry (Polygon/MultiPolygon)
|
geometry Json? // GeoJSON geometry (Polygon/MultiPolygon)
|
||||||
geometrySource String? // null = normal GIS sync, "NO_GEOMETRY" = eTerra immovable without GIS geometry
|
geometrySource String? // null = normal GIS sync, "NO_GEOMETRY" = eTerra immovable without GIS geometry
|
||||||
// NOTE: native PostGIS column 'geom' is managed via SQL trigger (see prisma/postgis-setup.sql)
|
// NOTE: native PostGIS column 'geom' is managed via SQL trigger (see prisma/postgis-setup.sql)
|
||||||
// Prisma doesn't need to know about it — trigger auto-populates from geometry JSON
|
// Prisma doesn't need to know about it — trigger auto-populates from geometry JSON
|
||||||
enrichment Json? // magic data: CF, owners, address, categories, etc.
|
enrichment Json? // magic data: CF, owners, address, categories, etc.
|
||||||
enrichedAt DateTime? // when enrichment was last fetched
|
enrichedAt DateTime? // when enrichment was last fetched
|
||||||
syncRunId String?
|
syncRunId String?
|
||||||
projectId String? // link to project tag
|
projectId String? // link to project tag
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
syncRun GisSyncRun? @relation(fields: [syncRunId], references: [id], onDelete: SetNull)
|
syncRun GisSyncRun? @relation(fields: [syncRunId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
@@ -83,16 +83,16 @@ model GisFeature {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model GisSyncRun {
|
model GisSyncRun {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
siruta String
|
siruta String
|
||||||
uatName String?
|
uatName String?
|
||||||
layerId String
|
layerId String
|
||||||
status String @default("pending") // pending | running | done | error
|
status String @default("pending") // pending | running | done | error
|
||||||
totalRemote Int @default(0)
|
totalRemote Int @default(0)
|
||||||
totalLocal Int @default(0)
|
totalLocal Int @default(0)
|
||||||
newFeatures Int @default(0)
|
newFeatures Int @default(0)
|
||||||
removedFeatures Int @default(0)
|
removedFeatures Int @default(0)
|
||||||
startedAt DateTime @default(now())
|
startedAt DateTime @default(now())
|
||||||
completedAt DateTime?
|
completedAt DateTime?
|
||||||
errorMessage String?
|
errorMessage String?
|
||||||
features GisFeature[]
|
features GisFeature[]
|
||||||
@@ -107,9 +107,9 @@ model GisUat {
|
|||||||
name String
|
name String
|
||||||
county String?
|
county String?
|
||||||
workspacePk Int?
|
workspacePk Int?
|
||||||
geometry Json? /// EsriGeometry { rings: number[][][] } in EPSG:3844
|
geometry Json? /// EsriGeometry { rings: number[][][] } in EPSG:3844
|
||||||
areaValue Float? /// Area in sqm from LIMITE_UAT AREA_VALUE field
|
areaValue Float? /// Area in sqm from LIMITE_UAT AREA_VALUE field
|
||||||
lastUpdatedDtm String? /// LAST_UPDATED_DTM from eTerra — for incremental sync
|
lastUpdatedDtm String? /// LAST_UPDATED_DTM from eTerra — for incremental sync
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@index([name])
|
@@index([name])
|
||||||
@@ -120,9 +120,9 @@ model GisUat {
|
|||||||
|
|
||||||
model RegistrySequence {
|
model RegistrySequence {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
company String // B, U, S, G (single-letter prefix)
|
company String // B, U, S, G (single-letter prefix)
|
||||||
year Int
|
year Int
|
||||||
type String // SEQ (shared across directions)
|
type String // SEQ (shared across directions)
|
||||||
lastSeq Int @default(0)
|
lastSeq Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
@@ -135,7 +135,7 @@ model RegistryAudit {
|
|||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
entryId String
|
entryId String
|
||||||
entryNumber String
|
entryNumber String
|
||||||
action String // created, updated, reserved_created, reserved_claimed, late_registration, closed, deleted
|
action String // created, updated, reserved_created, reserved_claimed, late_registration, closed, deleted
|
||||||
actor String
|
actor String
|
||||||
actorName String?
|
actorName String?
|
||||||
company String
|
company String
|
||||||
@@ -149,41 +149,49 @@ model RegistryAudit {
|
|||||||
// ─── ANCPI ePay: CF Extract Orders ──────────────────────────────────
|
// ─── ANCPI ePay: CF Extract Orders ──────────────────────────────────
|
||||||
|
|
||||||
model CfExtract {
|
model CfExtract {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
orderId String? // ePay orderId (shared across batch items)
|
orderId String? // ePay orderId (shared across batch items)
|
||||||
basketRowId Int? // ePay cart item ID
|
basketRowId Int? // ePay cart item ID
|
||||||
nrCadastral String // cadastral number
|
nrCadastral String // cadastral number
|
||||||
nrCF String? // CF number if different
|
nrCF String? // CF number if different
|
||||||
siruta String? // UAT SIRUTA code
|
siruta String? // UAT SIRUTA code
|
||||||
judetIndex Int // ePay county index (0-41)
|
judetIndex Int // ePay county index (0-41)
|
||||||
judetName String // county display name
|
judetName String // county display name
|
||||||
uatId Int // ePay UAT numeric ID
|
uatId Int // ePay UAT numeric ID
|
||||||
uatName String // UAT display name
|
uatName String // UAT display name
|
||||||
prodId Int @default(14200)
|
prodId Int @default(14200)
|
||||||
solicitantId String @default("14452")
|
solicitantId String @default("14452")
|
||||||
status String @default("pending") // pending|queued|cart|searching|ordering|polling|downloading|completed|failed|cancelled
|
status String @default("pending") // pending|queued|cart|searching|ordering|polling|downloading|completed|failed|cancelled
|
||||||
epayStatus String? // raw ePay status
|
epayStatus String? // raw ePay status
|
||||||
idDocument Int? // ePay document ID
|
idDocument Int? // ePay document ID
|
||||||
documentName String? // ePay filename
|
documentName String? // ePay filename
|
||||||
documentDate DateTime? // when ANCPI generated
|
documentDate DateTime? // when ANCPI generated
|
||||||
minioPath String? // MinIO object key
|
minioPath String? // MinIO object key
|
||||||
minioIndex Int? // file version index
|
minioIndex Int? // file version index
|
||||||
creditsUsed Int @default(1)
|
creditsUsed Int @default(1)
|
||||||
immovableId String? // eTerra immovable ID
|
immovableId String? // eTerra immovable ID
|
||||||
immovableType String? // T/C/A
|
immovableType String? // T/C/A
|
||||||
measuredArea String?
|
measuredArea String?
|
||||||
legalArea String?
|
legalArea String?
|
||||||
address String?
|
address String?
|
||||||
gisFeatureId String? // link to GisFeature
|
gisFeatureId String? // link to GisFeature
|
||||||
version Int @default(1) // increments on re-order
|
version Int @default(1) // increments on re-order
|
||||||
expiresAt DateTime? // 30 days after documentDate
|
expiresAt DateTime? // 30 days after documentDate
|
||||||
supersededById String? // newer version id
|
supersededById String? // newer version id
|
||||||
requestedBy String?
|
requestedBy String?
|
||||||
errorMessage String?
|
errorMessage String?
|
||||||
pollAttempts Int @default(0)
|
pollAttempts Int @default(0)
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
completedAt DateTime?
|
completedAt DateTime?
|
||||||
|
|
||||||
|
// DB columns historically added by hand (not via Prisma migrate).
|
||||||
|
// Surfaced in the schema so callers can set/read them without raw
|
||||||
|
// SQL. See feedback_cfextract_schema_drift.md (2026-05-20).
|
||||||
|
userId String? // Authentik sub of the orderer
|
||||||
|
type String? @default("epay") // 'epay' | 'admin'
|
||||||
|
pdfData Bytes? // legacy inline PDF storage (most rows use minioPath instead)
|
||||||
|
adminOrderedBy String? // admin user who placed the order on someone's behalf
|
||||||
|
|
||||||
@@index([nrCadastral])
|
@@index([nrCadastral])
|
||||||
@@index([status])
|
@@index([status])
|
||||||
@@ -191,4 +199,6 @@ model CfExtract {
|
|||||||
@@index([gisFeatureId])
|
@@index([gisFeatureId])
|
||||||
@@index([createdAt])
|
@@index([createdAt])
|
||||||
@@index([nrCadastral, version])
|
@@index([nrCadastral, version])
|
||||||
|
@@index([userId])
|
||||||
|
@@index([userId, nrCadastral])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
enqueueBatch,
|
enqueueBatch,
|
||||||
} from "@/modules/parcel-sync/services/epay-queue";
|
} from "@/modules/parcel-sync/services/epay-queue";
|
||||||
import type { CfExtractCreateInput } from "@/modules/parcel-sync/services/epay-types";
|
import type { CfExtractCreateInput } from "@/modules/parcel-sync/services/epay-types";
|
||||||
|
import { getAuthSession } from "@/core/auth/require-auth";
|
||||||
|
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
@@ -95,27 +96,40 @@ export async function POST(req: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stamp the orderer's session id on each enqueued row so CfExtract
|
||||||
|
// carries ownership info (was NULL before — see
|
||||||
|
// feedback_cfextract_schema_drift.md). Falls back to undefined when
|
||||||
|
// the route is hit without a session (dev tools / cron).
|
||||||
|
const session = await getAuthSession();
|
||||||
|
const userId =
|
||||||
|
((session?.user as { id?: string } | undefined)?.id ||
|
||||||
|
session?.user?.email) ?? undefined;
|
||||||
|
const stampedParcels: CfExtractCreateInput[] = parcels.map((p) => ({
|
||||||
|
...p,
|
||||||
|
userId: p.userId ?? userId,
|
||||||
|
}));
|
||||||
|
|
||||||
let responseBody: {
|
let responseBody: {
|
||||||
orders: Array<{ id: string; nrCadastral: string; status: string }>;
|
orders: Array<{ id: string; nrCadastral: string; status: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (parcels.length === 1) {
|
if (stampedParcels.length === 1) {
|
||||||
const id = await enqueueOrder(parcels[0]!);
|
const id = await enqueueOrder(stampedParcels[0]!);
|
||||||
responseBody = {
|
responseBody = {
|
||||||
orders: [
|
orders: [
|
||||||
{
|
{
|
||||||
id,
|
id,
|
||||||
nrCadastral: parcels[0]!.nrCadastral,
|
nrCadastral: stampedParcels[0]!.nrCadastral,
|
||||||
status: "queued",
|
status: "queued",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
const ids = await enqueueBatch(parcels);
|
const ids = await enqueueBatch(stampedParcels);
|
||||||
responseBody = {
|
responseBody = {
|
||||||
orders: ids.map((id, i) => ({
|
orders: ids.map((id, i) => ({
|
||||||
id,
|
id,
|
||||||
nrCadastral: parcels[i]?.nrCadastral ?? "",
|
nrCadastral: stampedParcels[i]?.nrCadastral ?? "",
|
||||||
status: "queued",
|
status: "queued",
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -138,6 +138,12 @@ export async function enqueueBatch(
|
|||||||
prodId: input.prodId ?? 14200,
|
prodId: input.prodId ?? 14200,
|
||||||
status: "queued",
|
status: "queued",
|
||||||
version: (agg._max.version ?? 0) + 1,
|
version: (agg._max.version ?? 0) + 1,
|
||||||
|
// userId: Authentik sub of the orderer (propagated from
|
||||||
|
// /api/ancpi/order's session). Falls back to undefined for
|
||||||
|
// legacy callers that don't pass it — DB allows NULL after
|
||||||
|
// the 2026-05-20 schema patch.
|
||||||
|
userId: input.userId,
|
||||||
|
type: "epay",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -95,6 +95,10 @@ export type CfExtractCreateInput = {
|
|||||||
uatName: string;
|
uatName: string;
|
||||||
gisFeatureId?: string;
|
gisFeatureId?: string;
|
||||||
prodId?: number;
|
prodId?: number;
|
||||||
|
/** Authentik sub (or any stable session id) of the user placing the
|
||||||
|
* order. Persisted on `CfExtract.userId` so we can audit who ordered
|
||||||
|
* what + scope RLS later. Optional for legacy callers. */
|
||||||
|
userId?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type OrderMetadata = {
|
export type OrderMetadata = {
|
||||||
|
|||||||
Reference in New Issue
Block a user