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
feat(purchasing): store supplier part prices in the supplier's currency (#1885)
Brad Barbin1d31b4923f99
diff --git a/.claude/rules/purchasing-conversion-factors.md b/.claude/rules/purchasing-conversion-factors.mdindex 3a37e8f171..fbd4861737 100644--- a/.claude/rules/purchasing-conversion-factors.md+++ b/.claude/rules/purchasing-conversion-factors.md@@ -3,6 +3,8 @@ paths:- "apps/erp/app/modules/purchasing/**"- "apps/erp/app/components/Form/ConversionFactor.tsx"- "packages/server-functions/src/{create,convert,update-purchased-prices}/index.ts"+ - "packages/server-functions/src/finalize-supplier-quote/index.ts"+ - "packages/database/src/supplier-part-price.ts"- "packages/database/supabase/migrations/*conversion*.sql"---@@ -98,6 +100,32 @@ divide price by it for inventory unit price (`SupplierQuoteLinePricing.tsx`).clamped to 2 dp and rounded distributor prices like `0.164` on entry), so thefactor is now stored exactly as entered. See `.claude/rules/numeric-precision.md`.+## Supplier part prices: per purchase unit, in the part's currency++`supplierPart.supplierUnitPrice` and `supplierPartPrice.supplierUnitPrice` (renamed+from `unitPrice` in `20261009181437_supplier-part-currency.sql`) hold the price as+the supplier quoted it: per PURCHASE unit, in `supplierPart.currencyCode` (NULL =+the company base currency; the migration backfilled base). Break quantities are+purchase quantities. Nothing stores a converted copy — every reader converts at+the CURRENT rate through `@carbon/database/supplier-part-price`:++- **Onto a purchase document** (PO/invoice line forms, planning orders, kanban,+ replacement PO, return lines): `convertUnitPrice(price, partCurrency,+ documentCurrency)` — identity when the codes match, else through base at the+ part currency's `get_exchange_rate` and the document's stamped rate. ERP forms+ load `getSupplierPartPricing` and call `resolveSupplierPrice`.+- **Into quote costing** (base per INVENTORY unit): `buildSupplierPriceMap`, used+ by `getSupplierPriceBreaksForItems` (ERP) and its `methods.ts` mirror; a part+ whose currency has no rate is left out, never costed at par.+- **Writers that learn a price** (`finalize-supplier-quote`, `convert`+ supplierQuoteToPurchaseOrder, `update-purchased-prices`) record the document's+ `supplierUnitPrice` per purchase unit. A part they create takes the document's+ currency; an existing part keeps its own and the price is converted into it+ (`getSupplierPartPriceConverter`, `server-functions/src/lib`).++Before this, convert and finalize stored base per INVENTORY unit while every+reader assumed per purchase unit; the migration repaired those rows.+## UI component`apps/erp/app/components/Form/ConversionFactor.tsx` — modal input showing bothdiff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex cd5045e9e2..caa71de6fc 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -410,6 +410,18 @@ export const currencyValidator = z.object({)});+// The currency drawer saves its config and its exchange rate with one button.+// The rate is pinned as an override only when it differs from the rate in+// effect, so saving the config never freezes the market rate.+export const currencyFormValidator = currencyValidator.extend({+ rate: zfd.numeric(+ z.number().positive({ message: "Rate must be positive" }).optional()+ ),+ // The rate the drawer opened with. A submitted rate equal to it was not+ // edited, so it is never pinned — even if the market moved meanwhile.+ displayedRate: zfd.numeric(z.number().optional())+});+export const exchangeRateOverrideValidator = z.object({currencyCode: z.string().trim().min(1, { message: "Currency is required" }),rate: zfd.numeric(z.number().positive({ message: "Rate must be positive" }))diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.tsindex e7616d7f4e..17611ea428 100644--- a/apps/erp/app/modules/accounting/accounting.server.ts+++ b/apps/erp/app/modules/accounting/accounting.server.ts@@ -4,7 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import type { Database } from "@carbon/database";+import type { Database, Json } from "@carbon/database";import { getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";import { getNextSequence } from "@carbon/database/sequence";@@ -35,6 +35,70 @@ import {runPostingTargets} from "./accounting.utils";+/**+ * Saves a currency's config and, when given, pins its exchange rate as a+ * company override — in ONE transaction, so a failed pin never leaves the+ * config saved behind a "failed to save" message. The route has already+ * checked `update: accounting`; the writes are scoped to the company group+ * (config) and the company (override). Returns null when the currency is not+ * in the group.+ */+export async function saveCurrencyWithRateOverride(+ db: Kysely<KyselyDatabase>,+ args: {+ currencyId: string;+ companyId: string;+ companyGroupId: string;+ userId: string;+ config: {+ decimalPlaces: number;+ historicalExchangeRate: number | null;+ customFields: Json;+ };+ overrideRate: number | null;+ }+): Promise<{ code: string } | null> {+ return db.transaction().execute(async (trx) => {+ const currency = await trx+ .updateTable("currency")+ .set({+ decimalPlaces: args.config.decimalPlaces,+ historicalExchangeRate: args.config.historicalExchangeRate,+ customFields: args.config.customFields,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", args.currencyId)+ .where("companyGroupId", "=", args.companyGroupId)+ .returning("code")+ .executeTakeFirst();++ if (!currency) return null;++ if (args.overrideRate !== null) {+ // Update-in-place on conflict so re-pinning keeps the original creator.+ await trx+ .insertInto("exchangeRateOverride")+ .values({+ companyId: args.companyId,+ currencyCode: currency.code,+ rate: args.overrideRate,+ createdBy: args.userId+ })+ .onConflict((oc) =>+ oc.columns(["companyId", "currencyCode"]).doUpdateSet({+ rate: args.overrideRate as number,+ updatedBy: args.userId,+ updatedAt: datetime.timestamp()+ })+ )+ .execute();+ }++ return { code: currency.code };+ });+}+/** The company's business day, `YYYY-MM-DD`. */export async function getCompanyToday(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsxindex 6be3b293f0..075e724466 100644--- a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx@@ -65,8 +65,8 @@ import {import { usePermissions, useUser } from "~/hooks";import { path } from "~/utils/path";import {- currencyValidator,- exchangeRateOverrideValidator+ currencyFormValidator,+ type currencyValidator} from "../../accounting.models";import ExchangeRateSourceBadge from "./ExchangeRateSourceBadge";@@ -161,67 +161,49 @@ const CurrencyForm = ({</DrawerTitle></DrawerHeader><DrawerBody>- {isEditing && (- <ValidatedForm- validator={exchangeRateOverrideValidator}- method="post"- action={path.to.exchangeRate(initialValues.id!)}- defaultValues={{- currencyCode: initialValues.code,- rate: rate ?? undefined- }}- className="w-full mb-6"- >- <Hidden name="intent" value="override" />- <Hidden name="currencyCode" value={initialValues.code} />- <VStack spacing={4}>- <NumberField- name="rate"- label={t`Exchange Rate`}- termId="exchange-rate"- minValue={0}- step={INPUT_STEP.exchangeRate}- formatOptions={INPUT_FORMAT.exchangeRate}- helperText={exchangeRateHelperText}- isDisabled={isBaseCurrency}- />- <HStack className="w-full justify-between">- <ExchangeRateSourceBadge source={rateSource} />- {!isBaseCurrency && (- <HStack>- {rateSource === "override" && (- <Button- type="button"- variant="secondary"- isDisabled={isDisabled}- isLoading={resetFetcher.state !== "idle"}- onClick={onResetToMarketRate}- >- {t`Reset to market rate`}- </Button>- )}- <Submit isDisabled={isDisabled}>{t`Save Rate`}</Submit>- </HStack>- )}- </HStack>- </VStack>- </ValidatedForm>- )}-<ValidatedFormid={CONFIG_FORM_ID}- validator={currencyValidator}+ validator={currencyFormValidator}method="post"action={isEditing? path.to.exchangeRate(initialValues.id!): path.to.newExchangeRate}- defaultValues={initialValues}+ defaultValues={{ ...initialValues, rate: rate ?? undefined }}className="w-full"><Hidden name="id" />+ {rate !== null && <Hidden name="displayedRate" value={rate} />}<VStack spacing={4}>+ {isEditing && (+ <>+ <NumberField+ name="rate"+ label={t`Exchange Rate`}+ termId="exchange-rate"+ minValue={0}+ step={INPUT_STEP.exchangeRate}+ formatOptions={INPUT_FORMAT.exchangeRate}+ helperText={exchangeRateHelperText}+ isDisabled={isBaseCurrency}+ />+ <HStack className="w-full justify-between">+ <ExchangeRateSourceBadge source={rateSource} />+ {!isBaseCurrency && rateSource === "override" && (+ <Button+ type="button"+ variant="secondary"+ isDisabled={isDisabled}+ isLoading={resetFetcher.state !== "idle"}+ onClick={onResetToMarketRate}+ >+ {t`Reset to market rate`}+ </Button>+ )}+ </HStack>+ </>+ )}<Input name="name" label={t`Name`} isReadOnly /><Input name="code" label={t`Code`} isReadOnly /><NumberFielddiff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsxindex b9c13628cc..c51a51920f 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { convertUnitPrice } from "@carbon/database/supplier-part-price";import {Combobox,DatePicker,@@ -31,6 +32,7 @@ import {TabsContent,TabsList,TabsTrigger,+ toast,useDisclosure,useMount,VStack@@ -73,12 +75,13 @@ import type { PurchaseInvoice } from "~/modules/invoicing";import { purchaseInvoiceLineValidator } from "~/modules/invoicing";import {EACH_UNIT_OF_MEASURE_CODE,- getSupplierPartPriceBreaks+ getSupplierPartPricing} from "~/modules/items";import {type ItemType,itemType,- resolveSupplierPrice+ resolveSupplierPrice,+ type SupplierPartPricing} from "~/modules/shared";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -150,7 +153,9 @@ const PurchaseInvoiceLineForm = ({minimumOrderQuantity?: number;taxAmount: number;taxPercent: number;- priceBreaks: Array<{ quantity: number; unitPrice: number }>;+ pricing: SupplierPartPricing | null;+ // In the INVOICE's currency: the price used when the supplier part has+ // none for the quantity.fallbackUnitPrice: number;}>({itemId: initialValues.itemId ?? "",@@ -165,14 +170,16 @@ const PurchaseInvoiceLineForm = ({minimumOrderQuantity: undefined,taxAmount: initialValues.supplierTaxAmount ?? 0,taxPercent: initialValues.taxPercent ?? 0,- priceBreaks: [],- // fallbackUnitPrice is BASE currency, matching what resolveSupplierPrice- // expects. initialValues.supplierUnitPrice is the SUPPLIER's, so divide.- fallbackUnitPrice:- (initialValues.supplierUnitPrice ?? 0) /- (routeData?.purchaseInvoice?.exchangeRate || 1)+ pricing: null,+ fallbackUnitPrice: initialValues.supplierUnitPrice ?? 0});+ // The invoice's currency and rate: what a supplier part's price converts into.+ const invoiceCurrencyRate = {+ currencyCode: invoiceCurrency,+ exchangeRate: routeData?.purchaseInvoice?.exchangeRate ?? 1+ };+// Re-derive the tax amount when the line's base changes — never on mount, so// a saved manual override survives being reopened.const itemTax = useTaxPair({@@ -272,7 +279,8 @@ const PurchaseInvoiceLineForm = ({setIndirectData((d) => ({ ...d, taxPercent: percent, taxAmount: amount }))});- // Load price breaks+ // Load price breaks. The part's own price is left out: below every break+ // the line keeps the price it already has.useMount(() => {if (!isEditing || !initialValues.itemId) return;const supplierId = routeData?.purchaseInvoice?.supplierId;@@ -281,18 +289,25 @@ const PurchaseInvoiceLineForm = ({(async () => {const supplierPart = await carbon.from("supplierPart")- .select("id")+ .select("id, companyId, currencyCode, supplierUnitPrice").eq("itemId", initialValues.itemId!).eq("companyId", company.id).eq("supplierId", supplierId).maybeSingle();if (supplierPart?.data?.id) {- const breaks = await getSupplierPartPriceBreaks(+ const pricing = await getSupplierPartPricing(carbon,- supplierPart.data.id+ supplierPart.data,+ company.baseCurrencyCode,+ invoiceCurrency);- setItemData((d) => ({ ...d, priceBreaks: breaks }));+ if (pricing.data) {+ setItemData((d) => ({+ ...d,+ pricing: { ...pricing.data, supplierUnitPrice: null }+ }));+ }}})();});@@ -335,7 +350,7 @@ const PurchaseInvoiceLineForm = ({minimumOrderQuantity: undefined,taxAmount: 0,taxPercent: 0,- priceBreaks: [],+ pricing: null,fallbackUnitPrice: 0});};@@ -379,24 +394,32 @@ const PurchaseInvoiceLineForm = ({const itemCost = item?.data?.itemCost?.[0];const itemReplenishment = item?.data?.itemReplenishment;- const exchangeRate = routeData?.purchaseInvoice?.exchangeRate ?? 1;const initialQty = supplierPart?.data?.minimumOrderQuantity ?? 1;- // BASE currency: supplierPart.unitPrice and itemCost.unitCost are both- // stored in base. resolveSupplierPrice converts to the supplier's.- const baseFallback =- supplierPart?.data?.unitPrice !== null &&- supplierPart?.data?.unitPrice !== undefined- ? supplierPart.data.unitPrice- : (itemCost?.unitCost ?? 0);+ // The item's cost is in BASE currency; the line wants the invoice's.+ const fallbackUnitPrice = convertUnitPrice(+ itemCost?.unitCost ?? 0,+ { currencyCode: company.baseCurrencyCode, exchangeRate: 1 },+ invoiceCurrencyRate+ );- const breaks = supplierPart?.data?.id- ? await getSupplierPartPriceBreaks(carbon, supplierPart.data.id)- : [];+ // The supplier's price is in the supplier part's currency, converted+ // into the invoice's at the current rate.+ const pricing = supplierPart?.data+ ? await getSupplierPartPricing(+ carbon,+ supplierPart.data,+ company.baseCurrencyCode,+ invoiceCurrency+ )+ : null;+ if (pricing?.error) {+ toast.error(pricing.error.message);+ }const resolvedPrice = resolveSupplierPrice(- breaks,+ pricing?.data ?? null,initialQty,- baseFallback,- exchangeRate+ invoiceCurrencyRate,+ fallbackUnitPrice);// A service is always bought and "stocked" in EA, 1:1.@@ -424,8 +447,8 @@ const PurchaseInvoiceLineForm = ({storageUnitId: inventory.data?.defaultStorageUnitId ?? null,taxAmount: 0,taxPercent: 0,- priceBreaks: breaks,- fallbackUnitPrice: baseFallback+ pricing: pricing?.data ?? null,+ fallbackUnitPrice});if (item.data?.type) {@@ -654,16 +677,14 @@ const PurchaseInvoiceLineForm = ({label={t`Quantity`}value={itemData.quantity}onChange={(value) => {- const exchangeRate =- routeData?.purchaseInvoice?.exchangeRate ?? 1;setItemData((d) => ({...d,quantity: value,supplierUnitPrice: resolveSupplierPrice(- d.priceBreaks,+ d.pricing,value,- d.fallbackUnitPrice,- exchangeRate+ invoiceCurrencyRate,+ d.fallbackUnitPrice)}));}}diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 32e02d8b83..f454a5cd13 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -53,7 +53,7 @@ pnpm --filter @carbon/erp test| `itemPostingGroup` | Maps item categories to GL accounts || `unitOfMeasure` | UoM definitions || `configurationParameter` / `configurationRule` / `configurationParameterGroup` | Product configurator |-| `supplierPart` / `supplierPartPrice` | Supplier-item pricing with conversion factors and price breaks |+| `supplierPart` / `supplierPartPrice` | Supplier-item pricing with conversion factors and price breaks. `supplierUnitPrice` is per purchase unit in `supplierPart.currencyCode` (NULL = base); readers convert at today's rate (`.claude/rules/purchasing-conversion-factors.md`) || `pickMethod` | Default storage unit and pick strategy per item/location || `itemShelfLife` | Shelf life tracking configuration per item || `itemSupersession` | Item replacement chains |@@ -70,7 +70,8 @@ pnpm --filter @carbon/erp test- `createRevision(client, db, args)` / `activateMethodVersion` — revision and version management; the revision's item row and the planning and purchasing setup it inherits from the source are written in one Kysely transaction, gated by `assert_company_access(companyId, 'parts_create')` through the caller's client- `updateItemMethodAndSourcing` — cascades replenishment/sourcing changes to Draft method materials- `getItemCost` / `getItemQuantities` / `getItemDemand` / `getItemSupply` — cost and planning reads-- `getSupplierParts` / `getSupplierPriceBreaksForItems` / `lookupBuyPrice` — vendor pricing+- `getSupplierParts` / `getSupplierPriceBreaksForItems` / `lookupBuyPrice` — vendor pricing (the latter two in base per inventory unit, for costing); `getSupplierPartPricing` — a part's price + breaks with its currency's current rate, for `resolveSupplierPrice` on a purchase document+- `getSupplierPartsBySupplier` — every active supplier part naming one supplier, with its item embedded, paged past the 1000-row cap (`fetchAllRecords`); backs the supplier's **Parts** tab (`x+/supplier+/$supplierId.parts.tsx`, `purchasing/ui/Supplier/SupplierParts.tsx`, client-side search). Its New / edit drawers post to the picked item's own purchasing routes (`SupplierPartForm` with `selectItem`), so every item-type edit route returns `{ success }` instead of redirecting- `upsertPickMethodWithShelfLife` — pick method with shelf life configuration- `getConfigurationParameters` / `getConfigurationRules` — product configurator- `createItemDocumentUploadUrl` — MCP file upload (step 1): presigned URL for an item document (`parts/{itemId}` folder); pair with `documents_insertUploadedDocument`. See `.claude/rules/mcp-tools-reference.md` → "File uploads"diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex aca28c5c18..2801fa164a 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -1009,7 +1009,9 @@ export const supplierPartValidator = z.object({minimumOrderQuantity: zfd.numeric(z.number().min(0)),orderMultiple: zfd.numeric(z.number().min(1)).optional(),conversionFactor: zfd.numeric(z.number().min(0)),- unitPrice: zfd.numeric(z.number().min(0).optional())+ // Per purchase unit, in currencyCode — the price as the supplier quoted it.+ currencyCode: zfd.text(z.string().optional()),+ supplierUnitPrice: zfd.numeric(z.number().min(0).optional())});export const toolValidator = applyStorageAndShelfLifeRefines(diff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsindex 09056430c0..ab537d6277 100644--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -503,7 +503,8 @@ function supplierPart(over: Record<string, unknown> = {}) {minimumOrderQuantity: 10,orderMultiple: 5,conversionFactor: 12,- unitPrice: 4.5,+ currencyCode: "USD",+ supplierUnitPrice: 4.5,active: true,customFields: null,tags: null,@@ -549,7 +550,7 @@ describe("diffMethod — supplier parts", () => {supplierPart({ id: "sp-2", supplierId: "sup-2" })],targetSupplierParts: [- supplierPart({ id: "sp-9", itemId: "item-b", unitPrice: 5 }),+ supplierPart({ id: "sp-9", itemId: "item-b", supplierUnitPrice: 5 }),supplierPart({ id: "sp-11", itemId: "item-b", supplierId: "sup-3" })]});@@ -561,7 +562,7 @@ describe("diffMethod — supplier parts", () => {["removed", "sup-2"]]);expect(supplierParts[0].changedFields).toEqual({- unitPrice: { before: 4.5, after: 5 }+ supplierUnitPrice: { before: 4.5, after: 5 }});});diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex cafd0ca927..b97c1e5ba4 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -3,13 +3,22 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Database, Json } from "@carbon/database";-import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";+import {+ fetchAllFromTable,+ fetchAllRecords,+ getCompanyTimeZone+} from "@carbon/database";import type {ExpressionBuilder,Kysely,KyselyDatabase,KyselyTx} from "@carbon/database/client";+import {+ buildSupplierPriceMap,+ type SupplierPriceBreak,+ supplierPartCurrency+} from "@carbon/database/supplier-part-price";import { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";@@ -35,8 +44,8 @@ import {lookupBuyPriceFromMap,type MethodType,normalizeOperationSourceIds,- type PriceBreak,type SourcingType,+ type SupplierPartPricing,type SupplierPriceMap} from "../shared";import { updateSortOrder } from "../shared/sort-order";@@ -329,7 +338,8 @@ async function copyItemPlanningAndPurchasing("minimumOrderQuantity","orderMultiple","conversionFactor",- "unitPrice",+ "supplierUnitPrice",+ "currencyCode","active","customFields","tags",@@ -347,7 +357,8 @@ async function copyItemPlanningAndPurchasing("minimumOrderQuantity","orderMultiple","conversionFactor",- "unitPrice",+ "supplierUnitPrice",+ "currencyCode","active","customFields","tags",@@ -367,7 +378,7 @@ async function copyItemPlanningAndPurchasing(.columns(["supplierPartId","quantity",- "unitPrice",+ "supplierUnitPrice","leadTime","sourceType","sourceDocumentId",@@ -390,7 +401,7 @@ async function copyItemPlanningAndPurchasing(.select((eb) => ["target.id as supplierPartId","price.quantity",- "price.unitPrice",+ "price.supplierUnitPrice","price.leadTime","price.sourceType","price.sourceDocumentId",@@ -2487,6 +2498,26 @@ export async function getSupplierParts(.eq("companyId", companyId);}+/** @mcp read */+export async function getSupplierPartsBySupplier(+ client: SupabaseClient<Database>,+ supplierId: string,+ companyId: string+) {+ // Paged past PostgREST's 1000-row cap: a distributor can supply thousands of parts.+ return fetchAllRecords(() =>+ client+ .from("supplierPart")+ .select(+ "*, item(id, readableIdWithRevision, name, type, thumbnailPath, unitOfMeasureCode)"+ )+ .eq("active", true)+ .eq("supplierId", supplierId)+ .eq("companyId", companyId)+ .order("id")+ );+}+/** @mcp read */export async function getTool(client: SupabaseClient<Database>,@@ -6633,11 +6664,13 @@ export async function upsertTool(}/**- * Batch pre-fetch supplier price breaks for multiple items.- * Builds a SupplierPriceMap keyed by itemId, pooling price break- * tiers from ALL suppliers for each item.+ * Batch pre-fetch supplier pricing for multiple items, for costing.+ * Builds a SupplierPriceMap keyed by itemId, pooling the price breaks of ALL+ * suppliers for each item, converted to base currency per INVENTORY unit at+ * today's exchange rates (`buildSupplierPriceMap`).** Used by the quote loader to pre-load pricing data for BOM costing.+ * Mirrored in `packages/database/src/methods.ts`.* @mcp read*/export async function getSupplierPriceBreaksForItems(@@ -6648,55 +6681,59 @@ export async function getSupplierPriceBreaksForItems(const supplierParts = await client.from("supplierPart")- .select("id, itemId, unitPrice")+ .select(+ "id, itemId, companyId, currencyCode, conversionFactor, supplierUnitPrice"+ ).in("itemId", itemIds);if (!supplierParts.data?.length) return {};+ const companyId = supplierParts.data[0].companyId;const supplierPartIds = supplierParts.data.map((sp) => sp.id);- const prices = await client- .from("supplierPartPrice")- .select("supplierPartId, quantity, unitPrice")- .in("supplierPartId", supplierPartIds)- .order("quantity", { ascending: true });-- // Build a lookup from supplierPartId → itemId- const spToItem = new Map<string, string>();- for (const sp of supplierParts.data) {- spToItem.set(sp.id, sp.itemId);- }-- const result: SupplierPriceMap = {};-- // Initialize entries with fallback prices- for (const sp of supplierParts.data) {- if (!result[sp.itemId]) {- result[sp.itemId] = { priceBreaks: [], fallbackUnitPrice: null };- }- const current = result[sp.itemId].fallbackUnitPrice;- if (sp.unitPrice != null && (current === null || sp.unitPrice < current)) {- result[sp.itemId].fallbackUnitPrice = sp.unitPrice;- }- }+ const [prices, rates, company] = await Promise.all([+ client+ .from("supplierPartPrice")+ .select("supplierPartId, quantity, supplierUnitPrice")+ .in("supplierPartId", supplierPartIds)+ .eq("companyId", companyId),+ client.rpc("get_exchange_rates", { p_company_id: companyId }),+ client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single()+ ]);- // Add price breaks+ const breaksByPart = new Map<string, SupplierPriceBreak[]>();for (const price of prices.data ?? []) {- const itemId = spToItem.get(price.supplierPartId);- if (itemId && result[itemId]) {- result[itemId].priceBreaks.push({- quantity: price.quantity,- unitPrice: price.unitPrice- });- }+ const breaks = breaksByPart.get(price.supplierPartId) ?? [];+ breaks.push({+ quantity: price.quantity,+ supplierUnitPrice: price.supplierUnitPrice+ });+ breaksByPart.set(price.supplierPartId, breaks);}- return result;+ return buildSupplierPriceMap(+ supplierParts.data.map((sp) => ({+ itemId: sp.itemId,+ currencyCode: sp.currencyCode,+ conversionFactor: sp.conversionFactor,+ supplierUnitPrice: sp.supplierUnitPrice,+ priceBreaks: breaksByPart.get(sp.id) ?? []+ })),+ Object.fromEntries(+ (rates.data ?? []).map((rate) => [rate.currencyCode, rate.rate])+ ),+ company.data?.baseCurrencyCode ?? "USD"+ );}/**- * Async price lookup across ALL suppliers for an item.- * Delegates to getSupplierPriceBreaksForItems + lookupBuyPriceFromMap.+ * Async price lookup across ALL suppliers for an item, in base currency per+ * inventory unit. Delegates to getSupplierPriceBreaksForItems ++ * lookupBuyPriceFromMap.** Used in quote creation where the specific supplier isn't known.* @mcp read@@ -6712,23 +6749,82 @@ export async function lookupBuyPrice(}/**- * Fetch price breaks array for a specific supplier part.- * Used by PO and Invoice forms to cache breaks in state.+ * A supplier part's pricing for a purchase document: its price and breaks as+ * the supplier quoted them (per purchase unit, in the part's currency), with+ * that currency's CURRENT exchange rate, so `resolveSupplierPrice` can convert+ * them into the document's currency. A part in the document's own currency+ * needs no rate; a missing rate is an error, never par.+ * @mcp read+ */+export async function getSupplierPartPricing(+ client: SupabaseClient<Database>,+ supplierPart: {+ id: string;+ companyId: string;+ currencyCode: string | null;+ supplierUnitPrice: number | null;+ },+ baseCurrencyCode: string,+ documentCurrencyCode: string+): Promise<+ | { data: SupplierPartPricing; error: null }+ | { data: null; error: { message: string } }+> {+ const currencyCode = supplierPartCurrency(+ supplierPart.currencyCode,+ baseCurrencyCode+ );+ const needsRate =+ currencyCode !== baseCurrencyCode && currencyCode !== documentCurrencyCode;++ const [priceBreaks, rate] = await Promise.all([+ getSupplierPartPriceBreaks(client, supplierPart.id),+ needsRate+ ? client.rpc("get_exchange_rate", {+ p_company_id: supplierPart.companyId,+ p_currency_code: currencyCode+ })+ : Promise.resolve({ data: 1, error: null })+ ]);++ if (rate.error || !rate.data) {+ return {+ data: null,+ error: {+ message: rate.error?.message ?? `No exchange rate for ${currencyCode}`+ }+ };+ }++ return {+ data: {+ priceBreaks,+ supplierUnitPrice: supplierPart.supplierUnitPrice,+ currency: { currencyCode, exchangeRate: Number(rate.data) }+ },+ error: null+ };+}++/**+ * Fetch price breaks array for a specific supplier part, as the supplier+ * quoted them: purchase quantity and price per purchase unit, in the supplier+ * part's currency. Used by PO and Invoice forms to cache breaks in state.* @mcp read*/export async function getSupplierPartPriceBreaks(client: SupabaseClient<Database>,supplierPartId: string-): Promise<PriceBreak[]> {+): Promise<SupplierPriceBreak[]> {const result = await client.from("supplierPartPrice")- .select("quantity, unitPrice")+ .select("quantity, supplierUnitPrice").eq("supplierPartId", supplierPartId).order("quantity", { ascending: true });return (result.data ?? []).map((pb) => ({quantity: pb.quantity,- unitPrice: pb.unitPrice+ supplierUnitPrice: pb.supplierUnitPrice}));}// =============================================================================diff --git a/apps/erp/app/modules/items/types.ts b/apps/erp/app/modules/items/types.tsindex 38f58be8f7..6019de9715 100644--- a/apps/erp/app/modules/items/types.ts+++ b/apps/erp/app/modules/items/types.ts@@ -38,6 +38,7 @@ import type {getService,getServices,getSupplierParts,+ getSupplierPartsBySupplier,getTool,getTools,getUnitOfMeasure,@@ -235,6 +236,10 @@ export type SupplierPart = NonNullable<Awaited<ReturnType<typeof getSupplierParts>>["data"]>[number];+export type SupplierPartWithItem = NonNullable<+ Awaited<ReturnType<typeof getSupplierPartsBySupplier>>["data"]+>[number];+export type Tool = Database["public"]["Views"]["tools"]["Row"];export type ToolListItem = NonNullable<diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsxindex 1f441fb4e7..7fa856f2df 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeDiffViewer.tsx@@ -77,7 +77,8 @@ const FIELD_LABELS: Record<string, string> = {key: "Parameter",toolId: "Tool",supplierPartId: "Part #",- unitPrice: "Unit price",+ supplierUnitPrice: "Unit price",+ currencyCode: "Currency",minimumOrderQuantity: "Min order qty",orderMultiple: "Order multiple",conversionFactor: "Conversion factor",diff --git a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemForm.tsxindex bad74f2e86..936edb6cc5 100644--- a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemForm.tsx@@ -213,6 +213,23 @@ export function getLinkToItemDetails(type: ItemType, id: string) {}}+export function getLinkToItemPurchasing(type: ItemType, id: string) {+ switch (type) {+ case "Part":+ return path.to.partPurchasing(id);+ case "Material":+ return path.to.materialPurchasing(id);+ case "Tool":+ return path.to.toolPurchasing(id);+ case "Consumable":+ return path.to.consumablePurchasing(id);+ case "Service":+ return path.to.servicePurchasing(id);+ default:+ throw new Error("Invalid type");+ }+}+export function getLinkToItemManufacturing(type: ItemType, id: string) {switch (type) {case "Part":diff --git a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsxindex 68b6cba44d..0eeccb7c14 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useCarbon } from "@carbon/auth";import { ValidatedForm } from "@carbon/form";import {Button,@@ -45,9 +46,11 @@ import { DateTime } from "~/components";import { EditableNumber } from "~/components/Editable";import {ConversionFactor,+ Currency,CustomFormFields,Hidden,Input,+ Item,Number,Submit,Supplier,@@ -60,40 +63,67 @@ import {usePermissions,useUser} from "~/hooks";+import { useItems } from "~/stores";import { path } from "~/utils/path";import { supplierPartValidator } from "../../items.models";+/** The item types a supplier part can be saved for: each has a purchasing route. */+export const supplierPartItemTypes = [+ "Part",+ "Material",+ "Tool",+ "Consumable",+ "Service"+] as const;+export type SupplierPartItemType = (typeof supplierPartItemTypes)[number];++export function isSupplierPartItemType(+ type: string | null | undefined+): type is SupplierPartItemType {+ return supplierPartItemTypes.includes(type as SupplierPartItemType);+}+type PriceBreak = {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;+ leadTime: number;sourceType: string;sourceDocumentId: string | null;createdAt: string;};+// leadTime is not edited here, but rides along so saving the drawer (which+// rewrites every break) keeps the lead times a quote or order recorded.type PriceBreakRow = {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;+ leadTime: number;};type PurchaseHistoryItem = {id: string;purchaseQuantity: number | null;- unitPrice: number | null;+ supplierUnitPrice: number | null;purchaseOrderId: string;purchaseOrder: {purchaseOrderId: string;supplierId: string;orderDate: string | null;+ currencyCode: string | null;};};type SupplierPartFormProps = {initialValues: z.infer<typeof supplierPartValidator>;- type: "Part" | "Service" | "Tool" | "Consumable" | "Material";+ type: SupplierPartItemType;unitOfMeasureCode: string;priceBreaks?: PriceBreak[];purchasingHistory?: PurchaseHistoryItem[];+ // Opened from a supplier rather than an item: the item is picked in the form+ // and the supplier is fixed. The picked item decides the type and unit.+ selectItem?: boolean;+ // Items the picker leaves out: those the supplier already has a supplier part for.+ excludeItemIds?: string[];onClose: () => void;};@@ -103,14 +133,37 @@ const SupplierPartForm = ({unitOfMeasureCode,priceBreaks: initialPriceBreaks = [],purchasingHistory = [],+ selectItem = false,+ excludeItemIds,onClose}: SupplierPartFormProps) => {const permissions = usePermissions();const { t } = useLingui();+ const { carbon } = useCarbon();const { company } = useUser();const baseCurrency = company?.baseCurrencyCode ?? "USD";- const currencyDecimals = useCurrencyDecimals(baseCurrency);++ // The price and its breaks are in this currency — the supplier's own by+ // default, so a price is entered exactly as the supplier quoted it.+ const [currencyCode, setCurrencyCode] = useState<string>(+ initialValues.currencyCode ?? baseCurrency+ );+ const currencyDecimals = useCurrencyDecimals(currencyCode);++ const onSupplierChange = async (supplierId: string | undefined) => {+ if (!supplierId || !carbon) return;+ const { data, error } = await carbon+ .from("supplier")+ .select("currencyCode")+ .eq("id", supplierId)+ .single();+ if (error) {+ toast.error(t`Error fetching supplier data`);+ return;+ }+ setCurrencyCode(data.currencyCode ?? baseCurrency);+ };let { itemId } = useParams();@@ -118,6 +171,19 @@ const SupplierPartForm = ({itemId = initialValues.itemId;}+ const [items] = useItems();+ const [selectedItemId, setSelectedItemId] = useState(initialValues.itemId);+ const selectedItem = selectItem+ ? items.find((item) => item.id === selectedItemId)+ : undefined;+ const itemType =+ selectedItem && isSupplierPartItemType(selectedItem.type)+ ? selectedItem.type+ : type;+ const inventoryCode = selectItem+ ? selectedItem?.unitOfMeasureCode+ : unitOfMeasureCode;+const [purchaseUnitOfMeasure, setPurchaseUnitOfMeasure] = useState<string | undefined>(initialValues.supplierUnitOfMeasureCode);@@ -125,12 +191,13 @@ const SupplierPartForm = ({const [priceBreaks, setPriceBreaks] = useState<PriceBreakRow[]>(initialPriceBreaks.map((pb) => ({quantity: pb.quantity,- unitPrice: pb.unitPrice+ supplierUnitPrice: pb.supplierUnitPrice,+ leadTime: pb.leadTime})));const hasInvalidPriceBreaks = priceBreaks.some(- (pb) => pb.quantity <= 0 || pb.unitPrice <= 0+ (pb) => pb.quantity <= 0 || pb.supplierUnitPrice <= 0);const isEditing = initialValues.id !== undefined;@@ -138,7 +205,12 @@ const SupplierPartForm = ({? !permissions.can("update", "parts"): !permissions.can("create", "parts");- const action = getAction(isEditing, type, itemId, initialValues.id);+ const action = getAction(+ isEditing,+ itemType,+ selectItem ? selectedItemId : itemId,+ initialValues.id+ );const fetcher = useFetcher<{ success: boolean; message: string }>();// biome-ignore lint/correctness/useExhaustiveDependencies: onClose must be excluded — it is a new ref each render in route components, which would cause an infinite re-fire loop@@ -174,23 +246,49 @@ const SupplierPartForm = ({</DrawerHeader><DrawerBody><Hidden name="id" />- <Hidden name="itemId" />+ {!selectItem && <Hidden name="itemId" />}<Hidden name="priceBreaks" value={JSON.stringify(priceBreaks)} /><VStack spacing={4}><div className="grid grid-cols-1 lg:grid-cols-2 gap-4 w-full">- <Supplier name="supplierId" label={t`Supplier`} />+ {selectItem && (+ <Item+ name="itemId"+ label={t`Item`}+ type="Item"+ validItemTypes={[...supplierPartItemTypes]}+ replenishmentSystem="Buy"+ blacklist={excludeItemIds}+ isOptional={false}+ onChange={(value) => setSelectedItemId(value?.value ?? "")}+ />+ )}+ <Supplier+ name="supplierId"+ label={t`Supplier`}+ isReadOnly={selectItem}+ onChange={(value) => onSupplierChange(value?.value)}+ /><Inputname="supplierPartId"label={t`Supplier Part ID`}termId="supplier-part-id"/>+ <Currency+ name="currencyCode"+ label={t`Currency`}+ value={currencyCode}+ onChange={(value) => {+ if (value?.value) setCurrencyCode(value.value);+ }}+ /><Number- name="unitPrice"+ name="supplierUnitPrice"label={t`Unit Price`}+ helperText={t`Per purchase unit`}minValue={0}formatOptions={INPUT_FORMAT.rate(- baseCurrency,+ currencyCode,currencyDecimals)}/>@@ -205,7 +303,7 @@ const SupplierPartForm = ({name="conversionFactor"label={t`Conversion Factor`}termId="conversion-factor"- inventoryCode={unitOfMeasureCode ?? undefined}+ inventoryCode={inventoryCode ?? undefined}purchasingCode={purchaseUnitOfMeasure}/><Number@@ -225,7 +323,7 @@ const SupplierPartForm = ({<PriceBreakspriceBreaks={priceBreaks}onChange={setPriceBreaks}- baseCurrency={baseCurrency}+ currencyCode={currencyCode}isDisabled={isDisabled}/><PurchaseHistory@@ -240,6 +338,7 @@ const SupplierPartForm = ({isDisabled={isDisabled ||hasInvalidPriceBreaks ||+ (selectItem && !selectedItemId) ||fetcher.state !== "idle"}isLoading={fetcher.state !== "idle"}@@ -266,10 +365,6 @@ function PurchaseHistory({baseCurrency: string;}) {const { t } = useLingui();- const priceFormatter = useCurrencyFormatter({- rate: true,- currency: baseCurrency- });if (history.length === 0) return null;return (@@ -328,7 +423,13 @@ function PurchaseHistory({<Tr><Td>{line.purchaseQuantity}</Td><Td>- {priceFormatter.format(line.unitPrice ?? 0)}+ <PurchaseHistoryPrice+ price={line.supplierUnitPrice ?? 0}+ currencyCode={+ line.purchaseOrder.currencyCode ??+ baseCurrency+ }+ /></Td></Tr></Tbody>@@ -351,21 +452,39 @@ function PurchaseHistory({);}+// What the order paid, in the order's own currency.+function PurchaseHistoryPrice({+ price,+ currencyCode+}: {+ price: number;+ currencyCode: string;+}) {+ const formatter = useCurrencyFormatter({+ rate: true,+ currency: currencyCode+ });+ return <>{formatter.format(price)}</>;+}+function PriceBreaks({priceBreaks,onChange,- baseCurrency,+ currencyCode,isDisabled}: {priceBreaks: PriceBreakRow[];onChange: React.Dispatch<React.SetStateAction<PriceBreakRow[]>>;- baseCurrency: string;+ currencyCode: string;isDisabled: boolean;}) {- const currencyDecimals = useCurrencyDecimals(baseCurrency);+ const currencyDecimals = useCurrencyDecimals(currencyCode);const { t } = useLingui();- // unitPrice is a RATE, not a settlement amount — see numeric-precision.md- const formatter = useCurrencyFormatter({ rate: true });+ // supplierUnitPrice is a RATE, not a settlement amount — see numeric-precision.md+ const formatter = useCurrencyFormatter({+ rate: true,+ currency: currencyCode+ });const removeRow = useCallback((index: number) => {@@ -375,7 +494,10 @@ function PriceBreaks({);const addRow = useCallback(() => {- onChange((prev) => [...prev, { quantity: 0, unitPrice: 0 }]);+ onChange((prev) => [+ ...prev,+ { quantity: 0, supplierUnitPrice: 0, leadTime: 0 }+ ]);}, [onChange]);const noOpMutation = useCallback(@@ -394,11 +516,11 @@ function PriceBreaks({const editableComponents = useMemo(() => ({quantity: EditableNumber(noOpMutation),- unitPrice: EditableNumber(noOpMutation, {- formatOptions: INPUT_FORMAT.rate(baseCurrency, currencyDecimals)+ supplierUnitPrice: EditableNumber(noOpMutation, {+ formatOptions: INPUT_FORMAT.rate(currencyCode, currencyDecimals)})}),- [noOpMutation, baseCurrency, currencyDecimals]+ [noOpMutation, currencyCode, currencyDecimals]);const columns = useMemo<ColumnDef<PriceBreakRow>[]>(() => {@@ -411,9 +533,9 @@ function PriceBreaks({)},{- accessorKey: "unitPrice",+ accessorKey: "supplierUnitPrice",header: t`Unit Price`,- cell: ({ row }) => formatter.format(row.original.unitPrice)+ cell: ({ row }) => formatter.format(row.original.supplierUnitPrice)}];diff --git a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierPartPrice.tsx b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierPartPrice.tsxnew file mode 100644index 0000000000..36e8f45ba1--- /dev/null+++ b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierPartPrice.tsx@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useCurrencyFormatter, useUser } from "~/hooks";++/**+ * A supplier part's price as the supplier quoted it: in the part's own+ * currency (NULL = the company's base currency). A price is a rate, not a+ * settlement amount, so it keeps its sub-cent digits.+ */+const SupplierPartPrice = ({+ price,+ currencyCode+}: {+ price: number | null | undefined;+ currencyCode: string | null | undefined;+}) => {+ const { company } = useUser();+ const formatter = useCurrencyFormatter({+ rate: true,+ currency: currencyCode ?? company.baseCurrencyCode+ });+ if (price === null || price === undefined) return null;+ return <>{formatter.format(price)}</>;+};++export default SupplierPartPrice;diff --git a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsxindex 7d26a2624d..e851ba61f0 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierParts/SupplierParts.tsx@@ -12,17 +12,19 @@ import { SupplierAvatar } from "~/components";import Grid from "~/components/Grid";import Hyperlink from "~/components/Hyperlink";import { ConfirmDelete } from "~/components/Modals";-import { useCurrencyFormatter, usePermissions } from "~/hooks";+import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import { useSuppliers } from "~/stores/suppliers";import type { SupplierPart } from "../../../types";+import SupplierPartPrice from "./SupplierPartPrice";type Part = Pick<SupplierPart,| "id"| "supplierId"| "supplierPartId"- | "unitPrice"+ | "currencyCode"+ | "supplierUnitPrice"| "supplierUnitOfMeasureCode"| "minimumOrderQuantity"| "conversionFactor"@@ -52,7 +54,6 @@ const SupplierParts = ({const permissions = usePermissions();const canEdit = permissions.can("update", "parts") && !isReadOnly;const canDelete = permissions.can("delete", "parts") && !isReadOnly;- const formatter = useCurrencyFormatter();const customColumns = useCustomColumns<Part>("supplierPart");const [suppliers] = useSuppliers();@@ -80,13 +81,16 @@ const SupplierParts = ({cell: (item) => item.getValue()},{- accessorKey: "unitPrice",+ // In each supplier part's own currency, so a column total would add+ // euros to dollars — there is none.+ accessorKey: "supplierUnitPrice",header: t`Unit Price`,- cell: (item) => formatter.format(item.getValue<number>()),- meta: {- formatter: formatter.format,- renderTotal: true- }+ cell: ({ row }) => (+ <SupplierPartPrice+ price={row.original.supplierUnitPrice}+ currencyCode={row.original.currencyCode}+ />+ )},{accessorKey: "supplierUnitOfMeasureCode",@@ -129,7 +133,7 @@ const SupplierParts = ({}return cols;- }, [customColumns, formatter, t, canDelete, deleteSupplierPath]);+ }, [customColumns, t, canDelete, deleteSupplierPath]);return (<>diff --git a/apps/erp/app/modules/items/ui/Item/SupplierParts/index.ts b/apps/erp/app/modules/items/ui/Item/SupplierParts/index.tsindex 14c20e54c6..f140720db4 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierParts/index.ts+++ b/apps/erp/app/modules/items/ui/Item/SupplierParts/index.ts@@ -2,6 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import SupplierPartPrice from "./SupplierPartPrice";import SupplierParts from "./SupplierParts";+export { SupplierPartPrice };export default SupplierParts;diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 0217243a0d..cd8aaf21c8 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -5,6 +5,10 @@import type { Database, Json } from "@carbon/database";import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ convertUnitPrice,+ supplierPartCurrency+} from "@carbon/database/supplier-part-price";import { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";@@ -1687,7 +1691,7 @@ export async function insertPurchaseOrder(customFields?: Json;}): Promise<{- data: { id: string; purchaseOrderId: string } | null;+ data: { id: string; purchaseOrderId: string; exchangeRate: number } | null;error: import("@supabase/supabase-js").PostgrestError | null;}> {let purchaseOrderId: string;@@ -1812,7 +1816,7 @@ export async function insertPurchaseOrder(return { data: null, error: delivery.error ?? payment.error };}- return { data: { id: orderId, purchaseOrderId }, error: null };+ return { data: { id: orderId, purchaseOrderId, exchangeRate }, error: null };}/** @mcp update */@@ -5038,7 +5042,9 @@ export async function createReplacementPurchaseOrder(const supplierParts = await client.from("supplierPart")- .select("itemId, unitPrice, conversionFactor, supplierUnitOfMeasureCode")+ .select(+ "itemId, currencyCode, supplierUnitPrice, conversionFactor, supplierUnitOfMeasureCode"+ ).eq("supplierId", order.data.supplierId).eq("companyId", companyId).in(@@ -5068,6 +5074,54 @@ export async function createReplacementPurchaseOrder(}const purchaseOrderId = purchaseOrder.data.id;+ // A supplier part's price is in its own currency; the replacement order is+ // in the return's, so it converts at today's rate.+ const [company, exchangeRates] = await Promise.all([+ client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single(),+ client.rpc("get_exchange_rates", { p_company_id: companyId })+ ]);+ if (company.error || exchangeRates.error) {+ await deletePurchaseOrder(client, purchaseOrderId);+ return { data: null, error: company.error ?? exchangeRates.error };+ }+ const baseCurrencyCode = company.data.baseCurrencyCode;+ const exchangeRateByCurrency = new Map(+ exchangeRates.data.map((rate) => [rate.currencyCode, rate.rate])+ );+ const orderCurrency = {+ currencyCode: order.data.currencyCode ?? baseCurrencyCode,+ exchangeRate: purchaseOrder.data.exchangeRate+ };+ const supplierPartPrice = (+ supplierPart:+ | { currencyCode: string | null; supplierUnitPrice: number | null }+ | undefined+ ) => {+ if (supplierPart?.supplierUnitPrice == null) return null;+ const currencyCode = supplierPartCurrency(+ supplierPart.currencyCode,+ baseCurrencyCode+ );+ // Base is always 1, whether or not the group lists it.+ const exchangeRate =+ currencyCode === orderCurrency.currencyCode+ ? orderCurrency.exchangeRate+ : currencyCode === baseCurrencyCode+ ? 1+ : exchangeRateByCurrency.get(currencyCode);+ // No rate: leave it to the next fallback rather than price it at par.+ if (!exchangeRate) return null;+ return convertUnitPrice(+ supplierPart.supplierUnitPrice,+ { currencyCode, exchangeRate },+ orderCurrency+ );+ };+const lineTypeFor = (itemType: string | null | undefined): Database["public"]["Enums"]["purchaseOrderLineType"] => {@@ -5095,7 +5149,7 @@ export async function createReplacementPurchaseOrder(// unitPrice generated column is base currency and would double-convertconst unitPrice = Number(poLine?.supplierUnitPrice ??- supplierPart?.unitPrice ??+ supplierPartPrice(supplierPart) ??Number(line.unitPrice) * conversionFactor);const purchaseQuantity =@@ -5109,6 +5163,7 @@ export async function createReplacementPurchaseOrder(itemId: line.itemId,purchaseQuantity,supplierUnitPrice: unitPrice,+ exchangeRate: orderCurrency.exchangeRate,conversionFactor,purchaseUnitOfMeasureCode:poLine?.purchaseUnitOfMeasureCode ??diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsxindex 4ef0b07b97..57d0aa9388 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx@@ -41,11 +41,12 @@ import { LuCircleCheck, LuCirclePlus, LuExternalLink } from "react-icons/lu";import { Link, useFetcher } from "react-router";import { SupplierAvatar } from "~/components";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";-import { useCurrencyFormatter, useQuantityFormatter } from "~/hooks";+import { useQuantityFormatter } from "~/hooks";import type { SupplierPart } from "~/modules/items/types";import { SupplierPartForm } from "~/modules/items/ui/Item";import { getLinkToItemPlanning } from "~/modules/items/ui/Item/ItemForm";import { ItemPlanningChart } from "~/modules/items/ui/Item/ItemPlanningChart";+import { SupplierPartPrice } from "~/modules/items/ui/Item/SupplierParts";import type { PlanningAction } from "~/modules/production";import {type PlanningActionHandlers,@@ -160,7 +161,6 @@ export const PurchasingPlanningOrderDrawer = memo(const { revalidate } = useRevalidator();const { carbon } = useCarbon();- const formatter = useCurrencyFormatter();const formatQuantity = useQuantityFormatter();const unitOfMeasureOptions = useUnitOfMeasure();@@ -661,7 +661,12 @@ export const PurchasingPlanningOrderDrawer = memo(}</Td><Td>{part.conversionFactor}</Td>- <Td>{formatter.format(part.unitPrice ?? 0)}</Td>+ <Td>+ <SupplierPartPrice+ price={part.supplierUnitPrice}+ currencyCode={part.currencyCode}+ />+ </Td><Td className="text-end"><Buttonvariant="secondary"@@ -712,7 +717,7 @@ export const PurchasingPlanningOrderDrawer = memo(itemId: selectedItem.id,supplierId: "",supplierPartId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex d245855a08..a321a72a30 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { convertUnitPrice } from "@carbon/database/supplier-part-price";import {Combobox,DatePicker,@@ -32,6 +33,7 @@ import {TabsContent,TabsList,TabsTrigger,+ toast,useDisclosure,useMount,VStack@@ -75,7 +77,7 @@ import {} from "~/hooks";import {EACH_UNIT_OF_MEASURE_CODE,- getSupplierPartPriceBreaks+ getSupplierPartPricing} from "~/modules/items";import type { PurchaseOrder, PurchaseOrderLine } from "~/modules/purchasing";import {@@ -85,7 +87,8 @@ import {import {type ItemType,itemType,- resolveSupplierPrice+ resolveSupplierPrice,+ type SupplierPartPricing} from "~/modules/shared";import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.details";import { useItems } from "~/stores";@@ -150,10 +153,12 @@ const PurchaseOrderLineForm = ({itemId: string;conversionFactor: number;description: string;+ // In the ORDER's currency: the price used when the supplier part has none+ // for the quantity.fallbackUnitPrice: number;inventoryUom: string;minimumOrderQuantity?: number;- priceBreaks: Array<{ quantity: number; unitPrice: number }>;+ pricing: SupplierPartPricing | null;purchaseQuantity: number;purchaseUom: string;requiredDate: string | null;@@ -167,16 +172,12 @@ const PurchaseOrderLineForm = ({itemId: initialValues.itemId ?? "",conversionFactor: initialValues.conversionFactor ?? 1,description: initialValues.description ?? "",- // fallbackUnitPrice is BASE currency, matching what resolveSupplierPrice- // expects. initialValues.supplierUnitPrice is the SUPPLIER's, so divide.- fallbackUnitPrice:- (initialValues.supplierUnitPrice ?? 0) /- (routeData?.purchaseOrder?.exchangeRate || 1),+ fallbackUnitPrice: initialValues.supplierUnitPrice ?? 0,inventoryUom: initialValues.inventoryUnitOfMeasureCode ?? "",minimumOrderQuantity: undefined,purchaseQuantity: initialValues.purchaseQuantity ?? 1,purchaseUom: initialValues.purchaseUnitOfMeasureCode ?? "",- priceBreaks: [],+ pricing: null,requiredDate: initialValues?.requiredDate ?? null,storageUnitId: initialValues.storageUnitId ?? "",supplierPartId: initialValues.supplierPartId ?? "",@@ -291,7 +292,15 @@ const PurchaseOrderLineForm = ({})();});- // Load price breaks on mount when editing so quantity changes resolve correctly+ // The order's currency and rate: what a supplier part's price converts into.+ const orderCurrencyRate = {+ currencyCode: orderCurrency,+ exchangeRate: routeData?.purchaseOrder?.exchangeRate ?? 1+ };++ // Load price breaks on mount when editing so quantity changes resolve+ // correctly. The part's own price is left out: below every break the line+ // keeps the price it already has.useMount(() => {if (!isEditing || !initialValues.itemId) return;const supplierId = routeData?.purchaseOrder?.supplierId;@@ -300,18 +309,25 @@ const PurchaseOrderLineForm = ({(async () => {const supplierPart = await carbon.from("supplierPart")- .select("id")+ .select("id, companyId, currencyCode, supplierUnitPrice").eq("itemId", initialValues.itemId!).eq("companyId", company.id).eq("supplierId", supplierId).maybeSingle();if (supplierPart?.data?.id) {- const breaks = await getSupplierPartPriceBreaks(+ const pricing = await getSupplierPartPricing(carbon,- supplierPart.data.id+ supplierPart.data,+ company.baseCurrencyCode,+ orderCurrency);- setItemData((d) => ({ ...d, priceBreaks: breaks }));+ if (pricing.data) {+ setItemData((d) => ({+ ...d,+ pricing: { ...pricing.data, supplierUnitPrice: null }+ }));+ }}})();});@@ -349,7 +365,7 @@ const PurchaseOrderLineForm = ({fallbackUnitPrice: 0,inventoryUom: "",minimumOrderQuantity: undefined,- priceBreaks: [],+ pricing: null,purchaseQuantity: 1,purchaseUom: "",requiredDate: null,@@ -401,25 +417,33 @@ const PurchaseOrderLineForm = ({const itemCost = item?.data?.itemCost?.[0];const itemReplenishment = item?.data?.itemReplenishment;- const exchangeRate = routeData?.purchaseOrder?.exchangeRate ?? 1;const initialQty = supplierPart?.data?.minimumOrderQuantity ?? 1;const leadTime = item?.data?.itemReplenishment?.leadTime ?? 0;- // BASE currency: supplierPart.unitPrice and itemCost.unitCost are both- // stored in base. resolveSupplierPrice converts to the supplier's.- const baseFallback =- supplierPart?.data?.unitPrice !== null &&- supplierPart?.data?.unitPrice !== undefined- ? supplierPart.data.unitPrice- : (itemCost?.unitCost ?? 0);+ // The item's cost is in BASE currency; the line wants the order's.+ const fallbackUnitPrice = convertUnitPrice(+ itemCost?.unitCost ?? 0,+ { currencyCode: company.baseCurrencyCode, exchangeRate: 1 },+ orderCurrencyRate+ );- const breaks = supplierPart?.data?.id- ? await getSupplierPartPriceBreaks(carbon, supplierPart.data.id)- : [];+ // The supplier's price is in the supplier part's currency, converted+ // into the order's at the current rate.+ const pricing = supplierPart?.data+ ? await getSupplierPartPricing(+ carbon,+ supplierPart.data,+ company.baseCurrencyCode,+ orderCurrency+ )+ : null;+ if (pricing?.error) {+ toast.error(pricing.error.message);+ }const resolvedPrice = resolveSupplierPrice(- breaks,+ pricing?.data ?? null,initialQty,- baseFallback,- exchangeRate+ orderCurrencyRate,+ fallbackUnitPrice);// A service is always bought and "stocked" in EA, 1:1.@@ -452,8 +476,8 @@ const PurchaseOrderLineForm = ({supplierPartId: supplierPart?.data?.supplierPartId ?? "",supplierTaxAmount: 0,taxPercent: 0,- priceBreaks: breaks,- fallbackUnitPrice: baseFallback+ pricing: pricing?.data ?? null,+ fallbackUnitPrice});if (item.data?.type) {@@ -711,16 +735,14 @@ const PurchaseOrderLineForm = ({label={t`Quantity`}value={itemData.purchaseQuantity}onChange={(value) => {- const exchangeRate =- routeData?.purchaseOrder?.exchangeRate ?? 1;setItemData((d) => ({...d,purchaseQuantity: value,supplierUnitPrice: resolveSupplierPrice(- d.priceBreaks,+ d.pricing,value,- d.fallbackUnitPrice,- exchangeRate+ orderCurrencyRate,+ d.fallbackUnitPrice)}));}}diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderLineForm.tsxindex 1c7d1d1ba0..1b074d69e9 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderLineForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { convertUnitPrice } from "@carbon/database/supplier-part-price";import { Combobox, ValidatedForm } from "@carbon/form";import type { TrackedEntityOption } from "@carbon/react";import {@@ -54,6 +55,7 @@ import {useRouteData,useUser} from "~/hooks";+import { getSupplierPartPricing } from "~/modules/items";import { path } from "~/utils/path";import {isPurchaseReturnOrderLocked,@@ -193,7 +195,9 @@ const PurchaseReturnOrderLineForm = ({supplierId? carbon.from("supplierPart")- .select("unitPrice, conversionFactor")+ .select(+ "id, companyId, currencyCode, supplierUnitPrice, conversionFactor"+ ).eq("itemId", itemId).eq("supplierId", supplierId).eq("companyId", company.id)@@ -206,14 +210,35 @@ const PurchaseReturnOrderLineForm = ({return;}- // supplierPart prices are per purchase unit — the line stores inventory- // units, so divide by the conversion factor.+ // supplierPart prices are per purchase unit, in the part's currency — the+ // line stores inventory units in the return's currency, so convert at+ // today's rate and divide by the conversion factor.const part = supplierPart.data?.[0];const conversionFactor = part?.conversionFactor ?? 1;+ const pricing = part+ ? await getSupplierPartPricing(+ carbon,+ part,+ company.baseCurrencyCode,+ currencyCode+ )+ : null;+ if (pricing?.error) toast.error(pricing.error.message);+ const purchaseUnitPrice =+ pricing?.data?.supplierUnitPrice != null+ ? convertUnitPrice(+ pricing.data.supplierUnitPrice,+ pricing.data.currency,+ {+ currencyCode,+ exchangeRate: routeData?.purchaseReturnOrder?.exchangeRate ?? 1+ }+ )+ : 0;const unitPrice =conversionFactor > 0- ? (part?.unitPrice ?? 0) / conversionFactor- : (part?.unitPrice ?? 0);+ ? purchaseUnitPrice / conversionFactor+ : purchaseUnitPrice;setItemData({itemId,diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierParts.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierParts.tsxnew file mode 100644index 0000000000..70d9644a0e--- /dev/null+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierParts.tsx@@ -0,0 +1,237 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ HStack,+ IconButton,+ Input,+ InputGroup,+ InputLeftElement,+ MENU_ITEM_SHORTCUTS+} from "@carbon/react";+import { distinctItemText } from "@carbon/utils";+import { Trans, useLingui } from "@lingui/react/macro";+import { useMemo, useState } from "react";+import {+ LuEllipsisVertical,+ LuExternalLink,+ LuPencil,+ LuSearch+} from "react-icons/lu";+import { Link, useNavigate, useParams } from "react-router";+import { ItemThumbnail, New } from "~/components";+import { usePermissions, useUser } from "~/hooks";+import type { SupplierPartWithItem } from "~/modules/items";+import { getLinkToItemPurchasing } from "~/modules/items/ui/Item/ItemForm";+import { SupplierPartPrice } from "~/modules/items/ui/Item/SupplierParts";+import { type ItemType, itemType } from "~/modules/shared";+import { path } from "~/utils/path";++type SupplierPartsProps = {+ supplierParts: SupplierPartWithItem[];+};++function matchesSearch(supplierPart: SupplierPartWithItem, query: string) {+ return [+ supplierPart.item?.readableIdWithRevision,+ supplierPart.item?.name,+ supplierPart.supplierPartId+ ].some((value) => value?.toLowerCase().includes(query));+}++/** The supplier parts that name this supplier: one row per item it supplies. */+const SupplierParts = ({ supplierParts }: SupplierPartsProps) => {+ const { supplierId } = useParams();+ if (!supplierId) throw new Error("supplierId not found");++ const { t } = useLingui();+ const navigate = useNavigate();+ const permissions = usePermissions();+ const canCreate = permissions.can("create", "parts");+ const { company } = useUser();++ // Local state rather than a URL param: opening a row's drawer and closing it+ // navigates without the query string, and the search should survive that.+ const [search, setSearch] = useState("");+ const searchText = search.trim();+ const query = searchText.toLowerCase();+ const filteredParts = useMemo(+ () =>+ query+ ? supplierParts.filter((supplierPart) =>+ matchesSearch(supplierPart, query)+ )+ : supplierParts,+ [supplierParts, query]+ );++ return (+ <Card>+ <HStack className="justify-between items-start">+ <CardHeader>+ <CardTitle>+ <Trans>Supplier Parts</Trans>+ </CardTitle>+ </CardHeader>+ <CardAction>+ <HStack>+ {supplierParts.length > 0 && (+ <InputGroup size="sm">+ <InputLeftElement>+ <LuSearch className="text-muted-foreground w-3.5 h-3.5 mt-[-2px]" />+ </InputLeftElement>+ <Input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={t`Search`}+ aria-label={t`Search supplier parts`}+ className="w-[160px] sm:w-[240px] text-sm"+ />+ </InputGroup>+ )}+ {canCreate && <New to={path.to.newSupplierPart(supplierId)} />}+ </HStack>+ </CardAction>+ </HStack>+ <CardContent>+ {supplierParts.length === 0 ? (+ <div className="my-8 text-center w-full">+ <p className="text-muted-foreground text-sm">+ <Trans>No supplier parts have been added yet.</Trans>+ </p>+ </div>+ ) : filteredParts.length === 0 ? (+ <div className="my-8 text-center w-full">+ <p className="text-muted-foreground text-sm">+ <Trans>No supplier parts match "{searchText}".</Trans>+ </p>+ </div>+ ) : (+ <ul className="w-full divide-y divide-border">+ {filteredParts.map((supplierPart) => {+ const item = supplierPart.item;+ const type = (itemType as readonly string[]).includes(+ item?.type ?? ""+ )+ ? (item?.type as ItemType)+ : null;+ const editPath = path.to.supplierPart(+ supplierId,+ supplierPart.id!+ );+ // A supplier part's price is in its own currency (NULL = base),+ // per the supplier's unit of measure.+ const currencyCode =+ supplierPart.currencyCode ?? company.baseCurrencyCode;++ return (+ <li+ key={supplierPart.id}+ className="flex items-center justify-between gap-4 py-4 first:pt-0 last:pb-0"+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <ItemThumbnail+ size="md"+ thumbnailPath={item?.thumbnailPath}+ type={type ?? "Part"}+ />+ <div className="min-w-0 flex-1">+ <Link+ to={editPath}+ className="block truncate text-sm font-medium hover:underline"+ >+ {item?.readableIdWithRevision}+ </Link>+ {distinctItemText(+ item?.readableIdWithRevision,+ item?.name+ ) && (+ <p className="truncate text-sm text-muted-foreground">+ {item?.name}+ </p>+ )}+ {supplierPart.supplierPartId && (+ <p className="truncate font-mono text-xs text-muted-foreground">+ {supplierPart.supplierPartId}+ </p>+ )}+ </div>+ </div>++ {supplierPart.supplierUnitPrice !== null && (+ <p className="shrink-0 text-sm tabular-nums">+ <SupplierPartPrice+ price={supplierPart.supplierUnitPrice}+ currencyCode={currencyCode}+ />+ {supplierPart.supplierUnitOfMeasureCode && (+ <span className="text-muted-foreground">+ {" / "}+ {supplierPart.supplierUnitOfMeasureCode}+ </span>+ )}+ <span className="ml-2 font-mono text-muted-foreground">+ {currencyCode}+ </span>+ </p>+ )}++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`Supplier part actions`}+ icon={<LuEllipsisVertical />}+ variant="secondary"+ className="shrink-0"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.edit}+ onClick={() => navigate(editPath)}+ >+ <LuPencil className="mr-2" />+ <Trans>Edit Supplier Part</Trans>+ </DropdownMenuItem>+ {type && item?.id ? (+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.view}+ asChild+ >+ <Link to={getLinkToItemPurchasing(type, item.id)}>+ <LuExternalLink className="mr-2" />+ <Trans>View Item</Trans>+ </Link>+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ shortcut={MENU_ITEM_SHORTCUTS.view}+ disabled+ >+ <LuExternalLink className="mr-2" />+ <Trans>View Item</Trans>+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ );+ })}+ </ul>+ )}+ </CardContent>+ </Card>+ );+};++export default SupplierParts;diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsxindex 981e607b22..bf0f8f1a8c 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx@@ -22,14 +22,15 @@ const SupplierSidebar = () => {);const routeData = useRouteData<{- purchaseOrder: SupplierDetail;+ supplier: SupplierDetail;contacts: SupplierContact[];locations: SupplierLocation[];}>(path.to.supplier(supplierId));const links = useSupplierSidebar({contacts: routeData?.contacts.length ?? 0,- locations: routeData?.locations.length ?? 0+ locations: routeData?.locations.length ?? 0,+ parts: routeData?.supplier?.partCount ?? 0});return <DetailSidebar links={links} />;diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsxindex 94572ce47f..9fdd1048ec 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx@@ -11,6 +11,7 @@ import {LuLandmark,LuLayoutList,LuMapPin,+ LuPackage,LuPackageSearch,LuReceipt,LuRedoDot,@@ -26,9 +27,10 @@ import { path } from "~/utils/path";type Props = {contacts: number;locations: number;+ parts: number;};-export function useSupplierSidebar({ contacts, locations }: Props) {+export function useSupplierSidebar({ contacts, locations, parts }: Props) {const { t } = useLingui();const permissions = usePermissions();const { supplierId } = useParams();@@ -85,6 +87,13 @@ export function useSupplierSidebar({ contacts, locations }: Props) {icon: <LuRedoDot />,shortcut: DETAIL_TAB_SHORTCUTS.processes},+ {+ name: t`Parts`,+ to: path.to.supplierParts(supplierId),+ role: ["employee"],+ count: parts,+ icon: <LuPackage />+ },{name: t`Documents`,to: path.to.supplierDocuments(supplierId),diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/index.ts b/apps/erp/app/modules/purchasing/ui/Supplier/index.tsindex daca617e62..544d20a4b2 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/index.ts+++ b/apps/erp/app/modules/purchasing/ui/Supplier/index.ts@@ -10,6 +10,7 @@ import SupplierForm from "./SupplierForm";import SupplierHeader from "./SupplierHeader";import SupplierLocationForm from "./SupplierLocationForm";import SupplierLocations from "./SupplierLocations";+import SupplierParts from "./SupplierParts";import SupplierPaymentForm from "./SupplierPaymentForm";import SupplierProcesses from "./SupplierProcesses";import SupplierProcessForm from "./SupplierProcessForm";@@ -26,6 +27,7 @@ export {SupplierHeader,SupplierLocationForm,SupplierLocations,+ SupplierParts,SupplierPaymentForm,SupplierProcessForm,SupplierProcesses,diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.tsindex 79f7318643..388fb80727 100644--- a/apps/erp/app/modules/shared/shared.models.ts+++ b/apps/erp/app/modules/shared/shared.models.ts@@ -2,6 +2,12 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type {+ BuyPriceBreak,+ CurrencyRate,+ SupplierPriceBreak,+ SupplierPriceMap+} from "@carbon/database/supplier-part-price";import { textToTiptap } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";@@ -444,15 +450,17 @@ export const standardFactorType = ["Total Minutes"] as const;-export type PriceBreak = {- quantity: number;- unitPrice: number;-};+/** A costing break: inventory quantity, base-currency price per inventory unit. */+export type PriceBreak = BuyPriceBreak;-export type SupplierPriceMap = Record<- string,- {- priceBreaks: PriceBreak[];- fallbackUnitPrice: number | null;- }->;+export type { SupplierPriceMap };++/**+ * A supplier part's pricing as the supplier quoted it — per purchase unit, in+ * `currency.currencyCode` — with that currency's current rate.+ */+export type SupplierPartPricing = {+ priceBreaks: SupplierPriceBreak[];+ supplierUnitPrice: number | null;+ currency: CurrencyRate;+};diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 7a942e331e..975302d78a 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -4,6 +4,11 @@import type { Database, Tables } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import {+ type CurrencyRate,+ convertUnitPrice,+ supplierPriceForQuantity+} from "@carbon/database/supplier-part-price";import {getContentType,getFileExtension,@@ -19,7 +24,11 @@ import type {} from "@supabase/supabase-js";import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";-import type { PriceBreak, SupplierPriceMap } from "./shared.models";+import type {+ PriceBreak,+ SupplierPartPricing,+ SupplierPriceMap+} from "./shared.models";import type { ItemModelUpload } from "./types";const logger = getLogger("erp", "shared");@@ -516,28 +525,33 @@ export function resolveBuyUnitCost(}/**- * Resolve the supplier unit price for a quantity.+ * Resolve the supplier unit price for a purchase quantity, in the DOCUMENT's+ * currency — what a purchase order or invoice line's `supplierUnitPrice` holds.*- * `supplierPart.unitPrice` and `supplierPartPrice.unitPrice` are stored in the- * company BASE currency -- neither table has a currency column, and all three- * writers put base there. The field this feeds (`supplierUnitPrice`) is in the- * SUPPLIER's currency. The document's `exchangeRate` is foreign-per-base, so- * base to supplier is MULTIPLY.+ * The supplier part's breaks and price are in its own currency, per purchase+ * unit. A part in the document's currency lands as quoted; any other converts+ * through base at the part currency's current rate and the document's rate+ * (`convertUnitPrice`). With no supplier price for the quantity the+ * `documentFallbackPrice` (already in the document's currency) is used.*- * @param fallbackUnitPrice base currency, used when no break matches- * @returns the price in the supplier's currency+ * @param document the document's currency and its exchange rate (foreign per base)* @mcp read*/export function resolveSupplierPrice(- priceBreaks: PriceBreak[],+ pricing: SupplierPartPricing | null,quantity: number,- fallbackUnitPrice: number,- exchangeRate: number+ document: CurrencyRate,+ documentFallbackPrice: number): number {- const basePrice = priceBreaks.length- ? lookupPriceFromBreaks(priceBreaks, quantity, fallbackUnitPrice)- : fallbackUnitPrice;- return basePrice * exchangeRate;+ const supplierPrice = pricing+ ? supplierPriceForQuantity(+ pricing.priceBreaks,+ quantity,+ pricing.supplierUnitPrice+ )+ : null;+ if (supplierPrice === null || !pricing) return documentFallbackPrice;+ return convertUnitPrice(supplierPrice, pricing.currency, document);}// -----------------------------------------------------------------------------diff --git a/apps/erp/app/modules/shared/supplier-price.test.ts b/apps/erp/app/modules/shared/supplier-price.test.tsnew file mode 100644index 0000000000..3a28c7bd99--- /dev/null+++ b/apps/erp/app/modules/shared/supplier-price.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// shared.service's graph loads @carbon/content/glossary, whose module-load+// Lingui `msg` macro is not transformed under plain vitest. The pure function+// under test needs none of it.+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn()+}));++const { resolveSupplierPrice } = await import("./shared.service");++const EUR_PART = {+ priceBreaks: [+ { quantity: 1, supplierUnitPrice: 10 },+ { quantity: 100, supplierUnitPrice: 8 }+ ],+ supplierUnitPrice: 12,+ currency: { currencyCode: "EUR", exchangeRate: 0.8 }+};++describe("resolveSupplierPrice", () => {+ it("puts a price on an order in the supplier's currency exactly as quoted", () => {+ const order = { currencyCode: "EUR", exchangeRate: 0.75 };+ expect(resolveSupplierPrice(EUR_PART, 150, order, 0)).toBe(8);+ });++ it("converts a foreign price onto a base-currency order at the current rate", () => {+ const order = { currencyCode: "USD", exchangeRate: 1 };+ // 8 EUR at 0.8 EUR per USD+ expect(resolveSupplierPrice(EUR_PART, 150, order, 0)).toBe(10);+ });++ it("crosses through base onto an order in a third currency", () => {+ const order = { currencyCode: "GBP", exchangeRate: 0.5 };+ // 10 EUR = 12.5 USD = 6.25 GBP+ expect(resolveSupplierPrice(EUR_PART, 5, order, 0)).toBe(6.25);+ });++ it("uses the document fallback when the part has no price for the quantity", () => {+ const order = { currencyCode: "USD", exchangeRate: 1 };+ const noPrice = { ...EUR_PART, priceBreaks: [], supplierUnitPrice: null };+ expect(resolveSupplierPrice(noPrice, 5, order, 3.5)).toBe(3.5);+ expect(resolveSupplierPrice(null, 5, order, 3.5)).toBe(3.5);+ });+});diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex 72a221ceed..78ae79752c 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -7,6 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";import type { Database } from "@carbon/database";+import { convertUnitPrice } from "@carbon/database/supplier-part-price";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";@@ -23,7 +24,7 @@ import {getKanban,insertStockTransfer} from "~/modules/inventory";-import { getItemReplenishment } from "~/modules/items";+import { getItemReplenishment, getSupplierPartPricing } from "~/modules/items";import {getActiveJobOperationByJobId,insertJob,@@ -35,6 +36,7 @@ import {insertPurchaseOrder,upsertPurchaseOrderLine} from "~/modules/purchasing";+import { resolveSupplierPrice } from "~/modules/shared";import {getCompanyTimeZone,getLocationTimeZone@@ -240,13 +242,15 @@ async function handleKanban({} else if (kanban.data.replenishmentSystem === "Buy") {const existingPurchaseOrder = await client.from("purchaseOrder")- .select("id")+ .select("id, currencyCode, exchangeRate").eq("supplierId", kanban.data.supplierId!).in("status", ["Planned", "Draft"]).eq("companyId", companyId).maybeSingle();let purchaseOrderId = existingPurchaseOrder.data?.id;+ let orderCurrencyCode = existingPurchaseOrder.data?.currencyCode ?? null;+ let orderExchangeRate = existingPurchaseOrder.data?.exchangeRate ?? 1;if (!purchaseOrderId) {const newPurchaseOrder = await insertPurchaseOrder(client, {@@ -269,9 +273,11 @@ async function handleKanban({}purchaseOrderId = newPurchaseOrder.data.id;+ orderCurrencyCode = null;+ orderExchangeRate = newPurchaseOrder.data.exchangeRate;}- const [item, supplierPart, inventory] = await Promise.all([+ const [item, supplierPart, inventory, company] = await Promise.all([client.from("item").select(@@ -293,12 +299,47 @@ async function handleKanban({.eq("itemId", kanban.data.itemId!).eq("companyId", companyId).eq("locationId", kanban.data.locationId!)- .maybeSingle()+ .maybeSingle(),+ client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single()]);const itemCost = item?.data?.itemCost?.[0];const itemReplenishment = item?.data?.itemReplenishment;+ // The line is in the ORDER's currency: the supplier part's price converts+ // from its own currency at today's rate, the item cost from base.+ const baseCurrencyCode = company.data?.baseCurrencyCode ?? "USD";+ const order = {+ currencyCode: orderCurrencyCode ?? baseCurrencyCode,+ exchangeRate: orderExchangeRate+ };+ const pricing = supplierPart.data+ ? await getSupplierPartPricing(+ client,+ supplierPart.data,+ baseCurrencyCode,+ order.currencyCode+ )+ : null;+ if (pricing?.error) {+ logger.error("Kanban operation failed", { error: pricing.error });+ return { data: null, error: pricing.error.message };+ }+ const supplierUnitPrice = resolveSupplierPrice(+ pricing?.data ?? null,+ kanban.data.quantity!,+ order,+ convertUnitPrice(+ itemCost?.unitCost ?? 0,+ { currencyCode: baseCurrencyCode, exchangeRate: 1 },+ order+ )+ );+if (item.error) {logger.error("Kanban operation failed", { error: item.error });return {@@ -312,12 +353,11 @@ async function handleKanban({purchaseOrderLineType: item.data?.type as any,itemId: kanban.data.itemId!,purchaseQuantity: kanban.data.quantity!,- supplierUnitPrice:- supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,+ supplierUnitPrice,supplierShippingCost: 0,supplierTaxAmount: 0,taxPercent: 0,- exchangeRate: 1,+ exchangeRate: order.exchangeRate,purchaseUnitOfMeasureCode: kanban.data.purchaseUnitOfMeasureCode!,inventoryUnitOfMeasureCode:item.data?.unitOfMeasureCode || kanban.data.purchaseUnitOfMeasureCode!,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 46f6cb7469..9c3568b90b 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1545,+ "totalTools": 1547,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -494,8 +494,10 @@{"name":"items_getServices","classification":"READ","paramCount":5,"schema":"4b3bc8e78cef","response":"0bc4d668f038","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},{"name":"items_getServicesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getSupersessionChain","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"57cd7c34e332","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierPartPriceBreaks","classification":"READ","paramCount":1,"schema":"0b5fc4acf371","response":"87777c880401","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getSupplierParts","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4089d780d70d","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPartPriceBreaks","classification":"READ","paramCount":1,"schema":"0b5fc4acf371","response":"f4acc38f3c75","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPartPricing","classification":"READ","paramCount":3,"schema":"12f5a9bff481","response":"6cefe4692145","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierParts","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"77be6c5a4141","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getSupplierPartsBySupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"8acf1878d779","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getSupplierPriceBreaksForItems","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc0d300695e0","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getTool","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getTools","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"2b6244653ec7","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},@@ -561,7 +563,7 @@{"name":"items_upsertPickMethod","classification":"WRITE","paramCount":5,"schema":"0e196a6930be","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"pickMethod(itemId,locationId)"},{"name":"items_upsertPickMethodWithShelfLife","classification":"DESTRUCTIVE","paramCount":6,"schema":"3af3fd086443","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},{"name":"items_upsertService","classification":"WRITE","paramCount":19,"schema":"e780e7384b56","response":"87c54a97c0fa","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},- {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":10,"schema":"3f49bc187ea4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},+ {"name":"items_upsertSupplierPart","classification":"WRITE","paramCount":11,"schema":"b7fbcd164308","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"items_upsertTool","classification":"WRITE","paramCount":21,"schema":"121d76f81f4e","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"item(id)|item(readableId=id)"},{"name":"items_upsertUnitOfMeasure","classification":"WRITE","paramCount":4,"schema":"85315f99e855","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},{"name":"people_clockIn","classification":"WRITE","paramCount":1,"schema":"3d90cb5d0437","response":"bcde375ebd4c","injectAuth":"companyId","permission":"people:update","paginates":false},@@ -937,7 +939,7 @@{"name":"purchasing_getSupplierType","classification":"READ","paramCount":1,"schema":"900045091850","response":"8b3eca34dbfd","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"7c6550dea5b1","injectAuth":"companyId","permission":"purchasing:view","paginates":true,"defaults":"always"},{"name":"purchasing_getSupplierTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","paramCount":15,"schema":"27513cc48e8d","response":"f5212679d580","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},+ {"name":"purchasing_insertPurchaseOrder","classification":"WRITE","paramCount":15,"schema":"27513cc48e8d","response":"73785d310369","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertPurchaseReturnOrder","classification":"WRITE","paramCount":12,"schema":"d3253380f7e2","response":"d53d13c89312","injectAuth":"companyGroupId+companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"cb4ec49c926e","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},{"name":"purchasing_insertSupplier","classification":"WRITE","paramCount":9,"schema":"05cf2198c6ac","response":"9d2416e8ad75","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create","paginates":false},@@ -1513,7 +1515,7 @@{"name":"shared_lookupBuyPriceFromMap","classification":"READ","paramCount":4,"schema":"4360b71230e3","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_lookupPriceFromBreaks","classification":"READ","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_resolveBuyUnitCost","classification":"WRITE","paramCount":3,"schema":"4c58915f44dd","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_resolveSupplierPrice","classification":"READ","paramCount":4,"schema":"c92834c91ef5","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},+ {"name":"shared_resolveSupplierPrice","classification":"READ","paramCount":4,"schema":"cb376986b1ab","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"none","paginates":false,"result":"envelopes"},{"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},diff --git a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsxindex 758f608194..33e9808cdb 100644--- a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx+++ b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx@@ -6,23 +6,27 @@ import { assertIsPost, error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import { redirect } from "@carbon/utils";+import { getLogger } from "@carbon/logger";+import { redirect, round } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {- currencyValidator,+ currencyFormValidator,deleteExchangeRateOverride,exchangeRateOverrideValidator,getCurrency,getExchangeRateHistory,getExchangeRates,- upsertCurrency,upsertExchangeRateOverride} from "~/modules/accounting";+import { saveCurrencyWithRateOverride } from "~/modules/accounting/accounting.server";import { ExchangeRateForm } from "~/modules/accounting/ui/ExchangeRates";+import { getDatabaseClient } from "~/services/database.server";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";+const logger = getLogger("erp", "accounting-exchange-rate");+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "accounting",@@ -146,30 +150,73 @@ export async function action({ request }: ActionFunctionArgs) {);}- const validation = await validator(currencyValidator).validate(formData);+ const validation = await validator(currencyFormValidator).validate(formData);if (validation.error) {return validationError(validation.error);}- const { id, ...d } = validation.data;+ const { id, rate, displayedRate, ...d } = validation.data;if (!id) throw new Error("id not found");- const updateCurrency = await upsertCurrency(client, {- id,- ...d,- companyGroupId,- customFields: setCustomFields(formData),- updatedBy: userId- });+ // The rate field is disabled (so not posted) for the base currency. Pin it+ // only when the user changed it from the rate the drawer showed — a rate+ // that moved while the drawer was open is not an edit — and when it differs+ // from the rate in effect, compared at the scale the input shows. Otherwise+ // saving the config would freeze the market rate.+ let overrideRate: number | null = null;+ if (+ rate !== undefined &&+ (displayedRate === undefined || round(displayedRate) !== round(rate))+ ) {+ const current = await getExchangeRates(client, companyId);+ if (current.error) {+ logger.error("Failed to read exchange rates before pinning a rate", {+ companyId,+ currencyCode: d.code,+ error: current.error+ });+ return data(+ {},+ await flash(+ request,+ error(current.error, "Failed to read the current exchange rate")+ )+ );+ }+ const resolved = current.data.find((r) => r.currencyCode === d.code);+ if (+ resolved?.source !== "base" &&+ (resolved?.rate == null || round(Number(resolved.rate)) !== round(rate))+ ) {+ overrideRate = rate;+ }+ }- if (updateCurrency.error) {+ try {+ const saved = await saveCurrencyWithRateOverride(getDatabaseClient(), {+ currencyId: id,+ companyId,+ companyGroupId,+ userId,+ config: {+ decimalPlaces: d.decimalPlaces,+ historicalExchangeRate: d.historicalExchangeRate ?? null,+ customFields: setCustomFields(formData)+ },+ overrideRate+ });+ if (!saved) throw notFound("Currency not found");+ } catch (err) {+ if (err instanceof Response) throw err;+ logger.error("Failed to update currency", {+ companyId,+ currencyId: id,+ error: err+ });return data({},- await flash(- request,- error(updateCurrency.error, "Failed to update currency")- )+ await flash(request, error(err, "Failed to update currency")));}diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsxindex 6cc4ab84f2..55287c3d9d 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx@@ -2,12 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { isUniqueViolation, redirect } from "@carbon/utils";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ConsumableSummary } from "~/modules/items";@@ -47,7 +46,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -107,7 +106,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];const db = getDatabaseClient();@@ -124,7 +123,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -137,10 +136,9 @@ export async function action({ request, params }: ActionFunctionArgs) {});}- throw redirect(- path.to.consumablePurchasing(itemId),- await flash(request, success("Supplier part updated"))- );+ // Fetcher-friendly success, as on the part route: the form's fetcher effect+ // toasts and fires onClose, so a caller outside the item page stays put.+ return { success: true, message: "Supplier part updated" };}export default function EditConsumableSupplierRoute() {@@ -162,7 +160,8 @@ export default function EditConsumableSupplierRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsxindex 6be011eeb4..276ed4b298 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx@@ -62,7 +62,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (newSupplierPartId && priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];if (priceBreaks.length > 0) {@@ -70,7 +70,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId: newSupplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -100,7 +100,7 @@ export default function NewConsumableSupplierRoute() {itemId: itemId,supplierId: "",supplierConsumableId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.$supplierPartId.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.$supplierPartId.tsxindex 82b19a0a4a..578065f84e 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.$supplierPartId.tsx@@ -28,7 +28,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.single(),client.from("supplierPartPrice")- .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ ).eq("supplierPartId", supplierPartId).order("quantity", { ascending: true })]);@@ -41,7 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -79,7 +81,8 @@ export default function ChangeNoticeEditSupplierPartRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.new.tsx b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.new.tsxindex fb8cb19436..52af37493d 100644--- a/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.new.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice+/$id.$affectedId.details.new.tsx@@ -37,7 +37,7 @@ export default function ChangeNoticeNewSupplierPartRoute() {itemId: affected.draftItemId,supplierId: "",supplierPartId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsxindex 04738458b7..b71a704129 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx@@ -2,12 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { isUniqueViolation, redirect } from "@carbon/utils";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { MaterialSummary } from "~/modules/items";@@ -34,7 +33,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.single(),client.from("supplierPartPrice")- .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ ).eq("supplierPartId", supplierPartId).order("quantity", { ascending: true })]);@@ -47,7 +48,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -107,7 +108,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];const db = getDatabaseClient();@@ -124,7 +125,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -137,10 +138,9 @@ export async function action({ request, params }: ActionFunctionArgs) {});}- throw redirect(- path.to.materialPurchasing(itemId),- await flash(request, success("Supplier part updated"))- );+ // Fetcher-friendly success, as on the part route: the form's fetcher effect+ // toasts and fires onClose, so a caller outside the item page stays put.+ return { success: true, message: "Supplier part updated" };}export default function EditMaterialSupplierRoute() {@@ -162,7 +162,8 @@ export default function EditMaterialSupplierRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsxindex d350962a50..c9a4c58ebd 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx@@ -62,7 +62,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (newSupplierPartId && priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];if (priceBreaks.length > 0) {@@ -70,7 +70,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId: newSupplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -96,7 +96,7 @@ export default function NewMaterialSupplierRoute() {itemId: itemId,supplierId: "",supplierMaterialId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsxindex e1bf1fccd1..843e636b83 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx@@ -33,7 +33,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.single(),client.from("supplierPartPrice")- .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ ).eq("supplierPartId", supplierPartId).order("quantity", { ascending: true })]);@@ -46,7 +48,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -106,7 +108,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];const db = getDatabaseClient();@@ -123,7 +125,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -161,7 +163,8 @@ export default function EditPartSupplierRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsxindex c7325e3a65..0a6f1712b1 100644--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx@@ -65,7 +65,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (newSupplierPartId && priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];if (priceBreaks.length > 0) {@@ -73,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId: newSupplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -100,7 +100,7 @@ export default function NewPartSupplierRoute() {itemId: itemId,supplierId: "",supplierPartId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsxindex fb21842e3c..7187a758b2 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx@@ -6,6 +6,10 @@ import { hasPermission } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getUserClaims } from "@carbon/auth/users.server";import type { Database } from "@carbon/database";+import {+ convertUnitPrice,+ supplierPartCurrency+} from "@carbon/database/supplier-part-price";import { getLogger } from "@carbon/logger";import { applyRate, datetime, SCALE, taxableBase } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";@@ -307,7 +311,7 @@ export async function action({ request }: ActionFunctionArgs) {);}- const [suppliers, supplierParts, company, currencies] =+ const [suppliers, supplierParts, company, currencies, exchangeRates] =await Promise.all([client.from("supplier")@@ -327,7 +331,9 @@ export async function action({ request }: ActionFunctionArgs) {client.from("currencies").select("code, decimalPlaces")- .eq("companyGroupId", companyGroupId)+ .eq("companyGroupId", companyGroupId),+ // Today's rate for each currency a supplier part is priced in.+ client.rpc("get_exchange_rates", { p_company_id: companyId })]);if (suppliers.error) {@@ -371,6 +377,12 @@ export async function action({ request }: ActionFunctionArgs) {);const baseCurrencyCode = company.data?.baseCurrencyCode ?? "USD";+ const exchangeRateByCurrency = new Map(+ (exchangeRates.data ?? []).map((rate) => [+ rate.currencyCode,+ rate.rate+ ])+ );// Settlement amounts round at the currency's own decimals, so the// planned order carries a real money value rather than a raw product.@@ -407,7 +419,7 @@ export async function action({ request }: ActionFunctionArgs) {const openPurchaseOrders = await client.from("purchaseOrder").select(- "id, purchaseOrderId, supplierId, currencyCode, createdFromPlanning, purchaseOrderDelivery!inner(locationId), purchaseOrderLine(id, itemId, requiredDate, purchaseQuantity, supplierUnitPrice, supplierShippingCost, taxPercent, supplierTaxAmount)"+ "id, purchaseOrderId, supplierId, currencyCode, exchangeRate, createdFromPlanning, purchaseOrderDelivery!inner(locationId), purchaseOrderLine(id, itemId, requiredDate, purchaseQuantity, supplierUnitPrice, supplierShippingCost, taxPercent, supplierTaxAmount)").eq("companyId", companyId).in("supplierId", Array.from(ordersBySupplier.keys()))@@ -438,6 +450,7 @@ export async function action({ request }: ActionFunctionArgs) {purchaseOrderId: po.purchaseOrderId,supplierId: po.supplierId,currencyCode: po.currencyCode,+ exchangeRate: po.exchangeRate ?? 1,createdFromPlanning: po.createdFromPlanning,purchaseOrderLine: po.purchaseOrderLine ?? []}));@@ -528,6 +541,7 @@ export async function action({ request }: ActionFunctionArgs) {purchaseOrderId: createPO.data.purchaseOrderId,supplierId,currencyCode,+ exchangeRate: createPO.data.exchangeRate,createdFromPlanning: true,purchaseOrderLine: []};@@ -665,7 +679,49 @@ export async function action({ request }: ActionFunctionArgs) {existing.taxPercent = tax.percent;existing.supplierTaxAmount = tax.amount;} else {- const supplierUnitPrice = supplierPart?.unitPrice ?? 0;+ // The supplier part's price is in its own currency; the line+ // holds the order's, converted at today's rate.+ const partCurrency = supplierPartCurrency(+ supplierPart?.currencyCode,+ baseCurrencyCode+ );+ // Base is always 1, whether or not the group lists it.+ const partRate =+ partCurrency === baseCurrencyCode+ ? 1+ : exchangeRateByCurrency.get(partCurrency);+ if (+ supplierPart?.supplierUnitPrice != null &&+ partCurrency !== currencyCode &&+ !partRate+ ) {+ logger.error("No exchange rate for supplier part currency", {+ companyId,+ userId,+ locationId,+ purchaseOrderId,+ itemId,+ currencyCode: partCurrency+ });+ errors.push(+ `No exchange rate for ${partCurrency}: set one in Accounting → Exchange Rates`+ );+ continue;+ }+ const supplierUnitPrice =+ supplierPart?.supplierUnitPrice != null+ ? convertUnitPrice(+ supplierPart.supplierUnitPrice,+ {+ currencyCode: partCurrency,+ exchangeRate: partRate ?? 1+ },+ {+ currencyCode,+ exchangeRate: purchaseOrder.exchangeRate+ }+ )+ : 0;const taxPercent = supplier.taxPercent ?? 0;// supplier.taxPercent is a 0..1 fraction; the amount follows// the canonical denominator. Shipping is hardcoded 0 on this@@ -687,6 +743,7 @@ export async function action({ request }: ActionFunctionArgs) {inventoryUnitOfMeasureCode: order.unitOfMeasureCode,conversionFactor: supplierPart?.conversionFactor ?? 1,supplierUnitPrice,+ exchangeRate: purchaseOrder.exchangeRate,taxPercent,supplierTaxAmount,supplierShippingCost: 0,diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsxindex 8788d30d8d..129ae3fdb1 100644--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx@@ -2,12 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { isUniqueViolation, redirect } from "@carbon/utils";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ServiceSummary } from "~/modules/items";@@ -34,7 +33,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.single(),client.from("supplierPartPrice")- .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ ).eq("supplierPartId", supplierPartId).order("quantity", { ascending: true })]);@@ -47,7 +48,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -107,7 +108,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];const db = getDatabaseClient();@@ -124,7 +125,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -137,10 +138,9 @@ export async function action({ request, params }: ActionFunctionArgs) {});}- throw redirect(- path.to.servicePurchasing(itemId),- await flash(request, success("Supplier part updated"))- );+ // Fetcher-friendly success, as on the part route: the form's fetcher effect+ // toasts and fires onClose, so a caller outside the item page stays put.+ return { success: true, message: "Supplier part updated" };}export default function EditServiceSupplierRoute() {@@ -162,7 +162,8 @@ export default function EditServiceSupplierRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsxindex fa5cdfbe1b..36cad42d17 100644--- a/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx@@ -65,7 +65,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (newSupplierPartId && priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];if (priceBreaks.length > 0) {@@ -73,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId: newSupplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -103,7 +103,7 @@ export default function NewServiceSupplierRoute() {itemId: itemId,supplierId: "",supplierPartId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.parts.$supplierPartId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.$supplierPartId.tsxnew file mode 100644index 0000000000..7a9e649c2e--- /dev/null+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.$supplierPartId.tsx@@ -0,0 +1,123 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { redirect } from "@carbon/utils";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData, useNavigate, useParams } from "react-router";+import { SupplierPartForm } from "~/modules/items/ui/Item";+import { isSupplierPartItemType } from "~/modules/items/ui/Item/SupplierPartForm";+import { getCustomFields } from "~/utils/form";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "purchasing"+ });++ const { supplierId, supplierPartId } = params;+ if (!supplierId) throw new Error("Could not find supplierId");+ if (!supplierPartId) throw new Error("Could not find supplierPartId");++ const [supplierPartResult, priceBreaksResult] = await Promise.all([+ client+ .from("supplierPart")+ .select("*, item(type, unitOfMeasureCode)")+ .eq("id", supplierPartId)+ .eq("supplierId", supplierId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("supplierPartPrice")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ )+ .eq("supplierPartId", supplierPartId)+ .order("quantity", { ascending: true })+ ]);++ const supplierPart = supplierPartResult.data;+ if (!supplierPart || !isSupplierPartItemType(supplierPart.item?.type)) {+ throw redirect(+ path.to.supplierParts(supplierId),+ await flash(+ request,+ error(supplierPartResult.error, "Failed to load supplier part")+ )+ );+ }++ // The form posts its price breaks back in full and the save replaces the+ // stored ones, so an unread list must not reach it as an empty one.+ if (priceBreaksResult.error) {+ throw redirect(+ path.to.supplierParts(supplierId),+ await flash(+ request,+ error(priceBreaksResult.error, "Failed to load supplier price breaks")+ )+ );+ }++ const purchasingHistory = await client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)"+ )+ .eq("itemId", supplierPart.itemId)+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)+ .order("createdAt", { ascending: false })+ .limit(10);++ return {+ supplierPart,+ itemType: supplierPart.item.type,+ unitOfMeasureCode: supplierPart.item.unitOfMeasureCode ?? "",+ priceBreaks: priceBreaksResult.data ?? [],+ purchasingHistory: purchasingHistory.data ?? []+ };+}++export default function SupplierEditSupplierPartRoute() {+ const { supplierId } = useParams();+ if (!supplierId) throw new Error("Could not find supplierId");++ const {+ supplierPart,+ itemType,+ unitOfMeasureCode,+ priceBreaks,+ purchasingHistory+ } = useLoaderData<typeof loader>();++ const navigate = useNavigate();+ const onClose = () => navigate(path.to.supplierParts(supplierId));++ const initialValues = {+ id: supplierPart.id,+ itemId: supplierPart.itemId,+ supplierId: supplierPart.supplierId,+ supplierPartId: supplierPart.supplierPartId ?? "",+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,+ supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",+ minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,+ orderMultiple: supplierPart.orderMultiple ?? 1,+ conversionFactor: supplierPart.conversionFactor ?? 1,+ ...getCustomFields(supplierPart.customFields)+ };++ return (+ <SupplierPartForm+ type={itemType}+ initialValues={initialValues}+ unitOfMeasureCode={unitOfMeasureCode}+ priceBreaks={priceBreaks}+ purchasingHistory={purchasingHistory}+ onClose={onClose}+ />+ );+}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.parts.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.new.tsxnew file mode 100644index 0000000000..bf838d8d5d--- /dev/null+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.new.tsx@@ -0,0 +1,94 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { fetchAllRecords } from "@carbon/database";+import { redirect } from "@carbon/utils";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData, useNavigate, useParams } from "react-router";+import { SupplierPartForm } from "~/modules/items/ui/Item";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "purchasing"+ });++ const { supplierId } = params;+ if (!supplierId) throw new Error("Could not find supplierId");++ // Every item this supplier already has a supplier part for, inactive ones+ // included: the Parts tab lists only active rows, but a second row for the+ // same item and supplier is refused either way.+ const [existing, supplier] = await Promise.all([+ fetchAllRecords(() =>+ client+ .from("supplierPart")+ .select("itemId")+ .eq("supplierId", supplierId)+ .eq("companyId", companyId)+ .order("itemId")+ ),+ client+ .from("supplier")+ .select("currencyCode")+ .eq("id", supplierId)+ .eq("companyId", companyId)+ .single()+ ]);++ if (existing.error) {+ throw redirect(+ path.to.supplierParts(supplierId),+ await flash(+ request,+ error(existing.error, "Failed to load supplier parts")+ )+ );+ }++ return {+ excludeItemIds: (existing.data ?? []).map((part) => part.itemId),+ // The supplier is fixed on this form, so its currency is the default the+ // supplier field would otherwise set on change.+ currencyCode: supplier.data?.currencyCode ?? undefined+ };+}++// The form posts to the picked item's own create route, so this route has no+// action; the item decides the type and the inventory unit.+export default function SupplierNewSupplierPartRoute() {+ const { supplierId } = useParams();+ if (!supplierId) throw new Error("Could not find supplierId");++ const { excludeItemIds, currencyCode } = useLoaderData<typeof loader>();++ const navigate = useNavigate();+ const onClose = () => navigate(path.to.supplierParts(supplierId));++ const initialValues = {+ itemId: "",+ supplierId,+ supplierPartId: "",+ currencyCode,+ supplierUnitPrice: 0,+ supplierUnitOfMeasureCode: "EA",+ minimumOrderQuantity: 1,+ orderMultiple: 1,+ conversionFactor: 1+ };++ return (+ <SupplierPartForm+ selectItem+ excludeItemIds={excludeItemIds}+ type="Part"+ initialValues={initialValues}+ unitOfMeasureCode=""+ onClose={onClose}+ />+ );+}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.parts.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.tsxnew file mode 100644index 0000000000..558b722dc0--- /dev/null+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.parts.tsx@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { RecordOutlet } from "@carbon/react";+import { redirect } from "@carbon/utils";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData } from "react-router";+import { getSupplierPartsBySupplier } from "~/modules/items";+import SupplierParts from "~/modules/purchasing/ui/Supplier/SupplierParts";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "purchasing"+ });++ const { supplierId } = params;+ if (!supplierId) throw new Error("Could not find supplierId");++ const supplierParts = await getSupplierPartsBySupplier(+ client,+ supplierId,+ companyId+ );++ if (supplierParts.error) {+ throw redirect(+ path.to.supplier(supplierId),+ await flash(+ request,+ error(supplierParts.error, "Failed to load supplier parts")+ )+ );+ }++ return {+ supplierParts: (supplierParts.data ?? []).sort((a, b) =>+ (a.item?.readableIdWithRevision ?? "").localeCompare(+ b.item?.readableIdWithRevision ?? ""+ )+ )+ };+}++export default function SupplierPartsRoute() {+ const { supplierParts } = useLoaderData<typeof loader>();++ return (+ <>+ <SupplierParts supplierParts={supplierParts} />+ <RecordOutlet />+ </>+ );+}diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsxindex d2fc6eecb8..dff0872c96 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx@@ -2,12 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useRouteData } from "@carbon/react";-import { isUniqueViolation, redirect } from "@carbon/utils";+import { isUniqueViolation } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import type { ToolSummary } from "~/modules/items";@@ -34,7 +33,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.single(),client.from("supplierPartPrice")- .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")+ .select(+ "quantity, supplierUnitPrice, leadTime, sourceType, sourceDocumentId, createdAt"+ ).eq("supplierPartId", supplierPartId).order("quantity", { ascending: true })]);@@ -47,7 +48,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const purchasingHistory = await client.from("purchaseOrderLine").select(- "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"+ "id, purchaseQuantity, supplierUnitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate, currencyCode)").eq("itemId", supplierPart.itemId).eq("purchaseOrder.supplierId", supplierPart.supplierId)@@ -107,7 +108,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];const db = getDatabaseClient();@@ -124,7 +125,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -137,10 +138,9 @@ export async function action({ request, params }: ActionFunctionArgs) {});}- throw redirect(- path.to.toolPurchasing(itemId),- await flash(request, success("Supplier part updated"))- );+ // Fetcher-friendly success, as on the part route: the form's fetcher effect+ // toasts and fires onClose, so a caller outside the item page stays put.+ return { success: true, message: "Supplier part updated" };}export default function EditToolSupplierRoute() {@@ -162,7 +162,8 @@ export default function EditToolSupplierRoute() {itemId: supplierPart.itemId,supplierId: supplierPart.supplierId,supplierPartId: supplierPart.supplierPartId ?? "",- unitPrice: supplierPart.unitPrice ?? 0,+ currencyCode: supplierPart.currencyCode ?? undefined,+ supplierUnitPrice: supplierPart.supplierUnitPrice ?? 0,supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,orderMultiple: supplierPart.orderMultiple ?? 1,diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsxindex c187c07789..5eaab33085 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx@@ -65,7 +65,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (newSupplierPartId && priceBreaksRaw) {const priceBreaks = JSON.parse(priceBreaksRaw as string) as {quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}[];if (priceBreaks.length > 0) {@@ -73,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {priceBreaks.map((pb) => ({supplierPartId: newSupplierPartId,quantity: pb.quantity,- unitPrice: pb.unitPrice,+ supplierUnitPrice: pb.supplierUnitPrice,leadTime: pb.leadTime ?? 0,sourceType: "Manual Entry" as const,companyId,@@ -103,7 +103,7 @@ export default function NewToolSupplierRoute() {itemId: itemId,supplierId: "",supplierToolId: "",- unitPrice: 0,+ supplierUnitPrice: 0,supplierUnitOfMeasureCode: "EA",minimumOrderQuantity: 1,orderMultiple: 1,diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex b518a5f8cd..97ec98674f 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1829,6 +1829,8 @@ export const path = {generatePath(`${x}/supplier/${id}/contacts/new`),newSupplierLocation: (id: string) =>generatePath(`${x}/supplier/${id}/locations/new`),+ newSupplierPart: (id: string) =>+ generatePath(`${x}/supplier/${id}/parts/new`),newSupplierProcess: (id: string) =>generatePath(`${x}/supplier/${id}/processes/new`),newSupplierQuote: `${x}/supplier-quote/new`,@@ -2443,6 +2445,9 @@ export const path = {generatePath(`${x}/supplier/${supplierId}/locations/${id}`),supplierLocations: (id: string) =>generatePath(`${x}/supplier/${id}/locations`),+ supplierPart: (supplierId: string, id: string) =>+ generatePath(`${x}/supplier/${supplierId}/parts/${id}`),+ supplierParts: (id: string) => generatePath(`${x}/supplier/${id}/parts`),supplierPayment: (id: string) =>generatePath(`${x}/supplier/${id}/payments`),supplierProcess: (supplierId: string, id: string) =>diff --git a/docs/content/docs/reference/supplier-quotes.mdx b/docs/content/docs/reference/supplier-quotes.mdxindex e19b34829d..114e4ae5c8 100644--- a/docs/content/docs/reference/supplier-quotes.mdx+++ b/docs/content/docs/reference/supplier-quotes.mdx@@ -62,8 +62,8 @@ When you've picked a winning quote, **"Convert to Order"** turns it into a purchConversion also updates the item's **supplier part**. For each converted line, Carbon writes quantity-break prices to the supplier's `supplierPart` record (source: `Purchase Order`) and sets its primary unit price to the best tier. Later orders can reuse these prices.-<Callout type="note" title="Converting updates item costs">-The quantity-break prices land on the supplier part in *inventory* units: the supplier's per-purchase-unit price is divided by both the exchange rate and the conversion factor before it's stored. That's why a quote in another currency, in the supplier's pack size, still shows a sensible per-stock-unit cost afterward.+<Callout type="note" title="Prices are kept as quoted">+The quantity-break prices land on the supplier part as the supplier quoted them: per purchase unit, in the quote's currency. A supplier part that already exists in another currency keeps its currency, and the prices are converted into it. Each later order converts the stored price into its own currency at the exchange rate of that day.</Callout>For the full narrative, from sending the RFQ through comparing quotes to raising the order, see the [RFQ to PO guide](/guides/rfq-to-po). For what happens to the order once it exists, see [purchase orders](/docs/reference/purchase-orders).diff --git a/docs/content/docs/reference/suppliers-and-customers.mdx b/docs/content/docs/reference/suppliers-and-customers.mdxindex 9e6e201d12..bf68a52617 100644--- a/docs/content/docs/reference/suppliers-and-customers.mdx+++ b/docs/content/docs/reference/suppliers-and-customers.mdx@@ -7,7 +7,9 @@ description: The parties you buy from and sell to, and the ways their records di## Suppliers-A supplier lives in purchasing and anchors the buy side: <Term id="purchase-order">purchase orders</Term>, <Term id="supplier-quote">supplier quotes</Term>, and bills all reference it. Its **status** is a fixed set: *Active*, *Inactive*, *Pending*, *Rejected*. A supplier links to the items you buy through **supplier parts**, each carrying the supplier's own part number, a minimum order quantity, and a <Term>conversion factor</Term> from their pack to your stock unit.+A supplier lives in purchasing and anchors the buy side: <Term id="purchase-order">purchase orders</Term>, <Term id="supplier-quote">supplier quotes</Term>, and bills all reference it. Its **status** is a fixed set: *Active*, *Inactive*, *Pending*, *Rejected*. A supplier links to the items you buy through **supplier parts**, each carrying the supplier's own part number, a minimum order quantity, and a <Term>conversion factor</Term> from their pack to your stock unit. The supplier's **Parts** tab lists every supplier part that names it, with each price in its own currency, and a search box filters the list by part number, name, or the supplier's part number. **New** adds one by picking a purchased item, and opening a row edits it in place. The same records can be added from the item's Purchasing tab.++A supplier part's **unit price** and its price breaks are stored as the supplier quoted them: per purchase unit, in the supplier part's **currency**. A new supplier part takes the supplier's currency, and you can change it. When the price lands on a purchase order or bill, Carbon converts it into the document's currency at the current exchange rate. A price already in the document's currency is used exactly as entered. Quote costing converts the same price into your base currency per stock unit.<Callout type="note">A supplier part has **no lead time** — purchasing lead time is set per item, not per supplier-part. The supplier part is about identity and pack size, not delivery time.diff --git a/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts b/packages/checks/src/conformance/no-unscoped-kysely-write.test.tsindex 06370c7f4c..602b84c5cf 100644--- a/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts+++ b/packages/checks/src/conformance/no-unscoped-kysely-write.test.ts@@ -44,6 +44,36 @@ describe("noUnscopedKyselyWrite", () => {expect(scan(ts)).toHaveLength(0);});+ it("accepts companyGroupId on a group-scoped table with no companyId", () => {+ const ts = [+ "await trx",+ ' .updateTable("currency")',+ " .set({ decimalPlaces })",+ ' .where("id", "=", id)',+ ' .where("companyGroupId", "=", companyGroupId)',+ " .execute();"+ ].join("\n");+ expect(scan(ts)).toHaveLength(0);+ });++ it("does not accept companyGroupId on a company-scoped table", () => {+ const ts = [+ "await trx",+ ' .updateTable("quoteLine")',+ " .set({ sortOrder })",+ ' .where("id", "=", id)',+ ' .where("companyGroupId", "=", companyGroupId)',+ " .execute();"+ ].join("\n");+ expect(scan(ts)).toHaveLength(1);+ });++ it("still flags a group-scoped table written by id alone", () => {+ const ts =+ 'await trx.updateTable("currency").set({ decimalPlaces }).where("id", "=", id).execute();';+ expect(scan(ts)).toHaveLength(1);+ });+it("accepts an aliased table's qualified companyId", () => {const ts ='await trx.updateTable("job as j").set({ status }).where("j.id", "=", id).where("j.companyId", "=", companyId).executeTakeFirst();';diff --git a/packages/checks/src/conformance/no-unscoped-kysely-write.ts b/packages/checks/src/conformance/no-unscoped-kysely-write.tsindex 859b205366..1482632a89 100644--- a/packages/checks/src/conformance/no-unscoped-kysely-write.ts+++ b/packages/checks/src/conformance/no-unscoped-kysely-write.ts@@ -24,7 +24,9 @@ import type { ConformanceCheck, Violation } from "../check";* were read under `companyId` a few lines up. A scoped read proves nothing* once the code is refactored so the ids come from somewhere else, and the* extra predicate costs nothing. The only exemption is `company`, whose `id`- * IS the tenant.+ * IS the tenant. Tables shared by a company GROUP carry no `companyId` at all+ * (`GROUP_SCOPED_TABLES`); their tenant key is `companyGroupId`, so a write to+ * one must name that instead.** Scope: Node code that holds the superuser `db` — the ERP's modules and* routes, the MES app, `packages/jobs` and `packages/server-functions`. The@@ -59,9 +61,19 @@ const SCOPED_PREFIXES = [/** Tables whose own `id` is the tenant key, or that are keyed by user alone. */const EXEMPT_TABLES = new Set(["company", "userPermission"]);+/**+ * Tables with no `companyId` column, shared by every company in a group. A+ * `companyGroupId` predicate is their tenant boundary. Only add a table that+ * genuinely lacks `companyId` — on any other table a group predicate is wider+ * than the tenant.+ */+const GROUP_SCOPED_TABLES = new Set(["currency"]);+const WRITE = /\.(updateTable|deleteFrom)\s*\(/g;const COMPANY_PREDICATE =/\.where(?:Ref)?\s*\(\s*["'`](?:\w+\.)?companyId["'`]/;+const COMPANY_GROUP_PREDICATE =+ /\.where(?:Ref)?\s*\(\s*["'`](?:\w+\.)?companyGroupId["'`]/;const STATEMENT_END = /^\.(?:execute\w*|compile)\s*\(/;const ROWS_WRITE = /\b(updateRows|deleteRows)\s*\(/g;const ROWS_MESSAGE =@@ -183,6 +195,13 @@ export const noUnscopedKyselyWrite: ConformanceCheck = {const statement = statementFrom(text, start + 1);if (COMPANY_PREDICATE.test(statement)) continue;+ if (+ table &&+ GROUP_SCOPED_TABLES.has(table) &&+ COMPANY_GROUP_PREDICATE.test(statement)+ ) {+ continue;+ }const call = text.slice(start, text.indexOf(")", openParen) + 1);violations.push({diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex ac6e799f85..c9debc5bdd 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -77,6 +77,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h| `./json` | `toJson` / `toJsonColumns` — pre-serialise `json`/`jsonb` values written through Kysely (the driver sends strings and arrays unquoted) || `./price-trace` | `quoteToOrderPriceTrace` — the price trace a sales order line carries when the `convert` server function turns a quote into an order || `./supersession-pick` | The supersession rules shared by MRP, get-method and picking (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) |+| `./supplier-part-price` | Supplier part prices are stored as quoted (per purchase unit, in the part's `currencyCode`); `convertUnitPrice` puts one on a purchase document in its currency, `buildSupplierPriceMap` turns them into base per-inventory-unit costing breaks. Shared by the ERP, `methods.ts` and the server functions so every reader converts the same way || `./picked-consumption` | Consumption follows what was picked (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush || `./posting` | `buildPaymentJournal` / `buildMemoJournal` (`src/build-payment-journal.ts`, `src/build-memo-journal.ts`) for the `post-payment` / `post-memo` server functions and the dataset tiers || `./precision` / `./accounting-currency` / `./accounting-posting` / `./sales-posting-amounts` / `./ledger` | The pure numeric-precision API, FX conversion, journal role vocabulary, sales posting amounts, and ledger helpers (`AccountType`, `AccountClass`, `isAccountClass`, `credit`, `debit`, `accountTypeFromClass`). They live here, not in `@carbon/utils`, because the posting builders need them and this package cannot import `@carbon/utils` (turbo cycle); `@carbon/utils` re-exports them, so app code imports them from there. Keep them free of imports outside each other |diff --git a/packages/database/package.json b/packages/database/package.jsonindex b809c8ba0b..6443aacd26 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -29,6 +29,7 @@"./methods": "./src/methods.ts","./mrp-engine": "./src/mrp-engine.ts","./supersession-pick": "./src/supersession-pick.ts",+ "./supplier-part-price": "./src/supplier-part-price.ts","./contract-schedule": "./src/contract-schedule.ts","./contract-revenue-schedule": "./src/contract-revenue-schedule.ts","./contract-position": "./src/contract-position.ts",diff --git a/packages/database/src/datasets/tiers/02-items.ts b/packages/database/src/datasets/tiers/02-items.tsindex 53b79a2962..1313f0d540 100644--- a/packages/database/src/datasets/tiers/02-items.ts+++ b/packages/database/src/datasets/tiers/02-items.ts@@ -330,16 +330,18 @@ export async function runTier2(ctx: Ctx): Promise<void> {const itemRef = needItem(sl.item);const supplierId = need(ctx.refs.suppliers, sl.supplier);+ // Authored in the company's base currency: currencyCode stays NULL, which+ // every reader takes as base.const spId = await insertId(ctx, "supplierPart", {itemId: itemRef.id,supplierId,- unitPrice: sl.price,+ supplierUnitPrice: sl.price,minimumOrderQuantity: 1});await insertRow(ctx, "supplierPartPrice", {supplierPartId: spId,quantity: 1,- unitPrice: sl.price,+ supplierUnitPrice: sl.price,leadTime: sl.leadTime,sourceType: "Manual Entry"});diff --git a/packages/database/src/methods.ts b/packages/database/src/methods.tsindex d911a6edba..7b4203d4be 100644--- a/packages/database/src/methods.ts+++ b/packages/database/src/methods.ts@@ -14,6 +14,11 @@ import {single,updateRows} from "./rows.ts";+import {+ buildSupplierPriceMap,+ type SupplierPriceBreak,+ type SupplierPriceMap+} from "./supplier-part-price.ts";import type { Database } from "./types.ts";import { type AnyPostgresClient, isKysely } from "./utils.ts";@@ -344,14 +349,6 @@ export const getRatesFromSupplierProcesses =};};-type SupplierPriceMap = Record<- string,- {- priceBreaks: { quantity: number; unitPrice: number }[];- fallbackUnitPrice: number | null;- }->;-type CostCategoryKey =| "materialCost"| "partCost"@@ -377,6 +374,12 @@ const costCategoryKeys: CostCategoryKey[] = [type CostEffects = Record<CostCategoryKey, ((qty: number) => number)[]>;+/**+ * Mirror of `getSupplierPriceBreaksForItems` in+ * `apps/erp/app/modules/items/items.service.ts` — keep both in sync. Prices+ * are converted to base per inventory unit at today's rates by the shared+ * `buildSupplierPriceMap`.+ */async function getSupplierPriceBreaksForItems(client: AnyPostgresClient,itemIds: string[]@@ -388,61 +391,115 @@ async function getSupplierPriceBreaksForItems(client,"supplierPart",{ itemId: itemIds },- { columns: ["id", "itemId", "unitPrice"] }+ {+ columns: [+ "id",+ "itemId",+ "companyId",+ "currencyCode",+ "conversionFactor",+ "supplierUnitPrice"+ ]+ }): await client.from("supplierPart")- .select("id, itemId, unitPrice")+ .select(+ "id, itemId, companyId, currencyCode, conversionFactor, supplierUnitPrice"+ ).in("itemId", itemIds);if (!supplierParts.data?.length) return {};+ const companyId = supplierParts.data[0]!.companyId;const supplierPartIds = supplierParts.data.map((sp) => sp.id);- const prices = isKysely(client)- ? await many(- client,- "supplierPartPrice",- { supplierPartId: supplierPartIds },- {- columns: ["supplierPartId", "quantity", "unitPrice"],- orderBy: ["quantity"]- }- )- : await client- .from("supplierPartPrice")- .select("supplierPartId, quantity, unitPrice")- .in("supplierPartId", supplierPartIds)- .order("quantity", { ascending: true });-- const spToItem = new Map<string, string>();- for (const sp of supplierParts.data) {- spToItem.set(sp.id, sp.itemId);+ const [prices, rates] = await Promise.all([+ isKysely(client)+ ? many(+ client,+ "supplierPartPrice",+ { supplierPartId: supplierPartIds },+ { columns: ["supplierPartId", "quantity", "supplierUnitPrice"] }+ )+ : client+ .from("supplierPartPrice")+ .select("supplierPartId, quantity, supplierUnitPrice")+ .in("supplierPartId", supplierPartIds),+ getExchangeRatesByCode(client, companyId)+ ]);++ const breaksByPart = new Map<string, SupplierPriceBreak[]>();+ for (const price of prices.data ?? []) {+ const breaks = breaksByPart.get(price.supplierPartId) ?? [];+ breaks.push({+ quantity: Number(price.quantity),+ supplierUnitPrice: Number(price.supplierUnitPrice)+ });+ breaksByPart.set(price.supplierPartId, breaks);}- const result: SupplierPriceMap = {};-- for (const sp of supplierParts.data) {- if (!result[sp.itemId]) {- result[sp.itemId] = { priceBreaks: [], fallbackUnitPrice: null };- }- const current = result[sp.itemId]!.fallbackUnitPrice;- if (sp.unitPrice != null && (current === null || sp.unitPrice < current)) {- result[sp.itemId]!.fallbackUnitPrice = sp.unitPrice;- }- }+ return buildSupplierPriceMap(+ supplierParts.data.map((sp) => ({+ itemId: sp.itemId,+ currencyCode: sp.currencyCode,+ conversionFactor: sp.conversionFactor,+ supplierUnitPrice: sp.supplierUnitPrice,+ priceBreaks: breaksByPart.get(sp.id) ?? []+ })),+ rates.exchangeRates,+ rates.baseCurrencyCode+ );+}- for (const price of prices.data ?? []) {- const itemId = spToItem.get(price.supplierPartId);- if (itemId && result[itemId]) {- result[itemId].priceBreaks.push({- quantity: price.quantity,- unitPrice: price.unitPrice- });- }- }+/** Today's foreign-per-base rate for every currency configured for the company. */+async function getExchangeRatesByCode(+ client: AnyPostgresClient,+ companyId: string+): Promise<{+ baseCurrencyCode: string;+ exchangeRates: Record<string, number | null>;+}> {+ const rows: { currencyCode: string; rate: number | null; source: string }[] =+ isKysely(client)+ ? (+ await sql<{+ currencyCode: string;+ rate: number | null;+ source: string;+ }>`+ SELECT "currencyCode", "rate", "source"+ FROM get_exchange_rates(${companyId})+ `.execute(client)+ ).rows+ : ((await client.rpc("get_exchange_rates", { p_company_id: companyId }))+ .data ?? []);++ const company = isKysely(client)+ ? await single(+ client,+ "company",+ { id: companyId },+ { columns: ["baseCurrencyCode"] }+ )+ : await client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single();- return result;+ return {+ baseCurrencyCode:+ company.data?.baseCurrencyCode ??+ rows.find((row) => row.source === "base")?.currencyCode ??+ "USD",+ exchangeRates: Object.fromEntries(+ rows.map((row) => [+ row.currencyCode,+ row.rate == null ? null : Number(row.rate)+ ])+ )+ };}function lookupPriceFromBreaks(diff --git a/packages/database/src/supplier-part-price.test.ts b/packages/database/src/supplier-part-price.test.tsnew file mode 100644index 0000000000..2a5ed431f2--- /dev/null+++ b/packages/database/src/supplier-part-price.test.ts@@ -0,0 +1,141 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ buildSupplierPriceMap,+ convertUnitPrice,+ supplierPriceForQuantity+} from "./supplier-part-price.ts";++const USD = { currencyCode: "USD", exchangeRate: 1 };+const EUR = { currencyCode: "EUR", exchangeRate: 0.8 };+const GBP = { currencyCode: "GBP", exchangeRate: 0.5 };++describe("convertUnitPrice", () => {+ it("returns a price in the same currency untouched", () => {+ expect(+ convertUnitPrice(1.23456789, EUR, { ...EUR, exchangeRate: 0.7 })+ ).toBe(1.23456789);+ });++ it("divides into base", () => {+ expect(convertUnitPrice(8, EUR, USD)).toBe(10);+ });++ it("multiplies out of base", () => {+ expect(convertUnitPrice(10, USD, EUR)).toBe(8);+ });++ it("crosses through base between two foreign currencies", () => {+ // 8 EUR = 10 USD = 5 GBP+ expect(convertUnitPrice(8, EUR, GBP)).toBe(5);+ });++ it("refuses an unusable rate rather than converting at par", () => {+ expect(() =>+ convertUnitPrice(8, { currencyCode: "EUR", exchangeRate: 0 }, USD)+ ).toThrow();+ });+});++describe("supplierPriceForQuantity", () => {+ const breaks = [+ { quantity: 1, supplierUnitPrice: 10 },+ { quantity: 100, supplierUnitPrice: 8 },+ { quantity: 50, supplierUnitPrice: 9 }+ ];++ it("takes the highest break at or below the quantity", () => {+ expect(supplierPriceForQuantity(breaks, 75, 12)).toBe(9);+ expect(supplierPriceForQuantity(breaks, 100, 12)).toBe(8);+ });++ it("falls back to the part's price below every break", () => {+ expect(supplierPriceForQuantity(breaks, 0.5, 12)).toBe(12);+ expect(supplierPriceForQuantity([], 5, null)).toBeNull();+ });+});++describe("buildSupplierPriceMap", () => {+ it("costs per inventory unit in base, with break quantities in inventory units", () => {+ // A box of 10 for 8 EUR = 10 USD = 1 USD each.+ const map = buildSupplierPriceMap(+ [+ {+ itemId: "item",+ currencyCode: "EUR",+ conversionFactor: 10,+ supplierUnitPrice: 8,+ priceBreaks: [{ quantity: 5, supplierUnitPrice: 4 }]+ }+ ],+ { EUR: 0.8 },+ "USD"+ );+ expect(map.item).toEqual({+ fallbackUnitPrice: 1,+ priceBreaks: [{ quantity: 50, unitPrice: 0.5 }]+ });+ });++ it("reads a part with no currency as base", () => {+ const map = buildSupplierPriceMap(+ [+ {+ itemId: "item",+ currencyCode: null,+ conversionFactor: 1,+ supplierUnitPrice: 3,+ priceBreaks: []+ }+ ],+ {},+ "USD"+ );+ expect(map.item?.fallbackUnitPrice).toBe(3);+ });++ it("compares suppliers in different currencies on one basis", () => {+ const map = buildSupplierPriceMap(+ [+ {+ itemId: "item",+ currencyCode: "USD",+ conversionFactor: 1,+ supplierUnitPrice: 9,+ priceBreaks: []+ },+ {+ itemId: "item",+ currencyCode: "GBP",+ conversionFactor: 1,+ // 4 GBP = 8 USD, cheaper than the 9 USD supplier+ supplierUnitPrice: 4,+ priceBreaks: []+ }+ ],+ { GBP: 0.5 },+ "USD"+ );+ expect(map.item?.fallbackUnitPrice).toBe(8);+ });++ it("leaves out a part whose currency has no rate", () => {+ const map = buildSupplierPriceMap(+ [+ {+ itemId: "item",+ currencyCode: "JPY",+ conversionFactor: 1,+ supplierUnitPrice: 100,+ priceBreaks: [{ quantity: 1, supplierUnitPrice: 90 }]+ }+ ],+ { JPY: null },+ "USD"+ );+ expect(map.item).toBeUndefined();+ });+});diff --git a/packages/database/src/supplier-part-price.ts b/packages/database/src/supplier-part-price.tsnew file mode 100644index 0000000000..85ea7f96d2--- /dev/null+++ b/packages/database/src/supplier-part-price.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// A supplier part's price is stored as the supplier quoted it:+// `supplierUnitPrice` per PURCHASE unit, in the part's `currencyCode` (NULL =+// the company base currency). Price breaks (`supplierPartPrice`) share the+// part's currency and are keyed by PURCHASE quantity.+//+// Nothing stores a converted copy. Every reader converts at the CURRENT rate+// when it uses the price, through this module:+// - a purchase document (order, invoice) wants it in the DOCUMENT's currency+// → `convertUnitPrice`;+// - quote costing wants base currency per INVENTORY unit+// → `buildSupplierPriceMap`.+//+// Rates are foreign-per-base ("units of the currency per 1 unit of the+// company's base currency"), the convention every document header stamps.++import { assertExchangeRate } from "./accounting-currency.ts";+import { round } from "./precision.ts";++/** A currency and its rate: units of `currencyCode` per 1 base unit. */+export type CurrencyRate = {+ currencyCode: string;+ exchangeRate: number;+};++/**+ * Convert a per-unit price from one currency to another through the company+ * base. The same code on both sides returns the price untouched — no FX round+ * trip, so a EUR price lands on a EUR order exactly as quoted.+ */+export function convertUnitPrice(+ price: number,+ from: CurrencyRate,+ to: CurrencyRate+): number {+ if (from.currencyCode === to.currencyCode) return price;+ assertExchangeRate(from.exchangeRate);+ assertExchangeRate(to.exchangeRate);+ return round((price / from.exchangeRate) * to.exchangeRate);+}++export type SupplierPriceBreak = {+ quantity: number;+ supplierUnitPrice: number;+};++/**+ * The supplier's price for a purchase quantity, in the part's own currency:+ * the highest break at or below the quantity, else the part's price.+ */+export function supplierPriceForQuantity(+ priceBreaks: SupplierPriceBreak[],+ quantity: number,+ fallbackUnitPrice: number | null+): number | null {+ let best: SupplierPriceBreak | null = null;+ for (const pb of priceBreaks) {+ if (pb.quantity <= quantity && (!best || pb.quantity > best.quantity)) {+ best = pb;+ }+ }+ return best ? best.supplierUnitPrice : fallbackUnitPrice;+}++/** The currency a supplier part's price is in; NULL predates the column. */+export function supplierPartCurrency(+ currencyCode: string | null | undefined,+ baseCurrencyCode: string+): string {+ return currencyCode ?? baseCurrencyCode;+}++export type SupplierPartPricing = {+ itemId: string;+ currencyCode: string | null;+ conversionFactor: number | null;+ supplierUnitPrice: number | null;+ priceBreaks: SupplierPriceBreak[];+};++/** A costing break: INVENTORY quantity and base-currency price per inventory unit. */+export type BuyPriceBreak = {+ quantity: number;+ unitPrice: number;+};++export type SupplierPriceMap = Record<+ string,+ {+ priceBreaks: BuyPriceBreak[];+ fallbackUnitPrice: number | null;+ }+>;++/**+ * Pool every supplier's pricing per item for quote costing, in base currency+ * per INVENTORY unit with break quantities in inventory units — the basis a+ * quote's bill of materials is costed on. Each supplier part is converted at+ * its own currency's current rate, so suppliers quoting in different+ * currencies compare on one basis. A part whose currency has no rate is left+ * out rather than costed at par.+ *+ * @param exchangeRates foreign-per-base rate by currency code+ */+export function buildSupplierPriceMap(+ parts: SupplierPartPricing[],+ exchangeRates: Record<string, number | null | undefined>,+ baseCurrencyCode: string+): SupplierPriceMap {+ const result: SupplierPriceMap = {};++ for (const part of parts) {+ const code = supplierPartCurrency(part.currencyCode, baseCurrencyCode);+ const rate = code === baseCurrencyCode ? 1 : exchangeRates[code];+ if (!rate || !Number.isFinite(rate) || rate <= 0) continue;++ const factor =+ part.conversionFactor && part.conversionFactor > 0+ ? part.conversionFactor+ : 1;+ const toInventoryBase = (price: number) => price / rate / factor;++ const entry = (result[part.itemId] ??= {+ priceBreaks: [],+ fallbackUnitPrice: null+ });++ if (part.supplierUnitPrice != null) {+ const price = toInventoryBase(part.supplierUnitPrice);+ if (entry.fallbackUnitPrice === null || price < entry.fallbackUnitPrice) {+ entry.fallbackUnitPrice = price;+ }+ }++ for (const pb of part.priceBreaks) {+ entry.priceBreaks.push({+ quantity: pb.quantity * factor,+ unitPrice: toInventoryBase(pb.supplierUnitPrice)+ });+ }+ }++ for (const entry of Object.values(result)) {+ entry.priceBreaks.sort((a, b) => a.quantity - b.quantity);+ }++ return result;+}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 39de922aa0..af89bdb5e8 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -20722,7 +20722,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPart.customFields"},{- $ref: "#/parameters/rowFilter.supplierPart.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPart.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPart.tags"@@ -20730,6 +20730,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPart.orderMultiple"},+ {+ $ref: "#/parameters/rowFilter.supplierPart.currencyCode"+ },{$ref: "#/parameters/select"},@@ -20832,7 +20835,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPart.customFields"},{- $ref: "#/parameters/rowFilter.supplierPart.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPart.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPart.tags"@@ -20840,6 +20843,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPart.orderMultiple"},+ {+ $ref: "#/parameters/rowFilter.supplierPart.currencyCode"+ },{$ref: "#/parameters/preferReturn"}@@ -20896,7 +20902,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPart.customFields"},{- $ref: "#/parameters/rowFilter.supplierPart.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPart.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPart.tags"@@ -20904,6 +20910,9 @@ export default {{$ref: "#/parameters/rowFilter.supplierPart.orderMultiple"},+ {+ $ref: "#/parameters/rowFilter.supplierPart.currencyCode"+ },{$ref: "#/parameters/body.supplierPart"},@@ -37993,7 +38002,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPartPrice.quantity"},{- $ref: "#/parameters/rowFilter.supplierPartPrice.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPartPrice.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPartPrice.sourceType"@@ -38085,7 +38094,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPartPrice.quantity"},{- $ref: "#/parameters/rowFilter.supplierPartPrice.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPartPrice.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPartPrice.sourceType"@@ -38131,7 +38140,7 @@ export default {$ref: "#/parameters/rowFilter.supplierPartPrice.quantity"},{- $ref: "#/parameters/rowFilter.supplierPartPrice.unitPrice"+ $ref: "#/parameters/rowFilter.supplierPartPrice.supplierUnitPrice"},{$ref: "#/parameters/rowFilter.supplierPartPrice.sourceType"@@ -62502,6 +62511,12 @@ export default {{$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"+ },{$ref: "#/parameters/select"},@@ -62591,6 +62606,12 @@ export default {{$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"+ },{$ref: "#/parameters/preferReturn"}@@ -62634,6 +62655,12 @@ export default {{$ref: "#/parameters/rowFilter.shipmentFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.shipmentFixedAssetLine.meter"+ },{$ref: "#/parameters/body.shipmentFixedAssetLine"},@@ -101052,6 +101079,24 @@ export default {{$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"+ },{$ref: "#/parameters/select"},@@ -101141,6 +101186,24 @@ export default {{$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"+ },{$ref: "#/parameters/preferReturn"}@@ -101184,6 +101247,24 @@ export default {{$ref: "#/parameters/rowFilter.receiptFixedAssetLine.updatedBy"},+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.rentalAgreementLineId"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.meter"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.notes"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.takeOutOfService"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.outOfServiceReason"+ },+ {+ $ref: "#/parameters/rowFilter.receiptFixedAssetLine.residualDestination"+ },{$ref: "#/parameters/body.receiptFixedAssetLine"},@@ -119099,7 +119180,8 @@ export default {"Inbound Transfer","Outbound Transfer","Manufacturing Consumption",- "Manufacturing Output"+ "Manufacturing Output",+ "Rental Agreement"],format: 'public."receiptSourceDocument"',type: "string"@@ -120466,7 +120548,8 @@ export default {"Inbound Transfer","Outbound Transfer","Manufacturing Consumption",- "Manufacturing Output"+ "Manufacturing Output",+ "Rental Agreement"],format: 'public."receiptSourceDocument"',type: "string"@@ -124475,8 +124558,10 @@ export default {customFields: {format: "jsonb"},- unitPrice: {+ supplierUnitPrice: {default: 0,+ description:+ "Price per purchase unit (supplierUnitOfMeasureCode), in currencyCode.",format: "numeric",type: "number"},@@ -124491,6 +124576,12 @@ export default {default: 1,format: "integer",type: "integer"+ },+ currencyCode: {+ description:+ "Currency of supplierUnitPrice and of every supplierPartPrice row. NULL = the company base currency.\n\nNote:\nThis is a Foreign Key to `currencyCode.code`.<fk table='currencyCode' column='code'/>",+ format: "text",+ type: "string"}},type: "object"@@ -132710,7 +132801,7 @@ export default {required: ["supplierPartId","quantity",- "unitPrice",+ "supplierUnitPrice","sourceType","companyId","createdBy",@@ -132729,7 +132820,9 @@ export default {format: "numeric",type: "number"},- unitPrice: {+ supplierUnitPrice: {+ description:+ "Price per purchase unit at this purchase quantity, in the supplier part's currencyCode.",format: "numeric",type: "number"},@@ -141134,7 +141227,8 @@ export default {"Purchase Invoice","Purchase Return Order","Inbound Transfer",- "Outbound Transfer"+ "Outbound Transfer",+ "Rental Agreement"],format: 'public."shipmentSourceDocument"',type: "string"@@ -143964,7 +144058,6 @@ export default {required: ["id","shipmentId",- "salesOrderLineId","shipped","companyId","createdBy",@@ -144022,6 +144115,14 @@ export default {updatedBy: {format: "text",type: "string"+ },+ rentalAgreementLineId: {+ format: "text",+ type: "string"+ },+ meter: {+ format: "numeric",+ type: "number"}},type: "object"@@ -162831,11 +162932,11 @@ export default {required: ["id","receiptId",- "purchaseOrderLineId","received","companyId","createdBy",- "createdAt"+ "createdAt",+ "takeOutOfService"],properties: {id: {@@ -162889,6 +162990,31 @@ export default {updatedBy: {format: "text",type: "string"+ },+ rentalAgreementLineId: {+ format: "text",+ type: "string"+ },+ meter: {+ format: "numeric",+ type: "number"+ },+ notes: {+ format: "text",+ type: "string"+ },+ takeOutOfService: {+ default: false,+ format: "boolean",+ type: "boolean"+ },+ outOfServiceReason: {+ format: "text",+ type: "string"+ },+ residualDestination: {+ format: "text",+ type: "string"}},type: "object"@@ -174115,8 +174241,10 @@ export default {in: "query",type: "string"},- "rowFilter.supplierPart.unitPrice": {- name: "unitPrice",+ "rowFilter.supplierPart.supplierUnitPrice": {+ name: "supplierUnitPrice",+ description:+ "Price per purchase unit (supplierUnitOfMeasureCode), in currencyCode.",required: false,in: "query",type: "string"@@ -174133,6 +174261,14 @@ export default {in: "query",type: "string"},+ "rowFilter.supplierPart.currencyCode": {+ name: "currencyCode",+ description:+ "Currency of supplierUnitPrice and of every supplierPartPrice row. NULL = the company base currency.",+ required: false,+ in: "query",+ type: "string"+ },"body.partner": {name: "partner",description: "partner",@@ -183350,8 +183486,10 @@ export default {in: "query",type: "string"},- "rowFilter.supplierPartPrice.unitPrice": {- name: "unitPrice",+ "rowFilter.supplierPartPrice.supplierUnitPrice": {+ name: "supplierUnitPrice",+ description:+ "Price per purchase unit at this purchase quantity, in the supplier part's currencyCode.",required: false,in: "query",type: "string"@@ -195866,6 +196004,18 @@ export default {in: "query",type: "string"},+ "rowFilter.shipmentFixedAssetLine.rentalAgreementLineId": {+ name: "rentalAgreementLineId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.shipmentFixedAssetLine.meter": {+ name: "meter",+ required: false,+ in: "query",+ type: "string"+ },"body.customerContractInvoiceLine": {name: "customerContractInvoiceLine",description: "customerContractInvoiceLine",@@ -216870,6 +217020,42 @@ export default {in: "query",type: "string"},+ "rowFilter.receiptFixedAssetLine.rentalAgreementLineId": {+ name: "rentalAgreementLineId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.receiptFixedAssetLine.meter": {+ name: "meter",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.receiptFixedAssetLine.notes": {+ name: "notes",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.receiptFixedAssetLine.takeOutOfService": {+ name: "takeOutOfService",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.receiptFixedAssetLine.outOfServiceReason": {+ name: "outOfServiceReason",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.receiptFixedAssetLine.residualDestination": {+ name: "residualDestination",+ required: false,+ in: "query",+ type: "string"+ },"body.kanban": {name: "kanban",description: "kanban",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5b2ef93155..28fe63f73a 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -63969,6 +63969,7 @@ export type Database = {conversionFactor: numbercreatedAt: stringcreatedBy: string+ currencyCode: string | nullcustomFields: Json | nullid: stringitemId: string@@ -63977,8 +63978,8 @@ export type Database = {supplierId: stringsupplierPartId: string | nullsupplierUnitOfMeasureCode: string | null+ supplierUnitPrice: number | nulltags: string[] | null- unitPrice: number | nullupdatedAt: string | nullupdatedBy: string | null}@@ -63988,6 +63989,7 @@ export type Database = {conversionFactor?: numbercreatedAt?: stringcreatedBy: string+ currencyCode?: string | nullcustomFields?: Json | nullid?: stringitemId: string@@ -63996,8 +63998,8 @@ export type Database = {supplierId: stringsupplierPartId?: string | nullsupplierUnitOfMeasureCode?: string | null+ supplierUnitPrice?: number | nulltags?: string[] | null- unitPrice?: number | nullupdatedAt?: string | nullupdatedBy?: string | null}@@ -64007,6 +64009,7 @@ export type Database = {conversionFactor?: numbercreatedAt?: stringcreatedBy?: string+ currencyCode?: string | nullcustomFields?: Json | nullid?: stringitemId?: string@@ -64015,8 +64018,8 @@ export type Database = {supplierId?: stringsupplierPartId?: string | nullsupplierUnitOfMeasureCode?: string | null+ supplierUnitPrice?: number | nulltags?: string[] | null- unitPrice?: number | nullupdatedAt?: string | nullupdatedBy?: string | null}@@ -64181,6 +64184,13 @@ export type Database = {isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "supplierPart_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]}]}@@ -64194,7 +64204,7 @@ export type Database = {sourceDocumentId: string | nullsourceType: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId: string- unitPrice: number+ supplierUnitPrice: numberupdatedAt: string | nullupdatedBy: string | null}@@ -64207,7 +64217,7 @@ export type Database = {sourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId: string- unitPrice: number+ supplierUnitPrice: numberupdatedAt?: string | nullupdatedBy?: string | null}@@ -64220,7 +64230,7 @@ export type Database = {sourceDocumentId?: string | nullsourceType?: Database["public"]["Enums"]["supplierPartPriceSourceType"]supplierPartId?: string- unitPrice?: number+ supplierUnitPrice?: numberupdatedAt?: string | nullupdatedBy?: string | null}diff --git a/packages/database/supabase/migrations/20261009181437_supplier-part-currency.sql b/packages/database/supabase/migrations/20261009181437_supplier-part-currency.sqlnew file mode 100644index 0000000000..99cfc01d61--- /dev/null+++ b/packages/database/supabase/migrations/20261009181437_supplier-part-currency.sql@@ -0,0 +1,466 @@+-- Supplier part prices in the supplier's currency.+--+-- A supplier quotes in its own currency, so a supplier part's price is now+-- stored as quoted: "supplierUnitPrice" in "currencyCode", per PURCHASE unit+-- (the supplier's unit of measure). Readers convert it at the CURRENT exchange+-- rate when they use it — onto a purchase order or invoice in the document's+-- currency, or into base for quote costing — so the price never goes stale+-- against a rate snapshot.+--+-- Price breaks ("supplierPartPrice") are in their supplier part's currency.++-- 1. The price columns hold the supplier's currency now: rename, keep the data.+-- The renames and the one-time per-unit repair (formerly step 4) run in+-- ONE block, and only while the old column still exists: a retried file+-- neither fails on the rename nor multiplies prices by conversionFactor a+-- second time.+DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_schema = 'public' AND table_name = 'supplierPart'+ AND column_name = 'unitPrice'+ ) THEN+ ALTER TABLE "supplierPart" RENAME COLUMN "unitPrice" TO "supplierUnitPrice";+ IF EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_schema = 'public' AND table_name = 'supplierPartPrice'+ AND column_name = 'unitPrice'+ ) THEN+ ALTER TABLE "supplierPartPrice" RENAME COLUMN "unitPrice" TO "supplierUnitPrice";+ END IF;++ -- One unit: per PURCHASE unit. Converting a supplier quote to a purchase+ -- order and finalizing a supplier quote stored the price per INVENTORY unit+ -- (÷ conversionFactor), while the purchase order and invoice forms, planning+ -- and update-purchased-prices all read and write it per purchase unit. The+ -- two only disagree when conversionFactor is not 1.+ --+ -- Price breaks from those two writers carry their source, so they are+ -- repaired exactly. The part's own price has no source; it was set to the+ -- cheapest of those breaks, so a part whose price still equals one of its+ -- Quote / Purchase Order breaks is repaired with them. A price that matches+ -- none was last written per purchase unit and is left alone. Runs before+ -- the break repair, which changes the values it compares against.+ UPDATE "supplierPart" sp+ SET "supplierUnitPrice" = sp."supplierUnitPrice" * sp."conversionFactor"+ WHERE sp."conversionFactor" IS NOT NULL+ AND sp."conversionFactor" NOT IN (0, 1)+ AND sp."supplierUnitPrice" IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM "supplierPartPrice" spp+ WHERE spp."supplierPartId" = sp."id"+ AND spp."companyId" = sp."companyId"+ AND spp."sourceType" IN ('Quote', 'Purchase Order')+ AND spp."supplierUnitPrice" = sp."supplierUnitPrice"+ );++ UPDATE "supplierPartPrice" spp+ SET "supplierUnitPrice" = spp."supplierUnitPrice" * sp."conversionFactor"+ FROM "supplierPart" sp+ WHERE sp."id" = spp."supplierPartId"+ AND sp."companyId" = spp."companyId"+ AND spp."sourceType" IN ('Quote', 'Purchase Order')+ AND sp."conversionFactor" IS NOT NULL+ AND sp."conversionFactor" NOT IN (0, 1);+ END IF;+END $$;++-- 2. The currency the price is in. Nullable so a backup taken before this+-- column still restores; readers treat NULL as the company's base currency,+-- which is what every price written before this migration was.+ALTER TABLE "supplierPart" ADD COLUMN IF NOT EXISTS "currencyCode" TEXT;++DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint WHERE conname = 'supplierPart_currencyCode_fkey'+ ) THEN+ ALTER TABLE "supplierPart"+ ADD CONSTRAINT "supplierPart_currencyCode_fkey"+ FOREIGN KEY ("currencyCode") REFERENCES "currencyCode"("code")+ ON UPDATE CASCADE ON DELETE SET NULL;+ END IF;+END $$;++CREATE INDEX IF NOT EXISTS "supplierPart_currencyCode_idx"+ ON "supplierPart" ("currencyCode");++COMMENT ON COLUMN "supplierPart"."supplierUnitPrice" IS+ 'Price per purchase unit (supplierUnitOfMeasureCode), in currencyCode.';+COMMENT ON COLUMN "supplierPart"."currencyCode" IS+ 'Currency of supplierUnitPrice and of every supplierPartPrice row. NULL = the company base currency.';+COMMENT ON COLUMN "supplierPartPrice"."supplierUnitPrice" IS+ 'Price per purchase unit at this purchase quantity, in the supplier part''s currencyCode.';++-- 3. Every existing price was written in base currency.+UPDATE "supplierPart" sp+SET "currencyCode" = c."baseCurrencyCode"+FROM "company" c+WHERE c."id" = sp."companyId"+ AND sp."currencyCode" IS NULL;++-- ============================================================+-- 5. get_purchasing_planning: each supplier now reports its price as quoted+-- (supplierUnitPrice + currencyCode) instead of the renamed base column.+-- Forked from 20261006130001_demand-forecast-consumption.sql.+-- ============================================================+CREATE OR REPLACE FUNCTION public.get_purchasing_planning(company_id text, location_id text, periods text[])+ RETURNS TABLE(id text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "purchasingBlocked" boolean, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "orderMultiple" integer, "quantityOnHand" numeric, "maximumInventoryQuantity" numeric, suppliers jsonb, "preferredSupplierId" text, "purchasingUnitOfMeasureCode" text, "conversionFactor" numeric, "quantityToOrder" numeric, "supersessionMode" text, "minimumReserveQuantity" numeric, week1 numeric, week2 numeric, week3 numeric, week4 numeric, week5 numeric, week6 numeric, week7 numeric, week8 numeric, week9 numeric, week10 numeric, week11 numeric, week12 numeric, week13 numeric, week14 numeric, week15 numeric, week16 numeric, week17 numeric, week18 numeric, week19 numeric, week20 numeric, week21 numeric, week22 numeric, week23 numeric, week24 numeric, week25 numeric, week26 numeric, week27 numeric, week28 numeric, week29 numeric, week30 numeric, week31 numeric, week32 numeric, week33 numeric, week34 numeric, week35 numeric, week36 numeric, week37 numeric, week38 numeric, week39 numeric, week40 numeric, week41 numeric, week42 numeric, week43 numeric, week44 numeric, week45 numeric, week46 numeric, week47 numeric, week48 numeric, week49 numeric, week50 numeric, week51 numeric, week52 numeric)+ LANGUAGE sql+ SECURITY DEFINER+AS $function$+ SELECT assert_company_access(company_id);+ WITH RECURSIVE+ supply_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "supplyActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "supplyForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ demand_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "demandActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "demandForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ -- Top-level manual projections, net of forecast consumption: actual+ -- demand consumed them during the MRP run (consumedQuantity), so only+ -- the unconsumed remainder still drives demand here. Without this arm a+ -- purchased item whose only demand is a projection never appears in+ -- purchasing planning and never drives a suggested order.+ SELECT "itemId", "periodId", NULL as "actualQuantity",+ GREATEST("forecastQuantity" - "consumedQuantity", 0) AS "forecastQuantity"+ FROM "demandProjection"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ base_items AS (+ SELECT DISTINCT ON (i."id")+ i."id",+ i."readableIdWithRevision",+ i."name",+ i."active",+ i."type",+ i."itemTrackingType",+ i."replenishmentSystem",+ CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END AS "thumbnailPath",+ i."unitOfMeasureCode",+ ir."leadTime",+ ir."purchasingBlocked",+ ir."lotSize",+ ir."preferredSupplierId",+ ir."purchasingUnitOfMeasureCode",+ ir."conversionFactor",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."orderMultiple",+ ip."maximumInventoryQuantity",+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",+ COALESCE((+ SELECT SUM("quantity")+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "itemId" = i."id"+ ), 0) AS "quantityOnHand"+ FROM "item" i+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"+ LEFT JOIN (+ SELECT+ ps."itemId",+ jsonb_agg(+ jsonb_build_object(+ 'id', ps."id",+ 'minimumOrderQuantity', ps."minimumOrderQuantity",+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",+ 'conversionFactor', ps."conversionFactor",+ 'supplierUnitPrice', ps."supplierUnitPrice",+ 'currencyCode', ps."currencyCode",+ 'supplierId', ps."supplierId",+ 'supplierPartId', ps."supplierPartId"+ )+ ) AS "suppliers"+ FROM "supplierPart" ps+ WHERE ps."companyId" = company_id+ AND ps.active = true+ GROUP BY ps."itemId"+ ) ps ON ps."itemId" = i."id"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" != 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ -- Supersession: drop obsolete items and items past their discontinuation+ -- date so no new orders are suggested.+ AND NOT EXISTS (+ SELECT 1 FROM "itemSupersession" ss+ WHERE ss."itemId" = i."id"+ AND (+ ss."supersessionMode" = 'No Stock'+ OR (+ -- date-based suppression applies only to the phase-out modes; Stock+ -- Only keeps replenishing to its reserve floor regardless of date.+ ss."supersessionMode" IN ('Consume First', 'Prefer New')+ AND ss."discontinuationDate" IS NOT NULL+ AND ss."discontinuationDate" <= CURRENT_DATE+ )+ )+ )+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ projections AS (+ SELECT+ bi.*,+ periods[1] as "periodId",+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ 1 as period_index+ FROM base_items bi+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]++ UNION ALL++ SELECT+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."quantityOnHand",+ periods[p.period_index + 1] as "periodId",+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ p.period_index + 1 as period_index+ FROM projections p+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]+ WHERE p.period_index < array_length(periods, 1)+ ),+ order_quantities AS (+ SELECT+ p."id",+ calculate_quantity_to_order(+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ array_agg(p."projection" ORDER BY p.period_index)+ ) AS "quantityToOrder"+ FROM projections p+ GROUP BY+ p."id",+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock"+ )+ SELECT DISTINCT ON (p."id")+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ CASE+ WHEN ss."supersessionMode" = 'Stock Only'+ THEN GREATEST(+ 0,+ COALESCE(rsv."minimumReserveQuantity", 0)+ - p."quantityOnHand"+ - COALESCE(sup."incomingSupply", 0)+ )+ ELSE COALESCE(oq."quantityToOrder", 0)+ END AS "quantityToOrder",+ ss."supersessionMode" AS "supersessionMode",+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"+ FROM projections p+ LEFT JOIN order_quantities oq ON p."id" = oq."id"+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id+ LEFT JOIN (+ SELECT "itemId", SUM("supply") AS "incomingSupply"+ FROM supply_data GROUP BY "itemId"+ ) sup ON sup."itemId" = p."id"+ GROUP BY+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ oq."quantityToOrder",+ ss."supersessionMode",+ rsv."minimumReserveQuantity",+ sup."incomingSupply";+$function$;diff --git a/packages/ee/src/workflows/catalog/events.generated.ts b/packages/ee/src/workflows/catalog/events.generated.tsindex aa995b1985..91eb5e51df 100644--- a/packages/ee/src/workflows/catalog/events.generated.ts+++ b/packages/ee/src/workflows/catalog/events.generated.ts@@ -1466,7 +1466,8 @@ export const WORKFLOW_ENTITY_ENUMS: Record<"Inbound Transfer","Outbound Transfer","Manufacturing Consumption",- "Manufacturing Output"+ "Manufacturing Output",+ "Rental Agreement"],status: ["Draft", "Pending", "Posted", "Voided"]},@@ -1507,7 +1508,8 @@ export const WORKFLOW_ENTITY_ENUMS: Record<"Purchase Invoice","Purchase Return Order","Inbound Transfer",- "Outbound Transfer"+ "Outbound Transfer",+ "Rental Agreement"],status: ["Draft", "Pending", "Posted", "Voided"]},diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex b961105847..a9b47aac69 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261009163952",+ "schemaVersion": "20261009181437","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-09T15:41:38.767Z",+ "exportedAt": "2026-10-09T16:38:00.554Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -7185,9 +7185,10 @@"updatedBy","updatedAt","customFields",- "unitPrice",+ "supplierUnitPrice","tags",- "orderMultiple"+ "orderMultiple",+ "currencyCode"]},{@@ -7196,7 +7197,7 @@"columns": ["supplierPartId","quantity",- "unitPrice",+ "supplierUnitPrice","sourceType","sourceDocumentId","companyId",diff --git a/packages/jobs/src/backups/renames.test.ts b/packages/jobs/src/backups/renames.test.tsindex eb38307153..abb5f7950d 100644--- a/packages/jobs/src/backups/renames.test.ts+++ b/packages/jobs/src/backups/renames.test.ts@@ -3,7 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { afterEach, describe, expect, it } from "vitest";-import { applyTableRenames, TABLE_RENAMES } from "./renames";+import {+ applyTableRenames,+ LIVE_COLUMN_RENAMES,+ TABLE_RENAMES+} from "./renames";const catalog = (...names: string[]) => ({tables: names.map((name) => ({ name }))@@ -148,6 +152,47 @@ describe("applyTableRenames", () => {expect(input.data.cardTransaction?.[0]).toHaveProperty("cardTransactionId");});+ it("renames a column on a table that kept its name", () => {+ const input = {+ manifest: {+ tables: [+ { name: "supplierPart", rows: 1, columns: ["id", "unitPrice"] }+ ]+ },+ data: { supplierPart: [{ id: "sp", unitPrice: 4.25 }] }+ };+ const out = applyTableRenames(catalog("supplierPart"), input);+ expect(out.manifest.tables[0]!.columns).toEqual([+ "id",+ "supplierUnitPrice"+ ]);+ expect(out.data.supplierPart).toEqual([+ { id: "sp", supplierUnitPrice: 4.25 }+ ]);+ expect(input.data.supplierPart[0]).toHaveProperty("unitPrice");+ });++ it("leaves a backup taken after the column rename alone", () => {+ expect(LIVE_COLUMN_RENAMES.supplierPart).toEqual({+ unitPrice: "supplierUnitPrice"+ });+ const input = {+ manifest: {+ tables: [+ {+ name: "supplierPart",+ rows: 1,+ columns: ["id", "supplierUnitPrice"]+ }+ ]+ },+ data: { supplierPart: [{ id: "sp", supplierUnitPrice: 4.25 }] }+ };+ const out = applyTableRenames(catalog("supplierPart"), input);+ expect(out.manifest.tables[0]).toBe(input.manifest.tables[0]);+ expect(out.data.supplierPart).toBe(input.data.supplierPart);+ });+it("does not mutate the backup it was given", () => {withRenames({ quoteLine: "quotationLine" });const input = backup({ quoteLine: 1 });diff --git a/packages/jobs/src/backups/renames.ts b/packages/jobs/src/backups/renames.tsindex 0d437cfd98..4cb167fb53 100644--- a/packages/jobs/src/backups/renames.ts+++ b/packages/jobs/src/backups/renames.ts@@ -47,6 +47,44 @@ export const COLUMN_RENAMES: Record<string, Record<string, string>> = {cardTransactionLine: { cardTransactionId: "chargeId" }};+/**+ * Columns renamed on a table that KEPT its name, keyed by the table's current+ * name. Without an entry an older backup's values for the old column are+ * reported "removed since this backup" and silently not restored. A column is+ * only renamed when the backup does not already carry the new name, so a+ * backup taken after the rename passes through untouched.+ */+export const LIVE_COLUMN_RENAMES: Record<string, Record<string, string>> = {+ // 2026-10 (supplier part currency): the price is now stored in the supplier+ // part's own currency, which every pre-rename price was (the base currency;+ // a NULL currencyCode reads as base).+ supplierPart: { unitPrice: "supplierUnitPrice" },+ supplierPartPrice: { unitPrice: "supplierUnitPrice" }+};++/** A live table's column list under its CURRENT column names. */+export function renameLiveColumns(table: string, columns: string[]): string[] {+ const map = liveColumnMap(table, columns);+ if (!map) return columns;+ return columns.map((column) => map[column] ?? column);+}++/** The renames that apply to this backup's copy of the table, if any. */+function liveColumnMap(+ table: string,+ columns: string[]+): Record<string, string> | null {+ const map = LIVE_COLUMN_RENAMES[table];+ if (!map) return null;+ const present = new Set(columns);+ const applicable = Object.fromEntries(+ Object.entries(map).filter(+ ([from, to]) => present.has(from) && !present.has(to)+ )+ );+ return Object.keys(applicable).length > 0 ? applicable : null;+}+/** A renamed table's column list under its CURRENT column names. */export function renameColumns(oldTable: string, columns: string[]): string[] {const map = COLUMN_RENAMES[oldTable];@@ -60,6 +98,13 @@ function renameRowColumns(): Record<string, unknown>[] {const map = COLUMN_RENAMES[oldTable];if (!map) return rows;+ return renameRows(map, rows);+}++function renameRows(+ map: Record<string, string>,+ rows: Record<string, unknown>[]+): Record<string, unknown>[] {return rows.map((row) => {const renamed: Record<string, unknown> = {};for (const [column, value] of Object.entries(row)) {@@ -105,12 +150,20 @@ export function applyTableRenames<delete data[t.name];continue;}- tables.push(- to === t.name- ? t- : { ...t, name: to, columns: renameColumns(t.name, t.columns) }- );- if (to !== t.name && backup.data[t.name]) {+ if (to === t.name) {+ const map = liveColumnMap(t.name, t.columns);+ if (!map) {+ tables.push(t);+ continue;+ }+ tables.push({ ...t, columns: renameLiveColumns(t.name, t.columns) });+ if (backup.data[t.name]) {+ data[t.name] = renameRows(map, backup.data[t.name]!);+ }+ continue;+ }+ tables.push({ ...t, name: to, columns: renameColumns(t.name, t.columns) });+ if (backup.data[t.name]) {data[to] = renameRowColumns(t.name, backup.data[t.name]!);delete data[t.name];}diff --git a/packages/jobs/src/backups/schema.test.ts b/packages/jobs/src/backups/schema.test.tsindex 79712c9af0..9a1e7b4698 100644--- a/packages/jobs/src/backups/schema.test.ts+++ b/packages/jobs/src/backups/schema.test.ts@@ -23,6 +23,10 @@ vi.mock("./renames", () => ({danglingRename: "alsoMissing"},COLUMN_RENAMES: { oldName: { legacyId: "newId" } },+ renameLiveColumns: (table: string, columns: string[]) =>+ table === "keptName" && !columns.includes("newPrice")+ ? columns.map((c) => (c === "oldPrice" ? "newPrice" : c))+ : columns,renameColumns: (table: string, columns: string[]) =>table === "oldName"? columns.map((c) => (c === "legacyId" ? "newId" : c))@@ -238,6 +242,16 @@ describe("reportBackupCompatibility — TABLE_RENAMES", () => {expect(result.blocked).toBe(false);});+ it("compares a renamed column on a kept table under its current name", () => {+ const result = reportBackupCompatibility(+ catalog([table("keptName", [col("id"), col("newPrice")])]),+ backup([{ name: "keptName", rows: 1, columns: ["id", "oldPrice"] }])+ );++ expect(result.findings).toEqual([]);+ expect(result.blocked).toBe(false);+ });+it("blocks when the rename target is also missing", () => {const result = reportBackupCompatibility(catalog([table("item", [col("id")])]),diff --git a/packages/jobs/src/backups/schema.ts b/packages/jobs/src/backups/schema.tsindex 82c56af6ab..e275ac877c 100644--- a/packages/jobs/src/backups/schema.ts+++ b/packages/jobs/src/backups/schema.ts@@ -5,7 +5,7 @@import type { TableName } from "@carbon/database/audit.config";import type { KyselyDatabase } from "@carbon/database/client";import { type Kysely, sql } from "kysely";-import { renameColumns, TABLE_RENAMES } from "./renames";+import { renameColumns, renameLiveColumns, TABLE_RENAMES } from "./renames";/*** Schema introspection + backup-compatibility logic, shared by the backup jobs@@ -562,10 +562,11 @@ export function reportBackupCompatibility(}}- // A renamed table's columns are compared under their CURRENT names, so a- // column that moved with the table is not reported as both added and removed.+ // A renamed table's (or renamed column's) values are compared under their+ // CURRENT names, so a column that moved is not reported as both added and+ // removed.const backupColumnNames = liveByName.has(backupTable.name)- ? backupTable.columns+ ? renameLiveColumns(backupTable.name, backupTable.columns): renameColumns(backupTable.name, backupTable.columns);const backupCols = new Set(backupColumnNames);for (const c of live.columns) {diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex dd845a19ce..6363d5d3de 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# Arbeitsgang hat keine Zeitstandards} other {# Arbeits#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# Datensatz benötigt Aufmerksamkeit} other {# Datensätze benötigen Aufmerksamkeit}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} Einheiten"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} erstellt, {updated} aktualisiert."msgid "{days}d"msgstr "{days}T"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} von {count} Arbeitsgängen"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {Und # weiterer Datensatz.} other {Und # weitere Datensätze.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} weitere: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Nachname"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Letzte Übertragung {when} fehlgeschlagen: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Letzte Übertragung {when}:"msgid "Last Quarter"msgstr "Letztes Quartal"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Letzte Ausführung"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Letzte geplante Übertragung {when}:"msgid "Last synced: <0/>"msgstr "Zuletzt synchronisiert: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Mehr Überstunden"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Weitere Datensätze warten. Übertragen Sie erneut, um fortzufahren."msgid "Morning, {name}."msgstr "Morgen, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Bewegung"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount hat {matches} Datensätze mit dieser Kennung. Löschen oder führen Sie die zusätzlichen Datensätze in Mount zusammen und übertragen Sie dann erneut."msgid "Move"msgstr "Verschieben"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Noch keine Kommentare. Seien Sie der Erste, der einen Kommentar hinzufügt."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Keine Unternehmen entsprechen „{query}\""msgid "No completed jobs within range"msgstr "Keine fertiggestellten Fertigungsaufträge im Bereich"@@ -13923,6 +13923,12 @@ msgstr "Keine Lagereinheiten oder Verfolgungsnummern stimmen überein."msgid "No Supplier"msgstr "Kein Lieferant"+msgid "No supplier parts have been added yet."+msgstr "Noch keine Lieferantenteile hinzugefügt."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Keine Lieferantenteile entsprechen „{searchText}\"."+msgid "No suppliers yet"msgstr "Noch keine Lieferanten"@@ -15203,6 +15209,9 @@ msgstr "pro Tag"msgid "per month"msgstr "pro Monat"+msgid "Per purchase unit"+msgstr "Pro Einkaufseinheit"+msgid "per quarter"msgstr "pro Quartal"@@ -18260,9 +18269,6 @@ msgstr "Entwurf speichern"msgid "Save Method"msgstr "Methode speichern"-msgid "Save Rate"-msgstr "Kurs speichern"-msgid "Save the form you're editing"msgstr "Das bearbeitete Formular speichern"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Felder durchsuchen..."msgid "Search for a company"-msgstr ""+msgstr "Nach einem Unternehmen suchen"msgid "Search for existing or create a new one"msgstr "Suchen Sie nach einem vorhandenen oder erstellen Sie einen neuen"@@ -18519,6 +18525,9 @@ msgstr "Nach verwandten Elementen suchen..."msgid "Search storage units and tracking numbers"msgstr "Lagereinheiten und Verfolgungsnummern suchen"+msgid "Search supplier parts"+msgstr "Lieferantenteile durchsuchen"+msgid "Search suppliers..."msgstr "Lieferanten durchsuchen..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Gestartet"msgid "Starting"-msgstr ""+msgstr "Wird gestartet"msgid "Starting…"msgstr "Wird gestartet…"@@ -20217,6 +20226,9 @@ msgstr "Lieferantenübersicht"msgid "Supplier Part"msgstr "Lieferantenteil"+msgid "Supplier part actions"+msgstr "Lieferantenteil-Aktionen"+msgid "Supplier Part ID"msgstr "Lieferantenartikelnummer"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "Die Bestellung"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Die Übertragung an Mount hat nicht begonnen. Versuchen Sie es erneut."msgid "The push to Mount failed"-msgstr ""+msgstr "Die Übertragung an Mount ist fehlgeschlagen"msgid "The push to Mount finished"-msgstr ""+msgstr "Die Übertragung an Mount ist abgeschlossen"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Die Übertragung an Mount ist abgeschlossen. Einige Datensätze benötigen Aufmerksamkeit"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Die Mengenestaffeln, zu denen diese Position bewertet ist; jede Spalte hat seinen eigenen Stückpreis für Käufer–Lieferant-Verhandlungen und für die Umwandlung in nachgelagerte Dokumente."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Auslöser"msgid "Try a different name."-msgstr ""+msgstr "Versuchen Sie einen anderen Namen."msgid "Tuesday"msgstr "Dienstag"@@ -23338,6 +23350,9 @@ msgstr "Im Projektplan anzeigen"msgid "View Issue"msgstr "Problem anzeigen"+msgid "View Item"+msgstr "Artikel anzeigen"+msgid "View Item Master"msgstr "Artikelstamm anzeigen"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex fc63f71cfa..983ca51462 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -13923,6 +13923,12 @@ msgstr "No storage units or tracking numbers match."msgid "No Supplier"msgstr "No Supplier"+msgid "No supplier parts have been added yet."+msgstr "No supplier parts have been added yet."++msgid "No supplier parts match \"{searchText}\"."+msgstr "No supplier parts match \"{searchText}\"."+msgid "No suppliers yet"msgstr "No suppliers yet"@@ -15203,6 +15209,9 @@ msgstr "per day"msgid "per month"msgstr "per month"+msgid "Per purchase unit"+msgstr "Per purchase unit"+msgid "per quarter"msgstr "per quarter"@@ -18260,9 +18269,6 @@ msgstr "Save Draft"msgid "Save Method"msgstr "Save Method"-msgid "Save Rate"-msgstr "Save Rate"-msgid "Save the form you're editing"msgstr "Save the form you're editing"@@ -18519,6 +18525,9 @@ msgstr "Search related items..."msgid "Search storage units and tracking numbers"msgstr "Search storage units and tracking numbers"+msgid "Search supplier parts"+msgstr "Search supplier parts"+msgid "Search suppliers..."msgstr "Search suppliers..."@@ -20217,6 +20226,9 @@ msgstr "Supplier Overview"msgid "Supplier Part"msgstr "Supplier Part"+msgid "Supplier part actions"+msgstr "Supplier part actions"+msgid "Supplier Part ID"msgstr "Supplier Part ID"@@ -23338,6 +23350,9 @@ msgstr "View in project plan"msgid "View Issue"msgstr "View Issue"+msgid "View Item"+msgstr "View Item"+msgid "View Item Master"msgstr "View Item Master"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 3411ff4d00..95cee869a4 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operación no tiene estándares de tiempo} other {# o#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# registro necesita atención} other {# registros necesitan atención}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} unidades"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} creados, {updated} actualizados."msgid "{days}d"msgstr "{days}d"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} de {count} operaciones"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {Y # registro más.} other {Y # registros más.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} más: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Apellido"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Último envío {when} falló: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Último envío {when}:"msgid "Last Quarter"msgstr "Trimestre Anterior"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Última ejecución"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Último envío programado {when}:"msgid "Last synced: <0/>"msgstr "Última sincronización: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Más horas extra"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Hay más registros en espera. Envía de nuevo para continuar."msgid "Morning, {name}."msgstr "Mañana, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Movimiento"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount tiene {matches} registros con este identificador. Elimina o fusiona los extras en Mount, luego envía de nuevo."msgid "Move"msgstr "Mover"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "No hay comentarios aún. Sé el primero en agregar un comentario."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Ninguna empresa coincide con «{query}»"msgid "No completed jobs within range"msgstr "No hay órdenes de trabajo completadas dentro del rango"@@ -13923,6 +13923,12 @@ msgstr "No coinciden unidades de almacenamiento ni números de seguimiento."msgid "No Supplier"msgstr "Sin proveedor"+msgid "No supplier parts have been added yet."+msgstr "Aún no se han añadido piezas de proveedor."++msgid "No supplier parts match \"{searchText}\"."+msgstr "No hay piezas de proveedor que coincidan con «{searchText}»."+msgid "No suppliers yet"msgstr "Sin proveedores aún"@@ -15203,6 +15209,9 @@ msgstr "por día"msgid "per month"msgstr "por mes"+msgid "Per purchase unit"+msgstr "Por unidad de compra"+msgid "per quarter"msgstr "por trimestre"@@ -18260,9 +18269,6 @@ msgstr "Guardar borrador"msgid "Save Method"msgstr "Guardar Método"-msgid "Save Rate"-msgstr "Guardar tipo de cambio"-msgid "Save the form you're editing"msgstr "Guardar el formulario que estás editando"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Buscar campos..."msgid "Search for a company"-msgstr ""+msgstr "Buscar una empresa"msgid "Search for existing or create a new one"msgstr "Buscar uno existente o crear uno nuevo"@@ -18519,6 +18525,9 @@ msgstr "Buscar elementos relacionados..."msgid "Search storage units and tracking numbers"msgstr "Buscar unidades de almacenamiento y números de seguimiento"+msgid "Search supplier parts"+msgstr "Buscar piezas de proveedor"+msgid "Search suppliers..."msgstr "Buscar proveedores..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Comenzó"msgid "Starting"-msgstr ""+msgstr "Iniciando"msgid "Starting…"msgstr "Iniciando…"@@ -20217,6 +20226,9 @@ msgstr "Descripción General del Proveedor"msgid "Supplier Part"msgstr "Parte del Proveedor"+msgid "Supplier part actions"+msgstr "Acciones de piezas de proveedor"+msgid "Supplier Part ID"msgstr "Referencia del proveedor"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "La orden de compra"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "El envío a Mount no se inició. Inténtalo de nuevo."msgid "The push to Mount failed"-msgstr ""+msgstr "El envío a Mount falló"msgid "The push to Mount finished"-msgstr ""+msgstr "El envío a Mount finalizó"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "El envío a Mount finalizó. Algunos registros necesitan atención"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Los puntos de ruptura de cantidad a los que se cotiza esta línea; cada columna lleva su propio precio por unidad para la negociación comprador-proveedor y para la conversión a documentos posteriores."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Disparadores"msgid "Try a different name."-msgstr ""+msgstr "Intenta un nombre diferente."msgid "Tuesday"msgstr "Martes"@@ -23338,6 +23350,9 @@ msgstr "Ver en plan del proyecto"msgid "View Issue"msgstr "Ver Problema"+msgid "View Item"+msgstr "Ver Artículo"+msgid "View Item Master"msgstr "Ver Maestro de Artículos"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex dd6e228f40..cf17f589e7 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# opération n'a pas de normes de temps} other {# opér#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# enregistrement nécessite une attention} other {# enregistrements nécessitent une attention}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} unités"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} créé(s), {updated} mis à jour."msgid "{days}d"msgstr "{days}j"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} sur {count} opérations"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {Et # enregistrement de plus.} other {Et # enregistrements de plus.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} autres : {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Nom de famille"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Le dernier envoi {when} a échoué : {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Dernier envoi {when} :"msgid "Last Quarter"msgstr "Dernier trimestre"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Dernière exécution"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Dernier envoi planifié {when} :"msgid "Last synced: <0/>"msgstr "Dernière synchronisation : <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Plus d'heures supplémentaires"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "D'autres enregistrements attendent. Envoyez à nouveau pour continuer."msgid "Morning, {name}."msgstr "Bon matin, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Motion"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount a {matches} enregistrements avec cet identifiant. Supprimez ou fusionnez les doublons dans Mount, puis envoyez à nouveau."msgid "Move"msgstr "Déplacer"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Aucun commentaire pour le moment. Soyez le premier à ajouter un commentaire."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Aucune société ne correspond à « {query} »"msgid "No completed jobs within range"msgstr "Aucun ordre de fabrication terminé dans cette plage"@@ -13923,6 +13923,12 @@ msgstr "Aucune unité de stockage ou numéro de suivi ne correspond."msgid "No Supplier"msgstr "Aucun fournisseur"+msgid "No supplier parts have been added yet."+msgstr "Aucune pièce fournisseur n'a été ajoutée pour le moment."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Aucune pièce fournisseur ne correspond à « {searchText} »."+msgid "No suppliers yet"msgstr "Aucun fournisseur pour le moment"@@ -15203,6 +15209,9 @@ msgstr "par jour"msgid "per month"msgstr "par mois"+msgid "Per purchase unit"+msgstr "Par unité d'achat"+msgid "per quarter"msgstr "par trimestre"@@ -18260,9 +18269,6 @@ msgstr "Enregistrer le brouillon"msgid "Save Method"msgstr "Enregistrer la méthode"-msgid "Save Rate"-msgstr "Enregistrer le taux"-msgid "Save the form you're editing"msgstr "Enregistrer le formulaire que vous modifiez"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Rechercher des champs..."msgid "Search for a company"-msgstr ""+msgstr "Rechercher une société"msgid "Search for existing or create a new one"msgstr "Rechercher un existant ou en créer un nouveau"@@ -18519,6 +18525,9 @@ msgstr "Rechercher les articles associés..."msgid "Search storage units and tracking numbers"msgstr "Rechercher les unités de stockage et numéros de suivi"+msgid "Search supplier parts"+msgstr "Rechercher des pièces fournisseur"+msgid "Search suppliers..."msgstr "Rechercher des fournisseurs..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Commencé"msgid "Starting"-msgstr ""+msgstr "Démarrage"msgid "Starting…"msgstr "Démarrage…"@@ -20217,6 +20226,9 @@ msgstr "Aperçu du fournisseur"msgid "Supplier Part"msgstr "Pièce Fournisseur"+msgid "Supplier part actions"+msgstr "Actions des pièces fournisseur"+msgid "Supplier Part ID"msgstr "Référence fournisseur"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "Le bon de commande"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "L'envoi vers Mount n'a pas commencé. Réessayez."msgid "The push to Mount failed"-msgstr ""+msgstr "L'envoi vers Mount a échoué"msgid "The push to Mount finished"-msgstr ""+msgstr "L'envoi vers Mount est terminé"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "L'envoi vers Mount est terminé. Certains enregistrements nécessitent une attention."msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Les points d'arrêt de quantité à laquelle cette ligne est tarifée; chaque colonne porte son propre prix par unité pour la négociation acheteur-fournisseur et la conversion en documents aval."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Déclencheurs"msgid "Try a different name."-msgstr ""+msgstr "Essayez un nom différent."msgid "Tuesday"msgstr "Mardi"@@ -23338,6 +23350,9 @@ msgstr "Afficher dans le plan du projet"msgid "View Issue"msgstr "Afficher le problème"+msgid "View Item"+msgstr "Afficher l'article"+msgid "View Item Master"msgstr "Afficher la fiche article"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 4727312d0f..899bdb037c 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# ऑपरेशन के लिए कोई सम#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# रिकॉर्ड को ध्यान की आवश्यकता है} other {# रिकॉर्ड को ध्यान की आवश्यकता है}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} इकाइयाँ"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} बनाया गया, {updated} अपडेट किया गया।"msgid "{days}d"msgstr "{days}d"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{count} ऑपरेशन में से {from}–{to}"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {और # अधिक रिकॉर्ड।} other {और # अधिक रिकॉर्ड।}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "और {hiddenCount}: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "अंतिम नाम"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "अंतिम पुश {when} विफल: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "अंतिम पुश {when}:"msgid "Last Quarter"msgstr "पिछली तिमाही"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "अंतिम रन"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "अंतिम निर्धारित पुश {when}:"msgid "Last synced: <0/>"msgstr "अंतिम सिंक: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "अधिक ओवरटाइम"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "अधिक रिकॉर्ड प्रतीक्षा कर रहे हैं। जारी रखने के लिए फिर से पुश करें।"msgid "Morning, {name}."msgstr "सुबह, {name}।"@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "गति"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount में इस पहचानकर्ता के साथ {matches} रिकॉर्ड हैं। Mount में अतिरिक्त को हटाएँ या विलय करें, फिर फिर से पुश करें।"msgid "Move"msgstr "स्थानांतरित करें"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "अभी कोई टिप्पणी नहीं है। पहली टिप्पणी जोड़ने वाले बनें।"msgid "No companies match \"{query}\""-msgstr ""+msgstr "कोई कंपनी \"{query}\" से मेल नहीं खाती"msgid "No completed jobs within range"msgstr "रेंज में कोई पूर्ण जॉब नहीं"@@ -13923,6 +13923,12 @@ msgstr "कोई भंडारण इकाई या ट्रैकिंmsgid "No Supplier"msgstr "कोई आपूर्तिकर्ता नहीं"+msgid "No supplier parts have been added yet."+msgstr "कोई आपूर्तिकर्ता पार्ट्स अभी तक नहीं जोड़े गए हैं।"++msgid "No supplier parts match \"{searchText}\"."+msgstr "कोई आपूर्तिकर्ता पार्ट्स \"{searchText}\" से मेल नहीं खाते।"+msgid "No suppliers yet"msgstr "अभी तक कोई आपूर्तिकर्ता नहीं"@@ -15203,6 +15209,9 @@ msgstr "प्रति दिन"msgid "per month"msgstr "प्रति माह"+msgid "Per purchase unit"+msgstr "प्रति खरीद इकाई"+msgid "per quarter"msgstr "प्रति तिमाही"@@ -18260,9 +18269,6 @@ msgstr "ड्राफ्ट सहेजें"msgid "Save Method"msgstr "विधि सहेजें"-msgid "Save Rate"-msgstr "दर सहेजें"-msgid "Save the form you're editing"msgstr "जिस फॉर्म को आप संपादित कर रहे हैं उसे सहेजें"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "फ़ील्ड खोजें..."msgid "Search for a company"-msgstr ""+msgstr "एक कंपनी के लिए खोजें"msgid "Search for existing or create a new one"msgstr "मौजूदा को खोजें या नया बनाएं"@@ -18519,6 +18525,9 @@ msgstr "संबंधित आइटम खोजें..."msgid "Search storage units and tracking numbers"msgstr "भंडारण इकाइयों और ट्रैकिंग संख्याओं को खोजें"+msgid "Search supplier parts"+msgstr "आपूर्तिकर्ता पार्ट्स को खोजें"+msgid "Search suppliers..."msgstr "आपूर्तिकर्ताओं को खोजें..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "शुरू किया गया"msgid "Starting"-msgstr ""+msgstr "शुरुआत"msgid "Starting…"msgstr "शुरू हो रहा है…"@@ -20217,6 +20226,9 @@ msgstr "आपूर्तिकर्ता अवलोकन"msgid "Supplier Part"msgstr "आपूर्तिकर्ता भाग"+msgid "Supplier part actions"+msgstr "आपूर्तिकर्ता पार्ट क्रियाएं"+msgid "Supplier Part ID"msgstr "आपूर्तिकर्ता पार्ट ID"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "क्रय आदेश"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Mount को पुश शुरू नहीं हुआ। फिर से कोशिश करें।"msgid "The push to Mount failed"-msgstr ""+msgstr "Mount को पुश विफल"msgid "The push to Mount finished"-msgstr ""+msgstr "Mount को पुश समाप्त हुआ"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Mount को पुश समाप्त हुआ। कुछ रिकॉर्ड को ध्यान की आवश्यकता है"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "मात्रा विभाजन बिंदु जिन पर इस पंक्ति की कीमत है; प्रत्येक कॉलम क्रेता-आपूर्तिकर्ता बातचीत और डाउनस्ट्रीम दस्तावेजों में परिवर्तित करने के लिए अपनी स्वयं की प्रति-यूनिट कीमत रखता है।"@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "ट्रिगर"msgid "Try a different name."-msgstr ""+msgstr "एक अलग नाम आज़माएँ।"msgid "Tuesday"msgstr "मंगलवार"@@ -23338,6 +23350,9 @@ msgstr "प्रोजेक्ट प्लान में देखें"msgid "View Issue"msgstr "समस्या देखें"+msgid "View Item"+msgstr "आइटम देखें"+msgid "View Item Master"msgstr "आइटम मास्टर देखें"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 8f8d52b31c..641f933a3d 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operazione senza standard di tempo} other {# operazio#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# record richiede attenzione} other {# record richiedono attenzione}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} unità"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} creati, {updated} aggiornati."msgid "{days}d"msgstr "{days}g"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} di {count} operazioni"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {E # altro record.} other {E # altri record.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} altri: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Cognome"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Ultimo push {when} non riuscito: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Ultimo push {when}:"msgid "Last Quarter"msgstr "Ultimo Trimestre"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Ultima esecuzione"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Ultimo push programmato {when}:"msgid "Last synced: <0/>"msgstr "Ultimo sincronismo: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Più straordinario"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Altri record sono in attesa. Esegui di nuovo il push per continuare."msgid "Morning, {name}."msgstr "Mattino, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Movimento"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount ha {matches} record con questo identificatore. Elimina o unisci i record aggiuntivi in Mount, quindi esegui di nuovo il push."msgid "Move"msgstr "Sposta"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Nessun commento ancora. Sii il primo ad aggiungere un commento."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Nessuna azienda corrisponde a \"{query}\""msgid "No completed jobs within range"msgstr "Nessun ordine di produzione completato entro l'intervallo"@@ -13923,6 +13923,12 @@ msgstr "Nessuna unità di stoccaggio o numero di tracciamento corrisponde."msgid "No Supplier"msgstr "Nessun fornitore"+msgid "No supplier parts have been added yet."+msgstr "Nessun componente fornitore è stato aggiunto finora."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Nessun componente fornitore corrisponde a \"{searchText}\"."+msgid "No suppliers yet"msgstr "Nessun fornitore ancora"@@ -15203,6 +15209,9 @@ msgstr "al giorno"msgid "per month"msgstr "al mese"+msgid "Per purchase unit"+msgstr "Per unità di acquisto"+msgid "per quarter"msgstr "per trimestre"@@ -18260,9 +18269,6 @@ msgstr "Salva bozza"msgid "Save Method"msgstr "Salva Metodo"-msgid "Save Rate"-msgstr "Salva tasso"-msgid "Save the form you're editing"msgstr "Salva il modulo che stai modificando"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Cerca campi..."msgid "Search for a company"-msgstr ""+msgstr "Cerca un'azienda"msgid "Search for existing or create a new one"msgstr "Cerca uno esistente o creane uno nuovo"@@ -18519,6 +18525,9 @@ msgstr "Cerca elementi correlati..."msgid "Search storage units and tracking numbers"msgstr "Cerca unità di stoccaggio e numeri di tracciamento"+msgid "Search supplier parts"+msgstr "Cerca componenti fornitori"+msgid "Search suppliers..."msgstr "Cerca fornitori..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Iniziato"msgid "Starting"-msgstr ""+msgstr "Avvio"msgid "Starting…"msgstr "Avvio in corso…"@@ -20217,6 +20226,9 @@ msgstr "Panoramica Fornitore"msgid "Supplier Part"msgstr "Parte Fornitore"+msgid "Supplier part actions"+msgstr "Azioni componenti fornitore"+msgid "Supplier Part ID"msgstr "Codice articolo fornitore"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "L'ordine di acquisto"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Il push su Mount non è stato avviato. Riprova."msgid "The push to Mount failed"-msgstr ""+msgstr "Il push su Mount non è riuscito"msgid "The push to Mount finished"-msgstr ""+msgstr "Il push su Mount è terminato"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Il push su Mount è terminato. Alcuni record necessitano attenzione"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "I punti di rottura della quantità a cui questa riga è quotata; ogni colonna ha il proprio prezzo unitario per la negoziazione acquirente-fornitore e per la conversione a documenti a valle."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Trigger"msgid "Try a different name."-msgstr ""+msgstr "Prova un nome diverso."msgid "Tuesday"msgstr "Martedì"@@ -23338,6 +23350,9 @@ msgstr "Visualizza nel piano del progetto"msgid "View Issue"msgstr "Visualizza Problema"+msgid "View Item"+msgstr "Visualizza Articolo"+msgid "View Item Master"msgstr "Visualizza Anagrafica Articolo"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex ba79686c06..54016bf727 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 工程に標準時間がない} other {# 工程に標#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# 件のレコードが対応を要しています} other {# 件のレコードが対応を要しています}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} 個"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} 件作成、{updated} 件更新されました。"msgid "{days}d"msgstr "{days}日"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} / {count} 件の工程"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {他に # 件のレコード} other {他に # 件のレコード}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} 件さらに表示: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "姓"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "最後のプッシュ {when} が失敗しました: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "最後のプッシュ {when}:"msgid "Last Quarter"msgstr "前四半期"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "最終実行"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "最後にスケジュールされたプッシュ {when}:"msgid "Last synced: <0/>"msgstr "最後に同期: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "残業を増やす"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "さらに多くのレコードが待機中です。続行するにはもう一度プッシュしてください。"msgid "Morning, {name}."msgstr "朝、{name}さん。"@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "モーション"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount に {matches} 件のこの識別子を持つレコードがあります。Mount の余分なレコードを削除するか統合してからもう一度プッシュしてください。"msgid "Move"msgstr "移動"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "まだコメントがありません。最初のコメントを追加してください。"msgid "No companies match \"{query}\""-msgstr ""+msgstr "「{query}」に一致する会社がありません"msgid "No completed jobs within range"msgstr "範囲内に完了した製造指図がありません"@@ -13923,6 +13923,12 @@ msgstr "保管ユニットまたはトラッキング番号に一致するものmsgid "No Supplier"msgstr "仕入先なし"+msgid "No supplier parts have been added yet."+msgstr "仕入先部品がまだ追加されていません。"++msgid "No supplier parts match \"{searchText}\"."+msgstr "「{searchText}」に一致する仕入先部品がありません。"+msgid "No suppliers yet"msgstr "仕入先がまだありません"@@ -15203,6 +15209,9 @@ msgstr "1日あたり"msgid "per month"msgstr "1か月あたり"+msgid "Per purchase unit"+msgstr "購入単位あたり"+msgid "per quarter"msgstr "四半期あたり"@@ -18260,9 +18269,6 @@ msgstr "下書きを保存"msgid "Save Method"msgstr "メソッドを保存"-msgid "Save Rate"-msgstr "レートを保存"-msgid "Save the form you're editing"msgstr "編集中のフォームを保存"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "フィールドを検索..."msgid "Search for a company"-msgstr ""+msgstr "会社を検索"msgid "Search for existing or create a new one"msgstr "既存のものを検索するか、新しいものを作成してください"@@ -18519,6 +18525,9 @@ msgstr "関連アイテムを検索..."msgid "Search storage units and tracking numbers"msgstr "保管ユニットとトラッキング番号を検索"+msgid "Search supplier parts"+msgstr "仕入先部品を検索"+msgid "Search suppliers..."msgstr "仕入先を検索..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "開始"msgid "Starting"-msgstr ""+msgstr "開始中"msgid "Starting…"msgstr "開始中…"@@ -20217,6 +20226,9 @@ msgstr "仕入先概要"msgid "Supplier Part"msgstr "仕入先品"+msgid "Supplier part actions"+msgstr "仕入先部品の操作"+msgid "Supplier Part ID"msgstr "仕入先品番"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "発注書"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Mount へのプッシュが開始されませんでした。もう一度試してください。"msgid "The push to Mount failed"-msgstr ""+msgstr "Mount へのプッシュが失敗しました"msgid "The push to Mount finished"-msgstr ""+msgstr "Mount へのプッシュが完了しました"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Mount へのプッシュが完了しました。いくつかのレコードが対応を要しています"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "この明細が価格設定される数量ブレークポイント。各列は買い手と仕入先の交渉および下流文書への変換用に、独自の単価を持ちます。"@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "トリガー"msgid "Try a different name."-msgstr ""+msgstr "別の名前を試してください。"msgid "Tuesday"msgstr "火曜日"@@ -23338,6 +23350,9 @@ msgstr "プロジェクトプランで表示"msgid "View Issue"msgstr "問題を表示"+msgid "View Item"+msgstr "品目を表示"+msgid "View Item Master"msgstr "アイテムマスターを表示"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex cab128c5bd..8818f884e8 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 공정에 표준시간이 없습니다} other {# 공#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# 기록에 주의가 필요합니다} other {# 기록에 주의가 필요합니다}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count}개"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} 생성됨, {updated} 업데이트됨."msgid "{days}d"msgstr "{days}일"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to}/{count} 공정"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {그리고 # 개 이상의 기록.} other {그리고 # 개 이상의 기록.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount}개 추가: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "성"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "마지막 푸시 {when} 실패: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "마지막 푸시 {when}:"msgid "Last Quarter"msgstr "지난 분기"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "마지막 실행"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "마지막 예약된 푸시 {when}:"msgid "Last synced: <0/>"msgstr "마지막 동기화: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "초과 근무 증가"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "더 많은 기록이 대기 중입니다. 계속하려면 다시 푸시하세요."msgid "Morning, {name}."msgstr "{name}님, 아침이군요."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "모션"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount에 이 식별자를 가진 {matches} 기록이 있습니다. Mount에서 추가 기록을 삭제하거나 병합한 후 다시 푸시하세요."msgid "Move"msgstr "이동"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "아직 댓글이 없습니다. 첫 번째 댓글을 추가하세요."msgid "No companies match \"{query}\""-msgstr ""+msgstr "일치하는 회사가 없습니다 「{query}」"msgid "No completed jobs within range"msgstr "범위 내에 완료된 작업 지시가 없습니다"@@ -13923,6 +13923,12 @@ msgstr "일치하는 보관 단위 또는 추적 번호가 없습니다."msgid "No Supplier"msgstr "공급업체 없음"+msgid "No supplier parts have been added yet."+msgstr "공급업체 부품이 아직 추가되지 않았습니다."++msgid "No supplier parts match \"{searchText}\"."+msgstr "일치하는 공급업체 부품이 없습니다 「{searchText}」."+msgid "No suppliers yet"msgstr "아직 공급업체가 없습니다"@@ -15203,6 +15209,9 @@ msgstr "일당"msgid "per month"msgstr "월당"+msgid "Per purchase unit"+msgstr "구매 단위당"+msgid "per quarter"msgstr "분기당"@@ -18260,9 +18269,6 @@ msgstr "초안 저장"msgid "Save Method"msgstr "저장 방법"-msgid "Save Rate"-msgstr "환율 저장"-msgid "Save the form you're editing"msgstr "편집 중인 양식 저장"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "필드 검색..."msgid "Search for a company"-msgstr ""+msgstr "회사 검색"msgid "Search for existing or create a new one"msgstr "기존 항목을 검색하거나 새로 생성하세요"@@ -18519,6 +18525,9 @@ msgstr "관련 품목 검색..."msgid "Search storage units and tracking numbers"msgstr "보관 단위 및 추적 번호 검색"+msgid "Search supplier parts"+msgstr "공급업체 부품 검색"+msgid "Search suppliers..."msgstr "공급업체 검색..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "시작됨"msgid "Starting"-msgstr ""+msgstr "시작 중"msgid "Starting…"msgstr "시작 중…"@@ -20217,6 +20226,9 @@ msgstr "공급업체 개요"msgid "Supplier Part"msgstr "공급업체 부품"+msgid "Supplier part actions"+msgstr "공급업체 부품 작업"+msgid "Supplier Part ID"msgstr "공급업체 품번"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "발주서"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Mount로의 푸시가 시작되지 않았습니다. 다시 시도하세요."msgid "The push to Mount failed"-msgstr ""+msgstr "Mount로의 푸시 실패"msgid "The push to Mount finished"-msgstr ""+msgstr "Mount로의 푸시 완료"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Mount로의 푸시 완료. 일부 기록에 주의가 필요합니다."msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "이 라인의 가격 책정 수량 구간점; 각 열은 구매자-공급업체 협상 및 다운스트림 문서로 변환하기 위한 자체 단가를 포함합니다."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "트리거"msgid "Try a different name."-msgstr ""+msgstr "다른 이름을 시도하세요."msgid "Tuesday"msgstr "화요일"@@ -23338,6 +23350,9 @@ msgstr "프로젝트 계획에서 보기"msgid "View Issue"msgstr "이슈 보기"+msgid "View Item"+msgstr "품목 보기"+msgid "View Item Master"msgstr "품목 마스터 보기"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex d3969ed324..4be030a919 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operacja nie ma standardów czasu} few {# operacje ni#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# rekord wymaga uwagi} other {# rekordy wymagają uwagi}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} sztuk"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} utworzono, {updated} zaktualizowano."msgid "{days}d"msgstr "{days}d"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} z {count} operacji"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {I jeszcze # rekord.} other {I jeszcze # rekordy.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} więcej: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Nazwisko"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Ostatni push {when} nie powiódł się: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Ostatni push {when}:"msgid "Last Quarter"msgstr "Ostatni kwartał"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Ostatnie uruchomienie"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Ostatni zaplanowany push {when}:"msgid "Last synced: <0/>"msgstr "Ostatnia synchronizacja: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Więcej nadgodzin"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Więcej rekordów czeka. Wyślij ponownie, aby kontynuować."msgid "Morning, {name}."msgstr "Poranek, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Ruch"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount ma {matches} rekordy z tym identyfikatorem. Usuń lub scal dodatkowe w Mount, a następnie wyślij ponownie."msgid "Move"msgstr "Przenieś"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Brak komentarzy. Bądź pierwszy i dodaj komentarz."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Brak firm pasujących do \"{query}\""msgid "No completed jobs within range"msgstr "Nie znaleziono zakończonych zleceń produkcyjnych w danym zakresie"@@ -13923,6 +13923,12 @@ msgstr "Brak zgodnych jednostek magazynowych ani numerów śledzenia."msgid "No Supplier"msgstr "Brak dostawcy"+msgid "No supplier parts have been added yet."+msgstr "Żadne części dostawcy nie zostały jeszcze dodane."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Brak części dostawcy pasujących do \"{searchText}\"."+msgid "No suppliers yet"msgstr "Brak dostawców"@@ -15203,6 +15209,9 @@ msgstr "na dzień"msgid "per month"msgstr "na miesiąc"+msgid "Per purchase unit"+msgstr "Za jednostkę zakupu"+msgid "per quarter"msgstr "za kwartał"@@ -18260,9 +18269,6 @@ msgstr "Zapisz wersję roboczą"msgid "Save Method"msgstr "Zapisz metodę"-msgid "Save Rate"-msgstr "Zapisz kurs"-msgid "Save the form you're editing"msgstr "Zapisz formularz, który edytujesz"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Wyszukaj pola..."msgid "Search for a company"-msgstr ""+msgstr "Szukaj firmy"msgid "Search for existing or create a new one"msgstr "Wyszukaj istniejący lub utwórz nowy"@@ -18519,6 +18525,9 @@ msgstr "Szukaj powiązanych elementów..."msgid "Search storage units and tracking numbers"msgstr "Szukaj jednostek magazynowych i numerów śledzenia"+msgid "Search supplier parts"+msgstr "Szukaj części dostawcy"+msgid "Search suppliers..."msgstr "Szukaj dostawców..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Rozpoczęto"msgid "Starting"-msgstr ""+msgstr "Rozpoczynanie"msgid "Starting…"msgstr "Uruchamianie…"@@ -20217,6 +20226,9 @@ msgstr "Przegląd dostawcy"msgid "Supplier Part"msgstr "Część dostawcy"+msgid "Supplier part actions"+msgstr "Akcje części dostawcy"+msgid "Supplier Part ID"msgstr "Numer artykułu dostawcy"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "Zamówienie zakupu"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Push do Mount nie rozpoczął się. Spróbuj ponownie."msgid "The push to Mount failed"-msgstr ""+msgstr "Push do Mount nie powiódł się"msgid "The push to Mount finished"-msgstr ""+msgstr "Push do Mount zakończył się"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Push do Mount zakończył się. Niektóre rekordy wymagają uwagi"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Punkty graniczne ilości, przy których ta pozycja jest wyceniona; każda kolumna nosi własną cenę za sztukę do negocjacji kupiec–dostawca i do konwersji na dokumenty następujące."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Wyzwalacze"msgid "Try a different name."-msgstr ""+msgstr "Spróbuj innej nazwy."msgid "Tuesday"msgstr "Wtorek"@@ -23338,6 +23350,9 @@ msgstr "Wyświetl w planie projektu"msgid "View Issue"msgstr "Wyświetl Problem"+msgid "View Item"+msgstr "Wyświetl Artykuł"+msgid "View Item Master"msgstr "Wyświetl Główny Katalog Pozycji"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 1541dbbb9a..74b523c2c5 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operação não tem padrões de tempo} other {# opera#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# registro precisa de atenção} other {# registros precisam de atenção}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} unidades"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} criado(s), {updated} atualizado(s)."msgid "{days}d"msgstr "{days}d"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} de {count} operações"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {E # mais registro.} other {E # mais registros.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} mais: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Sobrenome"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Último envio {when} falhou: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Último envio {when}:"msgid "Last Quarter"msgstr "Último Trimestre"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Última execução"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Último envio agendado {when}:"msgid "Last synced: <0/>"msgstr "Última sincronização: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Mais horas extras"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Mais registros estão aguardando. Envie novamente para continuar."msgid "Morning, {name}."msgstr "Bom dia, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Movimento"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount tem {matches} registros com este identificador. Exclua ou mescle os extras no Mount, então envie novamente."msgid "Move"msgstr "Mover"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Sem comentários ainda. Seja o primeiro a adicionar um comentário."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Nenhuma empresa corresponde a \"{query}\""msgid "No completed jobs within range"msgstr "Nenhuma ordem de produção concluída dentro do intervalo"@@ -13923,6 +13923,12 @@ msgstr "Nenhuma unidade de armazenamento ou número de rastreamento corresponde.msgid "No Supplier"msgstr "Sem fornecedor"+msgid "No supplier parts have been added yet."+msgstr "Nenhuma peça de fornecedor foi adicionada ainda."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Nenhuma peça de fornecedor corresponde a \"{searchText}\"."+msgid "No suppliers yet"msgstr "Nenhum fornecedor ainda"@@ -15203,6 +15209,9 @@ msgstr "por dia"msgid "per month"msgstr "por mês"+msgid "Per purchase unit"+msgstr "Por unidade de compra"+msgid "per quarter"msgstr "por trimestre"@@ -18260,9 +18269,6 @@ msgstr "Salvar Rascunho"msgid "Save Method"msgstr "Salvar Método"-msgid "Save Rate"-msgstr "Salvar taxa"-msgid "Save the form you're editing"msgstr "Salvar o formulário que você está editando"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Pesquisar campos..."msgid "Search for a company"-msgstr ""+msgstr "Pesquisar uma empresa"msgid "Search for existing or create a new one"msgstr "Pesquisar um existente ou criar um novo"@@ -18519,6 +18525,9 @@ msgstr "Pesquisar itens relacionados..."msgid "Search storage units and tracking numbers"msgstr "Pesquisar unidades de armazenamento e números de rastreamento"+msgid "Search supplier parts"+msgstr "Pesquisar peças de fornecedor"+msgid "Search suppliers..."msgstr "Pesquisar fornecedores..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Iniciado"msgid "Starting"-msgstr ""+msgstr "Iniciando"msgid "Starting…"msgstr "Iniciando…"@@ -20217,6 +20226,9 @@ msgstr "Visão Geral do Fornecedor"msgid "Supplier Part"msgstr "Peça do Fornecedor"+msgid "Supplier part actions"+msgstr "Ações de peça de fornecedor"+msgid "Supplier Part ID"msgstr "Referência do fornecedor"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "O pedido de compra"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "O envio para Mount não foi iniciado. Tente novamente."msgid "The push to Mount failed"-msgstr ""+msgstr "O envio para Mount falhou"msgid "The push to Mount finished"-msgstr ""+msgstr "O envio para Mount foi concluído"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "O envio para Mount foi concluído. Alguns registros precisam de atenção"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Os pontos de ruptura de quantidade em que essa linha é precificada; cada coluna possui seu próprio preço por unidade para negociação comprador-fornecedor e conversão para documentos posteriores."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Acionadores"msgid "Try a different name."-msgstr ""+msgstr "Tente um nome diferente."msgid "Tuesday"msgstr "Terça-feira"@@ -23338,6 +23350,9 @@ msgstr "Ver no plano do projeto"msgid "View Issue"msgstr "Ver Problema"+msgid "View Item"+msgstr "Visualizar Item"+msgid "View Item Master"msgstr "Ver Mestre do Item"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex e65bee0709..a4da5a72c9 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# операция не имеет временных#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# запись требует внимания} other {# записей требуют внимания}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} единиц"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} создано, {updated} обновлено."msgid "{days}d"msgstr "{days}д"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} из {count} операций"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {Еще # запись.} other {Еще # записей.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} еще: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Фамилия"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Последняя отправка {when} не удалась: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Последняя отправка {when}:"msgid "Last Quarter"msgstr "Последний квартал"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Последний запуск"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Последняя запланированная отправка {when}:"msgid "Last synced: <0/>"msgstr "Последняя синхронизация: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Больше переработки"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Больше записей ожидают. Отправьте еще раз, чтобы продолжить."msgid "Morning, {name}."msgstr "Доброе утро, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Движение"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount содержит {matches} записей с этим идентификатором. Удалите или объедините лишние в Mount, затем отправьте снова."msgid "Move"msgstr "Переместить"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Нет комментариев. Будьте первым, кто добавит комментарий."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Нет организаций, соответствующих запросу «{query}»"msgid "No completed jobs within range"msgstr "Нет завершенных производственных заказов в диапазоне"@@ -13923,6 +13923,12 @@ msgstr "Единицы хранения или номера отслеживанmsgid "No Supplier"msgstr "Нет поставщика"+msgid "No supplier parts have been added yet."+msgstr "Детали поставщика еще не добавлены."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Нет деталей поставщика, совпадающих с «{searchText}»."+msgid "No suppliers yet"msgstr "Поставщиков еще нет"@@ -15203,6 +15209,9 @@ msgstr "в день"msgid "per month"msgstr "в месяц"+msgid "Per purchase unit"+msgstr "За единицу закупки"+msgid "per quarter"msgstr "в квартал"@@ -18260,9 +18269,6 @@ msgstr "Сохранить черновик"msgid "Save Method"msgstr "Сохранить метод"-msgid "Save Rate"-msgstr "Сохранить курс"-msgid "Save the form you're editing"msgstr "Сохранить редактируемую форму"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Поиск полей..."msgid "Search for a company"-msgstr ""+msgstr "Поиск организации"msgid "Search for existing or create a new one"msgstr "Поиск существующей или создание новой"@@ -18519,6 +18525,9 @@ msgstr "Поиск связанных элементов..."msgid "Search storage units and tracking numbers"msgstr "Поиск единиц хранения и номеров отслеживания"+msgid "Search supplier parts"+msgstr "Поиск деталей поставщика"+msgid "Search suppliers..."msgstr "Поиск поставщиков..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Начал"msgid "Starting"-msgstr ""+msgstr "Запуск"msgid "Starting…"msgstr "Начинаю…"@@ -20217,6 +20226,9 @@ msgstr "Обзор поставщика"msgid "Supplier Part"msgstr "Поставщик Детали"+msgid "Supplier part actions"+msgstr "Действия с деталями поставщика"+msgid "Supplier Part ID"msgstr "Артикул поставщика"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "Заказ поставщику"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Отправка на Mount не началась. Попробуйте еще раз."msgid "The push to Mount failed"-msgstr ""+msgstr "Отправка на Mount не удалась"msgid "The push to Mount finished"-msgstr ""+msgstr "Отправка на Mount завершена"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Отправка на Mount завершена. Некоторые записи требуют внимания"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Точки разрыва по количеству, при которых рассчитывается цена этой строки; каждый столбец содержит свою цену за единицу для переговоров между закупщиком и поставщиком и для преобразования в последующие документы."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Триггеры"msgid "Try a different name."-msgstr ""+msgstr "Попробуйте другое имя."msgid "Tuesday"msgstr "Вторник"@@ -23338,6 +23350,9 @@ msgstr "Просмотреть в плане проекта"msgid "View Issue"msgstr "Просмотр проблемы"+msgid "View Item"+msgstr "Просмотр номенклатуры"+msgid "View Item Master"msgstr "Просмотр основных данных товара"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 74432db77c..5a7ff22135 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# operasyon için zaman standardı yok} other {# operas#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# kayıt dikkat gerektiriyor} other {# kayıt dikkat gerektiriyor}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} adet"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "{created} oluşturuldu, {updated} güncellendi."msgid "{days}d"msgstr "{days}g"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "{from}–{to} /{count} operasyon"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {Ve # daha fazla kayıt.} other {Ve # daha fazla kayıt.}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "{hiddenCount} daha: {hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "Soyadı"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "Son gönderim {when} başarısız oldu: {0}"msgid "Last push {when}:"-msgstr ""+msgstr "Son gönderim {when}:"msgid "Last Quarter"msgstr "Son Çeyrek"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "Son Çalıştırma"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "Son planlanan gönderim {when}:"msgid "Last synced: <0/>"msgstr "Son senkronizasyon: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "Daha fazla fazla mesai"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "Daha fazla kayıt bekleniyor. Devam etmek için yeniden gönderin."msgid "Morning, {name}."msgstr "Sabah, {name}."@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "Hareket"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount bu tanımlayıcıya sahip {matches} kayıt içeriyor. Fazlasını Mount'ta silin veya birleştirin, sonra yeniden gönderin."msgid "Move"msgstr "Taşış"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "Henüz yorum yok. İlk yorumu ekleyin."msgid "No companies match \"{query}\""-msgstr ""+msgstr "Hiçbir şirket \"{query}\" ile eşleşmiyor"msgid "No completed jobs within range"msgstr "Aralıkta tamamlanmış İş emri yok"@@ -13923,6 +13923,12 @@ msgstr "Depolama birimleri veya takip numaraları eşleşmiyor."msgid "No Supplier"msgstr "Tedarikçi yok"+msgid "No supplier parts have been added yet."+msgstr "Hiçbir tedarikçi parçası henüz eklenmemiş."++msgid "No supplier parts match \"{searchText}\"."+msgstr "Hiçbir tedarikçi parçası \"{searchText}\" ile eşleşmiyor."+msgid "No suppliers yet"msgstr "Henüz tedarikçi yok"@@ -15203,6 +15209,9 @@ msgstr "günde"msgid "per month"msgstr "ayda"+msgid "Per purchase unit"+msgstr "Satın alma birimi başına"+msgid "per quarter"msgstr "çeyrek başına"@@ -18260,9 +18269,6 @@ msgstr "Taslağı Kaydet"msgid "Save Method"msgstr "Yöntemi Kaydet"-msgid "Save Rate"-msgstr "Kuru kaydet"-msgid "Save the form you're editing"msgstr "Düzenlemekte olduğunuz formu kaydet"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "Alanları ara..."msgid "Search for a company"-msgstr ""+msgstr "Bir şirket arayın"msgid "Search for existing or create a new one"msgstr "Mevcut birini arayın veya yeni bir tane oluşturun"@@ -18519,6 +18525,9 @@ msgstr "İlgili öğeleri ara..."msgid "Search storage units and tracking numbers"msgstr "Depolama birimlerini ve takip numaralarını ara"+msgid "Search supplier parts"+msgstr "Tedarikçi parçalarını arayın"+msgid "Search suppliers..."msgstr "Tedarikçileri ara..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "Başlangıç"msgid "Starting"-msgstr ""+msgstr "Başlıyor"msgid "Starting…"msgstr "Başlanıyor…"@@ -20217,6 +20226,9 @@ msgstr "Tedarikçi Genel Bakışı"msgid "Supplier Part"msgstr "Tedarikçi Parçası"+msgid "Supplier part actions"+msgstr "Tedarikçi parçası işlemleri"+msgid "Supplier Part ID"msgstr "Tedarikçi parça numarası"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "Satın alma siparişi"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "Mount'a gönderim başlamadı. Lütfen tekrar deneyin."msgid "The push to Mount failed"-msgstr ""+msgstr "Mount'a gönderim başarısız oldu"msgid "The push to Mount finished"-msgstr ""+msgstr "Mount'a gönderim tamamlandı"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "Mount'a gönderim tamamlandı. Bazı kayıtlar dikkat gerektiriyor"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "Bu Satırın fiyatlandırıldığı Miktar kırılım noktaları; her sütun Satın almacı–Tedarikçi müzakereleri ve aşağı yönlü belgelere dönüştürme için kendi birim başına Fiyatını taşır."@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "Tetikleyiciler"msgid "Try a different name."-msgstr ""+msgstr "Farklı bir ad deneyin."msgid "Tuesday"msgstr "Salı"@@ -23338,6 +23350,9 @@ msgstr "Proje planında görüntüle"msgid "View Issue"msgstr "Sorunu Görüntüle"+msgid "View Item"+msgstr "Stok Kartını Görüntüle"+msgid "View Item Master"msgstr "Ürün Ana Verisine Görüntüle"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 1063a24934..0727853a35 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -69,7 +69,7 @@ msgstr "{0, plural, one {# 道工序无工时定额} other {# 道工序无工时#. placeholder {0}: issues.lengthmsgid "{0, plural, one {# record needs attention} other {# records need attention}}"-msgstr ""+msgstr "{0, plural, one {# 条记录需要关注} other {# 条记录需要关注}}"#. placeholder {0}: totalScopeRows(run.violationRowsByTable)msgid "{0, plural, one {# row links to data outside this company, so a safety copy of your current data can't be made.} other {# rows link to data outside this company, so a safety copy of your current data can't be made.}}"@@ -418,7 +418,7 @@ msgid "{count} units"msgstr "{count} 件"msgid "{created} created, {updated} updated."-msgstr ""+msgstr "已创建 {created} 条,已更新 {updated} 条。"msgid "{days}d"msgstr "{days}天"@@ -445,7 +445,7 @@ msgid "{from}–{to} of {count} operations"msgstr "第{from}–{to}个工序(共{count}个)"msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"-msgstr ""+msgstr "{hidden, plural, one {还有 # 条记录。} other {还有 # 条记录。}}"msgid "{hiddenCount} more: {hiddenNames}"msgstr "还有{hiddenCount}个:{hiddenNames}"@@ -11523,10 +11523,10 @@ msgstr "姓氏"#. placeholder {0}: record.errormsgid "Last push {when} failed: {0}"-msgstr ""+msgstr "最后一次推送 {when} 失败:{0}"msgid "Last push {when}:"-msgstr ""+msgstr "最后一次推送 {when}:"msgid "Last Quarter"msgstr "上一季度"@@ -11535,7 +11535,7 @@ msgid "Last Run"msgstr "最后运行"msgid "Last scheduled push {when}:"-msgstr ""+msgstr "最后一次计划推送 {when}:"msgid "Last synced: <0/>"msgstr "上次同步: <0/>"@@ -12701,7 +12701,7 @@ msgid "More overtime"msgstr "更多加班"msgid "More records are waiting. Push again to continue."-msgstr ""+msgstr "还有更多记录在等待。请再次推送以继续。"msgid "Morning, {name}."msgstr "早上,{name}。"@@ -12716,7 +12716,7 @@ msgid "Motion"msgstr "运动"msgid "Mount has {matches} records with this identifier. Delete or merge the extra ones in Mount, then push again."-msgstr ""+msgstr "Mount 中有 {matches} 条记录使用此标识符。请在 Mount 中删除或合并多余的记录,然后重新推送。"msgid "Move"msgstr "移动"@@ -13446,7 +13446,7 @@ msgid "No comments yet. Be the first to add a comment."msgstr "还没有评论。成为第一个添加评论的人。"msgid "No companies match \"{query}\""-msgstr ""+msgstr "没有公司与 \"{query}\" 匹配"msgid "No completed jobs within range"msgstr "范围内没有已完成的工单"@@ -13923,6 +13923,12 @@ msgstr "没有存储单元或追踪号与之匹配。"msgid "No Supplier"msgstr "无供应商"+msgid "No supplier parts have been added yet."+msgstr "尚未添加供应商零件。"++msgid "No supplier parts match \"{searchText}\"."+msgstr "没有供应商零件与 \"{searchText}\" 匹配。"+msgid "No suppliers yet"msgstr "还没有供应商"@@ -15203,6 +15209,9 @@ msgstr "每天"msgid "per month"msgstr "每月"+msgid "Per purchase unit"+msgstr "每采购单位"+msgid "per quarter"msgstr "每季度"@@ -18260,9 +18269,6 @@ msgstr "保存草稿"msgid "Save Method"msgstr "保存方法"-msgid "Save Rate"-msgstr "保存汇率"-msgid "Save the form you're editing"msgstr "保存您正在编辑的表单"@@ -18478,7 +18484,7 @@ msgid "Search fields..."msgstr "搜索字段..."msgid "Search for a company"-msgstr ""+msgstr "搜索公司"msgid "Search for existing or create a new one"msgstr "搜索现有问题或创建新问题"@@ -18519,6 +18525,9 @@ msgstr "搜索相关物料..."msgid "Search storage units and tracking numbers"msgstr "搜索存储单元和追踪号"+msgid "Search supplier parts"+msgstr "搜索供应商零件"+msgid "Search suppliers..."msgstr "搜索供应商..."@@ -19753,7 +19762,7 @@ msgid "Started"msgstr "开始于"msgid "Starting"-msgstr ""+msgstr "开始中"msgid "Starting…"msgstr "正在启动…"@@ -20217,6 +20226,9 @@ msgstr "供应商概览"msgid "Supplier Part"msgstr "供应商零件"+msgid "Supplier part actions"+msgstr "供应商零件操作"+msgid "Supplier Part ID"msgstr "供应商料号"@@ -21283,16 +21295,16 @@ msgid "The purchase order"msgstr "采购订单"msgid "The push to Mount did not start. Try again."-msgstr ""+msgstr "推送至 Mount 未启动。请重试。"msgid "The push to Mount failed"-msgstr ""+msgstr "推送至 Mount 失败"msgid "The push to Mount finished"-msgstr ""+msgstr "推送至 Mount 已完成"msgid "The push to Mount finished. Some records need attention"-msgstr ""+msgstr "推送至 Mount 已完成。某些记录需要关注"msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."msgstr "此行定价的数量断点;每一列都有自己的单位价格,用于采购方–供应商谈判和转换为下游文件。"@@ -22520,7 +22532,7 @@ msgid "Triggers"msgstr "触发器"msgid "Try a different name."-msgstr ""+msgstr "请尝试其他名称。"msgid "Tuesday"msgstr "星期二"@@ -23338,6 +23350,9 @@ msgstr "在项目计划中查看"msgid "View Issue"msgstr "查看问题"+msgid "View Item"+msgstr "查看物料"+msgid "View Item Master"msgstr "查看物料主数据"diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsxindex 200c484e5a..b9e0f9e05a 100644--- a/packages/react/src/Card.tsx+++ b/packages/react/src/Card.tsx@@ -97,7 +97,7 @@ const CardAction = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (<divref={ref}- className={cn("flex flex-col py-2 px-4", className)}+ className={cn("flex flex-col py-2 px-4 pr-6", className)}{...props}/>)diff --git a/packages/react/src/Menubar.tsx b/packages/react/src/Menubar.tsxindex 85d08ae195..e0bc851064 100644--- a/packages/react/src/Menubar.tsx+++ b/packages/react/src/Menubar.tsx@@ -14,7 +14,7 @@ const Menubar = forwardRef<HTMLDivElement, ComponentProps<"div">>(<div{...props}className={cn(- "min-h-[2.5rem] flex items-center bg-card border border-border rounded-lg justify-start p-1 w-full space-x-1 scrollbar-hide dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]",+ "min-h-[2.5rem] flex items-center bg-card border border-border rounded-xl justify-start p-1 w-full space-x-1 scrollbar-hide dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]",// Phones: the bar scrolls sideways (with a fade) instead of clipping."max-md:overflow-x-auto max-md:scroll-fade-x max-md:[&>*]:shrink-0",classNamediff --git a/packages/server-functions/src/convert/index.ts b/packages/server-functions/src/convert/index.tsindex 4a01db9beb..54c8d685a8 100644--- a/packages/server-functions/src/convert/index.ts+++ b/packages/server-functions/src/convert/index.ts@@ -23,10 +23,12 @@ import {getRemainingQuantityToInvoice} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+import { sql } from "kysely";import { z } from "zod";import { defineServerFn } from "../define-server-fn";import { NotFoundError } from "../errors";import getMethod from "../get-method";+import { getSupplierPartPriceConverter } from "../lib/supplier-part-currency";import { ServerFnContext } from "../server-fn-context";const logger = getLogger("server-functions", "convert");@@ -1821,107 +1823,110 @@ const convert = defineServerFn({}}- // Create a map to deduplicate supplier parts by itemId and supplierId- const supplierPartMap = new Map();-- quoteLines.data- .filter(- (line) =>- !!line.itemId &&- line.id &&- selectedLines &&- line.id in selectedLines- )- .forEach((line) => {- const key = `${line.itemId}-${quote.data.supplierId}`;- const selectedLine = selectedLines![line.id!];- const exchangeRate = quote.data.exchangeRate ?? 1;- const unitPriceInInventoryUnit =- selectedLine!.supplierUnitPrice /- (exchangeRate === 0 ? 1 : exchangeRate) /- (line.conversionFactor ?? 1);- supplierPartMap.set(key, {- companyId,- supplierId: quote.data?.supplierId!,- supplierPartId: line.supplierPartId!,- supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,- conversionFactor: line.conversionFactor,- itemId: line.itemId!,- createdBy: userId,- unitPrice: unitPriceInInventoryUnit- });- });-- const supplierPartToItemInserts = Array.from(- supplierPartMap.values()+ // Record the ordered prices in the supplier's price list, as quoted:+ // per purchase unit, in the quote's currency. A part created here+ // takes that currency; an existing part keeps its own and gets the+ // price converted into it.+ const pricedLines = quoteLines.data.filter(+ (line) =>+ !!line.itemId &&+ line.id &&+ selectedLines &&+ line.id in selectedLines);- if (supplierPartToItemInserts.length > 0) {+ // One supplier part per item; the later line wins.+ const supplierPartInserts = [+ ...new Map(+ pricedLines.map((line) => [+ line.itemId!,+ {+ companyId,+ supplierId: quote.data.supplierId,+ supplierPartId: line.supplierPartId,+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ conversionFactor: line.conversionFactor ?? 1,+ currencyCode: quote.data.currencyCode,+ itemId: line.itemId!,+ createdBy: userId+ }+ ])+ ).values()+ ];++ if (supplierPartInserts.length > 0) {await trx.insertInto("supplierPart")- .values(supplierPartToItemInserts)+ .values(supplierPartInserts).onConflict((oc) =>oc.columns(["itemId", "supplierId", "companyId"]).doUpdateSet((eb) => ({- supplierPartId: eb.ref("excluded.supplierPartId"),- unitPrice: eb.ref("excluded.unitPrice")+ supplierPartId: eb.ref("excluded.supplierPartId")}))).execute();const supplierParts = await trx.selectFrom("supplierPart")- .select(["id", "itemId"])+ .select(["id", "itemId", "currencyCode"]).where("supplierId", "=", quote.data.supplierId).where("companyId", "=", companyId).where("itemId","in",- supplierPartToItemInserts.map(- (i: { itemId: string }) => i.itemId- )+ supplierPartInserts.map((insert) => insert.itemId)).execute();+ const supplierPartByItemId = new Map(+ supplierParts.map((sp) => [sp.itemId, sp])+ );- const supplierPartIdByItemId = new Map(- supplierParts.map((sp) => [sp.itemId, sp.id])+ const converter = await getSupplierPartPriceConverter(+ trx,+ companyId,+ {+ currencyCode: quote.data.currencyCode,+ exchangeRate: quote.data.exchangeRate ?? 1+ },+ supplierParts.map((sp) => sp.currencyCode));- for (const line of quoteLines.data.filter(- (l) =>- !!l.itemId && l.id && selectedLines && l.id in selectedLines- )) {- const spId = supplierPartIdByItemId.get(line.itemId!);- if (!spId) continue;-- const selectedLine = selectedLines![line.id!];- const exchangeRate = quote.data.exchangeRate ?? 1;- const conversionFactor = line.conversionFactor ?? 1;- const unitPriceInInventoryUnit =- selectedLine!.supplierUnitPrice /- (exchangeRate === 0 ? 1 : exchangeRate) /- conversionFactor;+ // One break per (part, quantity); the later line wins.+ const priceBreaks = new Map<+ string,+ Database["public"]["Tables"]["supplierPartPrice"]["Insert"]+ >();+ for (const line of pricedLines) {+ const supplierPart = supplierPartByItemId.get(line.itemId!);+ if (!supplierPart) continue;+ const selectedLine = selectedLines![line.id!]!;+ priceBreaks.set(`${supplierPart.id}:${selectedLine.quantity}`, {+ supplierPartId: supplierPart.id,+ quantity: selectedLine.quantity,+ supplierUnitPrice: converter.toPartCurrency(+ selectedLine.supplierUnitPrice,+ supplierPart.currencyCode+ ),+ leadTime: selectedLine.leadTime ?? 0,+ sourceType: "Purchase Order",+ sourceDocumentId: insertedPurchaseOrderId,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ });+ }+ if (priceBreaks.size > 0) {await trx.insertInto("supplierPartPrice")- .values({- supplierPartId: spId,- quantity: selectedLine!.quantity,- unitPrice: unitPriceInInventoryUnit,- leadTime: selectedLine!.leadTime ?? 0,- sourceType: "Purchase Order",- sourceDocumentId: insertedPurchaseOrderId,- companyId,- createdBy: userId,- updatedBy: userId,- updatedAt: datetime.timestamp()- })+ .values([...priceBreaks.values()]).onConflict((oc) =>oc.columns(["supplierPartId", "quantity"]).doUpdateSet((eb) => ({- unitPrice: eb.ref("excluded.unitPrice"),+ supplierUnitPrice: eb.ref("excluded.supplierUnitPrice"),leadTime: eb.ref("excluded.leadTime"),sourceType: eb.ref("excluded.sourceType"),sourceDocumentId: eb.ref("excluded.sourceDocumentId"),@@ -1932,25 +1937,25 @@ const convert = defineServerFn({.execute();}- for (const [, spId] of supplierPartIdByItemId) {- const bestTier = await trx- .selectFrom("supplierPartPrice")- .select(["unitPrice", "quantity"])- .where("supplierPartId", "=", spId)- .orderBy("unitPrice", "asc")- .executeTakeFirst();-- if (bestTier) {- await trx- .updateTable("supplierPart")- .set({- unitPrice: Number(bestTier.unitPrice),- minimumOrderQuantity: Number(bestTier.quantity)- })- .where("id", "=", spId)- .where("companyId", "=", companyId)- .execute();- }+ // Each part's own price and minimum order quantity follow its+ // cheapest break.+ const supplierPartIds = supplierParts.map((sp) => sp.id);+ if (supplierPartIds.length > 0) {+ await sql`+ UPDATE "supplierPart" sp+ SET "supplierUnitPrice" = best."supplierUnitPrice",+ "minimumOrderQuantity" = best."quantity"+ FROM (+ SELECT DISTINCT ON ("supplierPartId")+ "supplierPartId", "supplierUnitPrice", "quantity"+ FROM "supplierPartPrice"+ WHERE "supplierPartId" = ANY(${supplierPartIds}::text[])+ AND "companyId" = ${companyId}+ ORDER BY "supplierPartId", "supplierUnitPrice" ASC+ ) best+ WHERE sp."id" = best."supplierPartId"+ AND sp."companyId" = ${companyId}+ `.execute(trx);}}});diff --git a/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.ts b/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.tsindex e9b521ab04..408186b8e4 100644--- a/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.ts+++ b/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.ts@@ -180,25 +180,31 @@ databaseTest(const part = await f.db.selectFrom("supplierPart")- .select(["id", "unitPrice", "minimumOrderQuantity"])+ .select(["id", "supplierUnitPrice", "minimumOrderQuantity"]).where("itemId", "=", f.ids.item).where("supplierId", "=", f.ids.supplier).executeTakeFirstOrThrow();- // The lowest quoted price, per inventory unit (2 to a purchase unit).- expect(Number(part.unitPrice)).toBe(4);+ // The lowest quoted price, as quoted: per purchase unit (2 inventory+ // units to one), not divided down to an inventory unit.+ expect(Number(part.supplierUnitPrice)).toBe(8);expect(Number(part.minimumOrderQuantity)).toBe(10);const breaks = await f.db.selectFrom("supplierPartPrice")- .select(["quantity", "unitPrice", "leadTime", "sourceDocumentId"])+ .select([+ "quantity",+ "supplierUnitPrice",+ "leadTime",+ "sourceDocumentId"+ ]).where("supplierPartId", "=", part.id).orderBy("quantity").execute();expect(- breaks.map((b) => [Number(b.quantity), Number(b.unitPrice)])+ breaks.map((b) => [Number(b.quantity), Number(b.supplierUnitPrice)])).toEqual([- [1, 5],- [10, 4]+ [1, 10],+ [10, 8]]);expect(breaks.every((b) => b.sourceDocumentId === f.ids.quote)).toBe(true@@ -213,6 +219,91 @@ databaseTest(});+databaseTest(+ "a quote in the supplier's currency is recorded in that currency",+ async () => {+ const f = await fixture();+ try {+ await f.db+ .updateTable("supplierQuote")+ .set({ currencyCode: "EUR", exchangeRate: 0.8 })+ .where("id", "=", f.ids.quote)+ .execute();++ const result = await finalizeSupplierQuote(f.ctx, {+ supplierQuoteId: f.ids.quote+ });+ expect(result.error).toBeNull();++ const part = await f.db+ .selectFrom("supplierPart")+ .select(["currencyCode", "supplierUnitPrice"])+ .where("itemId", "=", f.ids.item)+ .where("supplierId", "=", f.ids.supplier)+ .executeTakeFirstOrThrow();+ expect(part.currencyCode).toBe("EUR");+ expect(Number(part.supplierUnitPrice)).toBe(8);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "an existing part keeps its currency and gets the quote converted into it",+ async () => {+ const f = await fixture();+ try {+ await f.db+ .updateTable("supplierQuote")+ .set({ currencyCode: "EUR", exchangeRate: 0.8 })+ .where("id", "=", f.ids.quote)+ .execute();+ await f.db+ .insertInto("supplierPart")+ .values({+ itemId: f.ids.item,+ supplierId: f.ids.supplier,+ currencyCode: "USD",+ supplierUnitPrice: 99,+ companyId: f.companyId,+ createdBy: "system"+ })+ .execute();++ const result = await finalizeSupplierQuote(f.ctx, {+ supplierQuoteId: f.ids.quote+ });+ expect(result.error).toBeNull();++ const part = await f.db+ .selectFrom("supplierPart")+ .select(["id", "currencyCode", "supplierUnitPrice"])+ .where("itemId", "=", f.ids.item)+ .where("supplierId", "=", f.ids.supplier)+ .executeTakeFirstOrThrow();+ // 8 EUR at 0.8 EUR per USD.+ expect(part.currencyCode).toBe("USD");+ expect(Number(part.supplierUnitPrice)).toBe(10);++ const breaks = await f.db+ .selectFrom("supplierPartPrice")+ .select(["quantity", "supplierUnitPrice"])+ .where("supplierPartId", "=", part.id)+ .orderBy("quantity")+ .execute();+ expect(+ breaks.map((b) => [Number(b.quantity), Number(b.supplierUnitPrice)])+ ).toEqual([+ [1, 12.5],+ [10, 10]+ ]);+ } finally {+ await f.cleanup();+ }+ }+);+databaseTest("a line without a price and lead time finalizes nothing",async () => {diff --git a/packages/server-functions/src/finalize-supplier-quote/index.ts b/packages/server-functions/src/finalize-supplier-quote/index.tsindex c779bd66a7..fb56ad275a 100644--- a/packages/server-functions/src/finalize-supplier-quote/index.ts+++ b/packages/server-functions/src/finalize-supplier-quote/index.ts@@ -7,6 +7,7 @@ import { datetime, groupBy } from "@carbon/utils";import { z } from "zod";import { defineServerFn } from "../define-server-fn";import { InvalidInputError, NotFoundError, ServerFnError } from "../errors";+import { getSupplierPartPriceConverter } from "../lib/supplier-part-currency";export const finalizeSupplierQuoteInput = z.object({supplierQuoteId: z.string()@@ -17,6 +18,10 @@ export const finalizeSupplierQuoteInput = z.object({* price list, in one transaction: a supplier part per quoted item (created* when the supplier has none), one price break per quoted quantity, and the* lowest quoted price as the part's own.+ *+ * Prices are recorded as quoted — per purchase unit, in the quote's currency.+ * A part created here takes the quote's currency; an existing part in another+ * currency gets the price converted into its own.*/const finalizeSupplierQuote = defineServerFn({name: "finalize-supplier-quote",@@ -26,7 +31,7 @@ const finalizeSupplierQuote = defineServerFn({await db.transaction().execute(async (trx) => {const quote = await trx.selectFrom("supplierQuote")- .select(["id", "supplierId"])+ .select(["id", "supplierId", "currencyCode", "exchangeRate"]).where("id", "=", supplierQuoteId).where("companyId", "=", companyId).executeTakeFirst();@@ -112,6 +117,7 @@ const finalizeSupplierQuote = defineServerFn({supplierUnitOfMeasureCode:line.purchaseUnitOfMeasureCode ?? undefined,conversionFactor: line.conversionFactor ?? 1,+ currencyCode: quote.currencyCode,companyId,createdBy: userId}))@@ -123,15 +129,24 @@ const finalizeSupplierQuote = defineServerFn({const supplierParts = await trx.selectFrom("supplierPart")- .select(["id", "itemId"])+ .select(["id", "itemId", "currencyCode"]).where("supplierId", "=", supplierId).where("companyId", "=", companyId).where("itemId", "in", [...new Set(pricedLines.map((line) => line.itemId))]).execute();- const supplierPartIdByItem = new Map(- supplierParts.map((part) => [part.itemId, part.id])+ const supplierPartByItem = new Map(+ supplierParts.map((part) => [part.itemId, part])+ );+ const converter = await getSupplierPartPriceConverter(+ trx,+ companyId,+ {+ currencyCode: quote.currencyCode,+ exchangeRate: quote.exchangeRate ?? 1+ },+ supplierParts.map((part) => part.currencyCode));// Keyed by (part, quantity): when two lines quote one item at one@@ -141,18 +156,21 @@ const finalizeSupplierQuote = defineServerFn({{supplierPartId: string;quantity: number;- unitPrice: number;+ supplierUnitPrice: number;leadTime: number;}>();const updatedAt = datetime.timestamp();for (const line of pricedLines) {- const supplierPartId = supplierPartIdByItem.get(line.itemId);- if (!supplierPartId) {+ const supplierPart = supplierPartByItem.get(line.itemId);+ if (!supplierPart) {throw new ServerFnError("Failed to create supplier part", 500);}- const conversionFactor = line.conversionFactor ?? 1;+ const supplierPartId = supplierPart.id;+ // Quote prices are per purchase unit, the basis a supplier part keeps.+ const toPartCurrency = (price: number) =>+ converter.toPartCurrency(price, supplierPart.currencyCode);for (const price of line.prices) {if (!price.supplierUnitPrice) continue;@@ -160,21 +178,19 @@ const finalizeSupplierQuote = defineServerFn({priceBreaks.set(`${supplierPartId}:${quantity}`, {supplierPartId,quantity,- unitPrice: (price.unitPrice ?? 0) / conversionFactor,+ supplierUnitPrice: toPartCurrency(price.supplierUnitPrice),leadTime: price.leadTime ?? 0});}const bestPrice = line.prices- .filter((price) => price.unitPrice != null && price.unitPrice !== 0)- .sort(- (a, b) => (a.unitPrice ?? Infinity) - (b.unitPrice ?? Infinity)- )[0];+ .filter((price) => !!price.supplierUnitPrice)+ .sort((a, b) => a.supplierUnitPrice - b.supplierUnitPrice)[0];if (bestPrice) {await trx.updateTable("supplierPart").set({- unitPrice: (bestPrice.unitPrice ?? 0) / conversionFactor,+ supplierUnitPrice: toPartCurrency(bestPrice.supplierUnitPrice),minimumOrderQuantity: bestPrice.quantity ?? 1}).where("id", "=", supplierPartId)@@ -199,7 +215,7 @@ const finalizeSupplierQuote = defineServerFn({).onConflict((oc) =>oc.columns(["supplierPartId", "quantity"]).doUpdateSet((eb) => ({- unitPrice: eb.ref("excluded.unitPrice"),+ supplierUnitPrice: eb.ref("excluded.supplierUnitPrice"),leadTime: eb.ref("excluded.leadTime"),sourceType: eb.ref("excluded.sourceType"),sourceDocumentId: eb.ref("excluded.sourceDocumentId"),diff --git a/packages/server-functions/src/import-csv/index.ts b/packages/server-functions/src/import-csv/index.tsindex c6317863b7..e011f61c91 100644--- a/packages/server-functions/src/import-csv/index.ts+++ b/packages/server-functions/src/import-csv/index.ts@@ -1032,6 +1032,9 @@ async function writeSupplierPartLinks(const numericConversion = link.conversionFactor? Number.parseFloat(link.conversionFactor): 1;+ // The price is in the supplier part's currency: an existing part keeps+ // its own, a new one is created in base (currencyCode NULL), which is+ // what an imported price has always meant.const numericPrice = link.unitPrice? Number.parseFloat(link.unitPrice): null;@@ -1045,7 +1048,7 @@ async function writeSupplierPartLinks(minimumOrderQuantity: numericMOQ,orderMultiple: numericOrderMultiple,conversionFactor: numericConversion,- unitPrice: numericPrice,+ supplierUnitPrice: numericPrice,updatedAt: now,updatedBy: userId})@@ -1063,7 +1066,7 @@ async function writeSupplierPartLinks(minimumOrderQuantity: numericMOQ,orderMultiple: numericOrderMultiple,conversionFactor: numericConversion,- unitPrice: numericPrice,+ supplierUnitPrice: numericPrice,companyId,createdBy: userId})diff --git a/packages/server-functions/src/lib/supplier-part-currency.ts b/packages/server-functions/src/lib/supplier-part-currency.tsnew file mode 100644index 0000000000..ea94f2b8f2--- /dev/null+++ b/packages/server-functions/src/lib/supplier-part-currency.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { KyselyDatabase } from "@carbon/database/client";+import {+ type CurrencyRate,+ convertUnitPrice,+ supplierPartCurrency+} from "@carbon/database/supplier-part-price";+import { type Kysely, sql } from "kysely";++export type SupplierPartPriceConverter = {+ /** The currency a supplier part's price is in (NULL = base). */+ currencyOf: (partCurrencyCode: string | null) => string;+ /** A price per purchase unit in the DOCUMENT's currency, in the part's. */+ toPartCurrency: (price: number, partCurrencyCode: string | null) => number;+};++/**+ * Converts prices learned from a purchase document (a supplier quote, order or+ * invoice) into the currency of the supplier part that records them. A part+ * keeps the currency it was set up in; a price in that same currency is copied+ * exactly, any other crosses through base at the document's own rate and the+ * part currency's CURRENT rate. A missing rate raises (`get_exchange_rate`)+ * rather than recording the price at par.+ *+ * A NULL document or part currency is the company base currency. Rates are+ * loaded once, for every part currency the caller will convert into.+ */+export async function getSupplierPartPriceConverter(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ document: { currencyCode: string | null; exchangeRate: number },+ partCurrencyCodes: (string | null)[]+): Promise<SupplierPartPriceConverter> {+ const company = await db+ .selectFrom("company")+ .select("baseCurrencyCode")+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ const baseCurrencyCode = company.baseCurrencyCode;++ const currencyOf = (code: string | null) =>+ supplierPartCurrency(code, baseCurrencyCode);+ const from: CurrencyRate = {+ currencyCode: currencyOf(document.currencyCode),+ exchangeRate: document.exchangeRate+ };++ const codes = [+ ...new Set(+ partCurrencyCodes+ .map(currencyOf)+ .filter((code) => code !== from.currencyCode)+ )+ ];++ const rates = new Map<string, number>();+ if (codes.length > 0) {+ const { rows } = await sql<{ code: string; rate: number }>`+ SELECT code, get_exchange_rate(${companyId}, code) AS rate+ FROM unnest(${codes}::text[]) AS code+ `.execute(db);+ for (const row of rows) rates.set(row.code, Number(row.rate));+ }++ return {+ currencyOf,+ toPartCurrency: (price, partCurrencyCode) => {+ const currencyCode = currencyOf(partCurrencyCode);+ return convertUnitPrice(price, from, {+ currencyCode,+ exchangeRate:+ currencyCode === from.currencyCode+ ? from.exchangeRate+ : rates.get(currencyCode)!+ });+ }+ };+}diff --git a/packages/server-functions/src/update-purchased-prices/index.ts b/packages/server-functions/src/update-purchased-prices/index.tsindex 574d967da4..09102bf058 100644--- a/packages/server-functions/src/update-purchased-prices/index.ts+++ b/packages/server-functions/src/update-purchased-prices/index.ts@@ -11,6 +11,7 @@ import { sql } from "kysely";import { z } from "zod";import { defineServerFn } from "../define-server-fn";import { NotFoundError } from "../errors";+import { getSupplierPartPriceConverter } from "../lib/supplier-part-currency";const logger = getLogger("server-functions", "update-purchased-prices");@@ -32,7 +33,10 @@ export const updatePurchasedPricesInput = z.discriminatedUnion("source", [interface PurchaseLineData {itemId: string | null;jobOperationId: string | null;+ /** Base currency, per purchase unit. */unitPrice: number;+ /** The document's currency, per purchase unit — what the supplier charged. */+ supplierUnitPrice: number;quantity: number;conversionFactor: number | null;purchaseUnitOfMeasureCode: string | null;@@ -69,6 +73,7 @@ const updatePurchasedPrices = defineServerFn({let supplierId: string;let lines: PurchaseLineData[];+ let documentCurrency: { currencyCode: string | null; exchangeRate: number };switch (source) {case "purchaseOrder": {@@ -99,11 +104,16 @@ const updatePurchasedPrices = defineServerFn({throw new Error("Purchase order has no supplier");supplierId = purchaseOrder.data.supplierId;+ documentCurrency = {+ currencyCode: purchaseOrder.data.currencyCode,+ exchangeRate: purchaseOrder.data.exchangeRate ?? 1+ };lines = purchaseOrderLines.data.map((line) => ({itemId: line.itemId,jobOperationId: null,unitPrice: line.unitPrice ?? 0,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,quantity:(line.purchaseQuantity ?? 0) * (line.conversionFactor ?? 1),conversionFactor: line.conversionFactor,@@ -182,11 +192,16 @@ const updatePurchasedPrices = defineServerFn({throw new Error("Purchase invoice has no supplier");supplierId = purchaseInvoice.data.supplierId;+ documentCurrency = {+ currencyCode: purchaseInvoice.data.currencyCode,+ exchangeRate: purchaseInvoice.data.exchangeRate ?? 1+ };lines = purchaseInvoiceLines.data.map((line) => ({itemId: line.itemId,jobOperationId: line.jobOperationId,unitPrice: line.unitPrice ?? 0,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,quantity: (line.quantity ?? 0) * (line.conversionFactor ?? 1),conversionFactor: line.conversionFactor,purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode@@ -391,6 +406,21 @@ const updatePurchasedPrices = defineServerFn({}}+ // The supplier part records what the supplier charged, in its own+ // currency: copied exactly when it matches the document's, converted at+ // today's rate when it does not.+ const priceConverter =+ shouldUpdatePrices && itemIds.length > 0+ ? await getSupplierPartPriceConverter(+ db,+ companyId,+ documentCurrency,+ supplierPartRows+ .filter((sp) => sp.supplierId === supplierId)+ .map((sp) => sp.currencyCode)+ )+ : null;+lines.forEach((line) => {if (line.itemId && !line.jobOperationId) {const costHistory = historicalPartCosts[line.itemId];@@ -416,7 +446,10 @@ const updatePurchasedPrices = defineServerFn({if (supplierPart && supplierPart.id) {supplierPartUpdates.push({id: supplierPart.id,- unitPrice: line.unitPrice,+ supplierUnitPrice: priceConverter!.toPartCurrency(+ line.supplierUnitPrice,+ supplierPart.currencyCode+ ),conversionFactor: line.conversionFactor ?? 1,supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,updatedBy: "system"@@ -425,7 +458,8 @@ const updatePurchasedPrices = defineServerFn({supplierPartInserts.push({itemId: line.itemId,supplierId: supplierId,- unitPrice: line.unitPrice,+ supplierUnitPrice: line.supplierUnitPrice,+ currencyCode: documentCurrency.currencyCode,conversionFactor: line.conversionFactor ?? 1,supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,createdBy: "system",@@ -502,7 +536,8 @@ const updatePurchasedPrices = defineServerFn({.values(supplierPartInserts).onConflict((oc) =>oc.columns(["itemId", "supplierId", "companyId"]).doUpdateSet({- unitPrice: (eb) => eb.ref("excluded.unitPrice"),+ supplierUnitPrice: (eb) => eb.ref("excluded.supplierUnitPrice"),+ currencyCode: (eb) => eb.ref("excluded.currencyCode"),conversionFactor: (eb) => eb.ref("excluded.conversionFactor"),supplierUnitOfMeasureCode: (eb) =>eb.ref("excluded.supplierUnitOfMeasureCode"),diff --git a/packages/server-functions/src/update-purchased-prices/supplier-part-currency.test.ts b/packages/server-functions/src/update-purchased-prices/supplier-part-currency.test.tsnew file mode 100644index 0000000000..5f2fd1580c--- /dev/null+++ b/packages/server-functions/src/update-purchased-prices/supplier-part-currency.test.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { sql } from "kysely";+import { expect } from "vitest";+import {+ connectLocalTestDatabase,+ databaseTest+} from "../local-database-test-fixture";+import { ServerFnContext } from "../server-fn-context";+import updatePurchasedPrices from ".";++// A USD company buying one part from a supplier on a EUR purchase order at+// 0.8 EUR per USD: 8 EUR a box of 2.+async function fixture() {+ const db = await connectLocalTestDatabase();+ const p = `upptest-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;+ const companyId = `${p}-company`;+ const ids = {+ item: `${p}-item`,+ supplier: `${p}-supplier`,+ order: `${p}-po`+ };++ await db.transaction().execute(async (trx) => {+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);+ await sql`+ INSERT INTO "companyGroup" (id, name, "createdBy") VALUES (${`${p}-group`}, ${p}, 'system');+ `.execute(trx);+ await sql`+ INSERT INTO "company" (id, name, "companyGroupId", "baseCurrencyCode")+ VALUES (${companyId}, ${p}, ${`${p}-group`}, 'USD')+ `.execute(trx);+ await sql`+ INSERT INTO "supplier" (id, name, "readableId", "currencyCode", "companyId", "createdBy")+ VALUES (${ids.supplier}, 'One', 'S1', 'EUR', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")+ VALUES ('EA', 'Each', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "item" (id, "readableId", name, type, "replenishmentSystem", "defaultMethodType",+ "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES (${ids.item}, 'P-1', 'Part', 'Part', 'Buy', 'Pull from Inventory', 'Inventory', 'EA',+ ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "supplierInteraction" (id, "companyId", "supplierId")+ VALUES (${`${p}-interaction`}, ${companyId}, ${ids.supplier})+ `.execute(trx);+ await sql`+ INSERT INTO "purchaseOrder" (id, "purchaseOrderId", "supplierId", "supplierInteractionId",+ "currencyCode", "exchangeRate", "companyId", "createdBy")+ VALUES (${ids.order}, 'PO-T', ${ids.supplier}, ${`${p}-interaction`}, 'EUR', 0.8,+ ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "purchaseOrderLine" ("purchaseOrderId", "purchaseOrderLineType", "itemId",+ "purchaseQuantity", "supplierUnitPrice", "exchangeRate", "conversionFactor",+ "companyId", "createdBy")+ VALUES (${ids.order}, 'Part', ${ids.item}, 5, 8, 0.8, 2, ${companyId}, 'system')+ `.execute(trx);+ });++ return {+ db,+ companyId,+ ids,+ ctx: ServerFnContext.system({ db, companyId, userId: "system" }),+ supplierPart: () =>+ db+ .selectFrom("supplierPart")+ .select(["currencyCode", "supplierUnitPrice", "conversionFactor"])+ .where("itemId", "=", ids.item)+ .where("supplierId", "=", ids.supplier)+ .executeTakeFirst(),+ async cleanup() {+ await db.transaction().execute(async (trx) => {+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);+ await trx.deleteFrom("company").where("id", "=", companyId).execute();+ await trx+ .deleteFrom("companyGroup")+ .where("id", "=", `${p}-group`)+ .execute();+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`.execute(+ trx+ );+ });+ await db.destroy();+ }+ };+}++databaseTest(+ "a new supplier part records the order's price as the supplier charged it",+ async () => {+ const f = await fixture();+ try {+ const result = await updatePurchasedPrices(f.ctx, {+ source: "purchaseOrder",+ purchaseOrderId: f.ids.order+ });+ expect(result.error).toBeNull();++ const part = await f.supplierPart();+ // Per purchase unit (a box of 2), in EUR — not 10 USD, not 5 per each.+ expect(part?.currencyCode).toBe("EUR");+ expect(Number(part?.supplierUnitPrice)).toBe(8);+ expect(Number(part?.conversionFactor)).toBe(2);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "an existing supplier part keeps its currency and gets the price converted",+ async () => {+ const f = await fixture();+ try {+ await f.db+ .insertInto("supplierPart")+ .values({+ itemId: f.ids.item,+ supplierId: f.ids.supplier,+ currencyCode: "USD",+ supplierUnitPrice: 99,+ conversionFactor: 2,+ companyId: f.companyId,+ createdBy: "system"+ })+ .execute();++ const result = await updatePurchasedPrices(f.ctx, {+ source: "purchaseOrder",+ purchaseOrderId: f.ids.order+ });+ expect(result.error).toBeNull();++ const part = await f.supplierPart();+ // 8 EUR at the order's 0.8 EUR per USD.+ expect(part?.currencyCode).toBe("USD");+ expect(Number(part?.supplierUnitPrice)).toBe(10);+ } finally {+ await f.cleanup();+ }+ }+);