Skip to content

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.

fix: make database migrations idempotent and fix checks

Brad Barbinc64c3be9a52a
diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.ts
index c6febb9a71..fef241593a 100644
--- a/apps/erp/app/modules/documents/documents.service.ts
+++ b/apps/erp/app/modules/documents/documents.service.ts
@@ -112,9 +112,12 @@ export async function insertDocumentLabel(
client: SupabaseClient<Database>,
id: string,
label: string,
+ companyId: string,
userId: string
) {
- return client.from("documentLabel").insert({ documentId: id, label, userId });
+ return client
+ .from("documentLabel")
+ .insert({ documentId: id, label, companyId, userId });
}
export async function moveDocumentToTrash(
diff --git a/apps/erp/app/modules/documents/ui/Documents/useDocument.ts b/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
index 5e9e980cb0..bf181d3b80 100644
--- a/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
+++ b/apps/erp/app/modules/documents/ui/Documents/useDocument.ts
@@ -46,10 +46,11 @@ export const useDocument = () => {
return carbon?.from("documentTransaction").insert({
documentId: document.id,
type,
+ companyId: user.company.id,
userId: user.id
});
},
- [carbon, user?.id]
+ [carbon, user?.id, user.company.id]
);
const deleteLabel = useCallback(
@@ -148,6 +149,7 @@ export const useDocument = () => {
labels.map((label) => ({
documentId: document.id!,
label,
+ companyId: user.company.id,
userId: user.id
}))
);
@@ -155,7 +157,7 @@ export const useDocument = () => {
return insertTransaction(document, "Label");
},
- [insertTransaction, carbon, user.id]
+ [insertTransaction, carbon, user.id, user.company.id]
);
const makePreview = useCallback(
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx
index 38376e3cbb..cdf32d14a8 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx
@@ -3,12 +3,15 @@ import { Status } from "@carbon/react";
import { SALES_INVOICE_STATUS_COLOR_MAP } from "@carbon/utils";
type SalesInvoicingStatusProps = {
- status?: Database["public"]["Enums"]["salesInvoiceStatus"] | null;
+ status?: string | null;
};
const SalesInvoicingStatus = ({ status }: SalesInvoicingStatusProps) => {
if (!status) return null;
- const color = SALES_INVOICE_STATUS_COLOR_MAP[status];
+ const color =
+ SALES_INVOICE_STATUS_COLOR_MAP[
+ status as Database["public"]["Enums"]["salesInvoiceStatus"]
+ ];
if (!color) return null;
return <Status color={color}>{status}</Status>;
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index c876aada7e..08a8b674b5 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1016,6 +1016,7 @@ export async function insertSupplierContact(
supplierId: supplierContact.supplierId,
contactId,
supplierLocationId: supplierContact.supplierLocationId,
+ companyId: supplierContact.companyId,
customFields: supplierContact.customFields
}
])
@@ -1075,6 +1076,7 @@ export async function insertSupplierLocation(
supplierId: supplierLocation.supplierId,
addressId,
name: supplierLocation.name,
+ companyId: supplierLocation.companyId,
customFields: supplierLocation.customFields
}
])
diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.ts
index 7f7df1a7da..48b9fda83d 100644
--- a/apps/erp/app/modules/resources/resources.service.ts
+++ b/apps/erp/app/modules/resources/resources.service.ts
@@ -1161,6 +1161,7 @@ export async function upsertContractor(
id: string;
hoursPerWeek?: number;
abilities: string[];
+ companyId: string;
updatedBy: string;
customFields?: Json;
}
@@ -1194,6 +1195,7 @@ export async function upsertContractor(
return {
contractorId: contractor.id,
abilityId: ability,
+ companyId: contractor.companyId,
createdBy:
"createdBy" in contractor ? contractor.createdBy : contractor.updatedBy
};
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 0abcc0dd15..ad3681bf9c 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1863,6 +1863,7 @@ export async function insertCustomerContact(
customerId: customerContact.customerId,
contactId,
customerLocationId: customerContact.customerLocationId,
+ companyId: customerContact.companyId,
customFields: customerContact.customFields
}
])
@@ -1910,6 +1911,7 @@ export async function insertCustomerLocation(
customerId: customerLocation.customerId,
addressId,
name: customerLocation.name,
+ companyId: customerLocation.companyId,
customFields: customerLocation.customFields
}
])
@@ -4241,6 +4243,7 @@ export async function calculatePricesForQuantities(
priceRows.push({
quoteId,
quoteLineId,
+ companyId,
quantity: qty,
unitPrice: Number(finalPrice.toFixed(precision)),
categoryMarkups: defaultMarkups,
@@ -4306,6 +4309,7 @@ export async function resolveQuoteLinePrices(
priceRows.push({
quoteId,
quoteLineId,
+ companyId,
quantity: qty,
unitPrice: Number(resolved.finalPrice.toFixed(precision)),
exchangeRate,
@@ -4373,6 +4377,7 @@ export async function resolvePurchaseToOrderPrices(
priceRows.push({
quoteId,
quoteLineId,
+ companyId,
quantity: qty,
unitPrice: Number(resolved.finalPrice.toFixed(precision)),
exchangeRate,
@@ -4486,6 +4491,7 @@ export async function recalculateQuoteLinePrices(
updatedRows.push({
quoteId: row.quoteId,
quoteLineId: row.quoteLineId,
+ companyId: row.companyId,
quantity: row.quantity,
unitPrice: Number(finalPrice.toFixed(precision)),
categoryMarkups: markups,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index be281ae17b..5cb7077da1 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-06-30T03:55:04.384Z",
+ "generated": "2026-06-30T13:22:53.840Z",
"totalTools": 1248,
"modules": 15,
"tools": [
@@ -3072,6 +3072,7 @@
"client",
"id",
"label",
+ "companyId",
"userId"
],
"injectAuth": [
diff --git a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
index a15388bfee..f8b7bd2315 100644
--- a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
@@ -204,6 +204,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
priceInserts.push({
supplierQuoteId: quote.data.id,
supplierQuoteLineId: lineId,
+ companyId: quote.data.companyId,
quantity: quantity,
supplierUnitPrice: selectedLine.supplierUnitPrice ?? 0,
leadTime: selectedLine.leadTime ?? 0,
diff --git a/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx b/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx
index 415e602a98..ba1d333475 100644
--- a/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx
+++ b/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx
@@ -37,7 +37,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "resources"
});
@@ -58,6 +58,7 @@ export async function action({ request }: ActionFunctionArgs) {
// @ts-expect-error TS2339 - TODO: fix type
abilities: d.abilities ?? [],
customFields: setCustomFields(formData),
+ companyId,
updatedBy: userId
});
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index 3007b9a70c..3118cc9547 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -352,6 +352,24 @@ serve(async (req: Request) => {
resolvedDefaults[key] = accountIdByKey[number] ?? null;
}
+ // The four AR/AP defaults are NOT NULL in the schema. If a customized COA
+ // on an existing group is missing one of their accounts
+ // (6050/4130/4120/7060), the lookup yields null and the insert below would
+ // violate the not-null constraint. Fall back to an existing default of the
+ // same nature so the insert can't fail — mirrors the COALESCE backfill in
+ // 20260630093809_ar-ap-payments.sql.
+ const arApDefaultFallbacks: Record<string, string> = {
+ customerWriteOffAccount: "salesDiscountAccount",
+ supplierWriteOffAccount: "salesAccount",
+ realizedExchangeGainAccount: "salesAccount",
+ realizedExchangeLossAccount: "interestAccount",
+ };
+ for (const [key, fallbackKey] of Object.entries(arApDefaultFallbacks)) {
+ if (!resolvedDefaults[key]) {
+ resolvedDefaults[key] = resolvedDefaults[fallbackKey] ?? null;
+ }
+ }
+
// Company-specific accounting defaults and posting groups
await trx
.insertInto("accountDefault")
diff --git a/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql b/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql
index 39832f4161..60fc7bbc50 100644
--- a/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql
+++ b/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql
@@ -77,36 +77,48 @@ END $$;
-- Phase 3: Extend accountDefault with the four new mappings
-- ============================================================
-- Add nullable, backfill, then SET NOT NULL to match existing
--- column nullability convention on this table.
+-- column nullability convention on this table. Idempotent: this
+-- migration is not run in a transaction by the deploy runner, so
+-- a mid-file failure leaves committed state behind — every step
+-- here must be safe to re-run.
ALTER TABLE "accountDefault"
- ADD COLUMN "customerWriteOffAccount" TEXT,
- ADD COLUMN "supplierWriteOffAccount" TEXT,
- ADD COLUMN "realizedExchangeGainAccount" TEXT,
- ADD COLUMN "realizedExchangeLossAccount" TEXT;
+ ADD COLUMN IF NOT EXISTS "customerWriteOffAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "supplierWriteOffAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "realizedExchangeGainAccount" TEXT,
+ ADD COLUMN IF NOT EXISTS "realizedExchangeLossAccount" TEXT;
-- Backfill: look up the account.id for each company's group by account.number.
+-- These numbers (6050/4130/4120/7060) are only guaranteed present if the COA
+-- was seeded/reset cleanly; a group can be missing one (renumbered/deleted
+-- accounts, or a NULL companyGroupId). When the lookup misses, COALESCE to an
+-- existing, always-NOT-NULL default of the same nature so no NULL survives and
+-- SET NOT NULL below can never fail. Admins override these in account settings.
UPDATE "accountDefault" ad
SET
- "customerWriteOffAccount" = (
- SELECT a.id FROM "account" a
- INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
- WHERE c.id = ad."companyId" AND a.number = '6050' LIMIT 1
+ "customerWriteOffAccount" = COALESCE(
+ (SELECT a.id FROM "account" a
+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+ WHERE c.id = ad."companyId" AND a.number = '6050' LIMIT 1),
+ ad."salesDiscountAccount" -- contra-revenue fallback for an AR write-off
),
- "supplierWriteOffAccount" = (
- SELECT a.id FROM "account" a
- INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
- WHERE c.id = ad."companyId" AND a.number = '4130' LIMIT 1
+ "supplierWriteOffAccount" = COALESCE(
+ (SELECT a.id FROM "account" a
+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+ WHERE c.id = ad."companyId" AND a.number = '4130' LIMIT 1),
+ ad."salesAccount" -- income fallback for an AP write-off
),
- "realizedExchangeGainAccount" = (
- SELECT a.id FROM "account" a
- INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
- WHERE c.id = ad."companyId" AND a.number = '4120' LIMIT 1
+ "realizedExchangeGainAccount" = COALESCE(
+ (SELECT a.id FROM "account" a
+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+ WHERE c.id = ad."companyId" AND a.number = '4120' LIMIT 1),
+ ad."salesAccount" -- income fallback for an FX gain
),
- "realizedExchangeLossAccount" = (
- SELECT a.id FROM "account" a
- INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
- WHERE c.id = ad."companyId" AND a.number = '7060' LIMIT 1
+ "realizedExchangeLossAccount" = COALESCE(
+ (SELECT a.id FROM "account" a
+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+ WHERE c.id = ad."companyId" AND a.number = '7060' LIMIT 1),
+ ad."interestAccount" -- financial-expense fallback for an FX loss
);
ALTER TABLE "accountDefault"
@@ -115,6 +127,14 @@ ALTER TABLE "accountDefault"
ALTER COLUMN "realizedExchangeGainAccount" SET NOT NULL,
ALTER COLUMN "realizedExchangeLossAccount" SET NOT NULL;
+-- DROP IF EXISTS before ADD so re-running after a partial deploy doesn't trip
+-- on an already-created constraint.
+ALTER TABLE "accountDefault"
+ DROP CONSTRAINT IF EXISTS "accountDefault_customerWriteOffAccount_fkey",
+ DROP CONSTRAINT IF EXISTS "accountDefault_supplierWriteOffAccount_fkey",
+ DROP CONSTRAINT IF EXISTS "accountDefault_realizedExchangeGainAccount_fkey",
+ DROP CONSTRAINT IF EXISTS "accountDefault_realizedExchangeLossAccount_fkey";
+
ALTER TABLE "accountDefault"
ADD CONSTRAINT "accountDefault_customerWriteOffAccount_fkey"
FOREIGN KEY ("customerWriteOffAccount") REFERENCES "account"("id")
@@ -134,15 +154,25 @@ ALTER TABLE "accountDefault"
-- Phase 4: Enums
-- ============================================================
-CREATE TYPE "paymentType" AS ENUM ('Receipt', 'Disbursement');
-CREATE TYPE "paymentStatus" AS ENUM ('Draft', 'Posted', 'Voided');
+-- CREATE TYPE has no IF NOT EXISTS; guard each so a re-run after a partial
+-- deploy doesn't trip on an already-created type.
+DO $$ BEGIN
+ CREATE TYPE "paymentType" AS ENUM ('Receipt', 'Disbursement');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+DO $$ BEGIN
+ CREATE TYPE "paymentStatus" AS ENUM ('Draft', 'Posted', 'Voided');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
-- A credit/debit memo is a standalone, payment-shaped document (Phase 5b) — NOT
-- an invoice row. `direction` is whether it credits or debits the party's
-- control account (Credit ⇒ DR reason / CR control; Debit ⇒ DR control / CR
-- reason); status mirrors payment's lifecycle.
-CREATE TYPE "memoDirection" AS ENUM ('Credit', 'Debit');
-CREATE TYPE "memoStatus" AS ENUM ('Draft', 'Posted', 'Voided');
+DO $$ BEGIN
+ CREATE TYPE "memoDirection" AS ENUM ('Credit', 'Debit');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+DO $$ BEGIN
+ CREATE TYPE "memoStatus" AS ENUM ('Draft', 'Posted', 'Voided');
+EXCEPTION WHEN duplicate_object THEN NULL; END $$;
ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Payment';
-- post-memo writes its journal lines with documentType 'Memo'.
@@ -161,7 +191,7 @@ ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Debit Memo';
-- discriminated by paymentType. customerId xor supplierId enforced
-- by check matching the type.
-CREATE TABLE "payment" (
+CREATE TABLE IF NOT EXISTS "payment" (
"id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
"paymentId" TEXT NOT NULL,
"paymentType" "paymentType" NOT NULL,
@@ -214,14 +244,15 @@ CREATE TABLE "payment" (
CONSTRAINT "payment_voidedBy_fkey" FOREIGN KEY ("voidedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "payment_companyId_idx" ON "payment" ("companyId");
-CREATE INDEX "payment_customerId_idx" ON "payment" ("customerId") WHERE "customerId" IS NOT NULL;
-CREATE INDEX "payment_supplierId_idx" ON "payment" ("supplierId") WHERE "supplierId" IS NOT NULL;
-CREATE INDEX "payment_status_idx" ON "payment" ("status");
-CREATE INDEX "payment_paymentDate_idx" ON "payment" ("paymentDate");
+CREATE INDEX IF NOT EXISTS "payment_companyId_idx" ON "payment" ("companyId");
+CREATE INDEX IF NOT EXISTS "payment_customerId_idx" ON "payment" ("customerId") WHERE "customerId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_supplierId_idx" ON "payment" ("supplierId") WHERE "supplierId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_status_idx" ON "payment" ("status");
+CREATE INDEX IF NOT EXISTS "payment_paymentDate_idx" ON "payment" ("paymentDate");
ALTER TABLE "payment" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."payment";
CREATE POLICY "SELECT" ON "public"."payment"
FOR SELECT USING (
"companyId" = ANY (
@@ -229,6 +260,7 @@ FOR SELECT USING (
)
);
+DROP POLICY IF EXISTS "INSERT" ON "public"."payment";
CREATE POLICY "INSERT" ON "public"."payment"
FOR INSERT WITH CHECK (
"companyId" = ANY (
@@ -239,6 +271,7 @@ FOR INSERT WITH CHECK (
-- Mutability ties to status: Draft is freely editable, Posted only
-- transitions to Voided (via post-payment edge function), Voided is
-- terminal. App-side service rejects illegal transitions.
+DROP POLICY IF EXISTS "UPDATE" ON "public"."payment";
CREATE POLICY "UPDATE" ON "public"."payment"
FOR UPDATE USING (
"companyId" = ANY (
@@ -247,6 +280,7 @@ FOR UPDATE USING (
);
-- DELETE allowed only on Draft (Posted payments must be voided).
+DROP POLICY IF EXISTS "DELETE" ON "public"."payment";
CREATE POLICY "DELETE" ON "public"."payment"
FOR DELETE USING (
"status" = 'Draft' AND
@@ -273,7 +307,7 @@ FOR DELETE USING (
-- invoices via invoiceSettlement (source = memoId). Balance-increasing memos are
-- themselves open items, settled via invoiceSettlement (target = targetMemoId).
-CREATE TABLE "memo" (
+CREATE TABLE IF NOT EXISTS "memo" (
"id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
"memoId" TEXT NOT NULL,
"direction" "memoDirection" NOT NULL,
@@ -321,30 +355,34 @@ CREATE TABLE "memo" (
CONSTRAINT "memo_voidedBy_fkey" FOREIGN KEY ("voidedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "memo_companyId_idx" ON "memo" ("companyId");
-CREATE INDEX "memo_customerId_idx" ON "memo" ("customerId") WHERE "customerId" IS NOT NULL;
-CREATE INDEX "memo_supplierId_idx" ON "memo" ("supplierId") WHERE "supplierId" IS NOT NULL;
-CREATE INDEX "memo_status_idx" ON "memo" ("status");
-CREATE INDEX "memo_memoDate_idx" ON "memo" ("memoDate");
+CREATE INDEX IF NOT EXISTS "memo_companyId_idx" ON "memo" ("companyId");
+CREATE INDEX IF NOT EXISTS "memo_customerId_idx" ON "memo" ("customerId") WHERE "customerId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_supplierId_idx" ON "memo" ("supplierId") WHERE "supplierId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_status_idx" ON "memo" ("status");
+CREATE INDEX IF NOT EXISTS "memo_memoDate_idx" ON "memo" ("memoDate");
ALTER TABLE "memo" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."memo";
CREATE POLICY "SELECT" ON "public"."memo"
FOR SELECT USING (
"companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
);
+DROP POLICY IF EXISTS "INSERT" ON "public"."memo";
CREATE POLICY "INSERT" ON "public"."memo"
FOR INSERT WITH CHECK (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_create'))::text[])
);
+DROP POLICY IF EXISTS "UPDATE" ON "public"."memo";
CREATE POLICY "UPDATE" ON "public"."memo"
FOR UPDATE USING (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_update'))::text[])
);
-- DELETE allowed only on Draft (Posted memos must be voided).
+DROP POLICY IF EXISTS "DELETE" ON "public"."memo";
CREATE POLICY "DELETE" ON "public"."memo"
FOR DELETE USING (
"status" = 'Draft' AND
@@ -372,7 +410,7 @@ FOR DELETE USING (
-- counterparty) is enforced by the posting/apply functions — the source's
-- AR/AP side lives in the payment/memo row, not structurally here.
-CREATE TABLE "invoiceSettlement" (
+CREATE TABLE IF NOT EXISTS "invoiceSettlement" (
"id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),
-- funding source (exactly one): a cash payment OR a memo
"paymentId" TEXT,
@@ -438,16 +476,17 @@ CREATE TABLE "invoiceSettlement" (
CONSTRAINT "invoiceSettlement_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "invoiceSettlement_paymentId_idx" ON "invoiceSettlement" ("paymentId") WHERE "paymentId" IS NOT NULL;
-CREATE INDEX "invoiceSettlement_memoId_idx" ON "invoiceSettlement" ("memoId") WHERE "memoId" IS NOT NULL;
-CREATE INDEX "invoiceSettlement_targetSalesInvoiceId_idx" ON "invoiceSettlement" ("targetSalesInvoiceId") WHERE "targetSalesInvoiceId" IS NOT NULL;
-CREATE INDEX "invoiceSettlement_targetPurchaseInvoiceId_idx" ON "invoiceSettlement" ("targetPurchaseInvoiceId") WHERE "targetPurchaseInvoiceId" IS NOT NULL;
-CREATE INDEX "invoiceSettlement_targetMemoId_idx" ON "invoiceSettlement" ("targetMemoId") WHERE "targetMemoId" IS NOT NULL;
-CREATE INDEX "invoiceSettlement_appliedDate_idx" ON "invoiceSettlement" ("appliedDate");
-CREATE INDEX "invoiceSettlement_companyId_idx" ON "invoiceSettlement" ("companyId");
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_paymentId_idx" ON "invoiceSettlement" ("paymentId") WHERE "paymentId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_memoId_idx" ON "invoiceSettlement" ("memoId") WHERE "memoId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_targetSalesInvoiceId_idx" ON "invoiceSettlement" ("targetSalesInvoiceId") WHERE "targetSalesInvoiceId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_targetPurchaseInvoiceId_idx" ON "invoiceSettlement" ("targetPurchaseInvoiceId") WHERE "targetPurchaseInvoiceId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_targetMemoId_idx" ON "invoiceSettlement" ("targetMemoId") WHERE "targetMemoId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_appliedDate_idx" ON "invoiceSettlement" ("appliedDate");
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_companyId_idx" ON "invoiceSettlement" ("companyId");
ALTER TABLE "invoiceSettlement" ENABLE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS "SELECT" ON "public"."invoiceSettlement";
CREATE POLICY "SELECT" ON "public"."invoiceSettlement"
FOR SELECT USING (
"companyId" = ANY (
@@ -458,6 +497,7 @@ FOR SELECT USING (
-- Settlement rows are staged while their parent source (payment OR memo) is
-- Draft; the post-payment / post-memo edge function then posts them. Exactly one
-- of paymentId/memoId is set, so the other gate is a NULL no-op.
+DROP POLICY IF EXISTS "INSERT" ON "public"."invoiceSettlement";
CREATE POLICY "INSERT" ON "public"."invoiceSettlement"
FOR INSERT WITH CHECK (
("paymentId" IS NULL OR EXISTS (
@@ -471,6 +511,7 @@ FOR INSERT WITH CHECK (
)
);
+DROP POLICY IF EXISTS "UPDATE" ON "public"."invoiceSettlement";
CREATE POLICY "UPDATE" ON "public"."invoiceSettlement"
FOR UPDATE USING (
("paymentId" IS NULL OR EXISTS (
@@ -484,6 +525,7 @@ FOR UPDATE USING (
)
);
+DROP POLICY IF EXISTS "DELETE" ON "public"."invoiceSettlement";
CREATE POLICY "DELETE" ON "public"."invoiceSettlement"
FOR DELETE USING (
("paymentId" IS NULL OR EXISTS (
diff --git a/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql b/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql
index ef990d5f20..beec31c75c 100644
--- a/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql
+++ b/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql
@@ -12,22 +12,28 @@
-- applications are unchanged (source = paymentId, already gated on payment status).
-- ============================================================
+-- Idempotent: the deploy runner does not wrap a migration in a transaction, so
+-- every step must be safe to re-run after a partial commit.
ALTER TABLE "invoiceSettlement"
- ADD COLUMN "appliedViaPaymentId" TEXT;
+ ADD COLUMN IF NOT EXISTS "appliedViaPaymentId" TEXT;
-- Only memo-sourced settlements (credits) are "applied via" a payment; a cash
-- settlement's source IS the payment.
+ALTER TABLE "invoiceSettlement"
+ DROP CONSTRAINT IF EXISTS "invoiceSettlement_appliedViaPaymentId_check";
ALTER TABLE "invoiceSettlement"
ADD CONSTRAINT "invoiceSettlement_appliedViaPaymentId_check"
CHECK ("appliedViaPaymentId" IS NULL OR "memoId" IS NOT NULL);
-- Deleting the draft payment releases its staged credit applications.
+ALTER TABLE "invoiceSettlement"
+ DROP CONSTRAINT IF EXISTS "invoiceSettlement_appliedViaPaymentId_fkey";
ALTER TABLE "invoiceSettlement"
ADD CONSTRAINT "invoiceSettlement_appliedViaPaymentId_fkey"
FOREIGN KEY ("appliedViaPaymentId") REFERENCES "payment"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
-CREATE INDEX "invoiceSettlement_appliedViaPaymentId_idx"
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_appliedViaPaymentId_idx"
ON "invoiceSettlement" ("appliedViaPaymentId")
WHERE "appliedViaPaymentId" IS NOT NULL;
diff --git a/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql b/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql
index c26a38dea0..18c509a287 100644
--- a/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql
+++ b/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql
@@ -27,6 +27,10 @@ SET "invoiceId" = pi."invoiceId" || '-' || pi."id"
FROM ranked
WHERE ranked."id" = pi."id" AND ranked.rn > 1;
+-- Idempotent: drop-then-add so a retry after a partial commit doesn't trip on an
+-- already-created constraint (the deploy runner is not transactional).
+ALTER TABLE "purchaseInvoice"
+ DROP CONSTRAINT IF EXISTS "purchaseInvoice_invoiceId_key";
ALTER TABLE "purchaseInvoice"
ADD CONSTRAINT "purchaseInvoice_invoiceId_key" UNIQUE ("invoiceId", "companyId");
diff --git a/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql b/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql
index 00a845fe70..cc89c3beb2 100644
--- a/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql
+++ b/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql
@@ -11,29 +11,29 @@
-- ============================================================
-- payment
-CREATE INDEX "payment_currencyCode_idx" ON "payment" ("currencyCode");
-CREATE INDEX "payment_bankAccount_idx" ON "payment" ("bankAccount");
-CREATE INDEX "payment_journalId_idx" ON "payment" ("journalId") WHERE "journalId" IS NOT NULL;
-CREATE INDEX "payment_createdBy_idx" ON "payment" ("createdBy");
-CREATE INDEX "payment_updatedBy_idx" ON "payment" ("updatedBy") WHERE "updatedBy" IS NOT NULL;
-CREATE INDEX "payment_postedBy_idx" ON "payment" ("postedBy") WHERE "postedBy" IS NOT NULL;
-CREATE INDEX "payment_voidedBy_idx" ON "payment" ("voidedBy") WHERE "voidedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_currencyCode_idx" ON "payment" ("currencyCode");
+CREATE INDEX IF NOT EXISTS "payment_bankAccount_idx" ON "payment" ("bankAccount");
+CREATE INDEX IF NOT EXISTS "payment_journalId_idx" ON "payment" ("journalId") WHERE "journalId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_createdBy_idx" ON "payment" ("createdBy");
+CREATE INDEX IF NOT EXISTS "payment_updatedBy_idx" ON "payment" ("updatedBy") WHERE "updatedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_postedBy_idx" ON "payment" ("postedBy") WHERE "postedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "payment_voidedBy_idx" ON "payment" ("voidedBy") WHERE "voidedBy" IS NOT NULL;
-- memo
-CREATE INDEX "memo_currencyCode_idx" ON "memo" ("currencyCode");
-CREATE INDEX "memo_reasonAccount_idx" ON "memo" ("reasonAccount") WHERE "reasonAccount" IS NOT NULL;
-CREATE INDEX "memo_journalId_idx" ON "memo" ("journalId") WHERE "journalId" IS NOT NULL;
-CREATE INDEX "memo_createdBy_idx" ON "memo" ("createdBy");
-CREATE INDEX "memo_updatedBy_idx" ON "memo" ("updatedBy") WHERE "updatedBy" IS NOT NULL;
-CREATE INDEX "memo_postedBy_idx" ON "memo" ("postedBy") WHERE "postedBy" IS NOT NULL;
-CREATE INDEX "memo_voidedBy_idx" ON "memo" ("voidedBy") WHERE "voidedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_currencyCode_idx" ON "memo" ("currencyCode");
+CREATE INDEX IF NOT EXISTS "memo_reasonAccount_idx" ON "memo" ("reasonAccount") WHERE "reasonAccount" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_journalId_idx" ON "memo" ("journalId") WHERE "journalId" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_createdBy_idx" ON "memo" ("createdBy");
+CREATE INDEX IF NOT EXISTS "memo_updatedBy_idx" ON "memo" ("updatedBy") WHERE "updatedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_postedBy_idx" ON "memo" ("postedBy") WHERE "postedBy" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "memo_voidedBy_idx" ON "memo" ("voidedBy") WHERE "voidedBy" IS NOT NULL;
-- invoiceSettlement (paymentId / memoId / target* / appliedViaPaymentId already indexed)
-CREATE INDEX "invoiceSettlement_createdBy_idx" ON "invoiceSettlement" ("createdBy");
+CREATE INDEX IF NOT EXISTS "invoiceSettlement_createdBy_idx" ON "invoiceSettlement" ("createdBy");
-- accountDefault FK columns added by the AR/AP migration (one row per company, so
-- these are convention/consistency indexes — negligible runtime impact).
-CREATE INDEX "accountDefault_customerWriteOffAccount_idx" ON "accountDefault" ("customerWriteOffAccount");
-CREATE INDEX "accountDefault_supplierWriteOffAccount_idx" ON "accountDefault" ("supplierWriteOffAccount") WHERE "supplierWriteOffAccount" IS NOT NULL;
-CREATE INDEX "accountDefault_realizedExchangeGainAccount_idx" ON "accountDefault" ("realizedExchangeGainAccount");
-CREATE INDEX "accountDefault_realizedExchangeLossAccount_idx" ON "accountDefault" ("realizedExchangeLossAccount");
+CREATE INDEX IF NOT EXISTS "accountDefault_customerWriteOffAccount_idx" ON "accountDefault" ("customerWriteOffAccount");
+CREATE INDEX IF NOT EXISTS "accountDefault_supplierWriteOffAccount_idx" ON "accountDefault" ("supplierWriteOffAccount") WHERE "supplierWriteOffAccount" IS NOT NULL;
+CREATE INDEX IF NOT EXISTS "accountDefault_realizedExchangeGainAccount_idx" ON "accountDefault" ("realizedExchangeGainAccount");
+CREATE INDEX IF NOT EXISTS "accountDefault_realizedExchangeLossAccount_idx" ON "accountDefault" ("realizedExchangeLossAccount");
diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.ts
index 6151490f2d..cf5f791710 100644
--- a/packages/ee/src/paperless-parts/lib/lib.ts
+++ b/packages/ee/src/paperless-parts/lib/lib.ts
@@ -1464,7 +1464,8 @@ export async function getCustomerIdAndContactId(
.from("customerContact")
.insert({
customerId,
- contactId
+ contactId,
+ companyId: company.id
})
.select()
.single();
@@ -1598,7 +1599,8 @@ export async function getCustomerLocationIds(
? `${billingInfo.city}, ${billingInfo.state}`
: billingInfo.city || billingInfo.state || "",
customerId,
- addressId
+ addressId,
+ companyId: company.id
})
.select()
.single();
@@ -1721,7 +1723,8 @@ export async function getCustomerLocationIds(
.insert({
name,
customerId,
- addressId
+ addressId,
+ companyId: company.id
})
.select()
.single();
@@ -3022,6 +3025,7 @@ export async function insertQuoteLines(
component.quantities.map((qp) => ({
quoteId,
quoteLineId,
+ companyId,
quantity: qp.quantity ?? 1,
unitPrice: qp.unit_price ?? 0,
leadTime: qp.lead_time ?? 0,