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: currency conversion for purchase orders

Brad Barbin62f082390867
diff --git a/llm/cache/purchasing-conversion-factors.md b/llm/cache/purchasing-conversion-factors.md
new file mode 100644
index 0000000000..32dc2d34fb
--- /dev/null
+++ b/llm/cache/purchasing-conversion-factors.md
@@ -0,0 +1,149 @@
+# Purchasing Conversion Factors System
+
+## Overview
+
+Carbon's purchasing system includes comprehensive support for conversion factors to handle different units of measure between inventory tracking and purchasing transactions. This system allows items to be purchased in one unit of measure while being tracked in inventory in a different unit.
+
+## Database Structure
+
+### Core Tables with Conversion Factor Support
+
+#### Supplier Quote Lines (`supplierQuoteLine`)
+- `conversionFactor`: NUMERIC(10,5) NOT NULL DEFAULT 1
+- `inventoryUnitOfMeasureCode`: Unit used for inventory tracking
+- `purchaseUnitOfMeasureCode`: Unit used for purchasing from supplier
+- Created in migration: `20241202192419_supplier-quotes.sql`
+
+#### Purchase Order Lines (`purchaseOrderLine`)
+- `conversionFactor`: NUMERIC(10,2) DEFAULT 1
+- Added in migration: `20240402052512_purchasing-conversion-factors.sql`
+
+#### Purchase Invoice Lines (`purchaseInvoiceLine`)
+- `conversionFactor`: NUMERIC(10,2) DEFAULT 1
+- Added in migration: `20240402052512_purchasing-conversion-factors.sql`
+
+#### Receipt Lines (`receiptLine`)
+- `conversionFactor`: NUMERIC(10,2) DEFAULT 1
+- Added in migration: `20240402052512_purchasing-conversion-factors.sql`
+
+## UI Implementation
+
+### ConversionFactor Component
+**Location**: `/apps/erp/app/components/Form/ConversionFactor.tsx`
+
+**Key Features**:
+- Interactive modal-based UI for setting conversion factors
+- Bidirectional conversion direction switching (inventory-to-purchased / purchased-to-inventory)
+- Automatic calculation and display of conversion relationships
+- Visual explanation: "There are X inventory units in one purchased unit"
+- Disabled when inventory and purchase units are the same (defaults to 1)
+
+**Usage Example**:
+```typescript
+<ConversionFactor
+ name="conversionFactor"
+ purchasingCode={itemData.purchaseUom}
+ inventoryCode={itemData.inventoryUom}
+ value={itemData.conversionFactor}
+ onChange={(value) => setConversionFactor(value)}
+/>
+```
+
+## Unit Price Calculations
+
+### Supplier Quote Line Pricing
+**Location**: `/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx`
+
+**Key Calculation** (Line 250):
+```typescript
+const inventoryUnitPrice = supplierUnitPrice * exchangeRate / conversionFactor;
+```
+
+**Explanation**:
+1. **Supplier Unit Price**: Price per purchase unit (e.g., $100 per case)
+2. **Exchange Rate**: Currency conversion (e.g., 1.25 USD per CAD)
+3. **Conversion Factor**: Units conversion (e.g., 12 pieces per case)
+4. **Result**: Price per inventory unit (e.g., $100 * 1.25 / 12 = $10.42 per piece)
+
+### Price Display Structure
+- **Supplier Unit Price**: Shows price in purchase UOM with supplier currency
+- **Unit Price**: Shows converted price in inventory UOM with base currency
+- **Conversion Factor**: Applied to convert between purchase and inventory pricing
+
+## Workflow Integration
+
+### Supplier Quote to Purchase Order Flow
+1. Supplier quotes capture conversion factors during line creation
+2. Conversion factors are automatically inherited when creating purchase orders from quotes
+3. Unit prices are recalculated using the conversion factor for inventory costing
+
+### Purchase Order to Receipt Flow
+1. Purchase order lines maintain conversion factors for receiving
+2. Receipt lines inherit conversion factors to properly convert received quantities
+3. Inventory quantities are updated using converted amounts
+
+### Purchase Invoice Processing
+1. Invoice lines include conversion factors for accurate cost allocation
+2. Unit costs are calculated using converted prices for inventory valuation
+
+## Business Logic
+
+### Automatic Conversion Factor Detection
+When selecting items in purchasing forms:
+1. System checks for existing supplier parts with pre-defined conversion factors
+2. Loads item's default inventory unit of measure
+3. Loads supplier's preferred purchase unit of measure
+4. Sets conversion factor from supplier part relationship or defaults to 1
+
+### Validation Rules
+- Conversion factor must be greater than 0
+- Defaults to 1 when inventory and purchase units are identical
+- Required for all purchasing transactions to maintain unit consistency
+
+## Data Models
+
+### Supplier Quote Line Validator
+```typescript
+export const supplierQuoteLineValidator = z.object({
+ conversionFactor: zfd.numeric(z.number().optional()),
+ inventoryUnitOfMeasureCode: zfd.text(z.string().min(1)),
+ purchaseUnitOfMeasureCode: zfd.text(z.string().min(1)),
+ // ... other fields
+});
+```
+
+### Purchase Order Line Validator
+```typescript
+export const purchaseOrderLineValidator = z.object({
+ conversionFactor: zfd.numeric(z.number().optional()),
+ inventoryUnitOfMeasureCode: zfd.text(z.string().optional()),
+ purchaseUnitOfMeasureCode: zfd.text(z.string().optional()),
+ // ... other fields
+});
+```
+
+## Key Benefits
+
+1. **Flexible Purchasing**: Buy in bulk units (cases, rolls, etc.) while tracking individual units
+2. **Accurate Costing**: Proper unit cost calculation for inventory valuation
+3. **Supplier Integration**: Support supplier-specific units of measure
+4. **Audit Trail**: Complete traceability of unit conversions throughout purchase-to-pay cycle
+5. **Multi-Currency Support**: Works in conjunction with exchange rates for international purchasing
+
+## Example Scenarios
+
+### Scenario 1: Bulk Purchase with Individual Tracking
+- **Item**: Screws
+- **Inventory UOM**: Each (EA)
+- **Purchase UOM**: Box
+- **Conversion Factor**: 100 (100 screws per box)
+- **Supplier Price**: $50 per box
+- **Inventory Unit Cost**: $50 ÷ 100 = $0.50 per screw
+
+### Scenario 2: Material Purchase with Different Measurements
+- **Item**: Steel Sheet
+- **Inventory UOM**: Square Feet (SF)
+- **Purchase UOM**: Square Meters (SM)
+- **Conversion Factor**: 10.764 (10.764 SF per SM)
+- **Supplier Price**: €25 per SM
+- **Inventory Unit Cost**: €25 ÷ 10.764 = €2.32 per SF
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20250807094441_fix-purchasing-conversion-factor.sql b/packages/database/supabase/migrations/20250807094441_fix-purchasing-conversion-factor.sql
new file mode 100644
index 0000000000..95d654fbbd
--- /dev/null
+++ b/packages/database/supabase/migrations/20250807094441_fix-purchasing-conversion-factor.sql
@@ -0,0 +1,231 @@
+DROP VIEW IF EXISTS "purchaseOrders";
+DROP VIEW IF EXISTS "purchaseOrderLines";
+DROP VIEW IF EXISTS "purchaseInvoices";
+DROP VIEW IF EXISTS "purchaseInvoiceLines";
+
+-- Fix purchasing conversion factors
+-- The exchange rate should be used to convert FROM supplier currency TO base currency
+-- So we need to divide by exchange rate, not multiply
+
+-- Fix supplierQuoteLinePrice columns
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "taxAmount";
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "quantity"
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+-- Fix purchaseOrderLine columns
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "taxAmount";
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "purchaseQuantity"
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+-- Fix purchaseInvoiceLine columns
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "taxAmount";
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "quantity"
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+-- Fix totalAmount column for purchaseInvoiceLine
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "totalAmount";
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "totalAmount" NUMERIC GENERATED ALWAYS AS (
+ ("supplierUnitPrice" * "quantity" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END) +
+ ("supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END) +
+ ("supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END)
+) STORED;
+
+
+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 "purchaseOrderLines";
+CREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT DISTINCT ON (pl.id)
+ pl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i.name as "itemName",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.description as "itemDescription",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ sp."supplierPartId"
+ FROM "purchaseOrderLine" pl
+ INNER JOIN "purchaseOrder" so ON so.id = pl."purchaseOrderId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = so."supplierId" AND sp."itemId" = i.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";
+
+DROP VIEW IF EXISTS "purchaseInvoiceLines";
+CREATE OR REPLACE VIEW "purchaseInvoiceLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ pl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.name as "itemName",
+ i.description as "itemDescription",
+ ic."unitCost" as "unitCost",
+ sp."supplierPartId"
+ FROM "purchaseInvoiceLine" pl
+ INNER JOIN "purchaseInvoice" pi ON pi.id = pl."invoiceId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = pi."supplierId" AND sp."itemId" = i.id
+);
\ No newline at end of file