Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(db): unblock migrations broken by backdated view recreation
Sidwebworkscd180a6f98d9
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 410f1f98e5..6a3f2f5dc9 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -35,3 +35,13 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** Always use `validator(schema)` from `@carbon/form`, not the raw zod schema. Validate with `validator(schema).validate(formData)`, not `schema.parse()`.**Applies to:** All forms in `apps/erp/app/routes/`, `packages/form/`.++## Backdated migration timestamps break remote deploys++**Context:** CI `supabase db push --include-all` failed on all remotes with `column pi.balance does not exist` while applying `20260616061244`, which recreated the `purchaseInvoices` view.++**Problem:** A migration merged with a timestamp OLDER than already-deployed migrations gets applied out of order on remotes: the remote had already run `20260630095023` (drops `purchaseInvoice.balance`), so the backdated view recreation referenced a dropped column. Worse, the newer `20260630*` batch had forked its view body from a pre-fix definition, silently reverting the backdated migration's fix (`supplierShippingCost` multiply vs divide) — the backdated migration was both broken AND dead code.++**Rule:** Never merge a migration whose timestamp is older than the newest migration already on `main`/deployed. Before writing a view/RPC recreation, fork from the NEWEST definition of that view (grep all migrations, take the last). When rescuing a failed backdated migration, strip the superseded parts and re-land the still-wanted change in a fresh forward-dated migration; don't rename already-partially-applied files (re-applies them).++**Applies to:** `packages/database/supabase/migrations/`, `ci/src/migrations.ts`, any long-lived branch adding migrations.diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 8021dc25f1..adb260fddc 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8411,6 +8411,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_companyId_fkey"columns: ["companyId"]@@ -8418,6 +8425,41 @@ export type Database = {referencedRelation: "company"referencedColumns: ["id"]},+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_createdBy_fkey"columns: ["createdBy"]@@ -8425,13 +8467,48 @@ export type Database = {referencedRelation: "user"referencedColumns: ["id"]},+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]- }+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },]}documentFavorite: {@@ -41582,7 +41659,49 @@ export type Database = {},]}- searchIndex_d924dneua0gg2k9762jg: {+ searchIndex_Bi9qTnnxCWSejaHm7G2Tjn: {+ Row: {+ createdAt: string+ description: string | null+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json | null+ searchVector: unknown+ tags: string[] | null+ title: string+ updatedAt: string | null+ }+ Insert: {+ createdAt?: string+ description?: string | null+ entityId: string+ entityType: string+ id?: number+ link: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title: string+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ description?: string | null+ entityId?: string+ entityType?: string+ id?: number+ link?: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title?: string+ updatedAt?: string | null+ }+ Relationships: []+ }+ searchIndex_d92cchpf40h028gvbhsg: {Row: {createdAt: stringdescription: string | null@@ -63256,7 +63375,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -63270,14 +63389,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]- isOneToOne: false- referencedRelation: "country"- referencedColumns: ["alpha2"]- },- {- foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -63313,7 +63425,6 @@ export type Database = {locationId: string | nullopportunityId: string | nullpaymentTermId: string | null- paymentTermName: string | nullpostingDate: string | nullshipmentId: string | nullstatus: string | null@@ -69590,6 +69701,12 @@ export type Database = {| "Rework"| "Scrap"| "Use As Is"+ documentExtractionStatus:+ | "pending"+ | "processing"+ | "completed"+ | "failed"+ documentExtractionType: "purchaseInvoice" | "salesRfq"documentSourceType:| "Job"| "Part"@@ -69621,8 +69738,6 @@ export type Database = {| "invoice"| "receipt"| "shipment"- documentExtractionStatus: "pending" | "processing" | "completed" | "failed"- documentExtractionType: "purchaseInvoice" | "salesRfq"documentTransactionType:| "Download"| "Edit"@@ -70904,6 +71019,13 @@ export const Constants = {"Scrap","Use As Is",],+ documentExtractionStatus: [+ "pending",+ "processing",+ "completed",+ "failed",+ ],+ documentExtractionType: ["purchaseInvoice", "salesRfq"],documentSourceType: ["Job","Part",diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 8021dc25f1..adb260fddc 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8411,6 +8411,13 @@ export type Database = {updatedBy?: string | null}Relationships: [+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_companyId_fkey"columns: ["companyId"]@@ -8418,6 +8425,41 @@ export type Database = {referencedRelation: "company"referencedColumns: ["id"]},+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentExtraction_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_createdBy_fkey"columns: ["createdBy"]@@ -8425,13 +8467,48 @@ export type Database = {referencedRelation: "user"referencedColumns: ["id"]},+ {+ foreignKeyName: "documentExtraction_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },{foreignKeyName: "documentExtraction_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]- }+ },+ {+ foreignKeyName: "documentExtraction_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },]}documentFavorite: {@@ -41582,7 +41659,49 @@ export type Database = {},]}- searchIndex_d924dneua0gg2k9762jg: {+ searchIndex_Bi9qTnnxCWSejaHm7G2Tjn: {+ Row: {+ createdAt: string+ description: string | null+ entityId: string+ entityType: string+ id: number+ link: string+ metadata: Json | null+ searchVector: unknown+ tags: string[] | null+ title: string+ updatedAt: string | null+ }+ Insert: {+ createdAt?: string+ description?: string | null+ entityId: string+ entityType: string+ id?: number+ link: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title: string+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ description?: string | null+ entityId?: string+ entityType?: string+ id?: number+ link?: string+ metadata?: Json | null+ searchVector?: unknown+ tags?: string[] | null+ title?: string+ updatedAt?: string | null+ }+ Relationships: []+ }+ searchIndex_d92cchpf40h028gvbhsg: {Row: {createdAt: stringdescription: string | null@@ -63256,7 +63375,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -63270,14 +63389,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]- isOneToOne: false- referencedRelation: "country"- referencedColumns: ["alpha2"]- },- {- foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -63313,7 +63425,6 @@ export type Database = {locationId: string | nullopportunityId: string | nullpaymentTermId: string | null- paymentTermName: string | nullpostingDate: string | nullshipmentId: string | nullstatus: string | null@@ -69590,6 +69701,12 @@ export type Database = {| "Rework"| "Scrap"| "Use As Is"+ documentExtractionStatus:+ | "pending"+ | "processing"+ | "completed"+ | "failed"+ documentExtractionType: "purchaseInvoice" | "salesRfq"documentSourceType:| "Job"| "Part"@@ -69621,8 +69738,6 @@ export type Database = {| "invoice"| "receipt"| "shipment"- documentExtractionStatus: "pending" | "processing" | "completed" | "failed"- documentExtractionType: "purchaseInvoice" | "salesRfq"documentTransactionType:| "Download"| "Edit"@@ -70904,6 +71019,13 @@ export const Constants = {"Scrap","Use As Is",],+ documentExtractionStatus: [+ "pending",+ "processing",+ "completed",+ "failed",+ ],+ documentExtractionType: ["purchaseInvoice", "salesRfq"],documentSourceType: ["Job","Part",diff --git a/packages/database/supabase/migrations/20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sql b/packages/database/supabase/migrations/20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sqlindex f7a3e16dc4..0e2b11cdd7 100644--- a/packages/database/supabase/migrations/20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sql+++ b/packages/database/supabase/migrations/20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sql@@ -7,7 +7,7 @@ BEGIN"updatedBy" = COALESCE(NEW."updatedBy", 'system'),"updatedAt" = NOW()WHERE "invoiceId" = NEW."id";-+RETURN NEW;END;$$ LANGUAGE plpgsql SECURITY DEFINER;@@ -42,102 +42,9 @@ BEFORE INSERT ON "purchaseInvoiceLine"FOR EACH ROWEXECUTE FUNCTION sync_purchase_invoice_line_exchange_rate_on_insert();--- Fix purchaseOrders and purchaseInvoices views to correctly divide supplierShippingCost by exchangeRate instead of multiplying--- to convert it from supplier currency to company base currency (USD)--DROP VIEW IF EXISTS "purchaseOrders";-CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS- SELECT- p.*,- pl."thumbnailPath",- pl."itemType",- pl."orderTotal" + pd."supplierShippingCost" / CASE WHEN p."exchangeRate" = 0 THEN 1 ELSE p."exchangeRate" END AS "orderTotal",- pd."shippingMethodId",- pd."shippingTermId",- pd."receiptRequestedDate",- pd."receiptPromisedDate",- pd."deliveryDate",- pd."dropShipment",- pp."paymentTermId",- pd."locationId",- pd."supplierShippingCost"- FROM "purchaseOrder" p- LEFT JOIN (- SELECT- pol."purchaseOrderId",- MIN(CASE- WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"- ELSE i."thumbnailPath"- END) AS "thumbnailPath",- SUM(COALESCE(pol."purchaseQuantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",- MIN(i."type") AS "itemType"- FROM "purchaseOrderLine" pol- LEFT JOIN "item" i- ON i."id" = pol."itemId"- LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"- GROUP BY pol."purchaseOrderId"- ) pl ON pl."purchaseOrderId" = p."id"- LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"- LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"- LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id";---DROP VIEW IF EXISTS "purchaseInvoices";-CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS- SELECT- pi."id",- pi."invoiceId",- pi."supplierId",- pi."invoiceSupplierId",- pi."supplierInteractionId",- pi."supplierReference",- pi."invoiceSupplierContactId",- pi."invoiceSupplierLocationId",- pi."locationId",- pi."postingDate",- pi."dateIssued",- pi."dateDue",- pi."datePaid",- pi."paymentTermId",- pi."currencyCode",- pi."exchangeRate",- pi."exchangeRateUpdatedAt",- pi."subtotal",- pi."totalDiscount",- pi."totalAmount",- pi."totalTax",- pi."balance",- pi."assignee",- pi."createdBy",- pi."createdAt",- pi."updatedBy",- pi."updatedAt",- pi."internalNotes",- pi."customFields",- pi."companyId",- pl."thumbnailPath",- pl."itemType",- pl."orderTotal" + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",- CASE- WHEN pi."dateDue" < CURRENT_DATE AND pi."datePaid" IS NULL THEN 'Overdue'- ELSE pi."status"- END AS status,- pt."name" AS "paymentTermName"- FROM "purchaseInvoice" pi- LEFT JOIN (- SELECT- pol."invoiceId",- MIN(CASE- WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"- ELSE i."thumbnailPath"- END) AS "thumbnailPath",- SUM(COALESCE(pol."quantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",- MIN(i."type") AS "itemType"- FROM "purchaseInvoiceLine" pol- LEFT JOIN "item" i- ON i."id" = pol."itemId"- LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"- GROUP BY pol."invoiceId"- ) pl ON pl."invoiceId" = pi."id"- LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"- LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id";+-- NOTE: This migration previously also recreated the "purchaseOrders" and "purchaseInvoices"+-- views (to divide supplierShippingCost by exchangeRate). That section was removed: it is+-- backdated relative to the already-applied 20260630 invoice batch (20260630095023 drops the+-- purchaseInvoice."balance" column and 20260630151500 is the current view definition), so+-- recreating the view here fails with `column pi.balance does not exist` and is fully+-- superseded regardless. See the shippingCost/exchangeRate note flagged in the PR.diff --git a/packages/database/supabase/migrations/20260702061504_fix-supplier-shipping-cost-exchange-rate.sql b/packages/database/supabase/migrations/20260702061504_fix-supplier-shipping-cost-exchange-rate.sqlnew file mode 100644index 0000000000..dfdb539fbc--- /dev/null+++ b/packages/database/supabase/migrations/20260702061504_fix-supplier-shipping-cost-exchange-rate.sql@@ -0,0 +1,167 @@+-- ============================================================+-- Fix supplierShippingCost currency conversion: divide, not multiply+--+-- currency.exchangeRate stores foreign-units-per-base (see the+-- update-exchange-rates job: EUR-based API rates rebased via+-- value / baseRate), so converting a supplier-currency amount to the+-- company base currency is amount / exchangeRate. The line-level+-- generated columns have divided since 20250807094441+-- (fix-purchasing-conversion-factor), but the header-level+-- "purchaseOrders" / "purchaseInvoices" views still MULTIPLIED+-- supplierShippingCost by exchangeRate — inconsistent with the very+-- lines they sum.+--+-- This was originally fixed in 20260616061244, but that migration was+-- backdated: the 20260630 invoice batch (20260630095023 →+-- 20260630151500) forked its purchaseInvoices body from the pre-fix+-- 20260604120000 and silently reverted the divide. 20260616061244 has+-- since been stripped to its trigger fix only (its view recreation also+-- referenced the purchaseInvoice."balance" column dropped by+-- 20260630095023, which broke `supabase db push` on remotes that had+-- already applied the 20260630 batch).+--+-- Forked verbatim from the newest view definitions:+-- * purchaseOrders — 20260525120000_po-pdf-buyer-and-optional-state.sql+-- * purchaseInvoices — 20260630151500_invoice-dust-forgiveness.sql+-- Only the supplierShippingCost conversion changes: `* exchangeRate` →+-- `/ CASE WHEN exchangeRate = 0 THEN 1 ELSE exchangeRate END`+-- (zero-guard so a bad rate can't divide by zero).+-- ============================================================++DROP VIEW IF EXISTS "purchaseOrders";+CREATE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS+ SELECT+ p.*,+ pl."thumbnailPath",+ pl."itemType",+ pl."orderTotal" + pd."supplierShippingCost" / CASE WHEN p."exchangeRate" = 0 THEN 1 ELSE p."exchangeRate" END AS "orderTotal",+ pd."shippingMethodId",+ pd."shippingTermId",+ pd."receiptRequestedDate",+ pd."receiptPromisedDate",+ pd."deliveryDate",+ pd."dropShipment",+ pp."paymentTermId",+ pd."locationId",+ pd."supplierShippingCost",+ pd."incoterm",+ pd."incotermLocation",+ u."fullName" AS "createdByFullName",+ u."email" AS "createdByEmail",+ u."phone" AS "createdByPhone",+ ua."fullName" AS "assigneeFullName",+ ua."email" AS "assigneeEmail",+ ua."phone" AS "assigneePhone",+ uam."fullName" AS "accountManagerFullName",+ uam."email" AS "accountManagerEmail",+ uam."phone" AS "accountManagerPhone"+ FROM "purchaseOrder" p+ LEFT JOIN (+ SELECT+ pol."purchaseOrderId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(COALESCE(pol."purchaseQuantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseOrderLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."purchaseOrderId"+ ) pl ON pl."purchaseOrderId" = p."id"+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"+ LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"+ LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id"+ LEFT JOIN "user" u ON u."id" = p."createdBy"+ LEFT JOIN "user" ua ON ua."id" = p."assignee"+ LEFT JOIN "supplier" s ON s."id" = p."supplierId"+ LEFT JOIN "user" uam ON uam."id" = s."accountManagerId";+++DROP VIEW IF EXISTS "purchaseInvoices";+CREATE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ pa."targetPurchaseInvoiceId",+ SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS amount,+ MAX(pa."appliedDate") AS "lastSettlementDate"+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE p."status" = 'Posted' AND pa."targetPurchaseInvoiceId" IS NOT NULL+ GROUP BY pa."targetPurchaseInvoiceId"+ )+ SELECT+ pi."id",+ pi."invoiceId",+ pi."supplierId",+ pi."invoiceSupplierId",+ pi."supplierInteractionId",+ pi."supplierReference",+ pi."invoiceSupplierContactId",+ pi."invoiceSupplierLocationId",+ pi."locationId",+ pi."postingDate",+ pi."dateIssued",+ pi."dateDue",+ CASE+ WHEN COALESCE(s.amount, 0) > 0 AND pi."totalAmount" > 0 AND (pi."totalAmount" - COALESCE(s.amount, 0)) < 0.01 THEN COALESCE(s."lastSettlementDate", pi."datePaid")+ ELSE pi."datePaid"+ END AS "datePaid",+ pi."paymentTermId",+ pi."currencyCode",+ pi."exchangeRate",+ pi."exchangeRateUpdatedAt",+ COALESCE(pl."subtotal", 0) AS "subtotal",+ pi."totalDiscount",+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",+ COALESCE(pl."totalTax", 0) AS "totalTax",+ CASE+ WHEN COALESCE(s.amount, 0) > 0 AND (pi."totalAmount" - COALESCE(s.amount, 0)) > 0 AND (pi."totalAmount" - COALESCE(s.amount, 0)) < 0.01 THEN 0+ ELSE (pi."totalAmount" - COALESCE(s.amount, 0))+ END AS "balance",+ pi."assignee",+ pi."createdBy",+ pi."createdAt",+ pi."updatedBy",+ pi."updatedAt",+ pi."internalNotes",+ pi."customFields",+ pi."companyId",+ pl."thumbnailPath",+ pl."itemType",+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",+ CASE+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT+ WHEN COALESCE(s.amount, 0) > 0 AND pi."totalAmount" > 0 AND (pi."totalAmount" - COALESCE(s.amount, 0)) < 0.01 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'+ ELSE pi."status"::TEXT+ END AS status,+ pt."name" AS "paymentTermName"+ FROM "purchaseInvoice" pi+ LEFT JOIN (+ SELECT+ pol."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)+ ) AS "subtotal",+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)+ ) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseInvoiceLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."invoiceId"+ ) pl ON pl."invoiceId" = pi."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id";