Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
-updates to pricing lists nd duplication
Gaurav Bhatt6fdfd8371303
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex cc1cd93179..bf26852727 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -181,6 +181,15 @@ export const priceOverrideValidator = zpath: ["validTo"]});+export const duplicatePriceListValidator = z.object({+ sourceCustomerId: z.string().optional(),+ sourceCustomerTypeId: z.string().optional(),+ targetCustomerId: z.string().optional(),+ targetCustomerTypeId: z.string().optional(),+ conflictStrategy: z.enum(["skip", "overwrite"]),+ overrideIds: z.string().optional()+});+export const priceResolutionInputValidator = z.object({itemId: z.string().min(1),quantity: z.number().nonnegative(),diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 6f84ab9366..908c42717c 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -2232,21 +2232,38 @@ export async function resolvePriceList(customerId?: string;customerTypeId?: string;search?: string;- onlyOverrides?: boolean;quantity?: number;- allCustomers?: boolean;}): Promise<PriceListResult> {const date = new Date().toISOString().split("T")[0]!;const previewQuantity = Math.max(args.quantity ?? 1, 0);+ let scopeQuery = client+ .from("customerItemPriceOverride")+ .select("itemId")+ .eq("companyId", companyId)+ .eq("active", true);++ if (args.customerId) {+ scopeQuery = scopeQuery.eq("customerId", args.customerId);+ } else if (args.customerTypeId) {+ scopeQuery = scopeQuery.eq("customerTypeId", args.customerTypeId);+ }++ const { data: scopedOverrides } = await scopeQuery;+ const overriddenItemIds = (scopedOverrides ?? []).map((r) => r.itemId);+ if (overriddenItemIds.length === 0) {+ return { data: [], count: 0 };+ }+let itemQuery = client.from("item").select("id, readableId, name, thumbnailPath, itemUnitSalePrice(unitSalePrice), itemCost(itemPostingGroupId, unitCost)",{ count: "exact" })- .eq("active", true);+ .eq("active", true)+ .in("id", overriddenItemIds);if (args.search) {itemQuery = itemQuery.or(@@ -2254,8 +2271,6 @@ export async function resolvePriceList();}- // itemPostingGroupId lives on itemCost, not item — pre-resolve into itemIds- // and keep the rest of the filters on the item query.const { itemIds: postingGroupItemIds, filters: filtersWithoutPostingGroup } =await resolvePostingGroupFilter(client, companyId, args.filters);if (postingGroupItemIds !== null) {@@ -2277,10 +2292,8 @@ export async function resolvePriceList(const itemIds = items.map((i) => i.id);- let resolvedCustomerTypeId = args.allCustomers- ? null- : (args.customerTypeId ?? null);- if (!args.allCustomers && args.customerId && !resolvedCustomerTypeId) {+ let resolvedCustomerTypeId = args.customerTypeId ?? null;+ if (args.customerId && !resolvedCustomerTypeId) {const { data: cust } = await client.from("customer").select("customerTypeId")@@ -2317,50 +2330,38 @@ export async function resolvePriceList(const typeOverrideMap = new Map<string, OverrideEntry>();const allOverrideMap = new Map<string, OverrideEntry>();- if (args.allCustomers) {- const { data: allRows } = await client+ if (args.customerId) {+ const { data: rows } = await client.from("customerItemPriceOverride").select(overrideSelect).eq("companyId", companyId)- .is("customerId", null)- .is("customerTypeId", null)+ .eq("customerId", args.customerId).eq("active", true).in("itemId", itemIds);- fillMap(allRows as unknown as ParentRow[] | null, allOverrideMap);- } else {- if (args.customerId) {- const { data: rows } = await client- .from("customerItemPriceOverride")- .select(overrideSelect)- .eq("companyId", companyId)- .eq("customerId", args.customerId)- .eq("active", true)- .in("itemId", itemIds);- fillMap(rows as unknown as ParentRow[] | null, overrideMap);- }-- if (resolvedCustomerTypeId) {- const { data: rows } = await client- .from("customerItemPriceOverride")- .select(overrideSelect)- .eq("companyId", companyId)- .eq("customerTypeId", resolvedCustomerTypeId)- .eq("active", true)- .in("itemId", itemIds);- fillMap(rows as unknown as ParentRow[] | null, typeOverrideMap);- }+ fillMap(rows as unknown as ParentRow[] | null, overrideMap);+ }- const { data: allRows } = await client+ if (resolvedCustomerTypeId) {+ const { data: rows } = await client.from("customerItemPriceOverride").select(overrideSelect).eq("companyId", companyId)- .is("customerId", null)- .is("customerTypeId", null)+ .eq("customerTypeId", resolvedCustomerTypeId).eq("active", true).in("itemId", itemIds);- fillMap(allRows as unknown as ParentRow[] | null, allOverrideMap);+ fillMap(rows as unknown as ParentRow[] | null, typeOverrideMap);}+ const { data: allRows } = await client+ .from("customerItemPriceOverride")+ .select(overrideSelect)+ .eq("companyId", companyId)+ .is("customerId", null)+ .is("customerTypeId", null)+ .eq("active", true)+ .in("itemId", itemIds);+ fillMap(allRows as unknown as ParentRow[] | null, allOverrideMap);+let rulesQuery = client.from("pricingRule").select("*")@@ -2528,13 +2529,9 @@ export async function resolvePriceList(};});- const filtered = args.onlyOverrides- ? rows.filter((r) => r.isOverridden)- : rows;-return {- data: filtered,- count: args.onlyOverrides ? filtered.length : (count ?? 0)+ data: rows,+ count: count ?? 0};}@@ -2827,6 +2824,126 @@ export async function deleteCustomerItemPriceOverride(.eq("companyId", companyId);}+export async function duplicatePriceOverrides(+ client: SupabaseClient<Database>,+ companyId: string,+ userId: string,+ source: { customerId?: string; customerTypeId?: string },+ target: { customerId?: string; customerTypeId?: string },+ options?: {+ overrideIds?: string[];+ conflictStrategy?: "skip" | "overwrite";+ }+): Promise<{+ duplicated: number;+ skipped: number;+ overwritten: number;+ error: unknown;+}> {+ let query = client+ .from("customerItemPriceOverride")+ .select(+ "id, itemId, notes, validFrom, validTo, active, applyRulesOnTop, breaks:customerItemPriceOverrideBreak(quantity, overridePrice, active)"+ )+ .eq("companyId", companyId);++ if (source.customerId) {+ query = query.eq("customerId", source.customerId);+ } else if (source.customerTypeId) {+ query = query.eq("customerTypeId", source.customerTypeId);+ } else {+ query = query.is("customerId", null).is("customerTypeId", null);+ }++ if (options?.overrideIds?.length) {+ query = query.in("id", options.overrideIds);+ }++ const { data: sourceOverrides, error: fetchError } = await query;+ if (fetchError || !sourceOverrides) {+ return { duplicated: 0, skipped: 0, overwritten: 0, error: fetchError };+ }++ const strategy = options?.conflictStrategy ?? "skip";+ let duplicated = 0;+ let skipped = 0;+ let overwritten = 0;++ let existingLookup = client+ .from("customerItemPriceOverride")+ .select("id, itemId")+ .eq("companyId", companyId)+ .in(+ "itemId",+ sourceOverrides.map((s) => s.itemId)+ );++ existingLookup = target.customerId+ ? existingLookup.eq("customerId", target.customerId)+ : target.customerTypeId+ ? existingLookup.eq("customerTypeId", target.customerTypeId)+ : existingLookup.is("customerId", null).is("customerTypeId", null);++ const { data: existingOverrides } = await existingLookup;+ const existingByItemId = new Map(+ (existingOverrides ?? []).map((e) => [e.itemId, e.id])+ );++ for (const src of sourceOverrides) {+ const breaks = (+ (src.breaks as+ | { quantity: number; overridePrice: number; active: boolean }[]+ | null) ?? []+ ).map((b) => ({+ quantity: b.quantity,+ overridePrice: b.overridePrice,+ active: b.active+ }));++ if (breaks.length === 0) {+ skipped++;+ continue;+ }++ const existingId = existingByItemId.get(src.itemId);++ if (existingId && strategy === "skip") {+ skipped++;+ continue;+ }++ const result = await upsertCustomerItemPriceOverride(+ client,+ companyId,+ userId,+ {+ id: existingId ?? undefined,+ customerId: target.customerId,+ customerTypeId: target.customerTypeId,+ itemId: src.itemId,+ breaks,+ active: src.active,+ applyRulesOnTop: src.applyRulesOnTop ?? true,+ notes: src.notes ?? undefined,+ validFrom: src.validFrom ?? undefined,+ validTo: src.validTo ?? undefined+ }+ );++ if (result.error) {+ return { duplicated, skipped, overwritten, error: result.error };+ }++ if (existingId) {+ overwritten++;+ } else {+ duplicated++;+ }+ }++ return { duplicated, skipped, overwritten, error: null };+}+export async function getCustomerItemPriceOverrideById(client: SupabaseClient<Database>,id: string,diff --git a/apps/erp/app/modules/sales/ui/Pricing/DuplicatePriceListModal.tsx b/apps/erp/app/modules/sales/ui/Pricing/DuplicatePriceListModal.tsxnew file mode 100644index 0000000000..8d95493fb3--- /dev/null+++ b/apps/erp/app/modules/sales/ui/Pricing/DuplicatePriceListModal.tsx@@ -0,0 +1,164 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ ChoiceCardGroup,+ HStack,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect, useRef, useState } from "react";+import { useFetcher } from "react-router";+import { Customer, CustomerType, Hidden } from "~/components/Form";+import { path } from "~/utils/path";+import { duplicatePriceListValidator } from "../../sales.models";++type ScopeType = "customer" | "customerType";++type DuplicatePriceListModalProps = {+ sourceScope: { customerId?: string; customerTypeId?: string };+ overrideIds?: string[];+ onClose: () => void;+};++export function DuplicatePriceListModal({+ sourceScope,+ overrideIds,+ onClose+}: DuplicatePriceListModalProps) {+ const { t } = useLingui();+ const fetcher = useFetcher();+ const prevState = useRef(fetcher.state);++ useEffect(() => {+ if (prevState.current === "loading" && fetcher.state === "idle") {+ onClose();+ }+ prevState.current = fetcher.state;+ }, [fetcher.state, onClose]);++ const [scopeType, setScopeType] = useState<ScopeType>("customer");+ const [conflictStrategy, setConflictStrategy] = useState<+ "skip" | "overwrite"+ >("skip");++ const isSubmitting = fetcher.state !== "idle";++ return (+ <Modal open onOpenChange={(open) => !open && onClose()}>+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ {overrideIds ? (+ <Trans>Duplicate Item</Trans>+ ) : (+ <Trans>Duplicate Price List</Trans>+ )}+ </ModalTitle>+ <ModalDescription>+ {overrideIds ? (+ <Trans>Copy this item's pricing to another scope.</Trans>+ ) : (+ <Trans>+ Copy all items and pricing to another customer or type.+ </Trans>+ )}+ </ModalDescription>+ </ModalHeader>+ <ValidatedForm+ validator={duplicatePriceListValidator}+ fetcher={fetcher}+ action={path.to.duplicatePriceList}+ method="post"+ defaultValues={{+ sourceCustomerId: sourceScope.customerId ?? "",+ sourceCustomerTypeId: sourceScope.customerTypeId ?? "",+ targetCustomerId: "",+ targetCustomerTypeId: "",+ conflictStrategy: "skip",+ overrideIds: overrideIds ? JSON.stringify(overrideIds) : undefined+ }}+ >+ <Hidden name="sourceCustomerId" />+ <Hidden name="sourceCustomerTypeId" />+ <Hidden name="conflictStrategy" value={conflictStrategy} />+ {overrideIds && (+ <Hidden name="overrideIds" value={JSON.stringify(overrideIds)} />+ )}+ <ModalBody>+ <VStack spacing={4}>+ <ChoiceCardGroup<ScopeType>+ label={t`Duplicate To`}+ value={scopeType}+ onChange={setScopeType}+ options={[+ {+ value: "customer",+ title: t`Specific Customer`,+ description: t`Copy pricing to a single customer`+ },+ {+ value: "customerType",+ title: t`Customer Type`,+ description: t`Copy pricing to all customers of a type`+ }+ ]}+ />++ {scopeType === "customer" && (+ <>+ <Customer name="targetCustomerId" label={t`Customer`} />+ <Hidden name="targetCustomerTypeId" value="" />+ </>+ )}++ {scopeType === "customerType" && (+ <>+ <CustomerType+ name="targetCustomerTypeId"+ label={t`Customer Type`}+ />+ <Hidden name="targetCustomerId" value="" />+ </>+ )}++ <ChoiceCardGroup<"skip" | "overwrite">+ label={t`If items already exist`}+ value={conflictStrategy}+ onChange={setConflictStrategy}+ options={[+ {+ value: "skip",+ title: t`Skip Existing`,+ description: t`Keep existing pricing, only add new items`+ },+ {+ value: "overwrite",+ title: t`Overwrite Existing`,+ description: t`Replace existing pricing with source values`+ }+ ]}+ />+ </VStack>+ </ModalBody>+ <ModalFooter>+ <HStack>+ <Button type="submit" isLoading={isSubmitting}>+ <Trans>Duplicate</Trans>+ </Button>+ <Button variant="secondary" onClick={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ </HStack>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsxindex 9b266cbaef..feacc38735 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx@@ -35,7 +35,6 @@ import type { ColumnDef } from "@tanstack/react-table";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuEllipsisVertical,- LuGlobe,LuHistory,LuSquareUser,LuTrash,@@ -63,7 +62,7 @@ import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";import { priceOverrideValidator } from "../../sales.models";import type { PriceOverrideBreak } from "../../types";-type ScopeType = "customer" | "customerType" | "all";+type ScopeType = "customer" | "customerType";type PriceOverrideFormProps = {initialValues: z.infer<typeof priceOverrideValidator>;@@ -87,8 +86,6 @@ const PriceOverrideForm = ({const [scope, setScope] = useState<ScopeType>(() => {if (initialValues.customerId) return "customer";if (initialValues.customerTypeId) return "customerType";- // Edit with no IDs = All Customers. Create honors URL-provided scope hint.- if (initialValues.id) return "all";return initialScope ?? "customer";});@@ -150,12 +147,7 @@ const PriceOverrideForm = ({<Hidden name="id" /><Hidden name="breaks" value={JSON.stringify(breaks)} /><VStack spacing={4}>- <Item- name="itemId"- label={t`Item`}- type="Part"- isReadOnly={isEditing}- />+ <Item name="itemId" label={t`Item`} type="Part" /><ChoiceCardGroup<ScopeType>label={t`Apply To`}@@ -173,12 +165,6 @@ const PriceOverrideForm = ({title: t`Customer Type`,description: t`Override price for all customers of a type`,icon: <LuUsers />- },- {- value: "all",- title: t`All Customers`,- description: t`Fallback price when no other override matches`,- icon: <LuGlobe />}]}/>@@ -200,13 +186,6 @@ const PriceOverrideForm = ({</>)}- {scope === "all" && (- <>- <Hidden name="customerId" value="" />- <Hidden name="customerTypeId" value="" />- </>- )}-<PriceBreaksbreaks={breaks}onChange={setBreaks}@@ -294,18 +273,17 @@ function PriceBreaks({lastFetchedRef.current = null;return;}- if (!overrideId || !companyId) return;- const key = `${overrideId}:${historyBreakId}`;+ if (!companyId) return;+ const key = historyBreakId;if (lastFetchedRef.current === key) return;lastFetchedRef.current = key;const params = new URLSearchParams({- entityType: "priceOverride",- entityId: overrideId,- companyId,- recordId: historyBreakId+ entityType: "priceOverrideBreak",+ entityId: historyBreakId,+ companyId});fetcher.load(`/api/audit-log?${params.toString()}`);- }, [historyBreakId, overrideId, companyId, fetcher]);+ }, [historyBreakId, companyId, fetcher]);const breakHistoryEntries = fetcher.data?.entries ?? [];const isHistoryLoading = fetcher.state === "loading";diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsxindex 4267612b02..ebb34127d4 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx@@ -22,7 +22,7 @@ import {import { formatDate } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useMemo } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuBookMarked,LuCalendar,@@ -31,6 +31,7 @@ import {LuChevronUp,LuCircleDollarSign,LuCircleOff,+ LuCopy,LuGroup,LuPencil,LuPlus,@@ -44,13 +45,10 @@ import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";import type { PriceListRow } from "~/modules/sales";import { path } from "~/utils/path";+import { DuplicatePriceListModal } from "./DuplicatePriceListModal";import { PriceListScopeEmpty } from "./PriceListScopeEmpty";import { PriceTracePopover } from "./PriceTracePopover";-import {- ALL_CUSTOMERS_SCOPE,- type ScopeOption,- ScopePicker-} from "./ScopePicker";+import { type ScopeOption, ScopePicker } from "./ScopePicker";type PriceListTableProps = {data: PriceListRow[];@@ -81,14 +79,23 @@ const PriceListTable = memo(const [searchParams, setSearchParams] = useSearchParams();const previewQuantity = searchParams.get("quantity") ?? "1";const itemPostingGroups = useItemPostingGroups();+ const [duplicateState, setDuplicateState] = useState<{+ overrideIds?: string[];+ } | null>(null);++ const canCreate = permissions.can("create", "sales");+ const canDelete = permissions.can("delete", "sales");++ const currentCustomerId = searchParams.get("customerId") ?? undefined;+ const currentCustomerTypeId =+ searchParams.get("customerTypeId") ?? undefined;- const scopeId =- searchParams.get("customerId") ??- searchParams.get("customerTypeId") ??- (searchParams.get("customerScope") === ALL_CUSTOMERS_SCOPE- ? ALL_CUSTOMERS_SCOPE- : "");+ const scopeId = currentCustomerId ?? currentCustomerTypeId ?? "";+ const sourceScope = {+ customerId: currentCustomerId,+ customerTypeId: currentCustomerTypeId+ };const buildOverrideHref = useCallback((row: PriceListRow) => {const next = new URLSearchParams(searchParams);@@ -106,10 +113,7 @@ const PriceListTable = memo(const next = new URLSearchParams(searchParams);next.delete("customerId");next.delete("customerTypeId");- next.delete("customerScope");- if (selectedId === ALL_CUSTOMERS_SCOPE) {- next.set("customerScope", ALL_CUSTOMERS_SCOPE);- } else if (selectedId) {+ if (selectedId) {const picked = scopeOptions.find((o) => o.value === selectedId);if (picked) {next.set(@@ -272,25 +276,33 @@ const PriceListTable = memo(const renderContextMenu = useCallback((row: PriceListRow) => {- const canEdit = permissions.can(- row.overrideId ? "update" : "create",- "sales"- );+ const canUpdate = permissions.can("update", "sales");return (<><MenuItem- disabled={!canEdit || !hasScope}+ disabled={!(row.overrideId ? canUpdate : canCreate) || !hasScope}onClick={() => {navigate(buildOverrideHref(row));}}><MenuIcon icon={row.overrideId ? <LuPencil /> : <LuPlus />} />- {row.overrideId ? t`Edit Override` : t`Create Override`}+ {row.overrideId ? t`Edit Pricing` : t`Set Pricing`}</MenuItem>+ {row.overrideId && (+ <MenuItem+ disabled={!canCreate}+ onClick={() => {+ setDuplicateState({ overrideIds: [row.overrideId!] });+ }}+ >+ <MenuIcon icon={<LuCopy />} />+ {t`Duplicate to...`}+ </MenuItem>+ )}{row.overrideId && (<MenuItemdestructive- disabled={!permissions.can("delete", "sales")}+ disabled={!canDelete}onClick={() => {navigate(`${path.to.deletePriceOverride(@@ -300,13 +312,21 @@ const PriceListTable = memo(}}><MenuIcon icon={<LuTrash />} />- {t`Delete Override`}+ {t`Remove from Price List`}</MenuItem>)}</>);},- [buildOverrideHref, hasScope, navigate, permissions, searchParams, t]+ [+ buildOverrideHref,+ canCreate,+ canDelete,+ hasScope,+ navigate,+ searchParams,+ t+ ]);if (!hasScope) {@@ -320,64 +340,82 @@ const PriceListTable = memo(}return (- <Table<PriceListRow>- data={data}- columns={columns}- count={count}- primaryAction={- <div className="flex items-center gap-2">- <ScopePicker- size="sm"- value={scopeId}- options={scopeOptions}- onChange={handleScopeChange}- />- <Popover>- <PopoverTrigger asChild>- <Button variant="secondary" rightIcon={<LuChevronsUpDown />}>- {Number(previewQuantity) || 1}- </Button>- </PopoverTrigger>- <PopoverContent className="w-auto p-2" align="end">- <Label>- <Trans>Quantity</Trans>- </Label>- <NumberField- value={Number(previewQuantity) || 1}- minValue={1}- onChange={(value) => {- if (Number.isFinite(value) && value >= 1) {- handleQuantityCommit(String(value));- }- }}- aria-label={t`Preview Quantity`}- className="w-24"- >- <NumberInputGroup className="relative">- <NumberInput size="sm" min={1} />- <NumberInputStepper>- <NumberIncrementStepper>- <LuChevronUp size="1em" strokeWidth="3" />- </NumberIncrementStepper>- <NumberDecrementStepper>- <LuChevronDown size="1em" strokeWidth="3" />- </NumberDecrementStepper>- </NumberInputStepper>- </NumberInputGroup>- </NumberField>- </PopoverContent>- </Popover>- {permissions.can("create", "sales") && (- <New- label={t`Override`}- to={`${path.to.newPriceOverride}?${searchParams.toString()}`}+ <>+ <Table<PriceListRow>+ data={data}+ columns={columns}+ count={count}+ primaryAction={+ <div className="flex items-center gap-2">+ <ScopePicker+ size="sm"+ value={scopeId}+ options={scopeOptions}+ onChange={handleScopeChange}/>- )}- </div>- }- renderContextMenu={renderContextMenu}- title={t`Price List`}- />+ <Popover>+ <PopoverTrigger asChild>+ <Button variant="secondary" rightIcon={<LuChevronsUpDown />}>+ {Number(previewQuantity) || 1}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-auto p-2" align="end">+ <Label>+ <Trans>Quantity</Trans>+ </Label>+ <NumberField+ value={Number(previewQuantity) || 1}+ minValue={1}+ onChange={(value) => {+ if (Number.isFinite(value) && value >= 1) {+ handleQuantityCommit(String(value));+ }+ }}+ aria-label={t`Preview Quantity`}+ className="w-24"+ >+ <NumberInputGroup className="relative">+ <NumberInput size="sm" min={1} />+ <NumberInputStepper>+ <NumberIncrementStepper>+ <LuChevronUp size="1em" strokeWidth="3" />+ </NumberIncrementStepper>+ <NumberDecrementStepper>+ <LuChevronDown size="1em" strokeWidth="3" />+ </NumberDecrementStepper>+ </NumberInputStepper>+ </NumberInputGroup>+ </NumberField>+ </PopoverContent>+ </Popover>+ {data.length > 0 && canCreate && (+ <Button+ variant="secondary"+ leftIcon={<LuCopy />}+ onClick={() => setDuplicateState({})}+ >+ <Trans>Duplicate</Trans>+ </Button>+ )}+ {canCreate && (+ <New+ label={t`Item`}+ to={`${path.to.newPriceOverride}?${searchParams.toString()}`}+ />+ )}+ </div>+ }+ renderContextMenu={renderContextMenu}+ title={t`Price List`}+ />+ {duplicateState !== null && (+ <DuplicatePriceListModal+ sourceScope={sourceScope}+ overrideIds={duplicateState.overrideIds}+ onClose={() => setDuplicateState(null)}+ />+ )}+ </>);});diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsxindex aaa36af27a..9baa15e823 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx@@ -59,6 +59,9 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();+ const canCreate = permissions.can("create", "sales");+ const canUpdate = permissions.can("update", "sales");+ const canDelete = permissions.can("delete", "sales");const currencyFormatter = useCurrencyFormatter();const percentFormatter = usePercentFormatter();const fetcher = useFetcher();@@ -362,7 +365,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {return (<><MenuItem- disabled={!permissions.can("update", "sales")}+ disabled={!canUpdate}onClick={() => {navigate(`${path.to.pricingRule(row.id)}?${params.toString()}`);}}@@ -371,7 +374,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {{t`Edit Pricing Rule`}</MenuItem><MenuItem- disabled={!permissions.can("create", "sales")}+ disabled={!canCreate}onClick={() => {fetcher.submit({ intent: "duplicate" },@@ -387,7 +390,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {</MenuItem><MenuItemdestructive- disabled={!permissions.can("delete", "sales")}+ disabled={!canDelete}onClick={() => {navigate(`${path.to.deletePricingRule(row.id)}?${params.toString()}`@@ -400,7 +403,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {</>);},- [fetcher, navigate, params, permissions, t]+ [canCreate, canDelete, canUpdate, fetcher, navigate, params, t]);return (@@ -410,7 +413,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {count={count}defaultColumnVisibility={defaultColumnVisibility}primaryAction={- permissions.can("create", "sales") && (+ canCreate && (<Newlabel={t`Pricing Rule`}to={`${path.to.newPricingRule}?${params.toString()}`}diff --git a/apps/erp/app/modules/sales/ui/Pricing/ScopePicker.tsx b/apps/erp/app/modules/sales/ui/Pricing/ScopePicker.tsxindex 687fcea67e..61a2075ef1 100644--- a/apps/erp/app/modules/sales/ui/Pricing/ScopePicker.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/ScopePicker.tsx@@ -14,14 +14,12 @@ import {import { useLingui } from "@lingui/react/macro";import type { ComponentType } from "react";import { useMemo, useState } from "react";-import { LuCheck, LuGlobe, LuSquareUser, LuUsers } from "react-icons/lu";--export const ALL_CUSTOMERS_SCOPE = "all";+import { LuCheck, LuSquareUser, LuUsers } from "react-icons/lu";export type ScopeOption = {value: string;label: string;- helper: "Type" | "Customer" | "All";+ helper: "Type" | "Customer";};type ScopePickerProps = {@@ -39,7 +37,6 @@ const ScopeIcon = ({helper: ScopeOption["helper"];className?: string;}) => {- if (helper === "All") return <LuGlobe className={className} />;if (helper === "Type") return <LuUsers className={className} />;return <LuSquareUser className={className} />;};@@ -59,23 +56,17 @@ export function ScopePicker({setOpen(false);};- const { allOption, types, customers, selected } = useMemo(() => {- const allOption: ScopeOption = {- value: ALL_CUSTOMERS_SCOPE,- label: t`All Customers`,- helper: "All"- };+ const { types, customers, selected } = useMemo(() => {const types: ScopeOption[] = [];const customers: ScopeOption[] = [];- let selected: ScopeOption | undefined =- value === ALL_CUSTOMERS_SCOPE ? allOption : undefined;+ let selected: ScopeOption | undefined;for (const o of options) {if (o.value === value) selected = o;if (o.helper === "Type") types.push(o);else if (o.helper === "Customer") customers.push(o);}- return { allOption, types, customers, selected };- }, [options, value, t]);+ return { types, customers, selected };+ }, [options, value]);return (<Popover open={open} onOpenChange={setOpen}>@@ -84,7 +75,10 @@ export function ScopePicker({asButtonsize={size}role="combobox"- className={cn("min-w-[220px]", !value && "text-muted-foreground")}+ className={cn(+ "min-w-[220px] hover:!scale-100 focus-visible:!scale-100",+ !value && "text-muted-foreground"+ )}>{selected ? (<div className="flex items-center gap-2 truncate">@@ -111,16 +105,6 @@ export function ScopePicker({className="h-9"/><CommandList className="max-h-[320px]">- <CommandGroup>- <ScopeItem- option={allOption}- selected={value === ALL_CUSTOMERS_SCOPE}- onSelect={select}- />- </CommandGroup>-- {types.length > 0 && <CommandSeparator className="my-1" />}-{types.length > 0 && (<CommandGroupheading={@@ -194,12 +178,6 @@ function ScopeItem({value={`${option.label} ${option.helper} ${option.value}`}onSelect={() => onSelect(option.value)}>- {option.helper === "All" && (- <ScopeIcon- helper="All"- className="mr-2 size-3.5 shrink-0 text-muted-foreground"- />- )}<span className="flex-1 truncate">{option.label}</span><LuCheckclassName={cn("ml-2 size-4", selected ? "opacity-100" : "opacity-0")}diff --git a/apps/erp/app/routes/x+/sales+/price-list.delete.$overrideId.tsx b/apps/erp/app/routes/x+/sales+/price-list.delete.$overrideId.tsxindex e72cd8b022..e654a32046 100644--- a/apps/erp/app/routes/x+/sales+/price-list.delete.$overrideId.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.delete.$overrideId.tsx@@ -91,7 +91,7 @@ export default function DeletePriceOverrideRoute() {<ConfirmDeleteaction={path.to.deletePriceOverride(overrideId)}name={name}- text={t`Are you sure you want to delete this price override? This cannot be undone.`}+ text={t`Are you sure you want to remove this item from the price list? This cannot be undone.`}onCancel={() => navigate(path.to.salesPriceList)}/>);diff --git a/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsx b/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsxnew file mode 100644index 0000000000..5406add2cb--- /dev/null+++ b/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsx@@ -0,0 +1,79 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { duplicatePriceOverrides } from "~/modules/sales";+import { getParams, path } from "~/utils/path";++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "sales"+ });++ const formData = await request.formData();+ const sourceCustomerId =+ (formData.get("sourceCustomerId") as string) || undefined;+ const sourceCustomerTypeId =+ (formData.get("sourceCustomerTypeId") as string) || undefined;+ const targetCustomerId =+ (formData.get("targetCustomerId") as string) || undefined;+ const targetCustomerTypeId =+ (formData.get("targetCustomerTypeId") as string) || undefined;+ const conflictStrategy =+ (formData.get("conflictStrategy") as "skip" | "overwrite") || "skip";++ let overrideIds: string[] | undefined;+ const overrideIdsRaw = formData.get("overrideIds") as string;+ if (overrideIdsRaw) {+ try {+ overrideIds = JSON.parse(overrideIdsRaw);+ } catch {+ // ignore parse error+ }+ }++ if (!targetCustomerId && !targetCustomerTypeId) {+ throw redirect(+ `${path.to.salesPriceList}?${getParams(request)}`,+ await flash(request, error(null, "Please select a target scope"))+ );+ }++ const result = await duplicatePriceOverrides(+ client,+ companyId,+ userId,+ {+ customerId: sourceCustomerId,+ customerTypeId: sourceCustomerTypeId+ },+ {+ customerId: targetCustomerId,+ customerTypeId: targetCustomerTypeId+ },+ { overrideIds, conflictStrategy }+ );++ if (result.error) {+ throw redirect(+ `${path.to.salesPriceList}?${getParams(request)}`,+ await flash(+ request,+ error(result.error, "Failed to duplicate price list")+ )+ );+ }++ const parts = [];+ if (result.duplicated > 0) parts.push(`${result.duplicated} duplicated`);+ if (result.skipped > 0) parts.push(`${result.skipped} skipped`);+ if (result.overwritten > 0) parts.push(`${result.overwritten} overwritten`);+ const message = parts.length > 0 ? parts.join(", ") : "Nothing to duplicate";++ throw redirect(+ `${path.to.salesPriceList}?${getParams(request)}`,+ await flash(request, success(message))+ );+}diff --git a/apps/erp/app/routes/x+/sales+/price-list.new.tsx b/apps/erp/app/routes/x+/sales+/price-list.new.tsxindex 3c03dc89b8..f8999f17a5 100644--- a/apps/erp/app/routes/x+/sales+/price-list.new.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.new.tsx@@ -11,20 +11,23 @@ import {upsertCustomerItemPriceOverride} from "~/modules/sales";import PriceOverrideForm from "~/modules/sales/ui/Pricing/PriceOverrideForm";-import { ALL_CUSTOMERS_SCOPE } from "~/modules/sales/ui/Pricing/ScopePicker";import { getParams, path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, { create: "sales" });const url = new URL(request.url);- const customerScope = url.searchParams.get("customerScope");- const initialScope: "customer" | "customerType" | "all" | undefined =- customerScope === ALL_CUSTOMERS_SCOPE ? "all" : undefined;+ const customerId = url.searchParams.get("customerId") ?? undefined;+ const customerTypeId = url.searchParams.get("customerTypeId") ?? undefined;+ const initialScope: "customer" | "customerType" | undefined = customerId+ ? "customer"+ : customerTypeId+ ? "customerType"+ : undefined;return {initial: {- customerId: url.searchParams.get("customerId") ?? undefined,- customerTypeId: url.searchParams.get("customerTypeId") ?? undefined,+ customerId,+ customerTypeId,itemId: url.searchParams.get("itemId") ?? "",validFrom:url.searchParams.get("validFrom") ??diff --git a/apps/erp/app/routes/x+/sales+/price-list.tsx b/apps/erp/app/routes/x+/sales+/price-list.tsxindex f7747f5e7c..39f8606d5f 100644--- a/apps/erp/app/routes/x+/sales+/price-list.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.tsx@@ -4,7 +4,6 @@ import type { LoaderFunctionArgs } from "react-router";import { Outlet, useLoaderData } from "react-router";import { getBaseCatalog, resolvePriceList } from "~/modules/sales";import PriceListTable from "~/modules/sales/ui/Pricing/PriceOverridesTable";-import { ALL_CUSTOMERS_SCOPE } from "~/modules/sales/ui/Pricing/ScopePicker";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -25,9 +24,6 @@ export async function loader({ request }: LoaderFunctionArgs) {const search = searchParams.get("search");const customerId = searchParams.get("customerId");const customerTypeId = searchParams.get("customerTypeId");- const customerScope = searchParams.get("customerScope");- const allCustomers = customerScope === ALL_CUSTOMERS_SCOPE;- const onlyOverrides = searchParams.get("onlyOverrides") === "true";const rawQuantity = Number(searchParams.get("quantity") ?? "1");const quantity =Number.isFinite(rawQuantity) && rawQuantity >= 0 ? rawQuantity : 1;@@ -42,35 +38,31 @@ export async function loader({ request }: LoaderFunctionArgs) {.order("isCustomerTypeGroup", { ascending: false }).order("name");- const hasSpecificScope = Boolean(customerId || customerTypeId);- const listPromise =- hasSpecificScope || allCustomers- ? resolvePriceList(client, companyId, {- customerId: customerId ?? undefined,- customerTypeId: customerTypeId ?? undefined,- allCustomers,- quantity,- onlyOverrides,- search: search ?? undefined,- limit,- offset,- sorts,- filters- })- : getBaseCatalog(client, companyId, {- search: search ?? undefined,- limit,- offset,- sorts,- filters- });+ const hasScope = Boolean(customerId || customerTypeId);+ const listPromise = hasScope+ ? resolvePriceList(client, companyId, {+ customerId: customerId ?? undefined,+ customerTypeId: customerTypeId ?? undefined,+ quantity,+ search: search ?? undefined,+ limit,+ offset,+ sorts,+ filters+ })+ : getBaseCatalog(client, companyId, {+ search: search ?? undefined,+ limit,+ offset,+ sorts,+ filters+ });const [list, groupsResult] = await Promise.all([listPromise,groupOptionsQuery]);- // Drop the seed "All Customers" group — ScopePicker adds its own sentinel.const scopeOptions = (groupsResult.data ?? []).filter((g) => !g.id.startsWith("11111111-1111")).map((g) => ({@@ -85,7 +77,7 @@ export async function loader({ request }: LoaderFunctionArgs) {data: list.data ?? [],count: list.count ?? 0,scopeOptions,- hasScope: hasSpecificScope || allCustomers+ hasScope};}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 9631e3fb37..05a303eeb5 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1430,6 +1430,7 @@ export const path = {deletePriceOverride: (id: string) =>generatePath(`${x}/sales/price-list/delete/${id}`),newPriceOverride: `${x}/sales/price-list/new`,+ duplicatePriceList: `${x}/sales/price-list/duplicate`,priceOverride: (id: string) => generatePath(`${x}/sales/price-list/${id}`),salesPricingRules: `${x}/sales/pricing-rules`,pricingRule: (id: string) => generatePath(`${x}/sales/pricing-rules/${id}`),diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.tsindex 5567fe2e96..c2ea8f09b4 100644--- a/packages/database/src/audit.config.ts+++ b/packages/database/src/audit.config.ts@@ -270,10 +270,13 @@ export const auditConfig = {priceOverride: {label: "Price Override",tables: {- customerItemPriceOverride: { role: "root" },- customerItemPriceOverrideBreak: {- entityIdColumn: "customerItemPriceOverrideId"- }+ customerItemPriceOverride: { role: "root" }+ }+ },+ priceOverrideBreak: {+ label: "Quantity Break",+ tables: {+ customerItemPriceOverrideBreak: { role: "root" }}}} satisfies Record<string, EntityConfig>,diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 7f40f5122c..8c798fce2f 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -69160,6 +69160,63 @@ export default {tags: ["(rpc) get_period_start_date"],},},+ "/rpc/show_trgm": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "",+ required: true,+ type: "string",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) show_trgm"],+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ "": {+ format: "text",+ type: "string",+ },+ },+ required: [""],+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) show_trgm"],+ },+ },"/rpc/create_rfq_from_model_v1": {post: {parameters: [@@ -71865,6 +71922,47 @@ export default {tags: ["(rpc) has_valid_api_key_for_company"],},},+ "/rpc/show_limit": {+ get: {+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) show_limit"],+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ type: "object",+ },+ },+ {+ $ref: "#/parameters/preferParams",+ },+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json",+ ],+ responses: {+ "200": {+ description: "OK",+ },+ },+ tags: ["(rpc) show_limit"],+ },+ },"/rpc/search_company_index": {post: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 306cd9277c..06063bc443 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -58977,6 +58977,8 @@ export type Database = {title: string}[]}+ show_limit: { Args: never; Returns: number }+ show_trgm: { Args: { "": string }; Returns: string[] }storage_unit_block_location_change_with_children: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefineddiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 306cd9277c..06063bc443 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -58977,6 +58977,8 @@ export type Database = {title: string}[]}+ show_limit: { Args: never; Returns: number }+ show_trgm: { Args: { "": string }; Returns: string[] }storage_unit_block_location_change_with_children: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined