Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(sales): configuration pricing rules and sales order line configuration (#1768)

Brad Barbin7b445c334d0d
diff --git a/.ai/lessons.md b/.ai/lessons.md
index b103172eed..5fe2dc86f2 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2567,3 +2567,25 @@ keep the old name. Then run the seed itself. Docs count as hits too — main's n
**Applies to:** any branch that renames a table, column or enum value and then
merges main; `packages/database/src/datasets/wipe.ts` above all, since no automated
gate executes it.
+
+## Never `git checkout` a generated file to undo a local patch — the user may have regenerated it
+
+**Context:** Typechecking a new-column change in a worktree with no local database, the
+generated `packages/database/src/types.ts` was patched by hand as a throwaway so `tsgo`
+could see the columns, then "restored" with `git checkout -- …/types.ts`. Meanwhile the
+user had run `pnpm db:migrate`, which regenerated that file with the real columns.
+
+**Problem:** The checkout reverted the user's regeneration to `HEAD`, silently leaving the
+repo with types that no longer matched the live schema (the Deno copy,
+`functions/lib/types.ts`, was untouched, so the two outputs disagreed). The first symptom
+was a wall of `Duplicate identifier` errors from re-applying the throwaway patch on top of
+the regenerated file.
+
+**Rule:** Before reverting any generated file, `git diff` it and confirm the only changes
+are yours. Prefer regenerating (`pnpm generate:types`, needs the local stack) over a
+checkout; if there is no stack, keep the throwaway patch in a scratch copy rather than the
+tracked file.
+
+**Applies to:** `packages/database/src/types.ts`,
+`packages/database/supabase/functions/lib/types.ts`,
+`apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json`, any generated artifact.
diff --git a/.claude/rules/quote-discount-system.md b/.claude/rules/quote-discount-system.md
index 66f022dd50..7ce2043a4e 100644
--- a/.claude/rules/quote-discount-system.md
+++ b/.claude/rules/quote-discount-system.md
@@ -41,7 +41,7 @@ A trigger on `quote.exchangeRate` cascades the new rate into every `quoteLinePri
## Schema: `pricingRule` (`20260413120001_pricing-rules.sql`)
Standalone rules, `id` default `id('pr')`, scoped to a company. Columns: `name`,
-`ruleType` (`pricingRuleType` enum = `'Discount' | 'Markup'`), `amountType`
+`ruleType` (`pricingRuleType` enum = `'Discount' | 'Markup' | 'Configuration'`), `amountType`
(`pricingRuleAmountType` enum = `'Percentage' | 'Fixed'`, default `Percentage`),
`amount` NUMERIC, `priority` INT, `minQuantity`/`maxQuantity`, `customerIds[]`,
`customerTypeIds[]`, `itemIds[]`, `itemPostingGroupId`, `validFrom`/`validTo`,
@@ -55,14 +55,22 @@ Standalone rules, `id` default `id('pr')`, scoped to a company. Columns: `name`,
(also materialized in the generated `netUnitPrice` column). The UI computes the same
net for display; persistence is the generated columns.
-2. **Pricing-rule engine** (`resolvePrice` → `applyPriceRules` in `sales.service.ts`):
+2. **Pricing-rule engine** (`resolvePrice` in `sales.service.ts` → `applyPriceRules` in `sales.utils.ts`):
resolves a *base unit price* during quote-line price recalculation (cost rollup with
`categoryMarkups`, then `resolvePrice`). Precedence: customer override > customer-type
override > all-customers override > base (`itemUnitSalePrice`). Overrides may set
- `applyRulesOnTop=false` to skip rules. Then `applyPriceRules`:
+ `applyRulesOnTop=false` to skip the discount and markup rules. Then `applyPriceRules`:
- **Discount rules: non-stacking** — highest `priority` wins; ties broken by best
effective amount. Percentage = `price * amount`; Fixed = `amount`.
- **Markup rules: stack** in priority order, compounding on the running price.
+ - **Configuration rules** (`ruleType = 'Configuration'`, one configurable item, amount 0):
+ their `configurationPrices` are signed per-unit surcharges added to the starting price
+ BEFORE the discount, stacking across every matched Configuration rule; they need the
+ line's `configuration` (`quoteLine` / `salesOrderLine`), passed to `resolvePrice` as
+ `input.configuration`. Trace steps carry the parameter's `label`, saved on each
+ price entry by the rule form (no lookup at pricing time). An override with
+ `applyRulesOnTop=false` skips discounts and markups but still applies the
+ configuration prices (`applyPriceRules(..., { configurationOnly: true })`).
- Final price clamped to ≥ 0.
Each step is recorded as a `PriceTraceStep` (`{ step, source, amount, adjustment?, ruleId? }`)
into `priceTrace`. The winning rule's id lands on `quoteLine.pricingRuleId`.
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
index 86f49c6638..ff94570977 100644
--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx
@@ -44,6 +44,9 @@ interface FormData {
[key: string]: string | number | boolean | MaterialConfigurationData;
}
+// The values a configurator collects, keyed by configurationParameter key.
+export type ConfiguratorValues = FormData;
+
interface ParameterFieldProps {
parameter: ConfigurationParameter;
}
@@ -198,10 +201,12 @@ function ParameterField({ parameter }: ParameterFieldProps) {
);
case "boolean":
+ // Matches the bordered `Boolean` form field — this form keeps its own
+ // state, so it can't use the ValidatedForm-bound component.
return (
- <div className="flex flex-col items-start gap-2">
+ <div className="flex items-center justify-between gap-4 border border-border rounded-lg p-4">
<Label
- className="text-xs text-muted-foreground"
+ className="text-sm text-foreground cursor-pointer"
htmlFor={parameter.key}
>
{parameter.label}
@@ -561,7 +566,7 @@ type ConfiguratorStepProps = {
function ConfiguratorStep({ group, parameters }: ConfiguratorStepProps) {
return (
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2 w-full">
+ <div className="flex flex-col gap-4 w-full">
{parameters.map((parameter) => (
<ParameterField key={parameter.id} parameter={parameter} />
))}
diff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/index.ts b/apps/erp/app/components/Configurator/ConfiguratorForm/index.ts
index c8c7d79082..2c35c69b6c 100644
--- a/apps/erp/app/components/Configurator/ConfiguratorForm/index.ts
+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/index.ts
@@ -1 +1,2 @@
+export type { ConfiguratorValues } from "./ConfiguratorForm";
export { ConfiguratorModal } from "./ConfiguratorForm";
diff --git a/apps/erp/app/components/Configurator/ItemConfigurator.tsx b/apps/erp/app/components/Configurator/ItemConfigurator.tsx
new file mode 100644
index 0000000000..0baeb23fdd
--- /dev/null
+++ b/apps/erp/app/components/Configurator/ItemConfigurator.tsx
@@ -0,0 +1,119 @@
+import { useCarbon } from "@carbon/auth";
+import { Button, useDisclosure, useMount } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { useCallback, useRef, useState } from "react";
+import { useUser } from "~/hooks";
+import {
+ type ConfigurationParameter,
+ type ConfigurationParameterGroup,
+ getConfigurationParameters
+} from "~/modules/items";
+import { ConfiguratorModal, type ConfiguratorValues } from "./ConfiguratorForm";
+
+type ItemConfigurationParameters = {
+ parameters: ConfigurationParameter[];
+ groups: ConfigurationParameterGroup[];
+};
+
+/**
+ * The configurator of a document line: the line item's configuration
+ * parameters (null when the item needs no configuration) and the values
+ * chosen for them.
+ */
+export function useItemConfiguration(initial: {
+ itemId?: string;
+ configuration?: ConfiguratorValues | null;
+}) {
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const disclosure = useDisclosure();
+ const [parameters, setParameters] =
+ useState<ItemConfigurationParameters | null>(null);
+ const [configuration, setConfiguration] = useState<ConfiguratorValues | null>(
+ initial.configuration ?? null
+ );
+ // The item the latest load is for: a slower response for an item picked
+ // earlier must not overwrite it.
+ const requestedItemId = useRef<string | null>(null);
+
+ const load = useCallback(
+ async (itemId: string) => {
+ requestedItemId.current = itemId;
+ if (!carbon || !company.id) return;
+ const replenishment = await carbon
+ .from("itemReplenishment")
+ .select("requiresConfiguration")
+ .eq("itemId", itemId)
+ .eq("companyId", company.id)
+ .maybeSingle();
+ const result = replenishment.data?.requiresConfiguration
+ ? await getConfigurationParameters(carbon, itemId, company.id)
+ : null;
+ if (requestedItemId.current === itemId) setParameters(result);
+ },
+ [carbon, company.id]
+ );
+
+ useMount(() => {
+ if (initial.itemId) load(initial.itemId);
+ });
+
+ // A configuration belongs to one item's parameters.
+ const changeItem = (itemId: string) => {
+ setConfiguration(null);
+ load(itemId);
+ };
+
+ return {
+ parameters,
+ configuration,
+ setConfiguration,
+ changeItem,
+ disclosure
+ };
+}
+
+/**
+ * Configure / Reconfigure for a line whose item requires configuration, with
+ * its configurator modal. Renders nothing for any other item.
+ */
+export function ItemConfigureButton({
+ configurator,
+ isDisabled,
+ onConfigured
+}: {
+ configurator: ReturnType<typeof useItemConfiguration>;
+ isDisabled: boolean;
+ onConfigured: (values: ConfiguratorValues) => void;
+}) {
+ const { parameters, configuration, setConfiguration, disclosure } =
+ configurator;
+ if (!parameters) return null;
+
+ return (
+ <>
+ <Button
+ variant={configuration ? "secondary" : "primary"}
+ type="button"
+ isDisabled={isDisabled}
+ onClick={disclosure.onOpen}
+ >
+ {configuration ? <Trans>Reconfigure</Trans> : <Trans>Configure</Trans>}
+ </Button>
+ {disclosure.isOpen && (
+ <ConfiguratorModal
+ open
+ initialValues={configuration ?? {}}
+ groups={parameters.groups}
+ parameters={parameters.parameters}
+ onClose={disclosure.onClose}
+ onSubmit={(values) => {
+ setConfiguration(values);
+ disclosure.onClose();
+ onConfigured(values);
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/pricing.md b/apps/erp/app/modules/agent/kb/docs/reference/pricing.md
index cbd293de32..c233d98b4e 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/pricing.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/pricing.md
@@ -6,9 +6,9 @@ When you add an item to a quote line or a sales order line, Carbon doesn't just
## Pricing rules
-A **pricing rule** is a company-scoped rule that adjusts a price up or down. Each rule is a `Discount` or a `Markup`, expressed as either a `Percentage` or a `Fixed` amount, and it only fires when the line matches the rule's conditions.
+A **pricing rule** is a company-scoped rule that adjusts a price up or down. Each rule is a `Discount` or a `Markup`, expressed as either a `Percentage` or a `Fixed` amount, or a `Configuration` rule that prices a configured part's options (below). A rule only fires when the line matches its conditions.
- - **Rule type**: `Discount` (lowers the price) or `Markup` (raises it).
+ - **Rule type**: `Discount` (lowers the price), `Markup` (raises it), or `Configuration` (prices a configured part's options).
- **Amount type**: `Percentage` or `Fixed`. A percentage is stored as a fraction from 0 to 1 (10% is `0.10`), so the form caps it at 100%.
- **Amount**: The discount/markup value. For a percentage, the fraction of the running price; for fixed, an absolute amount.
- **Priority**: Higher priority wins among discounts and orders the markup stack. Defaults to `0`.
@@ -22,6 +22,18 @@ A rule matches a line only when every set condition holds: the quantity is withi
A `Percentage` amount is a fraction between 0 and 1 (`0.10` for 10%). The rule form rejects anything above 1. If you enter 15 expecting 15%, that's a 1500% adjustment.
+### Configuration rules
+
+A `Configuration` rule has no amount or item scope of its own. Instead you pick one **configured part** (only parts that require configuration are listed), and the form shows a **Configuration Prices** section listing that part's configuration parameters. Each amount is a per-unit surcharge added to the line's unit price when the line's configuration matches:
+
+- **List** parameters take an amount per option (`Color = Red → 10`).
+- **Boolean** parameters take an amount for when the value is true.
+- **Numeric** parameters take an amount per unit of the value (`0.50 × Length`).
+
+Text, date and material parameters can't be priced. Amounts are signed, so a negative amount gives a credit. The surcharges from every matching Configuration rule stack. They are added before the discount and markup rules, so a discount also applies to the surcharges. Each one appears in the price trace as a `Configuration` step labelled with the parameter's name. The customer scope, dates, quantity range and priority work as on any other rule. A price override that doesn't apply rules on top still takes the configuration prices, because they price the chosen options rather than the part.
+
+Configuration prices apply wherever the line has a configuration: quote lines, which reprice when a line is configured or reconfigured, and sales order lines, which have their own **Configure** button.
+
## Price overrides
A **price override** pins a negotiated price for a specific item, optionally with quantity breaks. Unlike a rule, an override replaces the base price outright rather than adjusting it. Overrides are scoped one of three ways, and a single override targets exactly one scope:
@@ -65,7 +77,7 @@ Discounts and markups combine differently, and this is the part that surprises p
- **Discounts don't stack — the single highest-priority discount wins.** When several discount rules match, Carbon ranks them by priority (ties broken by the larger effective amount) and applies **only the top one**. The rest are discarded. You never get two discounts on the same line.
- **Markups stack and compound.** Every matching markup rule applies, in priority order, each computed against the already-adjusted running price. A 10% markup after a 20% markup compounds, it doesn't simply add.
-Discounts are applied first, then the markup stack, then the zero floor.
+Configuration prices are added first, then the discount, then the markup stack, then the zero floor.
If a customer qualifies for both a 10% and a 15% discount rule, they get 15% only — never 25%, and never both applied in sequence. Markups are the opposite: all of them apply, compounding.
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index fdb6229246..37ad1b4849 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -1206,6 +1206,7 @@
"keywords": ["pricing", "rules", "and", "overrides", "docs", "reference"],
"headings": [
"Pricing rules",
+ "Configuration rules",
"Price overrides",
"How the engine picks a price",
"What wins when rules collide",
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 03874efec3..eab3eeea72 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -82,7 +82,7 @@ pnpm --filter @carbon/erp test
## Key Service Functions
-- `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines
+- `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured
- `getJob` / `getJobs` / `getJobMethodTree` / `getJobMethodTreeArray` — job reads with method hierarchy
- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility
- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index f840c43940..08d24f7e5f 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -47,6 +47,7 @@ import {
import { sanitize } from "~/utils/supabase";
import { getDefaultStorageUnitForJob } from "../inventory";
import { getEmployeeJob } from "../people";
+import { resolveJobConfiguration } from "../sales/sales.utils";
import type {
MethodType,
operationParameterValidator,
@@ -184,6 +185,21 @@ export async function convertSalesOrderLinesToJobs(
const quoteId = opportunity.data?.quotes[0]?.id;
const salesOrderId = opportunity.data?.salesOrders[0]?.id;
+ // A converted quote line shares its id with the order line, so its
+ // configuration is the fallback for an order line configured nowhere else.
+ const quoteLineConfigurations = new Map<string, unknown>();
+ if (quoteId) {
+ const quoteLines = await client
+ .from("quoteLine")
+ .select("id, configuration")
+ .eq("quoteId", quoteId)
+ .eq("companyId", companyId)
+ .in("id", lines.map((line) => line.id).filter(Boolean) as string[]);
+ for (const quoteLine of quoteLines.data ?? []) {
+ quoteLineConfigurations.set(quoteLine.id, quoteLine.configuration);
+ }
+ }
+
const errors: string[] = [];
let jobsCreated = 0;
@@ -206,6 +222,11 @@ export async function convertSalesOrderLinesToJobs(
const jobsToCreate = Math.max(1, totalJobs);
+ const { configuration, reconfigured } = resolveJobConfiguration(
+ line.configuration,
+ line.id ? quoteLineConfigurations.get(line.id) : null
+ );
+
const defaultLocation = await client
.from("location")
.select("id")
@@ -277,7 +298,8 @@ export async function convertSalesOrderLinesToJobs(
salesOrderLineId: line.id,
scrapQuantity,
storageUnitId: storageUnitId ?? undefined,
- unitOfMeasureCode: line.unitOfMeasureCode ?? "EA"
+ unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
+ configuration: configuration as Json
};
// Calculate priority based on due date and deadline type
@@ -326,7 +348,7 @@ export async function convertSalesOrderLinesToJobs(
source: "salesOrder"
});
- if (quoteId) {
+ if (quoteId && !reconfigured) {
const upsertMethod = await client.functions.invoke("get-method", {
body: {
type: "quoteLineToJob",
@@ -350,7 +372,8 @@ export async function convertSalesOrderLinesToJobs(
sourceId: data.itemId,
targetId: createJob.data.id,
companyId,
- userId
+ userId,
+ ...(configuration ? { configuration } : {})
}
});
@@ -3496,6 +3519,7 @@ export async function insertJob(
modelUploadId: input.modelUploadId,
notes: input.notes,
customFields: input.customFields,
+ configuration: (input.configuration as Json | undefined) ?? null,
companyId: input.companyId,
createdBy: input.createdBy,
updatedBy: input.createdBy
diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.md
index 4060c27acb..2691b845fb 100644
--- a/apps/erp/app/modules/sales/AGENTS.md
+++ b/apps/erp/app/modules/sales/AGENTS.md
@@ -8,7 +8,8 @@ Quotes (with cost rollup and pricing), sales orders, sales RFQs, customer manage
- **Quote** — detailed cost estimate with line items, each having a make method (BOM + routing) and quantity-break pricing. Statuses: Draft → Pending → Sent → Ordered / Lost / Cancelled.
- **Quote Revision** — `quote.revisionId`. Unlike a PO (amended in place), a quote revision is a **new `quote` row** created by `copyQuote` → the `get-method` edge function (`quoteToQuote`, `asRevision: true`), keeping the same `quoteId` with `revisionId = max + 1`, sharing the source `opportunityId`. Each revision gets its **own `externalLink`** row, whose `documentId` is revision-qualified (`Q000001-1`) because `externalLink` is UNIQUE on `(documentId, documentType, companyId)` — an unqualified id collides with the original's link. `deleteQuote` does not remove the link row, so that insert uses `onConflict … doUpdateSet` to reuse the orphan a deleted revision left behind. Displayed as `Q000001-1` when > 0 via `getQuoteDisplayId` (`@carbon/documents/utils`) on the PDF, email, share page, and filenames; two-tone in-app rendering uses `<RevisionSuffix>` (`~/components`).
- **Quote Line Pricing** — per-quantity-break pricing. PK is `(quoteLineId, quantity)` — no `id` column. `discountPercent` is a **fraction 0–1** (not 0–100). Generated columns compute net/converted prices. **Lead time can be PREDICTED from the shop schedule** rather than typed: the calendar-clock button on the Lead Time row opens `QuoteLeadTimeModal`, which POSTs `$quoteId.$lineId.lead-time.tsx` → `runQuoteLeadTimeWhatIf` (`@carbon/planning`) and applies one constraint's value to every break at once. The write goes through the grid's `onUpdateLeadTimes` (`quoteLinePrice.leadTime`, one state update for every break — never a loop over `onUpdatePrice`, which snapshots state per call; a failed row is rolled back and the modal stays open) — no new persistence, so `resolvePreservedQuoteLinePriceFields` is untouched.
-- **Pricing Rules** — company-scoped Discount/Markup rules. Discounts are non-stacking (highest-priority wins); Markups stack and compound in priority order.
+- **Pricing Rules** — company-scoped Discount/Markup/Configuration rules. Discounts are non-stacking (highest-priority wins); Markups stack and compound in priority order. A **Configuration** rule targets exactly ONE configurable item (`itemId` in the form → `itemIds: [id]`, amount 0, no item group — `normalizePricingRule` in `sales.service.ts`) and carries `configurationPrices` (JSONB `{ key, value, amount, label? }[]` — list option / `"true"` for a boolean / `null` = per unit of a numeric value; `label` is the parameter's label at save time, used by the price trace; validated by `pricingRuleConfigurationPriceValidator` in `sales.utils.ts`, which stays out of the `sales.models` import graph so the engine tests can load it). `toMatchedRule` parses a rule row for the engine; `applyPriceRules` (`sales.utils.ts`) adds those signed surcharges to the starting price before the discount, given the line's `configuration`. An override with `applyRulesOnTop = false` still takes them (`configurationOnly`) — they price the options, not the part. Every other rule type stores `configurationPrices` as null.
+- **Line configuration** — `quoteLine.configuration` and `salesOrderLine.configuration` (keyed by `configurationParameter.key`; the `convert` edge function copies it quote → order). Jobs made for an order line use `resolveJobConfiguration` (`sales.utils.ts`): the order line's configuration, else the quote line's; when the order line was configured differently from its quote the job is built with `itemToJob` + that configuration instead of copying the quote's method (an unset value — absent, null or blank — compares equal). The sales order line form keeps its configurator in `useItemConfiguration` + `ItemConfigureButton` (`~/components/Configurator/ItemConfigurator`), which loads parameters through `getConfigurationParameters` and ignores a stale load for an item no longer selected.
- **Price Overrides** — customer-specific or type-specific price overrides with quantity breaks via `customerItemPriceOverride` / `customerItemPriceOverrideBreak`. Precedence: customer > customer-type > all-customers > base price.
- **Sales Order** — confirmed order from a quote. Lines carry `methodType` (Make to Order, Make to Stock, etc.) that determines production handling.
- **Sales RFQ** — inbound request from a customer, convertible to a quote via the `convert` edge function.
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 02d93a96b1..8cf392d7b0 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -23,6 +23,7 @@ import {
standardFactorType,
taxExemptionReasons
} from "../shared";
+import { pricingRuleConfigurationPriceValidator } from "./sales.utils";
export const KPIs = [
{
@@ -339,10 +340,27 @@ export const priceResolutionInputValidator = z.object({
customerTypeId: z.string().optional(),
itemPostingGroupId: z.string().optional(),
date: z.string().optional(),
- existingBasePrice: z.number().optional()
+ existingBasePrice: z.number().optional(),
+ configuration: z.record(z.string(), z.unknown()).optional()
});
-export const pricingRuleTypes = ["Discount", "Markup"] as const;
+const parseJsonField = (value: unknown) => {
+ if (typeof value !== "string") return value;
+ if (value.trim() === "") return undefined;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+};
+
+// A Configuration rule prices one configurable item's parameter values
+// (`configurationPrices`) and has no discount or markup of its own.
+export const pricingRuleTypes = [
+ "Discount",
+ "Markup",
+ "Configuration"
+] as const;
export const pricingRuleAmountTypes = ["Percentage", "Fixed"] as const;
export const pricingRuleValidator = z
@@ -357,11 +375,17 @@ export const pricingRuleValidator = z
customerIds: z.array(z.string()).optional().default([]),
customerTypeIds: z.array(z.string()).optional().default([]),
itemIds: z.array(z.string()).optional().nullable().default([]),
+ // The single configurable item of a Configuration rule.
+ itemId: zfd.text(z.string().optional()),
itemPostingGroupId: zfd.text(z.string().optional()),
validFrom: zfd.text(z.string().optional()),
validTo: zfd.text(z.string().optional()),
priority: zfd.numeric(z.number().int().min(0).optional().default(0)),
- active: zfd.checkbox()
+ active: zfd.checkbox(),
+ configurationPrices: z.preprocess(
+ parseJsonField,
+ z.array(pricingRuleConfigurationPriceValidator).optional()
+ )
})
.refine((d) => d.amountType !== "Percentage" || d.amount <= 1, {
message: "Percentage must be between 0% and 100%",
@@ -370,7 +394,12 @@ export const pricingRuleValidator = z
.refine((d) => !d.validFrom || !d.validTo || d.validFrom <= d.validTo, {
message: "Valid From must be on or before Valid To",
path: ["validTo"]
- });
+ })
+ .refine(
+ (d) =>
+ d.ruleType !== "Configuration" || !!d.itemId || d.itemIds?.length === 1,
+ { message: "A configured part is required", path: ["itemId"] }
+ );
export const quoteLineStatusType = [
"Not Started",
@@ -929,7 +958,12 @@ export const salesOrderLineValidator = z
),
unitOfMeasureCode: zfd.text(z.string().optional()),
unitPrice: zfd.numeric(z.number().optional()),
- exchangeRate: zfd.numeric(z.number().optional())
+ exchangeRate: zfd.numeric(z.number().optional()),
+ // Configurator values keyed by configurationParameter key, posted as JSON.
+ configuration: z.preprocess(
+ parseJsonField,
+ z.record(z.string(), z.any()).nullable().optional()
+ )
})
.refine((data) => (data.salesOrderLineType === "Part" ? data.itemId : true), {
message: "Part is required",
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 22247c155a..ea46883b17 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -78,12 +78,14 @@ import type {
import { costCategoryKeys, OPEN_SALES_ORDER_STATUSES } from "./sales.models";
import type { CategoryMarkups, QuoteLinePriceSource } from "./sales.utils";
import {
+ applyPriceRules,
+ asConfiguration,
decideRecalcPricing,
getEffectiveDefaultMarkups,
- resolvePreservedQuoteLinePriceFields
+ resolvePreservedQuoteLinePriceFields,
+ toMatchedRule
} from "./sales.utils";
import type {
- MatchedRule,
OverrideEntry,
PriceListResult,
PriceListRow,
@@ -105,78 +107,6 @@ const SALES_ORDERS_LIST_COLUMNS =
const logger = getLogger("erp", "sales");
-export function applyPriceRules(
- startingPrice: number,
- matchedRules: MatchedRule[]
-): { finalPrice: number; appendedTrace: PriceTraceStep[] } {
- const appendedTrace: PriceTraceStep[] = [];
- let finalPrice = startingPrice;
-
- const markupRules = matchedRules.filter((r) => r.ruleType === "Markup");
- const discountRules = matchedRules.filter((r) => r.ruleType === "Discount");
-
- // Discounts: highest priority wins (non-stacking); ties broken by best
- // effective amount against the current running price.
- if (discountRules.length > 0) {
- const ranked = discountRules
- .map((rule) => ({
- rule,
- effective:
- rule.amountType === "Percentage"
- ? finalPrice * rule.amount
- : rule.amount
- }))
- .sort((a, b) => {
- if (b.rule.priority !== a.rule.priority) {
- return b.rule.priority - a.rule.priority;
- }
- return b.effective - a.effective;
- });
-
- const winner = ranked[0];
- if (winner && winner.effective > 0) {
- finalPrice = finalPrice - winner.effective;
- appendedTrace.push({
- step: "Discount",
- source: `Rule: ${winner.rule.name}`,
- amount: finalPrice,
- adjustment: -winner.effective,
- ruleId: winner.rule.id
- });
- }
- }
-
- // Markups: stack in priority order (highest first), compounding on the
- // running price so ordering + basis are both deterministic.
- const sortedMarkups = [...markupRules].sort(
- (a, b) => b.priority - a.priority
- );
- for (const rule of sortedMarkups) {
- const adjustment =
- rule.amountType === "Percentage" ? finalPrice * rule.amount : rule.amount;
- finalPrice = finalPrice + adjustment;
- appendedTrace.push({
- step: "Markup",
- source: `Rule: ${rule.name}`,
- amount: finalPrice,
- adjustment,
- ruleId: rule.id
- });
- }
-
- if (finalPrice < 0) {
- appendedTrace.push({
- step: "Floor",
- source: "Clamped to 0 (rules drove price negative)",
- amount: 0,
- adjustment: -finalPrice
- });
- finalPrice = 0;
- }
-
- return { finalPrice, appendedTrace };
-}
-
export async function closeSalesOrder(
client: SupabaseClient<Database>,
salesOrderId: string,
@@ -313,24 +243,26 @@ export async function createPricingRule(
userId: string,
data: z.infer<typeof pricingRuleValidator>
) {
+ const rule = normalizePricingRule(data);
return client
.from("pricingRule")
.insert([
{
- name: data.name,
- ruleType: data.ruleType,
- amountType: data.amountType,
- amount: data.amount,
- minQuantity: data.minQuantity ?? null,
- maxQuantity: data.maxQuantity ?? null,
- customerIds: data.customerIds ?? [],
- customerTypeIds: data.customerTypeIds ?? [],
- itemIds: data.itemIds ?? [],
- itemPostingGroupId: data.itemPostingGroupId ?? null,
- validFrom: data.validFrom || null,
- validTo: data.validTo || null,
- priority: data.priority ?? 0,
- active: data.active ?? true,
+ name: rule.name,
+ ruleType: rule.ruleType,
+ amountType: rule.amountType,
+ amount: rule.amount,
+ minQuantity: rule.minQuantity ?? null,
+ maxQuantity: rule.maxQuantity ?? null,
+ customerIds: rule.customerIds ?? [],
+ customerTypeIds: rule.customerTypeIds ?? [],
+ itemIds: rule.itemIds ?? [],
+ itemPostingGroupId: rule.itemPostingGroupId ?? null,
+ validFrom: rule.validFrom || null,
+ validTo: rule.validTo || null,
+ priority: rule.priority ?? 0,
+ active: rule.active ?? true,
+ configurationPrices: rule.configurationPrices ?? null,
companyId,
createdBy: userId
}
@@ -339,6 +271,41 @@ export async function createPricingRule(
.single();
}
+// A Configuration rule is one configurable item's parameter prices and
+// nothing else: its item comes from `itemId`, and it has no item group and
+// no discount/markup amount. Any other rule type carries no configuration
+// prices. A partial update that leaves `ruleType` alone is passed through.
+function normalizePricingRule<
+ T extends Partial<z.infer<typeof pricingRuleValidator>>
+>(
+ data: T
+): Omit<T, "itemId" | "configurationPrices"> & {
+ configurationPrices?: Json | null;
+} {
+ const { itemId, configurationPrices, ...rule } = data;
+ if (rule.ruleType === undefined) {
+ return configurationPrices === undefined
+ ? rule
+ : { ...rule, configurationPrices: configurationPrices as Json };
+ }
+ if (rule.ruleType !== "Configuration") {
+ return { ...rule, configurationPrices: null };
+ }
+ const itemIds = itemId ? [itemId] : (rule.itemIds ?? []);
+ const prices = (configurationPrices ?? []).filter(
+ (price) => price.amount !== 0
+ );
+ return {
+ ...rule,
+ itemIds,
+ itemPostingGroupId: undefined,
+ amountType: "Fixed" as const,
+ amount: 0,
+ configurationPrices:
+ itemIds.length === 1 && prices.length > 0 ? (prices as Json) : null
+ };
+}
+
export async function deleteCustomer(
client: SupabaseClient<Database>,
customerId: string
@@ -594,6 +561,7 @@ export async function duplicatePricingRule(
validFrom: original.validFrom,
validTo: original.validTo,
priority: original.priority,
+ configurationPrices: original.configurationPrices,
active: false,
companyId,
createdBy: userId
@@ -2296,8 +2264,10 @@ export async function resolvePrice(
}
}
+ // An override that skips the rules still takes the line's configuration
+ // prices — they price the chosen options, not the part.
let finalPrice = startingPrice;
- if (!skipRules) {
+ if (!skipRules || input.configuration) {
let rulesQuery = client
.from("pricingRule")
.select("*")
@@ -2309,7 +2279,7 @@ export async function resolvePrice(
const { data: allRules } = await rulesQuery;
- const matchedRules: MatchedRule[] = (allRules ?? []).filter((rule) => {
+ const matchedRules = (allRules ?? []).filter((rule) => {
if (rule.minQuantity !== null && input.quantity < rule.minQuantity)
return false;
if (rule.maxQuantity !== null && input.quantity > rule.maxQuantity)
@@ -2340,9 +2310,13 @@ export async function resolvePrice(
return false;
}
return true;
- }) as MatchedRule[];
+ });
- const ruleResult = applyPriceRules(startingPrice, matchedRules);
+ const ruleResult = applyPriceRules(
+ startingPrice,
+ matchedRules.map(toMatchedRule),
+ { configuration: input.configuration, configurationOnly: skipRules }
+ );
finalPrice = ruleResult.finalPrice;
trace.push(...ruleResult.appendedTrace);
}
@@ -2624,7 +2598,7 @@ export async function resolvePriceList(
let hasRuleAdjustment = false;
if (!skipRules) {
- const matchedRules: MatchedRule[] = (allRules ?? []).filter((rule) => {
+ const matchedRules = (allRules ?? []).filter((rule) => {
if (rule.minQuantity !== null && previewQuantity < rule.minQuantity)
return false;
if (rule.maxQuantity !== null && previewQuantity > rule.maxQuantity)
@@ -2662,7 +2636,10 @@ export async function resolvePriceList(
return true;
});
- const ruleResult = applyPriceRules(startingPrice, matchedRules);
+ const ruleResult = applyPriceRules(
+ startingPrice,
+ matchedRules.map(toMatchedRule)
+ );
finalPrice = ruleResult.finalPrice;
trace.push(...ruleResult.appendedTrace);
hasRuleAdjustment = ruleResult.appendedTrace.length > 0;
@@ -3239,7 +3216,7 @@ export async function updatePricingRule(
.from("pricingRule")
.update(
sanitize({
- ...data,
+ ...normalizePricingRule(data),
updatedBy: userId,
updatedAt: new Date().toISOString()
})
@@ -4545,7 +4522,7 @@ export async function buildMakeToOrderPriceRows(
.single(),
client
.from("quoteLine")
- .select("itemId, unitPricePrecision")
+ .select("itemId, unitPricePrecision, configuration")
.eq("id", quoteLineId)
.single()
]);
@@ -4615,7 +4592,8 @@ export async function buildMakeToOrderPriceRows(
itemId,
quantity: qty,
customerId,
- existingBasePrice: rollupPrice
+ existingBasePrice: rollupPrice,
+ configuration: asConfiguration(lineResult.data.configuration)
})
).finalPrice
: rollupPrice;
@@ -4685,7 +4663,7 @@ export async function buildPullFromInventoryPriceRows(
.single(),
client
.from("quoteLine")
- .select("itemId, unitPricePrecision")
+ .select("itemId, unitPricePrecision, configuration")
.eq("id", quoteLineId)
.single()
]);
@@ -4713,7 +4691,8 @@ export async function buildPullFromInventoryPriceRows(
const resolved = await resolvePrice(client, companyId, {
itemId,
quantity: qty,
- customerId
+ customerId,
+ configuration: asConfiguration(lineResult.data.configuration)
});
priceRows.push({
@@ -4781,7 +4760,7 @@ export async function buildPurchaseToOrderPriceRows(
.single(),
client
.from("quoteLine")
- .select("itemId, unitPricePrecision")
+ .select("itemId, unitPricePrecision, configuration")
.eq("id", quoteLineId)
.single()
]);
@@ -4812,7 +4791,8 @@ export async function buildPurchaseToOrderPriceRows(
itemId,
quantity: qty,
customerId,
- existingBasePrice: supplierPrice
+ existingBasePrice: supplierPrice,
+ configuration: asConfiguration(lineResult.data.configuration)
});
priceRows.push({
@@ -4873,7 +4853,7 @@ export async function recalculateQuoteLinePrices(
const [lineResult, quoteResult] = await Promise.all([
client
.from("quoteLine")
- .select("itemId, unitPricePrecision")
+ .select("itemId, unitPricePrecision, configuration")
.eq("id", quoteLineId)
.eq("quoteId", quoteId)
.eq("companyId", companyId)
@@ -4985,7 +4965,8 @@ export async function recalculateQuoteLinePrices(
itemId,
quantity: qty,
customerId,
- existingBasePrice: rollupPrice
+ existingBasePrice: rollupPrice,
+ configuration: asConfiguration(lineResult.data.configuration)
})
).finalPrice
: rollupPrice;
diff --git a/apps/erp/app/modules/sales/sales.utils.test.ts b/apps/erp/app/modules/sales/sales.utils.test.ts
index 591677be3b..355d1eafe2 100644
--- a/apps/erp/app/modules/sales/sales.utils.test.ts
+++ b/apps/erp/app/modules/sales/sales.utils.test.ts
@@ -1,10 +1,15 @@
import { describe, expect, it } from "vitest";
import {
+ applyPriceRules,
+ configurationSurcharge,
decideRecalcPricing,
getEffectiveDefaultMarkups,
reconcileQuantityBreaks,
- resolvePreservedQuoteLinePriceFields
+ resolveJobConfiguration,
+ resolvePreservedQuoteLinePriceFields,
+ toMatchedRule
} from "./sales.utils";
+import type { MatchedRule } from "./types";
describe("resolvePreservedQuoteLinePriceFields", () => {
const stored = {
@@ -178,3 +183,239 @@ describe("decideRecalcPricing", () => {
).toEqual({ mode: "reprice", markups: { laborCost: 20 } });
});
});
+
+describe("configurationSurcharge", () => {
+ it("prices a list option only when it is the chosen value", () => {
+ const price = { key: "color", value: "Red", amount: 10 };
+ expect(configurationSurcharge(price, { color: "Red" })).toBe(10);
+ expect(configurationSurcharge(price, { color: "Blue" })).toBe(0);
+ });
+
+ it("prices a boolean when it is true", () => {
+ const price = { key: "anodized", value: "true", amount: 4 };
+ expect(configurationSurcharge(price, { anodized: true })).toBe(4);
+ expect(configurationSurcharge(price, { anodized: false })).toBe(0);
+ });
+
+ it("prices a numeric parameter per unit of its value", () => {
+ const price = { key: "length", value: null, amount: 0.5 };
+ expect(configurationSurcharge(price, { length: 120 })).toBe(60);
+ expect(configurationSurcharge(price, { length: "12" })).toBe(6);
+ });
+
+ it("adds nothing for a missing or non-numeric value", () => {
+ const price = { key: "length", value: null, amount: 0.5 };
+ expect(configurationSurcharge(price, {})).toBe(0);
+ expect(configurationSurcharge(price, { length: "" })).toBe(0);
+ expect(configurationSurcharge(price, { length: "abc" })).toBe(0);
+ });
+
+ it("keeps a negative amount as a credit", () => {
+ const price = { key: "color", value: "Raw", amount: -3 };
+ expect(configurationSurcharge(price, { color: "Raw" })).toBe(-3);
+ });
+});
+
+describe("applyPriceRules with configuration prices", () => {
+ const rule = (overrides: Partial<MatchedRule>): MatchedRule => ({
+ id: "pr1",
+ name: "Rule",
+ ruleType: "Markup",
+ amountType: "Fixed",
+ amount: 0,
+ priority: 0,
+ configurationPrices: [],
+ ...overrides
+ });
+
+ it("adds surcharges to the starting price before the discount", () => {
+ const { finalPrice, appendedTrace } = applyPriceRules(
+ 100,
+ [
+ rule({
+ id: "options",
+ ruleType: "Configuration",
+ configurationPrices: [
+ { key: "color", value: "Red", amount: 20 },
+ { key: "length", value: null, amount: 1 }
+ ]
+ }),
+ rule({
+ id: "discount",
+ ruleType: "Discount",
+ amountType: "Percentage",
+ amount: 0.1
+ })
+ ],
+ { configuration: { color: "Red", length: 30 } }
+ );
+ // (100 + 20 + 30) × 0.9
+ expect(finalPrice).toBeCloseTo(135);
+ expect(appendedTrace.map((step) => step.step)).toEqual([
+ "Configuration",
+ "Configuration",
+ "Discount"
+ ]);
+ });
+
+ it("names a configuration step by its parameter label", () => {
+ const { appendedTrace } = applyPriceRules(
+ 100,
+ [
+ rule({
+ name: "Options",
+ ruleType: "Configuration",
+ configurationPrices: [
+ { key: "a3", value: "Green", amount: 400, label: "Color" }
+ ]
+ })
+ ],
+ { configuration: { a3: "Green" } }
+ );
+ expect(appendedTrace[0]).toMatchObject({
+ step: "Configuration",
+ label: "Color",
+ source: "Rule: Options (Color = Green)"
+ });
+ });
+
+ it("only takes configuration prices from Configuration rules", () => {
+ const { finalPrice } = applyPriceRules(
+ 100,
+ [
+ rule({
+ ruleType: "Markup",
+ configurationPrices: [{ key: "color", value: "Red", amount: 20 }]
+ })
+ ],
+ { configuration: { color: "Red" } }
+ );
+ expect(finalPrice).toBe(100);
+ });
+
+ it("ignores configuration prices without a configuration", () => {
+ const { finalPrice } = applyPriceRules(100, [
+ rule({
+ ruleType: "Configuration",
+ configurationPrices: [{ key: "color", value: "Red", amount: 20 }]
+ })
+ ]);
+ expect(finalPrice).toBe(100);
+ });
+
+ it("clamps a price driven negative by credits to zero", () => {
+ const { finalPrice } = applyPriceRules(
+ 10,
+ [
+ rule({
+ ruleType: "Configuration",
+ configurationPrices: [{ key: "color", value: "Raw", amount: -25 }]
+ })
+ ],
+ { configuration: { color: "Raw" } }
+ );
+ expect(finalPrice).toBe(0);
+ });
+
+ it("keeps configuration prices under an override that skips rules", () => {
+ const { finalPrice, appendedTrace } = applyPriceRules(
+ 100,
+ [
+ rule({
+ ruleType: "Configuration",
+ configurationPrices: [{ key: "color", value: "Red", amount: 20 }]
+ }),
+ rule({ ruleType: "Discount", amountType: "Percentage", amount: 0.5 }),
+ rule({ ruleType: "Markup", amountType: "Fixed", amount: 7 })
+ ],
+ { configuration: { color: "Red" }, configurationOnly: true }
+ );
+ expect(finalPrice).toBe(120);
+ expect(appendedTrace.map((step) => step.step)).toEqual(["Configuration"]);
+ });
+});
+
+describe("toMatchedRule", () => {
+ const row = {
+ id: "pr1",
+ name: "Options",
+ ruleType: "Configuration" as const,
+ amountType: "Fixed" as const,
+ amount: 0,
+ priority: 0
+ };
+
+ it("keeps the well-formed configuration prices of a Configuration rule", () => {
+ expect(
+ toMatchedRule({
+ ...row,
+ configurationPrices: [
+ { key: "color", value: "Red", amount: 10 },
+ { key: "color", value: "Blue" },
+ { key: "", value: null, amount: 1 },
+ "junk"
+ ]
+ }).configurationPrices
+ ).toEqual([{ key: "color", value: "Red", amount: 10 }]);
+ });
+
+ it("reads no configuration prices from any other rule type", () => {
+ expect(
+ toMatchedRule({
+ ...row,
+ ruleType: "Markup",
+ configurationPrices: [{ key: "color", value: "Red", amount: 10 }]
+ }).configurationPrices
+ ).toEqual([]);
+ });
+});
+
+describe("resolveJobConfiguration", () => {
+ it("falls back to the quote line's configuration", () => {
+ expect(resolveJobConfiguration(null, { color: "Red" })).toEqual({
+ configuration: { color: "Red" },
+ reconfigured: false
+ });
+ });
+
+ it("uses the order line's configuration when it matches the quote", () => {
+ expect(
+ resolveJobConfiguration(
+ { length: 10, color: "Red" },
+ { color: "Red", length: 10 }
+ )
+ ).toEqual({
+ configuration: { length: 10, color: "Red" },
+ reconfigured: false
+ });
+ });
+
+ it("flags an order line configured differently from its quote", () => {
+ expect(
+ resolveJobConfiguration({ color: "Blue" }, { color: "Red" })
+ ).toEqual({ configuration: { color: "Blue" }, reconfigured: true });
+ });
+
+ it("flags an order line configured where the quote was not", () => {
+ expect(resolveJobConfiguration({ color: "Blue" }, null)).toEqual({
+ configuration: { color: "Blue" },
+ reconfigured: true
+ });
+ });
+
+ it("treats an unset parameter the same whether absent, null or blank", () => {
+ expect(
+ resolveJobConfiguration(
+ { color: "Red", finish: "", coating: null },
+ { color: "Red" }
+ ).reconfigured
+ ).toBe(false);
+ });
+
+ it("treats an empty configuration as none", () => {
+ expect(resolveJobConfiguration({}, {})).toEqual({
+ configuration: null,
+ reconfigured: false
+ });
+ });
+});
diff --git a/apps/erp/app/modules/sales/sales.utils.ts b/apps/erp/app/modules/sales/sales.utils.ts
index 01e93637ac..f4d2c15c11 100644
--- a/apps/erp/app/modules/sales/sales.utils.ts
+++ b/apps/erp/app/modules/sales/sales.utils.ts
@@ -1,3 +1,10 @@
+import { z } from "zod";
+import type {
+ MatchedRule,
+ PriceTraceStep,
+ PricingRuleConfigurationPrice
+} from "./types";
+
export type CategoryMarkups = Record<string, number>;
export type QuoteLinePriceSource = "system" | "manual";
@@ -115,3 +122,224 @@ export function decideRecalcPricing(
}
return { mode: "reprice", markups: effectiveDefaults };
}
+
+// The surcharge one configuration price adds for a line's configuration: the
+// amount per unit of a numeric value (`value` null), else the amount when the
+// chosen value equals `value` (a list option, or "true" for a boolean).
+export function configurationSurcharge(
+ price: PricingRuleConfigurationPrice,
+ configuration: Record<string, unknown>
+): number {
+ const chosen = configuration[price.key];
+ if (chosen === undefined || chosen === null || chosen === "") return 0;
+ if (price.value === null) {
+ const units = typeof chosen === "number" ? chosen : Number(chosen);
+ return Number.isFinite(units) ? price.amount * units : 0;
+ }
+ return String(chosen) === price.value ? price.amount : 0;
+}
+
+// A signed per-unit surcharge for one configuration parameter value. `value`
+// is the list option (or "true" for a boolean); null prices a numeric
+// parameter per unit of its value. `label` is the parameter's label when the
+// rule was saved, so the price trace can name it without a lookup. Defined
+// here rather than in sales.models so the pricing engine (and its tests) stay
+// out of the models import graph; pricingRuleValidator reuses it.
+export const pricingRuleConfigurationPriceValidator = z.object({
+ key: z.string().min(1),
+ value: z.string().nullable(),
+ amount: z.number(),
+ label: z.string().optional()
+});
+
+// The stored JSONB, keeping only well-formed entries — one bad entry must not
+// discard a rule's other prices.
+function parseConfigurationPrices(
+ value: unknown
+): PricingRuleConfigurationPrice[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((entry) => {
+ const parsed = pricingRuleConfigurationPriceValidator.safeParse(entry);
+ return parsed.success && Number.isFinite(parsed.data.amount)
+ ? [parsed.data]
+ : [];
+ });
+}
+
+type PricingRuleRow = Omit<MatchedRule, "configurationPrices"> & {
+ configurationPrices: unknown;
+};
+
+// A `pricingRule` row as the engine reads it. Only a Configuration rule
+// carries configuration prices.
+export function toMatchedRule(row: PricingRuleRow): MatchedRule {
+ return {
+ id: row.id,
+ name: row.name,
+ ruleType: row.ruleType,
+ amountType: row.amountType,
+ amount: row.amount,
+ priority: row.priority,
+ configurationPrices:
+ row.ruleType === "Configuration"
+ ? parseConfigurationPrices(row.configurationPrices)
+ : []
+ };
+}
+
+type ApplyPriceRulesOptions = {
+ // The line's configurator values, keyed by configurationParameter key.
+ configuration?: Record<string, unknown> | null;
+ // A price override with `applyRulesOnTop = false` pins the part's price:
+ // discounts and markups are skipped, but the configuration prices still
+ // apply — they price the chosen options, not the part.
+ configurationOnly?: boolean;
+};
+
+export function applyPriceRules(
+ startingPrice: number,
+ matchedRules: MatchedRule[],
+ { configuration, configurationOnly = false }: ApplyPriceRulesOptions = {}
+): { finalPrice: number; appendedTrace: PriceTraceStep[] } {
+ const appendedTrace: PriceTraceStep[] = [];
+ let finalPrice = startingPrice;
+
+ // Configuration surcharges: signed amounts added to the starting price
+ // before any discount or markup, stacking across every matched
+ // Configuration rule.
+ if (configuration) {
+ const byPriority = matchedRules
+ .filter((rule) => rule.ruleType === "Configuration")
+ .sort((a, b) => b.priority - a.priority);
+ for (const rule of byPriority) {
+ for (const price of rule.configurationPrices) {
+ const adjustment = configurationSurcharge(price, configuration);
+ if (adjustment === 0) continue;
+ finalPrice = finalPrice + adjustment;
+ const label = price.label ?? price.key;
+ appendedTrace.push({
+ step: "Configuration",
+ label,
+ source: `Rule: ${rule.name} (${label} = ${String(
+ configuration[price.key]
+ )})`,
+ amount: finalPrice,
+ adjustment,
+ ruleId: rule.id
+ });
+ }
+ }
+ }
+
+ const adjustmentRules = configurationOnly ? [] : matchedRules;
+ const markupRules = adjustmentRules.filter((r) => r.ruleType === "Markup");
+ const discountRules = adjustmentRules.filter(
+ (r) => r.ruleType === "Discount"
+ );
+
+ // Discounts: highest priority wins (non-stacking); ties broken by best
+ // effective amount against the current running price.
+ if (discountRules.length > 0) {
+ const ranked = discountRules
+ .map((rule) => ({
+ rule,
+ effective:
+ rule.amountType === "Percentage"
+ ? finalPrice * rule.amount
+ : rule.amount
+ }))
+ .sort((a, b) => {
+ if (b.rule.priority !== a.rule.priority) {
+ return b.rule.priority - a.rule.priority;
+ }
+ return b.effective - a.effective;
+ });
+
+ const winner = ranked[0];
+ if (winner && winner.effective > 0) {
+ finalPrice = finalPrice - winner.effective;
+ appendedTrace.push({
+ step: "Discount",
+ source: `Rule: ${winner.rule.name}`,
+ amount: finalPrice,
+ adjustment: -winner.effective,
+ ruleId: winner.rule.id
+ });
+ }
+ }
+
+ // Markups: stack in priority order (highest first), compounding on the
+ // running price so ordering + basis are both deterministic.
+ const sortedMarkups = [...markupRules].sort(
+ (a, b) => b.priority - a.priority
+ );
+ for (const rule of sortedMarkups) {
+ const adjustment =
+ rule.amountType === "Percentage" ? finalPrice * rule.amount : rule.amount;
+ finalPrice = finalPrice + adjustment;
+ appendedTrace.push({
+ step: "Markup",
+ source: `Rule: ${rule.name}`,
+ amount: finalPrice,
+ adjustment,
+ ruleId: rule.id
+ });
+ }
+
+ if (finalPrice < 0) {
+ appendedTrace.push({
+ step: "Floor",
+ source: "Clamped to 0 (rules drove price negative)",
+ amount: 0,
+ adjustment: -finalPrice
+ });
+ finalPrice = 0;
+ }
+
+ return { finalPrice, appendedTrace };
+}
+
+type Configuration = Record<string, unknown>;
+
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== "object") {
+ return JSON.stringify(value) ?? "null";
+ }
+ if (Array.isArray(value)) {
+ return `[${value.map(stableStringify).join(",")}]`;
+ }
+ // An unset parameter reads the same whether it is absent, null or blank.
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, v]) => v !== undefined && v !== null && v !== "")
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return `{${entries
+ .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)
+ .join(",")}}`;
+}
+
+/**
+ * The configuration a job made for a sales order line is built with: the
+ * line's own, falling back to its quote line's. `reconfigured` is true when
+ * the order line was configured differently from the quote — the quote's
+ * method was built for another configuration, so the job must be built from
+ * the item with the order line's values instead of copied from the quote.
+ */
+export function resolveJobConfiguration(
+ salesOrderLineConfiguration: unknown,
+ quoteLineConfiguration: unknown
+): { configuration: Configuration | null; reconfigured: boolean } {
+ const orderLine = asConfiguration(salesOrderLineConfiguration);
+ const quoteLine = asConfiguration(quoteLineConfiguration);
+ if (!orderLine) return { configuration: quoteLine, reconfigured: false };
+ return {
+ configuration: orderLine,
+ reconfigured: stableStringify(orderLine) !== stableStringify(quoteLine)
+ };
+}
+
+// A stored line configuration (JSONB), or null when it is empty or not an
+// object.
+export function asConfiguration(value: unknown): Configuration | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ return Object.keys(value).length > 0 ? (value as Configuration) : null;
+}
diff --git a/apps/erp/app/modules/sales/types.ts b/apps/erp/app/modules/sales/types.ts
index 3362eaf860..fe1e357124 100644
--- a/apps/erp/app/modules/sales/types.ts
+++ b/apps/erp/app/modules/sales/types.ts
@@ -1,4 +1,5 @@
import type { Database } from "@carbon/database";
+import type { z } from "zod";
import type { jobStatus } from "../production/production.models";
import type { QuantityEffect } from "../shared";
import type {
@@ -31,17 +32,25 @@ import type {
getSalesRFQs,
priceSourceTypes
} from "./sales.service";
+import type { pricingRuleConfigurationPriceValidator } from "./sales.utils";
// Pricing types
export type MatchedRule = {
id: string;
name: string;
- ruleType: string;
- amountType: string;
+ ruleType: Database["public"]["Enums"]["pricingRuleType"];
+ amountType: Database["public"]["Enums"]["pricingRuleAmountType"];
amount: number;
priority: number;
+ // Parsed from the stored JSONB by `toMatchedRule`; empty for any rule type
+ // but Configuration.
+ configurationPrices: PricingRuleConfigurationPrice[];
};
+export type PricingRuleConfigurationPrice = z.infer<
+ typeof pricingRuleConfigurationPriceValidator
+>;
+
export type PriceOverrideBreak = {
id?: string;
quantity: number;
@@ -90,6 +99,7 @@ export type PriceResolutionInput = {
quantity: number;
date?: string;
existingBasePrice?: number;
+ configuration?: Record<string, unknown> | null;
};
export type PriceResolutionResult = {
@@ -106,6 +116,9 @@ export type PriceTraceStep = {
amount: number;
adjustment?: number;
ruleId?: string;
+ // A readable name for the step's badge — the parameter label on a
+ // Configuration step.
+ label?: string;
};
export type PricingRule = NonNullable<
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
index 349341a40d..cfc6a8766f 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
@@ -33,6 +33,8 @@ const STEP_BADGE: Record<
"All Override": { label: "All Override", variant: "gray" },
Discount: { label: "Discount", variant: "red" },
Markup: { label: "Markup", variant: "green" },
+ // Labelled with the parameter's name (`step.label`) when it has one.
+ Configuration: { label: "Configuration", variant: "purple" },
"Final Price": null
};
@@ -172,7 +174,7 @@ function StepTypeBadge({ step }: { step: PriceTraceStep }) {
const mapping = STEP_BADGE[step.step];
if (mapping === null) return null;
if (!mapping) return <Badge variant="gray">{step.step}</Badge>;
- return <Badge variant={mapping.variant}>{mapping.label}</Badge>;
+ return <Badge variant={mapping.variant}>{step.label ?? mapping.label}</Badge>;
}
export function DeltaPill({
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleConfigurationPrices.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleConfigurationPrices.tsx
new file mode 100644
index 0000000000..ad25594af2
--- /dev/null
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleConfigurationPrices.tsx
@@ -0,0 +1,217 @@
+import { useCarbon } from "@carbon/auth";
+import { NumberField, NumberInput, Subheading, toast } from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useMemo, useState } from "react";
+import { Hidden } from "~/components/Form";
+import { useCurrencyDecimals, useUser } from "~/hooks";
+import type { ConfigurationParameter } from "~/modules/items/types";
+import type { PricingRuleConfigurationPrice } from "../../types";
+
+// Parameter types a price can be attached to: a list option, a boolean when
+// true, or a numeric value per unit.
+const PRICEABLE_TYPES = ["list", "boolean", "numeric"] as const;
+
+type PriceRow = { value: string | null; label: string };
+
+function priceRows(
+ parameter: ConfigurationParameter,
+ labels: { yes: string; perUnit: string }
+) {
+ switch (parameter.dataType) {
+ case "list":
+ return (parameter.listOptions ?? []).map<PriceRow>((option) => ({
+ value: option,
+ label: option
+ }));
+ case "boolean":
+ return [{ value: "true", label: labels.yes }];
+ case "numeric":
+ return [{ value: null, label: labels.perUnit }];
+ default:
+ return [];
+ }
+}
+
+const priceKey = (key: string, value: string | null) =>
+ `${key}\u0000${value ?? ""}`;
+
+const toAmounts = (prices: PricingRuleConfigurationPrice[]) =>
+ new Map(
+ prices.map((price) => [priceKey(price.key, price.value), price.amount])
+ );
+
+type PricingRuleConfigurationPricesProps = {
+ itemId: string | null;
+ // The item the stored prices belong to (the rule's item when it was loaded).
+ initialItemId: string | null;
+ initialPrices: PricingRuleConfigurationPrice[];
+};
+
+/**
+ * Per-parameter surcharges of a Configuration rule, for its one configurable
+ * item. Must be rendered inside the pricing rule's ValidatedForm.
+ */
+const PricingRuleConfigurationPrices = ({
+ itemId,
+ initialItemId,
+ initialPrices
+}: PricingRuleConfigurationPricesProps) => {
+ const { t } = useLingui();
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
+
+ const [parameters, setParameters] = useState<ConfigurationParameter[]>([]);
+ // The item the parameters were loaded for. Until they load, the stored
+ // prices of the rule's own item are posted untouched, so a quick save (or a
+ // failed load) cannot drop them.
+ const [loadedItemId, setLoadedItemId] = useState<string | null>(null);
+ const [amounts, setAmounts] = useState(() => toAmounts(initialPrices));
+
+ // Prices are keyed by one item's parameters: another item starts from an
+ // empty price list, and switching back restores the stored prices.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset only when the item changes
+ useEffect(() => {
+ setAmounts(itemId === initialItemId ? toAmounts(initialPrices) : new Map());
+ }, [itemId]);
+
+ useEffect(() => {
+ if (!itemId || !carbon || !company?.id) {
+ setParameters([]);
+ return;
+ }
+
+ let cancelled = false;
+ (async () => {
+ const result = await carbon
+ .from("configurationParameter")
+ .select("*")
+ .eq("itemId", itemId)
+ .eq("companyId", company.id)
+ .in("dataType", [...PRICEABLE_TYPES])
+ .order("sortOrder", { ascending: true });
+
+ if (cancelled) return;
+ if (result.error) {
+ toast.error(t`Failed to load configuration parameters`);
+ setParameters([]);
+ return;
+ }
+ setParameters(result.data ?? []);
+ setLoadedItemId(itemId);
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [itemId, carbon, company?.id, t]);
+
+ const yes = t`Yes`;
+ const perUnit = t`Per unit`;
+ const rowsByParameter = useMemo(
+ () =>
+ parameters.map((parameter) => ({
+ parameter,
+ rows: priceRows(parameter, { yes, perUnit })
+ })),
+ [parameters, yes, perUnit]
+ );
+
+ const isLoading = itemId !== null && loadedItemId !== itemId;
+
+ const prices = useMemo(() => {
+ if (isLoading) return itemId === initialItemId ? initialPrices : [];
+ const result: PricingRuleConfigurationPrice[] = [];
+ for (const { parameter, rows } of rowsByParameter) {
+ for (const row of rows) {
+ const amount = amounts.get(priceKey(parameter.key, row.value));
+ if (amount) {
+ result.push({
+ key: parameter.key,
+ value: row.value,
+ amount,
+ label: parameter.label
+ });
+ }
+ }
+ }
+ return result;
+ }, [
+ isLoading,
+ itemId,
+ initialItemId,
+ initialPrices,
+ rowsByParameter,
+ amounts
+ ]);
+
+ const setAmount = (key: string, value: string | null, amount: number) => {
+ setAmounts((current) => {
+ const next = new Map(current);
+ next.set(priceKey(key, value), Number.isFinite(amount) ? amount : 0);
+ return next;
+ });
+ };
+
+ return (
+ <>
+ <Hidden name="configurationPrices" value={JSON.stringify(prices)} />
+ {!isLoading && rowsByParameter.length > 0 && (
+ <div className="flex flex-col gap-3 w-full">
+ <div className="flex flex-col gap-1">
+ <Subheading as="h3">
+ <Trans>Configuration Prices</Trans>
+ </Subheading>
+ <p className="text-xs text-muted-foreground">
+ <Trans>
+ Added to the unit price for the chosen values, before discounts
+ and markups. Use a negative amount for a credit.
+ </Trans>
+ </p>
+ </div>
+ {rowsByParameter.map(({ parameter, rows }) => (
+ <div
+ key={parameter.id}
+ className="flex flex-col gap-2 w-full rounded-md border border-border p-3"
+ >
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="text-sm font-medium">{parameter.label}</span>
+ <span className="text-xs text-muted-foreground font-mono">
+ {parameter.key}
+ </span>
+ </div>
+ {rows.map((row) => (
+ <div
+ key={row.value ?? "per-unit"}
+ className="grid grid-cols-2 items-center gap-3"
+ >
+ <span className="text-sm text-muted-foreground truncate">
+ {row.label}
+ </span>
+ <NumberField
+ aria-label={`${parameter.label} ${row.label}`}
+ value={amounts.get(priceKey(parameter.key, row.value)) ?? 0}
+ onChange={(amount) =>
+ setAmount(parameter.key, row.value, amount)
+ }
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate(
+ baseCurrency,
+ currencyDecimals
+ )}
+ >
+ <NumberInput size="sm" />
+ </NumberField>
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ );
+};
+
+export default PricingRuleConfigurationPrices;
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
index 9b85cb27de..bbca353b88 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
@@ -10,6 +10,7 @@ import {
ModalDrawerHeader,
ModalDrawerProvider,
ModalDrawerTitle,
+ Subheading,
VStack
} from "@carbon/react";
import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
@@ -31,11 +32,13 @@ import {
DatePicker,
Hidden,
Input,
+ Item,
ItemPostingGroup,
Items,
Number,
Select,
- Submit
+ Submit,
+ useConfigurableItems
} from "~/components/Form";
import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import {
@@ -43,6 +46,7 @@ import {
pricingRuleTypes,
pricingRuleValidator
} from "../../sales.models";
+import PricingRuleConfigurationPrices from "./PricingRuleConfigurationPrices";
type CustomerScopeType = "all" | "customer" | "customerType";
type ItemScopeType = "all" | "item" | "group";
@@ -60,6 +64,14 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
company?.baseCurrencyCode ?? "USD"
);
+ const [ruleType, setRuleType] = useState<(typeof pricingRuleTypes)[number]>(
+ initialValues.ruleType ?? "Discount"
+ );
+ const isConfiguration = ruleType === "Configuration";
+ const [configurationItemId, setConfigurationItemId] = useState<string | null>(
+ initialValues.itemId ?? null
+ );
+ const configurableItemIds = useConfigurableItems();
const [amountType, setAmountType] = useState<
(typeof pricingRuleAmountTypes)[number]
>(initialValues.amountType ?? "Percentage");
@@ -116,49 +128,62 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
label: rt,
value: rt
}))}
- />
- <Select
- name="amountType"
- label={t`Amount Type`}
- termId="pricing-rule-amount-type"
- options={pricingRuleAmountTypes.map((at) => ({
- label: at,
- value: at
- }))}
onChange={(v) => {
if (v)
- setAmountType(
- v.value as (typeof pricingRuleAmountTypes)[number]
- );
+ setRuleType(v.value as (typeof pricingRuleTypes)[number]);
}}
/>
-
- {amountType === "Percentage" ? (
- <Number
- name="amount"
- label={t`Amount`}
- minValue={0}
- maxValue={1}
- step={INPUT_STEP.percent}
- formatOptions={INPUT_FORMAT.percent}
- />
+ {isConfiguration ? (
+ <>
+ <Hidden name="amountType" value="Fixed" />
+ <Hidden name="amount" value="0" />
+ </>
) : (
- <Number
- name="amount"
- label={t`Amount`}
- minValue={0}
- formatOptions={INPUT_FORMAT.money(
- company?.baseCurrencyCode ?? "USD",
- currencyDecimals
+ <>
+ <Select
+ name="amountType"
+ label={t`Amount Type`}
+ termId="pricing-rule-amount-type"
+ options={pricingRuleAmountTypes.map((at) => ({
+ label: at,
+ value: at
+ }))}
+ onChange={(v) => {
+ if (v)
+ setAmountType(
+ v.value as (typeof pricingRuleAmountTypes)[number]
+ );
+ }}
+ />
+
+ {amountType === "Percentage" ? (
+ <Number
+ name="amount"
+ label={t`Amount`}
+ minValue={0}
+ maxValue={1}
+ step={INPUT_STEP.percent}
+ formatOptions={INPUT_FORMAT.percent}
+ />
+ ) : (
+ <Number
+ name="amount"
+ label={t`Amount`}
+ minValue={0}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
+ />
)}
- />
+ </>
)}
<BooleanField name="active" label={t`Active`} bordered />
- <p className="text-sm font-medium text-muted-foreground pt-2">
+ <Subheading as="h3" className="pt-2">
{t`Scope`}
- </p>
+ </Subheading>
<ChoiceCardGroup<CustomerScopeType>
label={t`Customer Scope`}
@@ -210,54 +235,81 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
/>
)}
- <ChoiceCardGroup<ItemScopeType>
- label={t`Item Scope`}
- value={itemScope}
- onChange={setItemScope}
- options={[
- {
- value: "all",
- title: t`All Items`,
- description: t`Rule applies to every item.`,
- icon: <LuLayers />
- },
- {
- value: "item",
- title: t`Specific Items`,
- description: t`Target one or more items.`,
- icon: <LuBlocks />
- },
- {
- value: "group",
- title: t`Item Group`,
- description: t`Target an item group.`,
- icon: <LuBoxes />
- }
- ]}
- />
+ {isConfiguration ? (
+ <>
+ <Item
+ name="itemId"
+ label={t`Configured Part`}
+ isOptional={false}
+ type="Part"
+ replenishmentSystem="Make"
+ whitelist={configurableItemIds}
+ onChange={(value) =>
+ setConfigurationItemId(value?.value ?? null)
+ }
+ />
+ <Hidden name="itemPostingGroupId" value="" />
+ <PricingRuleConfigurationPrices
+ itemId={configurationItemId}
+ initialItemId={initialValues.itemId ?? null}
+ initialPrices={initialValues.configurationPrices ?? []}
+ />
+ </>
+ ) : (
+ <>
+ <ChoiceCardGroup<ItemScopeType>
+ label={t`Item Scope`}
+ value={itemScope}
+ onChange={setItemScope}
+ options={[
+ {
+ value: "all",
+ title: t`All Items`,
+ description: t`Rule applies to every item.`,
+ icon: <LuLayers />
+ },
+ {
+ value: "item",
+ title: t`Specific Items`,
+ description: t`Target one or more items.`,
+ icon: <LuBlocks />
+ },
+ {
+ value: "group",
+ title: t`Item Group`,
+ description: t`Target an item group.`,
+ icon: <LuBoxes />
+ }
+ ]}
+ />
- <ClearArrayField name="itemIds" active={itemScope === "item"} />
+ <ClearArrayField
+ name="itemIds"
+ active={itemScope === "item"}
+ />
- {itemScope === "item" && (
- <Items
- name="itemIds"
- label={t`Items`}
- placeholder={t`Select items`}
- />
- )}
- {itemScope === "group" && (
- <ItemPostingGroup
- name="itemPostingGroupId"
- label={t`Item Group`}
- />
- )}
- {itemScope !== "group" && (
- <Hidden name="itemPostingGroupId" value="" />
+ {itemScope === "item" && (
+ <Items
+ name="itemIds"
+ label={t`Items`}
+ placeholder={t`Select items`}
+ />
+ )}
+ {itemScope === "group" && (
+ <ItemPostingGroup
+ name="itemPostingGroupId"
+ label={t`Item Group`}
+ />
+ )}
+ {itemScope !== "group" && (
+ <Hidden name="itemPostingGroupId" value="" />
+ )}
+ </>
)}
- <p className="text-sm font-medium text-muted-foreground pt-2">
+ <Subheading as="h3" className="pt-2">
{t`Optional`}
- </p>
+ </Subheading>
<div className="grid grid-cols-2 gap-3 w-full">
<DatePicker name="validFrom" label={t`Valid From`} />
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
index 86f8f35171..edfc9d6892 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
@@ -103,6 +103,9 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {
header: t`Type`,
cell: ({ row }) => {
const { amount, amountType, ruleType } = row.original;
+ if (ruleType === "Configuration") {
+ return <Badge variant="blue">{t`Configuration`}</Badge>;
+ }
return (
<Badge
variant={ruleType === "Discount" ? "red" : "green"}
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index e95b563de0..90a4990876 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -48,6 +48,11 @@ import {
import { useParams } from "react-router";
import type { z } from "zod";
import { ItemLifecycleBadge, MethodIcon } from "~/components";
+import type { ConfiguratorValues } from "~/components/Configurator/ConfiguratorForm";
+import {
+ ItemConfigureButton,
+ useItemConfiguration
+} from "~/components/Configurator/ItemConfigurator";
import {
CustomFormFields,
DatePicker,
@@ -163,6 +168,13 @@ const SalesOrderLineForm = ({
null
});
+ const configurator = useItemConfiguration({
+ itemId: initialValues.itemId,
+ configuration: initialValues.configuration as ConfiguratorValues | null
+ });
+ const { configuration } = configurator;
+ const requiresConfiguration = configurator.parameters !== null;
+
const isEditing = initialValues.id !== undefined;
const isFixedAsset = initialValues.salesOrderLineType === "Fixed Asset";
const [activeTab, setActiveTab] = useState<"item" | "asset">(
@@ -269,7 +281,11 @@ const SalesOrderLineForm = ({
const percentFormatter = usePercentFormatter();
const resolvePrice = useCallback(
- async (itemId: string, quantity: number) => {
+ async (
+ itemId: string,
+ quantity: number,
+ lineConfiguration: Record<string, unknown> | null
+ ) => {
const customerId = routeData?.salesOrder?.customerId;
if (!customerId) return null;
@@ -277,7 +293,12 @@ const SalesOrderLineForm = ({
const response = await fetch(path.to.api.salesResolvePrice, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ customerId, itemId, quantity })
+ body: JSON.stringify({
+ customerId,
+ itemId,
+ quantity,
+ ...(lineConfiguration ? { configuration: lineConfiguration } : {})
+ })
});
if (response.ok) {
const result = await response.json();
@@ -298,21 +319,24 @@ const SalesOrderLineForm = ({
[routeData?.salesOrder?.customerId]
);
+ const applyResolvedPrice = (
+ result: NonNullable<Awaited<ReturnType<typeof resolvePrice>>>
+ ) =>
+ setItemData((d) => ({
+ ...d,
+ unitPrice: result.finalPrice,
+ priceListId: result.priceListId,
+ priceListName: result.priceListName,
+ priceTrace: result.trace
+ }));
+
const debouncedQuantityResolve = useDebounce(async (qty: number) => {
if (!itemData.itemId) {
setIsPriceResolving(false);
return;
}
- const result = await resolvePrice(itemData.itemId, qty);
- if (result) {
- setItemData((d) => ({
- ...d,
- unitPrice: result.finalPrice,
- priceListId: result.priceListId,
- priceListName: result.priceListName,
- priceTrace: result.trace
- }));
- }
+ const result = await resolvePrice(itemData.itemId, qty, configuration);
+ if (result) applyResolvedPrice(result);
setIsPriceResolving(false);
}, 400);
@@ -322,10 +346,20 @@ const SalesOrderLineForm = ({
debouncedQuantityResolve(qty);
};
+ // A new configuration changes the configuration prices.
+ const onConfigured = async (values: ConfiguratorValues) => {
+ if (!itemData.itemId) return;
+ setIsPriceResolving(true);
+ const result = await resolvePrice(itemData.itemId, saleQuantity, values);
+ if (result) applyResolvedPrice(result);
+ setIsPriceResolving(false);
+ };
+
const onChange = async (itemId: string) => {
if (!itemId) return;
if (!carbon || !company.id) return;
setIsPriceResolving(true);
+ configurator.changeItem(itemId);
const [item, price] = await Promise.all([
carbon
.from("item")
@@ -356,7 +390,7 @@ const SalesOrderLineForm = ({
let resolvedPrice = price.data?.unitSalePrice ?? 0;
let priceListId: string | null = null;
- const result = await resolvePrice(itemId, saleQuantity);
+ const result = await resolvePrice(itemId, saleQuantity, null);
if (result) {
resolvedPrice = result.finalPrice;
priceListId = result.priceListId;
@@ -582,6 +616,10 @@ const SalesOrderLineForm = ({
}
/>
<Hidden name="unitOfMeasureCode" value={itemData.uom} />
+ <Hidden
+ name="configuration"
+ value={configuration ? JSON.stringify(configuration) : ""}
+ />
<VStack>
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<Item
@@ -1047,9 +1085,25 @@ const SalesOrderLineForm = ({
)}
</ModalCardBody>
<ModalCardFooter>
+ {activeTab === "item" && (
+ <ItemConfigureButton
+ configurator={configurator}
+ isDisabled={
+ !isEditable ||
+ (isEditing
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales"))
+ }
+ onConfigured={onConfigured}
+ />
+ )}
<Submit
isDisabled={
isPriceResolving ||
+ (!isEditing &&
+ requiresConfiguration &&
+ activeTab === "item" &&
+ !configuration) ||
!isEditable ||
(isEditing
? !permissions.can("update", "sales")
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.json
index d6197c220e..bab790beaf 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": 1558,
+ "totalTools": 1557,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},
@@ -1197,7 +1197,6 @@
{"name":"resources_upsertTrainingAssignment","classification":"WRITE","paramCount":3,"schema":"9f8996544bb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertTrainingQuestion","classification":"WRITE","paramCount":12,"schema":"f27342252292","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
{"name":"resources_upsertWorkCenter","classification":"DESTRUCTIVE","paramCount":15,"schema":"cc81867b6509","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false},
- {"name":"sales_applyPriceRules","classification":"WRITE","paramCount":2,"schema":"459afb77082a","response":"457db36e71eb","injectAuth":"companyId","permission":"sales:update","paginates":false},
{"name":"sales_buildMakeToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"89e850aef11d","injectAuth":"companyId","permission":"sales:update","paginates":false},
{"name":"sales_buildPullFromInventoryPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"89e850aef11d","injectAuth":"companyId","permission":"sales:update","paginates":false},
{"name":"sales_buildPurchaseToOrderPriceRows","classification":"WRITE","paramCount":4,"schema":"9ca94f5219fe","response":"89e850aef11d","injectAuth":"companyId","permission":"sales:update","paginates":false},
@@ -1212,7 +1211,7 @@
{"name":"sales_copyQuoteLine","classification":"WRITE","paramCount":9,"schema":"692ceb74fe3d","response":"24c3c39326f6","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
{"name":"sales_createOpportunityDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"45722937a7bb","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_createOpportunityLineDocumentUploadUrl","classification":"WRITE","paramCount":2,"schema":"27cead9c6af9","response":"4ad76afe0777","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
- {"name":"sales_createPricingRule","classification":"WRITE","paramCount":15,"schema":"306872f9cb7b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
+ {"name":"sales_createPricingRule","classification":"WRITE","paramCount":17,"schema":"8a6a210cb492","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_createReplacementSalesOrder","classification":"WRITE","paramCount":1,"schema":"f41daa12b05a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
{"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","paramCount":3,"schema":"b73e7908d9de","response":"00404e686415","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"sales:create","paginates":false},
{"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","paramCount":1,"schema":"09e48c79fb16","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:delete","paginates":false},
@@ -1242,7 +1241,7 @@
{"name":"sales_duplicatePricingRule","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},
{"name":"sales_finalizeQuote","classification":"WRITE","paramCount":1,"schema":"c726ae407913","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_getAllCustomersItemPriceOverride","classification":"READ","paramCount":3,"schema":"a6cc9782168c","response":"2dfcd06e591d","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getBaseCatalog","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"d3d1929f70c6","injectAuth":"companyId","permission":"sales:view","paginates":true},
+ {"name":"sales_getBaseCatalog","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:view","paginates":true},
{"name":"sales_getConfigurationParametersByQuoteLineId","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"c36ad21b447b","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getCreditableQuantities","classification":"READ","paramCount":1,"schema":"f41daa12b05a","response":"da2f02c5bdac","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"8642159293c2","injectAuth":"companyId","permission":"sales:view","paginates":false},
@@ -1275,8 +1274,8 @@
{"name":"sales_getOpportunity","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"cdaf9ce57087","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f7007e889f64","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"af7bb9de307a","injectAuth":"companyId","permission":"sales:view","paginates":true},
+ {"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a1e20313f8b","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"f3613d31804a","injectAuth":"companyId","permission":"sales:view","paginates":true},
{"name":"sales_getQuote","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee5f623bf074","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getQuoteAssemblies","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getQuoteAssembliesByLine","classification":"READ","paramCount":1,"schema":"e0050938a2c8","response":"9807da529af1","injectAuth":"companyId","permission":"sales:view","paginates":false},
@@ -1305,7 +1304,7 @@
{"name":"sales_getQuotes","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"dea28b562b72","injectAuth":"companyId","permission":"sales:view","paginates":true},
{"name":"sales_getQuoteShipment","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee2ac29cff92","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0ff25946068c","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","paramCount":2,"schema":"71f31780bb98","response":"0aa8762cb43e","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getRelatedPricesForQuoteLine","classification":"READ","paramCount":2,"schema":"71f31780bb98","response":"11d3b5e78712","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getReturnableLinesForCustomer","classification":"READ","paramCount":2,"schema":"e9ef772b4706","response":"8b3d2e7917fd","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getReturnReason","classification":"READ","paramCount":1,"schema":"937e7a95a060","response":"784c9ecc581f","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getReturnReasons","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1367348aaf16","injectAuth":"companyId","permission":"sales:view","paginates":true},
@@ -1318,10 +1317,10 @@
{"name":"sales_getSalesOrderInvoiceLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"1ff852ae9154","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"397cd2bf218b","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"cd5bcdc964de","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"680c6abfc2c8","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderLinesByItemIds","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"fdf53abafb04","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"3870424e8113","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"3870424e8113","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderLinesByItemIds","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"3870424e8113","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLineShipments","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"131473831fc0","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderPayment","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"e52a6a8beddf","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderRelatedItems","classification":"READ","paramCount":2,"schema":"651e9f51b36d","response":"a1a189394634","injectAuth":"companyId","permission":"sales:view","paginates":false},
@@ -1352,8 +1351,8 @@
{"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"6db20595d1b7","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_releaseSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_reopenSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},
- {"name":"sales_resolvePrice","classification":"WRITE","paramCount":1,"schema":"2f096dfc591c","response":"e21c67b9c2e5","injectAuth":"companyId","permission":"sales:update","paginates":false},
- {"name":"sales_resolvePriceList","classification":"WRITE","paramCount":6,"schema":"2ee3c5668f0c","response":"d3d1929f70c6","injectAuth":"companyId","permission":"sales:update","paginates":true},
+ {"name":"sales_resolvePrice","classification":"WRITE","paramCount":1,"schema":"e21d9e9b3005","response":"eb12029769da","injectAuth":"companyId","permission":"sales:update","paginates":false},
+ {"name":"sales_resolvePriceList","classification":"WRITE","paramCount":6,"schema":"2ee3c5668f0c","response":"7da40016b67c","injectAuth":"companyId","permission":"sales:update","paginates":true},
{"name":"sales_resolvePurchaseToOrderPrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},
{"name":"sales_resolveQuoteLinePrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update","paginates":false},
{"name":"sales_setSalesReturnOrderLineDisposition","classification":"WRITE","paramCount":2,"schema":"a8526e566c94","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"sales:update","paginates":false},
@@ -1364,7 +1363,7 @@
{"name":"sales_updateCustomerPayment","classification":"WRITE","paramCount":5,"schema":"f4b0bf1f4ec1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateCustomerShipping","classification":"WRITE","paramCount":7,"schema":"1c4be8a465fb","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateCustomerTax","classification":"WRITE","paramCount":8,"schema":"8f85c7bd9801","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
- {"name":"sales_updatePricingRule","classification":"WRITE","paramCount":2,"schema":"121160ebf01e","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
+ {"name":"sales_updatePricingRule","classification":"WRITE","paramCount":2,"schema":"62b6cf1b50c2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuote","classification":"WRITE","paramCount":17,"schema":"ad5fc3f2a158","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
{"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"fce9a5d72ad3","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},
@@ -1403,7 +1402,7 @@
{"name":"sales_upsertQuoteShipment","classification":"WRITE","paramCount":7,"schema":"b67f297e5398","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertReturnReason","classification":"WRITE","paramCount":4,"schema":"765854e5447a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesOrder","classification":"WRITE","paramCount":19,"schema":"c7fa1aa49c04","response":"5cc20a44d4fe","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
- {"name":"sales_upsertSalesOrderLine","classification":"WRITE","paramCount":23,"schema":"a5115dabd240","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
+ {"name":"sales_upsertSalesOrderLine","classification":"WRITE","paramCount":24,"schema":"df82fcdde982","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesOrderPayment","classification":"WRITE","paramCount":8,"schema":"310037cea6c3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesOrderShipment","classification":"WRITE","paramCount":17,"schema":"a1ab551afe2a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertSalesReturnOrderLine","classification":"WRITE","paramCount":12,"schema":"f4a19f25c389","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
diff --git a/apps/erp/app/routes/x+/quote+/methods+/get.tsx b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
index a263d3f9c6..35d8b385dc 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
@@ -6,6 +6,7 @@ import { data, redirect } from "react-router";
import {
copyQuoteLine,
getMethodValidator,
+ recalculateQuoteLinePrices,
upsertQuoteLineMethod,
upsertQuoteMaterialMakeMethod
} from "~/modules/sales";
@@ -59,8 +60,24 @@ export async function action({ request }: ActionFunctionArgs) {
lineMethodPayload
);
+ if (lineMethod.error) {
+ return { error: "Failed to get quote line method" };
+ }
+
+ // A new method (or configuration) changes the line's cost and its
+ // configuration surcharges, so reprice its existing quantities.
+ const recalculate = await recalculateQuoteLinePrices(
+ serviceRole,
+ companyId,
+ quoteId,
+ quoteLineId,
+ userId
+ );
+
return {
- error: lineMethod.error ? "Failed to get quote line method" : null
+ error: recalculate.error
+ ? "Failed to recalculate quote line prices"
+ : null
};
}
diff --git a/apps/erp/app/routes/x+/sales+/pricing-rules.$ruleId.tsx b/apps/erp/app/routes/x+/sales+/pricing-rules.$ruleId.tsx
index 9a5279ae98..1ed3b2ae98 100644
--- a/apps/erp/app/routes/x+/sales+/pricing-rules.$ruleId.tsx
+++ b/apps/erp/app/routes/x+/sales+/pricing-rules.$ruleId.tsx
@@ -8,6 +8,7 @@ import {
duplicatePricingRule,
getPricingRule,
pricingRuleValidator,
+ toMatchedRule,
updatePricingRule
} from "~/modules/sales";
import PricingRuleForm from "~/modules/sales/ui/Pricing/PricingRuleForm";
@@ -113,11 +114,16 @@ export default function EditPricingRuleRoute() {
customerIds: pricingRule.customerIds ?? [],
customerTypeIds: pricingRule.customerTypeIds ?? [],
itemIds: pricingRule.itemIds ?? [],
+ itemId:
+ pricingRule.ruleType === "Configuration"
+ ? (pricingRule.itemIds?.[0] ?? undefined)
+ : undefined,
itemPostingGroupId: pricingRule.itemPostingGroupId ?? undefined,
validFrom: pricingRule.validFrom ?? undefined,
validTo: pricingRule.validTo ?? undefined,
priority: pricingRule.priority ?? 0,
- active: pricingRule.active
+ active: pricingRule.active,
+ configurationPrices: toMatchedRule(pricingRule).configurationPrices
};
return (
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
index af8d00fc56..65fcd257d1 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
@@ -276,6 +276,8 @@ export default function EditSalesOrderLineRoute() {
unitPrice: line?.unitPrice ?? 0,
taxPercent: line?.taxPercent ?? 0,
shippingCost: line?.shippingCost ?? 0,
+ configuration:
+ (line?.configuration as Record<string, unknown> | null) ?? null,
assetReadableId: (line as any)?.assetReadableId ?? undefined,
assetName: (line as any)?.assetName ?? undefined,
...getCustomFields(line?.customFields)
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
index 6a6c32781c..0e350a4a2c 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
@@ -7,6 +7,7 @@ import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { insertJob, salesOrderToJobValidator } from "~/modules/production";
+import { resolveJobConfiguration } from "~/modules/sales/sales.utils";
import { requireCompanyRecord } from "~/modules/shared/shared.server";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -70,12 +71,37 @@ export async function action({ request, params }: ActionFunctionArgs) {
: null
]);
- const methodSource = d.quoteId && d.quoteLineId ? "quoteLine" : "item";
+ // The order line's configuration wins over its quote line's; a line
+ // reconfigured on the order is built from the item, not the quote's method.
+ const [salesOrderLine, quoteLine] = await Promise.all([
+ serviceRole
+ .from("salesOrderLine")
+ .select("configuration")
+ .eq("id", lineId)
+ .eq("companyId", companyId)
+ .single(),
+ d.quoteLineId
+ ? serviceRole
+ .from("quoteLine")
+ .select("configuration")
+ .eq("id", d.quoteLineId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ : Promise.resolve({ data: null })
+ ]);
+ const { configuration, reconfigured } = resolveJobConfiguration(
+ salesOrderLine.data?.configuration,
+ quoteLine.data?.configuration
+ );
+
+ const methodSource =
+ d.quoteId && d.quoteLineId && !reconfigured ? "quoteLine" : "item";
const createJob = await insertJob(
serviceRole,
{
...d,
+ configuration: configuration ?? d.configuration,
salesOrderId: orderId,
salesOrderLineId: lineId,
jobId: d.jobId || undefined,
diff --git a/docs/content/docs/reference/pricing.mdx b/docs/content/docs/reference/pricing.mdx
index fb6c2bb288..9926ed3cd6 100644
--- a/docs/content/docs/reference/pricing.mdx
+++ b/docs/content/docs/reference/pricing.mdx
@@ -7,10 +7,10 @@ When you add an item to a <Term>quote</Term> line or a <Term id="sales-order">sa
## Pricing rules
-A **pricing rule** is a company-scoped rule that adjusts a price up or down. Each rule is a `Discount` or a `Markup`, expressed as either a `Percentage` or a `Fixed` amount, and it only fires when the line matches the rule's conditions.
+A **pricing rule** is a company-scoped rule that adjusts a price up or down. Each rule is a `Discount` or a `Markup`, expressed as either a `Percentage` or a `Fixed` amount, or a `Configuration` rule that prices a configured part's options (below). A rule only fires when the line matches its conditions.
<FieldTable>
- <Field name="Rule type" type="enum" required>`Discount` (lowers the price) or `Markup` (raises it).</Field>
+ <Field name="Rule type" type="enum" required>`Discount` (lowers the price), `Markup` (raises it), or `Configuration` (prices a configured part's options).</Field>
<Field name="Amount type" type="enum" required>`Percentage` or `Fixed`. A percentage is stored as a fraction from 0 to 1 (10% is `0.10`), so the form caps it at 100%.</Field>
<Field name="Amount" type="number" required>The discount/markup value. For a percentage, the fraction of the running price; for fixed, an absolute amount.</Field>
<Field name="Priority" type="number">Higher priority wins among discounts and orders the markup stack. Defaults to `0`.</Field>
@@ -27,6 +27,18 @@ A rule matches a line only when every set condition holds: the quantity is withi
A `Percentage` amount is a fraction between 0 and 1 (`0.10` for 10%). The rule form rejects anything above 1. If you enter 15 expecting 15%, that's a 1500% adjustment.
</Callout>
+### Configuration rules
+
+A `Configuration` rule has no amount or item scope of its own. Instead you pick one **configured part** (only parts that require configuration are listed), and the form shows a **Configuration Prices** section listing that part's configuration parameters. Each amount is a per-unit surcharge added to the line's unit price when the line's configuration matches:
+
+- **List** parameters take an amount per option (`Color = Red → 10`).
+- **Boolean** parameters take an amount for when the value is true.
+- **Numeric** parameters take an amount per unit of the value (`0.50 × Length`).
+
+Text, date and material parameters can't be priced. Amounts are signed, so a negative amount gives a credit. The surcharges from every matching Configuration rule stack. They are added before the discount and markup rules, so a discount also applies to the surcharges. Each one appears in the price trace as a `Configuration` step labelled with the parameter's name. The customer scope, dates, quantity range and priority work as on any other rule. A price override that doesn't apply rules on top still takes the configuration prices, because they price the chosen options rather than the part.
+
+Configuration prices apply wherever the line has a configuration: quote lines, which reprice when a line is configured or reconfigured, and sales order lines, which have their own **Configure** button.
+
## Price overrides
A **price override** pins a negotiated price for a specific item, optionally with quantity breaks. Unlike a rule, an override replaces the base price outright rather than adjusting it. Overrides are scoped one of three ways, and a single override targets exactly one scope:
@@ -81,7 +93,7 @@ Discounts and markups combine differently, and this is the part that surprises p
- **Discounts don't stack — the single highest-priority discount wins.** When several discount rules match, Carbon ranks them by priority (ties broken by the larger effective amount) and applies **only the top one**. The rest are discarded. You never get two discounts on the same line.
- **Markups stack and compound.** Every matching markup rule applies, in priority order, each computed against the already-adjusted running price. A 10% markup after a 20% markup compounds, it doesn't simply add.
-Discounts are applied first, then the markup stack, then the zero floor.
+Configuration prices are added first, then the discount, then the markup stack, then the zero floor.
<Callout type="warning" title="Two discounts never combine">
If a customer qualifies for both a 10% and a 15% discount rule, they get 15% only — never 25%, and never both applied in sequence. Markups are the opposite: all of them apply, compounding.
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 513630dded..3a741109db 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -24879,6 +24879,9 @@ export default {
{
$ref: "#/parameters/rowFilter.pricingRule.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.pricingRule.configurationPrices"
+ },
{
$ref: "#/parameters/select"
},
@@ -24998,6 +25001,9 @@ export default {
{
$ref: "#/parameters/rowFilter.pricingRule.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.pricingRule.configurationPrices"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -25071,6 +25077,9 @@ export default {
{
$ref: "#/parameters/rowFilter.pricingRule.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.pricingRule.configurationPrices"
+ },
{
$ref: "#/parameters/body.pricingRule"
},
@@ -59466,6 +59475,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLines.convertedNonTaxableAddOnCost"
},
+ {
+ $ref: "#/parameters/rowFilter.salesOrderLines.configuration"
+ },
{
$ref: "#/parameters/rowFilter.salesOrderLines.itemReadableId"
},
@@ -71505,6 +71517,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
+ {
+ $ref: "#/parameters/rowFilter.salesOrderLine.configuration"
+ },
{
$ref: "#/parameters/select"
},
@@ -71696,6 +71711,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
+ {
+ $ref: "#/parameters/rowFilter.salesOrderLine.configuration"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -71841,6 +71859,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
+ {
+ $ref: "#/parameters/rowFilter.salesOrderLine.configuration"
+ },
{
$ref: "#/parameters/body.salesOrderLine"
},
@@ -118252,7 +118273,7 @@ export default {
type: "string"
},
ruleType: {
- enum: ["Discount", "Markup"],
+ enum: ["Discount", "Markup", "Configuration"],
format: 'public."pricingRuleType"',
type: "string"
},
@@ -118345,6 +118366,9 @@ export default {
updatedAt: {
format: "timestamp with time zone",
type: "string"
+ },
+ configurationPrices: {
+ format: "jsonb"
}
},
type: "object"
@@ -134431,6 +134455,9 @@ export default {
format: "numeric",
type: "number"
},
+ configuration: {
+ format: "jsonb"
+ },
itemReadableId: {
format: "text",
type: "string"
@@ -140675,6 +140702,9 @@ export default {
convertedNonTaxableAddOnCost: {
format: "numeric",
type: "number"
+ },
+ configuration: {
+ format: "jsonb"
}
},
type: "object"
@@ -164503,6 +164533,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.pricingRule.configurationPrices": {
+ name: "configurationPrices",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.location": {
name: "location",
description: "location",
@@ -182448,6 +182484,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.salesOrderLines.configuration": {
+ name: "configuration",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.salesOrderLines.itemReadableId": {
name: "itemReadableId",
required: false,
@@ -189389,6 +189431,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.salesOrderLine.configuration": {
+ name: "configuration",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.purchaseOrderFavorite": {
name: "purchaseOrderFavorite",
description: "purchaseOrderFavorite",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 4f2376f158..b84dc53ab5 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -39749,6 +39749,7 @@ export type Database = {
amount: number
amountType: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId: string
+ configurationPrices: Json | null
createdAt: string
createdBy: string
customerIds: string[] | null
@@ -39771,6 +39772,7 @@ export type Database = {
amount: number
amountType?: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId: string
+ configurationPrices?: Json | null
createdAt?: string
createdBy: string
customerIds?: string[] | null
@@ -39793,6 +39795,7 @@ export type Database = {
amount?: number
amountType?: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId?: string
+ configurationPrices?: Json | null
createdAt?: string
createdBy?: string
customerIds?: string[] | null
@@ -52025,6 +52028,7 @@ export type Database = {
addOnCost: number
assetId: string | null
companyId: string
+ configuration: Json | null
convertedAddOnCost: number | null
convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
@@ -52071,6 +52075,7 @@ export type Database = {
addOnCost?: number
assetId?: string | null
companyId: string
+ configuration?: Json | null
convertedAddOnCost?: number | null
convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
@@ -52117,6 +52122,7 @@ export type Database = {
addOnCost?: number
assetId?: string | null
companyId?: string
+ configuration?: Json | null
convertedAddOnCost?: number | null
convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
@@ -78771,6 +78777,7 @@ export type Database = {
assetReadableId: string | null
autodeskUrn: string | null
companyId: string | null
+ configuration: Json | null
convertedAddOnCost: number | null
convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
@@ -85965,7 +85972,7 @@ export type Database = {
| "Partial"
pickMethodSortMethod: "Default" | "FEFO" | "FIFO" | "LIFO"
pricingRuleAmountType: "Percentage" | "Fixed"
- pricingRuleType: "Discount" | "Markup"
+ pricingRuleType: "Discount" | "Markup" | "Configuration"
procedureStatus: "Draft" | "Active" | "Archived"
procedureStepType:
| "Value"
@@ -87413,7 +87420,7 @@ export const Constants = {
],
pickMethodSortMethod: ["Default", "FEFO", "FIFO", "LIFO"],
pricingRuleAmountType: ["Percentage", "Fixed"],
- pricingRuleType: ["Discount", "Markup"],
+ pricingRuleType: ["Discount", "Markup", "Configuration"],
procedureStatus: ["Draft", "Active", "Archived"],
procedureStepType: [
"Value",
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 45902a24e3..2d2146b135 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -723,6 +723,7 @@ serve(async (req: Request) => {
taxPercent: line.taxPercent,
shippingCost: price.shippingCost ?? 0,
sortOrder: line.sortOrder ?? 1,
+ configuration: toJson(line.configuration),
};
});
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 4f2376f158..b84dc53ab5 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -39749,6 +39749,7 @@ export type Database = {
amount: number
amountType: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId: string
+ configurationPrices: Json | null
createdAt: string
createdBy: string
customerIds: string[] | null
@@ -39771,6 +39772,7 @@ export type Database = {
amount: number
amountType?: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId: string
+ configurationPrices?: Json | null
createdAt?: string
createdBy: string
customerIds?: string[] | null
@@ -39793,6 +39795,7 @@ export type Database = {
amount?: number
amountType?: Database["public"]["Enums"]["pricingRuleAmountType"]
companyId?: string
+ configurationPrices?: Json | null
createdAt?: string
createdBy?: string
customerIds?: string[] | null
@@ -52025,6 +52028,7 @@ export type Database = {
addOnCost: number
assetId: string | null
companyId: string
+ configuration: Json | null
convertedAddOnCost: number | null
convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
@@ -52071,6 +52075,7 @@ export type Database = {
addOnCost?: number
assetId?: string | null
companyId: string
+ configuration?: Json | null
convertedAddOnCost?: number | null
convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
@@ -52117,6 +52122,7 @@ export type Database = {
addOnCost?: number
assetId?: string | null
companyId?: string
+ configuration?: Json | null
convertedAddOnCost?: number | null
convertedNonTaxableAddOnCost?: number | null
convertedShippingCost?: number | null
@@ -78771,6 +78777,7 @@ export type Database = {
assetReadableId: string | null
autodeskUrn: string | null
companyId: string | null
+ configuration: Json | null
convertedAddOnCost: number | null
convertedNonTaxableAddOnCost: number | null
convertedShippingCost: number | null
@@ -85965,7 +85972,7 @@ export type Database = {
| "Partial"
pickMethodSortMethod: "Default" | "FEFO" | "FIFO" | "LIFO"
pricingRuleAmountType: "Percentage" | "Fixed"
- pricingRuleType: "Discount" | "Markup"
+ pricingRuleType: "Discount" | "Markup" | "Configuration"
procedureStatus: "Draft" | "Active" | "Archived"
procedureStepType:
| "Value"
@@ -87413,7 +87420,7 @@ export const Constants = {
],
pickMethodSortMethod: ["Default", "FEFO", "FIFO", "LIFO"],
pricingRuleAmountType: ["Percentage", "Fixed"],
- pricingRuleType: ["Discount", "Markup"],
+ pricingRuleType: ["Discount", "Markup", "Configuration"],
procedureStatus: ["Draft", "Active", "Archived"],
procedureStepType: [
"Value",
diff --git a/packages/database/supabase/migrations/20260929203117_configuration-pricing.sql b/packages/database/supabase/migrations/20260929203117_configuration-pricing.sql
new file mode 100644
index 0000000000..3030a52af7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260929203117_configuration-pricing.sql
@@ -0,0 +1,51 @@
+-- Configuration pricing.
+--
+-- pricingRule.configurationPrices: per-parameter surcharges for a rule that
+-- targets one configurable item. Each entry is { key, value, amount } where
+-- `key` is the configurationParameter key, `value` is the list option / "true"
+-- for a boolean (null for a numeric parameter, which is priced per unit), and
+-- `amount` is a signed per-unit surcharge added to the base price before the
+-- rule discounts and markups apply.
+--
+-- salesOrderLine.configuration: the configurator values chosen on a sales
+-- order line, keyed by configurationParameter key (same shape as
+-- quoteLine.configuration). Used to price the line and to configure the job
+-- made for it.
+
+ALTER TABLE "pricingRule" ADD COLUMN IF NOT EXISTS "configurationPrices" JSONB;
+ALTER TABLE "salesOrderLine" ADD COLUMN IF NOT EXISTS "configuration" JSONB;
+
+-- salesOrderLines selects sl.*, which Postgres expands at creation time, so it
+-- is recreated (verbatim from 20260811123619) to expose the new column.
+DROP VIEW IF EXISTS "salesOrderLines";
+CREATE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ sl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ cp."customerPartId",
+ cp."customerPartRevision",
+ so."orderDate",
+ so."customerId",
+ so."salesOrderId" as "salesOrderReadableId",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "salesOrderLine" sl
+ INNER JOIN "salesOrder" so ON so.id = sl."salesOrderId"
+ LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = sl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "customerPartToItem" cp ON cp."customerId" = so."customerId" AND cp."itemId" = i.id
+ LEFT JOIN "fixedAsset" fa ON fa.id = sl."assetId"
+);
diff --git a/packages/database/supabase/migrations/20260929221847_pricing-rule-type-configuration.sql b/packages/database/supabase/migrations/20260929221847_pricing-rule-type-configuration.sql
new file mode 100644
index 0000000000..5002ffab59
--- /dev/null
+++ b/packages/database/supabase/migrations/20260929221847_pricing-rule-type-configuration.sql
@@ -0,0 +1,4 @@
+-- A "Configuration" pricing rule targets one configurable item and carries only
+-- per-parameter surcharges (pricingRule.configurationPrices) — no discount or
+-- markup of its own (amount stays 0).
+ALTER TYPE "pricingRuleType" ADD VALUE IF NOT EXISTS 'Configuration';
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index b6f9792d87..64343a9317 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Fügte {0} Linien hinzu"
msgid "Added for this customer"
msgstr "Für diesen Kunden hinzugefügt"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Wird zum Einzelpreis für die ausgewählten Werte hinzugefügt, vor Rabatten und Zuschlägen. Verwenden Sie einen negativen Betrag für eine Gutschrift."
+
msgid "Adding demo records"
msgstr "Demo-Datensätze werden hinzugefügt"
@@ -4085,6 +4088,9 @@ msgstr "Konfiguration"
msgid "Configuration Parameters"
msgstr "Konfigurationsparameter"
+msgid "Configuration Prices"
+msgstr "Konfigurationspreise"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Konfiguration, Datenmigration und alle Integrationen"
@@ -4160,6 +4166,9 @@ msgstr "konfiguriert"
msgid "Configured"
msgstr "Konfiguriert"
+msgid "Configured Part"
+msgstr "Konfiguriertes Teil"
+
msgid "Confirm"
msgstr "Bestätigen"
@@ -13019,6 +13028,9 @@ msgstr "Personal"
msgid "People"
msgstr "Personen"
+msgid "Per unit"
+msgstr "Pro Einheit"
+
msgid "Per Unit"
msgstr "Pro Einheit"
@@ -14385,6 +14397,9 @@ msgstr "Bei der Abstimmung wurden Abweichungen mit dem Anbieter gefunden"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Abstimmung einer Bestellung gegen das, was eingegangen und fakturiert wurde – implizit in Carbon über die Positionsmengen und den WE/RE-Saldo."
+msgid "Reconfigure"
+msgstr "Erneut konfigurieren"
+
msgid "Record"
msgstr "Aufnahme"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 5a86df89d3..2d01833972 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Added {0} lines"
msgid "Added for this customer"
msgstr "Added for this customer"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+
msgid "Adding demo records"
msgstr "Adding demo records"
@@ -4085,6 +4088,9 @@ msgstr "Configuration"
msgid "Configuration Parameters"
msgstr "Configuration Parameters"
+msgid "Configuration Prices"
+msgstr "Configuration Prices"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Configuration, data migration, and any integrations"
@@ -4160,6 +4166,9 @@ msgstr "configured"
msgid "Configured"
msgstr "Configured"
+msgid "Configured Part"
+msgstr "Configured Part"
+
msgid "Confirm"
msgstr "Confirm"
@@ -13019,6 +13028,9 @@ msgstr "people"
msgid "People"
msgstr "People"
+msgid "Per unit"
+msgstr "Per unit"
+
msgid "Per Unit"
msgstr "Per Unit"
@@ -14385,6 +14397,9 @@ msgstr "Reconciliation found discrepancies with the provider"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
+msgid "Reconfigure"
+msgstr "Reconfigure"
+
msgid "Record"
msgstr "Record"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index a4114869a3..ec55f8128b 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Se agregaron {0} líneas"
msgid "Added for this customer"
msgstr "Añadido para este cliente"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Se agrega al precio unitario por los valores seleccionados, antes de descuentos y recargos. Utilice un importe negativo para un haber."
+
msgid "Adding demo records"
msgstr "Agregando registros de demostración"
@@ -4085,6 +4088,9 @@ msgstr "Configuración"
msgid "Configuration Parameters"
msgstr "Parámetros de Configuración"
+msgid "Configuration Prices"
+msgstr "Precios de configuración"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Configuración, migración de datos e integraciones"
@@ -4160,6 +4166,9 @@ msgstr "configurado"
msgid "Configured"
msgstr "Configurado"
+msgid "Configured Part"
+msgstr "Pieza configurada"
+
msgid "Confirm"
msgstr "Confirmar"
@@ -13019,6 +13028,9 @@ msgstr "personal"
msgid "People"
msgstr "Personas"
+msgid "Per unit"
+msgstr "Por unidad"
+
msgid "Per Unit"
msgstr "Por unidad"
@@ -14385,6 +14397,9 @@ msgstr "La reconciliación encontró discrepancias con el proveedor"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Conciliación de una orden de compra contra lo que se recibió y se facturó — implícita en Carbon, a través de las cantidades de línea y el saldo de GR/IR."
+msgid "Reconfigure"
+msgstr "Reconfigurar"
+
msgid "Record"
msgstr "Registro"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 6c8bc20267..7e456acd75 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Ajout de {0} lignes"
msgid "Added for this customer"
msgstr "Ajouté pour ce client"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Ajouté au prix unitaire pour les valeurs choisies, avant les remises et les majorations. Utilisez un montant négatif pour un crédit."
+
msgid "Adding demo records"
msgstr "Ajout d'enregistrements de démonstration"
@@ -4085,6 +4088,9 @@ msgstr "Configuration"
msgid "Configuration Parameters"
msgstr "Paramètres de configuration"
+msgid "Configuration Prices"
+msgstr "Prix de configuration"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Configuration, migration de données et intégrations"
@@ -4160,6 +4166,9 @@ msgstr "configuré"
msgid "Configured"
msgstr "Configuré"
+msgid "Configured Part"
+msgstr "Pièce configurée"
+
msgid "Confirm"
msgstr "Confirmer"
@@ -13019,6 +13028,9 @@ msgstr "personnel"
msgid "People"
msgstr "Personnes"
+msgid "Per unit"
+msgstr "Par unité"
+
msgid "Per Unit"
msgstr "Par unité"
@@ -14385,6 +14397,9 @@ msgstr "La rapprochement a détecté des écarts avec le fournisseur"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Rapprochement d'un bon de commande par rapport à ce qui a été reçu et facturé — implicite dans Carbon, via les quantités de ligne et le solde GR/IR."
+msgid "Reconfigure"
+msgstr "Reconfigurer"
+
msgid "Record"
msgstr "Enregistrer"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 873ccfa610..a2656438d2 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1646,6 +1646,9 @@ msgstr "जोड़ी गई {0} लाइनें"
msgid "Added for this customer"
msgstr "इस ग्राहक के लिए जोड़ा गया"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "इकाई मूल्य में चुने गए मानों के लिए जोड़ा जाता है, छूट और अधिशुल्क से पहले। जमा के लिए नकारात्मक राशि का उपयोग करें।"
+
msgid "Adding demo records"
msgstr "डेमो रिकॉर्ड जोड़ रहे हैं"
@@ -4085,6 +4088,9 @@ msgstr "विन्यास"
msgid "Configuration Parameters"
msgstr "कॉन्फ़िगरेशन पैरामीटर"
+msgid "Configuration Prices"
+msgstr "कॉन्फ़िगरेशन मूल्य"
+
msgid "Configuration, data migration, and any integrations"
msgstr "कॉन्फ़िगरेशन, डेटा माइग्रेशन, और कोई भी एकीकरण"
@@ -4160,6 +4166,9 @@ msgstr "कॉन्फ़िगर किया गया"
msgid "Configured"
msgstr "कॉन्फ़िगर किया गया"
+msgid "Configured Part"
+msgstr "कॉन्फ़िगर की गई पार्ट"
+
msgid "Confirm"
msgstr "पुष्टि करें"
@@ -13019,6 +13028,9 @@ msgstr "लोग"
msgid "People"
msgstr "लोग"
+msgid "Per unit"
+msgstr "प्रति इकाई"
+
msgid "Per Unit"
msgstr "प्रति यूनिट"
@@ -14385,6 +14397,9 @@ msgstr "समन्वय ने प्रदाता के साथ वि
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "एक क्रय आदेश को जो प्राप्त और चालान किया गया था उसके खिलाफ सुलह करना — Carbon में अंतर्निहित, पंक्ति मात्रा और GR/IR शेष राशि के माध्यम से।"
+msgid "Reconfigure"
+msgstr "फिर से कॉन्फ़िगर करें"
+
msgid "Record"
msgstr "रिकॉर्ड करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 9a56d1cbf6..81d619798e 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Aggiunte {0} righe"
msgid "Added for this customer"
msgstr "Aggiunto per questo cliente"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Aggiunto al prezzo unitario per i valori scelti, prima degli sconti e degli aumenti. Utilizzare un importo negativo per un avere."
+
msgid "Adding demo records"
msgstr "Aggiunta di record demo"
@@ -4085,6 +4088,9 @@ msgstr "Configurazione"
msgid "Configuration Parameters"
msgstr "Parametri di Configurazione"
+msgid "Configuration Prices"
+msgstr "Prezzi di configurazione"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Configurazione, migrazione dei dati e qualsiasi integrazione"
@@ -4160,6 +4166,9 @@ msgstr "configurato"
msgid "Configured"
msgstr "Configurato"
+msgid "Configured Part"
+msgstr "Componente configurato"
+
msgid "Confirm"
msgstr "Conferma"
@@ -13019,6 +13028,9 @@ msgstr "personale"
msgid "People"
msgstr "Persone"
+msgid "Per unit"
+msgstr "Per unità"
+
msgid "Per Unit"
msgstr "Per unità"
@@ -14385,6 +14397,9 @@ msgstr "La riconciliazione ha riscontrato discrepanze con il provider"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Riconciliazione di un ordine di acquisto rispetto a ciò che è stato ricevuto e fatturato — implicito in Carbon, tramite le quantità di riga e il saldo GR/IR."
+msgid "Reconfigure"
+msgstr "Riconfigura"
+
msgid "Record"
msgstr "Registra"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 40331a162a..5e3f47000b 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1646,6 +1646,9 @@ msgstr "{0}行を追加しました"
msgid "Added for this customer"
msgstr "この得意先に追加済み"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "選択値に対する単価への加算で、値引およびマークアップの前に適用されます。クレジットには負の金額を使用してください。"
+
msgid "Adding demo records"
msgstr "デモレコードを追加中"
@@ -4085,6 +4088,9 @@ msgstr "設定"
msgid "Configuration Parameters"
msgstr "設定パラメータ"
+msgid "Configuration Prices"
+msgstr "構成価格"
+
msgid "Configuration, data migration, and any integrations"
msgstr "構成、データ移行、および任意の連携"
@@ -4160,6 +4166,9 @@ msgstr "設定済み"
msgid "Configured"
msgstr "設定済み"
+msgid "Configured Part"
+msgstr "構成済み部品"
+
msgid "Confirm"
msgstr "確認"
@@ -13019,6 +13028,9 @@ msgstr "人員"
msgid "People"
msgstr "人員"
+msgid "Per unit"
+msgstr "個当たり"
+
msgid "Per Unit"
msgstr "単位あたり"
@@ -14385,6 +14397,9 @@ msgstr "調整でプロバイダとの不一致が見つかりました"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "発注書を受け取られたものと請求済のものと照合する - Carbonでは、明細数量とGR/IRバランスを介して暗黙的に行われます。"
+msgid "Reconfigure"
+msgstr "再構成"
+
msgid "Record"
msgstr "記録"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index fcb8eb0689..cd3d5ca459 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -1646,6 +1646,9 @@ msgstr "{0}개 라인이 추가되었습니다"
msgid "Added for this customer"
msgstr "이 고객을 위해 추가됨"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "선택한 값에 대해 단가에 추가되며, 할인 및 마크업 전입니다. 대변을 위해 음수 금액을 사용하세요."
+
msgid "Adding demo records"
msgstr "데모 레코드 추가 중"
@@ -4085,6 +4088,9 @@ msgstr "구성"
msgid "Configuration Parameters"
msgstr "설정 파라미터"
+msgid "Configuration Prices"
+msgstr "구성 가격"
+
msgid "Configuration, data migration, and any integrations"
msgstr "설정, 데이터 마이그레이션 및 각종 연동"
@@ -4160,6 +4166,9 @@ msgstr "설정됨"
msgid "Configured"
msgstr "설정됨"
+msgid "Configured Part"
+msgstr "구성된 부품"
+
msgid "Confirm"
msgstr "확인"
@@ -13019,6 +13028,9 @@ msgstr "인원"
msgid "People"
msgstr "인원"
+msgid "Per unit"
+msgstr "개당"
+
msgid "Per Unit"
msgstr "단위당"
@@ -14385,6 +14397,9 @@ msgstr "조정 중에 공급자와의 불일치를 발견했습니다"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "발주서를 입고 및 송장 발행된 내용과 대조하기 — Carbon에서 라인 수량 및 GR/IR 잔액을 통해 암묵적으로 수행됩니다."
+msgid "Reconfigure"
+msgstr "재설정"
+
msgid "Record"
msgstr "기록"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 67e8c872fb..9785d3f4dc 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Dodano {0} wierszy"
msgid "Added for this customer"
msgstr "Dodane dla tego klienta"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Dodawane do ceny jednostkowej dla wybranych wartości, przed rabatami i narzutami. Użyj ujemnej kwoty, aby obniżyć cenę."
+
msgid "Adding demo records"
msgstr "Dodawanie przykładowych rekordów"
@@ -4085,6 +4088,9 @@ msgstr "Konfiguracja"
msgid "Configuration Parameters"
msgstr "Parametry konfiguracji"
+msgid "Configuration Prices"
+msgstr "Ceny Konfiguracji"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Konfiguracja, migracja danych i wszelkie integracje"
@@ -4160,6 +4166,9 @@ msgstr "skonfigurowane"
msgid "Configured"
msgstr "Skonfigurowane"
+msgid "Configured Part"
+msgstr "Skonfigurowana Część"
+
msgid "Confirm"
msgstr "Potwierdź"
@@ -13019,6 +13028,9 @@ msgstr "pracownicy"
msgid "People"
msgstr "Pracownicy"
+msgid "Per unit"
+msgstr "Na sztukę"
+
msgid "Per Unit"
msgstr "Na jednostkę"
@@ -14385,6 +14397,9 @@ msgstr "Reconcyliacja wykazała rozbieżności z dostawcą"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Uzgadnianie zamówienia zakupu z tym, co zostało przyjęte i zafakturowane — niejawne w Carbon, poprzez ilości pozycji i saldo GR/IR."
+msgid "Reconfigure"
+msgstr "Rekonfiguruj"
+
msgid "Record"
msgstr "Nagrywaj"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index efae023946..a2915e3273 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Adicionadas {0} linhas"
msgid "Added for this customer"
msgstr "Adicionado para este cliente"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Adicionado ao preço unitário para os valores escolhidos, antes de descontos e marcações. Use um valor negativo para crédito."
+
msgid "Adding demo records"
msgstr "Adicionando registos de demonstração"
@@ -4085,6 +4088,9 @@ msgstr "Configuração"
msgid "Configuration Parameters"
msgstr "Parâmetros de Configuração"
+msgid "Configuration Prices"
+msgstr "Preços de Configuração"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Configuração, migração de dados e quaisquer integrações"
@@ -4160,6 +4166,9 @@ msgstr "configurado"
msgid "Configured"
msgstr "Configurado"
+msgid "Configured Part"
+msgstr "Peça Configurada"
+
msgid "Confirm"
msgstr "Confirmar"
@@ -13019,6 +13028,9 @@ msgstr "pessoas"
msgid "People"
msgstr "Pessoas"
+msgid "Per unit"
+msgstr "Por unidade"
+
msgid "Per Unit"
msgstr "Por Unidade"
@@ -14385,6 +14397,9 @@ msgstr "A reconciliação encontrou discrepâncias com o provedor"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Reconciliação de um pedido de compra contra o que foi recebido e faturado — implícito no Carbon, através das quantidades das linhas e do saldo GR/IR."
+msgid "Reconfigure"
+msgstr "Reconfigurar"
+
msgid "Record"
msgstr "Gravar"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index dc1a0a34b3..15c1fe4ca8 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Добавлено строк: {0}"
msgid "Added for this customer"
msgstr "Добавлено для этого покупателя"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Добавляется к цене за единицу для выбранных значений, до скидок и надбавок. Используйте отрицательную сумму для кредита."
+
msgid "Adding demo records"
msgstr "Добавление демо-записей"
@@ -4085,6 +4088,9 @@ msgstr "Конфигурация"
msgid "Configuration Parameters"
msgstr "Параметры конфигурации"
+msgid "Configuration Prices"
+msgstr "Цены конфигурации"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Конфигурация, миграция данных и любые интеграции"
@@ -4160,6 +4166,9 @@ msgstr "настроено"
msgid "Configured"
msgstr "Настроено"
+msgid "Configured Part"
+msgstr "Сконфигурированная деталь"
+
msgid "Confirm"
msgstr "Подтвердить"
@@ -13019,6 +13028,9 @@ msgstr "сотрудники"
msgid "People"
msgstr "Сотрудники"
+msgid "Per unit"
+msgstr "За единицу"
+
msgid "Per Unit"
msgstr "За единицу"
@@ -14385,6 +14397,9 @@ msgstr "Сверка обнаружила расхождения с постав
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Сверка заказа поставщику с полученными товарами и выставленными счетами — выполняется автоматически в Carbon на основе количеств в строках и остатка GR/IR."
+msgid "Reconfigure"
+msgstr "Переконфигурировать"
+
msgid "Record"
msgstr "Записать"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b7b73d3515..0e6e1f637b 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -1646,6 +1646,9 @@ msgstr "Eklenen {0} satır"
msgid "Added for this customer"
msgstr "Bu müşteri için eklendi"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "Seçilen değerler için birim fiyata eklenir, iskontolar ve marjlar öncesi. İndirim için negatif tutar kullanın."
+
msgid "Adding demo records"
msgstr "Demo kayıtları ekleniyor"
@@ -4085,6 +4088,9 @@ msgstr "Yapılandırma"
msgid "Configuration Parameters"
msgstr "Yapılandırma Parametreleri"
+msgid "Configuration Prices"
+msgstr "Konfigürasyon Fiyatları"
+
msgid "Configuration, data migration, and any integrations"
msgstr "Yapılandırma, veri taşıması ve tüm entegrasyonlar"
@@ -4160,6 +4166,9 @@ msgstr "yapılandırıldı"
msgid "Configured"
msgstr "Yapılandırılmış"
+msgid "Configured Part"
+msgstr "Yapılandırılmış Parça"
+
msgid "Confirm"
msgstr "Onayla"
@@ -13019,6 +13028,9 @@ msgstr "personel"
msgid "People"
msgstr "Personel"
+msgid "Per unit"
+msgstr "Birim başına"
+
msgid "Per Unit"
msgstr "Birim Başı"
@@ -14385,6 +14397,9 @@ msgstr "Mutabakat sağlayıcıyla tutarsızlıklar buldu"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "Satın alma siparişinin alınan ve faturalandırılana karşı uzlaştırması — Carbon'da satır miktarları ve GR/IR bakiyesi aracılığıyla örtük olarak yapılır."
+msgid "Reconfigure"
+msgstr "Yeniden Yapılandır"
+
msgid "Record"
msgstr "Kayıt"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index da88fc5bb9..6d17e62be7 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1646,6 +1646,9 @@ msgstr "已添加 {0} 行"
msgid "Added for this customer"
msgstr "为此客户添加"
+msgid "Added to the unit price for the chosen values, before discounts and markups. Use a negative amount for a credit."
+msgstr "添加到所选配置的单价中,在折扣和加价之前生效。使用负数金额可作为抵扣。"
+
msgid "Adding demo records"
msgstr "正在添加演示记录"
@@ -4085,6 +4088,9 @@ msgstr "配置"
msgid "Configuration Parameters"
msgstr "配置参数"
+msgid "Configuration Prices"
+msgstr "配置价格"
+
msgid "Configuration, data migration, and any integrations"
msgstr "配置、数据迁移和任何集成"
@@ -4160,6 +4166,9 @@ msgstr "已配置"
msgid "Configured"
msgstr "已配置"
+msgid "Configured Part"
+msgstr "配置零件"
+
msgid "Confirm"
msgstr "确认"
@@ -13019,6 +13028,9 @@ msgstr "人员"
msgid "People"
msgstr "人员"
+msgid "Per unit"
+msgstr "每件"
+
msgid "Per Unit"
msgstr "每单位"
@@ -14385,6 +14397,9 @@ msgstr "对账发现与提供商的差异"
msgid "Reconciling a purchase order against what was received and invoiced — implicit in Carbon, via the line quantities and GR/IR balance."
msgstr "将采购订单与已收货和已开票的内容进行对账——在Carbon中隐含进行,通过行数量和GR/IR余额。"
+msgid "Reconfigure"
+msgstr "重新配置"
+
msgid "Record"
msgstr "录音"