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
Prevent deletion of non-Draft invoices
Sidwebworks9deb557e3ad0
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 72cc543d4e..9fc4aab101 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -83,9 +83,27 @@ export async function deletePurchaseInvoice(client: SupabaseClient<Database>,purchaseInvoiceId: string) {- // TODO: this should be a transaction that checks whether it is posted- // and then sets the status of the purchase order back to- // "To Receive and Invoice" | "To Invoice"+ // Check if invoice is in Draft status before deleting+ const invoice = await client+ .from("purchaseInvoice")+ .select("id, status")+ .eq("id", purchaseInvoiceId)+ .single();++ if (invoice.error) {+ return invoice;+ }++ if (invoice.data.status !== "Draft") {+ return {+ data: null,+ error: {+ message: `Cannot delete purchase invoice with status "${invoice.data.status}". Only Draft invoices can be deleted.`,+ code: "INVOICE_NOT_DRAFT"+ }+ };+ }+return client.from("purchaseInvoice").delete().eq("id", purchaseInvoiceId);}@@ -103,9 +121,27 @@ export async function deleteSalesInvoice(client: SupabaseClient<Database>,salesInvoiceId: string) {- // TODO: this should be a transaction that checks whether it is posted- // and then sets the status of the purchase order back to- // "To Receive and Invoice" | "To Invoice"+ // Check if invoice is in Draft status before deleting+ const invoice = await client+ .from("salesInvoice")+ .select("id, status")+ .eq("id", salesInvoiceId)+ .single();++ if (invoice.error) {+ return invoice;+ }++ if (invoice.data.status !== "Draft") {+ return {+ data: null,+ error: {+ message: `Cannot delete sales invoice with status "${invoice.data.status}". Only Draft invoices can be deleted.`,+ code: "INVOICE_NOT_DRAFT"+ }+ };+ }+return client.from("salesInvoice").delete().eq("id", salesInvoiceId);}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 7da731c605..a4b99b1648 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -65097,6 +65097,51 @@ export default {tags: ["(rpc) upsert_to_search_index"],},},+ "/rpc/prevent_posted_sales_invoice_deletion": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_new: {+ format: "jsonb",+ },+ p_old: {+ format: "jsonb",+ },+ p_operation: {+ format: "text",+ type: "string",+ },+ p_table: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_table", "p_operation", "p_new", "p_old"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) prevent_posted_sales_invoice_deletion"],+ },+ },"/rpc/get_active_job_count": {post: {parameters: [@@ -65584,6 +65629,51 @@ export default {tags: ["(rpc) get_direct_descendants_of_tracked_entity"],},},+ "/rpc/prevent_posted_purchase_invoice_deletion": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_new: {+ format: "jsonb",+ },+ p_old: {+ format: "jsonb",+ },+ p_operation: {+ format: "text",+ type: "string",+ },+ p_table: {+ format: "text",+ type: "string",+ },+ },+ required: ["p_table", "p_operation", "p_new", "p_old"],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) prevent_posted_purchase_invoice_deletion"],+ },+ },"/rpc/get_customer_ids_with_customer_permission": {post: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 42c490c16c..c52242bff5 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -48677,14 +48677,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -51808,14 +51808,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -56872,6 +56872,14 @@ export type Database = {Args: { p_company_id: string }Returns: undefined}+ prevent_posted_purchase_invoice_deletion: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }+ prevent_posted_sales_invoice_deletion: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }search_company_index: {Args: {p_company_id: stringdiff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex 67a1cf17a0..0ff5d47026 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -256,14 +256,24 @@ serve(async (req: Request) => {const uninvoicedLines = purchaseOrderLines?.data?.reduce<(typeof purchaseOrderLines)["data"]>((acc, line) => {- if (line?.quantityToInvoice && line.quantityToInvoice > 0) {+ if (+ line?.quantityToInvoice &&+ line.quantityToInvoice > 0 &&+ !line.invoicedComplete+ ) {acc.push(line);}return acc;}, []);- const uninvoicedSubtotal = uninvoicedLines?.reduce((acc, line) => {+ if (!uninvoicedLines || uninvoicedLines.length === 0) {+ throw new Error(+ "No lines available to invoice. All lines may already be marked as invoiced complete."+ );+ }++ const uninvoicedSubtotal = uninvoicedLines.reduce((acc, line) => {if (line?.quantityToInvoice &&line.unitPrice &&@@ -331,40 +341,30 @@ serve(async (req: Request) => {}).execute();- const purchaseInvoiceLines = uninvoicedLines?.reduce<- Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][]- >((acc, line) => {- if (- line?.quantityToInvoice &&- line.quantityToInvoice > 0 &&- !line.invoicedComplete- ) {- acc.push({- invoiceId: purchaseInvoiceId,- invoiceLineType: line.purchaseOrderLineType,- purchaseOrderId: line.purchaseOrderId,- purchaseOrderLineId: line.id,- itemId: line.itemId,- locationId: line.locationId,- shelfId: line.shelfId,- accountNumber: line.accountNumber,- assetId: line.assetId,- description: line.description,- quantity: line.quantityToInvoice,- supplierUnitPrice: line.supplierUnitPrice ?? 0,- supplierShippingCost: line.supplierShippingCost ?? 0,- supplierTaxAmount: line.supplierTaxAmount ?? 0,- purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,- inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,- conversionFactor: line.conversionFactor,- exchangeRate: line.exchangeRate ?? 1,- jobOperationId: line.jobOperationId,- companyId,- createdBy: userId,- });- }- return acc;- }, []);+ const purchaseInvoiceLines: Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][] =+ uninvoicedLines.map((line) => ({+ invoiceId: purchaseInvoiceId,+ invoiceLineType: line.purchaseOrderLineType,+ purchaseOrderId: line.purchaseOrderId,+ purchaseOrderLineId: line.id,+ itemId: line.itemId,+ locationId: line.locationId,+ shelfId: line.shelfId,+ accountNumber: line.accountNumber,+ assetId: line.assetId,+ description: line.description,+ quantity: line.quantityToInvoice,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,+ supplierShippingCost: line.supplierShippingCost ?? 0,+ supplierTaxAmount: line.supplierTaxAmount ?? 0,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,+ conversionFactor: line.conversionFactor,+ exchangeRate: line.exchangeRate ?? 1,+ jobOperationId: line.jobOperationId,+ companyId,+ createdBy: userId,+ }));await trx.insertInto("purchaseInvoiceLine")diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 42c490c16c..21fd9baa0e 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -56872,6 +56872,14 @@ export type Database = {Args: { p_company_id: string }Returns: undefined}+ prevent_posted_purchase_invoice_deletion: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }+ prevent_posted_sales_invoice_deletion: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }search_company_index: {Args: {p_company_id: stringdiff --git a/packages/database/supabase/migrations/20260205180700_prevent-posted-invoice-deletion.sql b/packages/database/supabase/migrations/20260205180700_prevent-posted-invoice-deletion.sqlnew file mode 100644index 0000000000..ee806de3a2--- /dev/null+++ b/packages/database/supabase/migrations/20260205180700_prevent-posted-invoice-deletion.sql@@ -0,0 +1,48 @@+-- Prevent deletion of non-Draft purchase and sales invoices+-- Uses the event system sync interceptor pattern++-- 1. Create interceptor function for purchase invoices+CREATE OR REPLACE FUNCTION prevent_posted_purchase_invoice_deletion(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+AS $$+BEGIN+ -- Only check DELETE operations+ IF p_operation = 'DELETE' THEN+ -- Check if the invoice status is not Draft+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete purchase invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$$;++-- 2. Create interceptor function for sales invoices+CREATE OR REPLACE FUNCTION prevent_posted_sales_invoice_deletion(+ p_table TEXT,+ p_operation TEXT,+ p_new JSONB,+ p_old JSONB+)+RETURNS VOID+LANGUAGE plpgsql+AS $$+BEGIN+ -- Only check DELETE operations+ IF p_operation = 'DELETE' THEN+ -- Check if the invoice status is not Draft+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete sales invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$$;++-- 3. Attach event triggers with sync interceptors+SELECT attach_event_trigger('purchaseInvoice', ARRAY['prevent_posted_purchase_invoice_deletion']::TEXT[]);+SELECT attach_event_trigger('salesInvoice', ARRAY['prevent_posted_sales_invoice_deletion']::TEXT[]);