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
- comment fixes
Gaurav Bhatt1d5cb766de0f
diff --git a/apps/erp/app/components/Form/Customer.tsx b/apps/erp/app/components/Form/Customer.tsxindex 0863c29d0e..29f961b21b 100644--- a/apps/erp/app/components/Form/Customer.tsx+++ b/apps/erp/app/components/Form/Customer.tsx@@ -13,6 +13,7 @@ type CustomerSelectProps = Omit<"options" | "inline"> & {inline?: boolean;+ exclude?: string[];};const CustomerPreview = (@@ -29,14 +30,12 @@ const Customer = (props: CustomerSelectProps) => {const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- const options = useMemo(- () =>- customers.map((c) => ({- value: c.id,- label: c.name- })) ?? [],- [customers]- );+ const options = useMemo(() => {+ const all = customers.map((c) => ({ value: c.id, label: c.name }));+ return props.exclude?.length+ ? all.filter((o) => !props.exclude!.includes(o.value))+ : all;+ }, [customers, props.exclude]);const { company } = useUser();diff --git a/apps/erp/app/components/Form/CustomerType.tsx b/apps/erp/app/components/Form/CustomerType.tsxindex d227da9c70..df4b548533 100644--- a/apps/erp/app/components/Form/CustomerType.tsx+++ b/apps/erp/app/components/Form/CustomerType.tsx@@ -8,7 +8,9 @@ import type { getCustomerTypesList } from "~/modules/sales";import { CustomerTypeForm } from "~/modules/sales/ui/CustomerTypes";import { path } from "~/utils/path";-type CustomerTypeSelectProps = Omit<ComboboxProps, "options">;+type CustomerTypeSelectProps = Omit<ComboboxProps, "options"> & {+ exclude?: string[];+};const CustomerType = (props: CustomerTypeSelectProps) => {const newCustomerTypeModal = useDisclosure();@@ -21,12 +23,13 @@ const CustomerType = (props: CustomerTypeSelectProps) => {<><CreatableComboboxref={triggerRef}- options={- options.map((o) => ({- value: o.value,- label: <Enumerable value={o.label} />- })) ?? []- }+ options={(props.exclude?.length+ ? options.filter((o) => !props.exclude!.includes(o.value))+ : options+ ).map((o) => ({+ value: o.value,+ label: <Enumerable value={o.label} />+ }))}{...props}label={props?.label ?? "CustomerType"}onCreateOption={(option) => {diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex bf26852727..77b9080e70 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -181,14 +181,19 @@ 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 duplicatePriceListValidator = z+ .object({+ sourceCustomerId: zfd.text(z.string().optional()),+ sourceCustomerTypeId: zfd.text(z.string().optional()),+ targetCustomerId: zfd.text(z.string().optional()),+ targetCustomerTypeId: zfd.text(z.string().optional()),+ conflictStrategy: z.enum(["skip", "overwrite"]),+ overrideIds: zfd.text(z.string().optional())+ })+ .refine((d) => d.targetCustomerId || d.targetCustomerTypeId, {+ message: "Please select a target scope",+ path: ["targetCustomerId"]+ });export const priceResolutionInputValidator = z.object({itemId: z.string().min(1),diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.tsnew file mode 100644index 0000000000..f6044736c3--- /dev/null+++ b/apps/erp/app/modules/sales/sales.server.ts@@ -0,0 +1,173 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { getDatabaseClient } from "~/services/database.server";++type BreakRow = { quantity: number; overridePrice: number; active: boolean };++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 };+ }++ if (sourceOverrides.length === 0) {+ return { duplicated: 0, skipped: 0, overwritten: 0, error: null };+ }++ const strategy = options?.conflictStrategy ?? "skip";++ 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])+ );++ const db = getDatabaseClient();++ try {+ const result = await db.transaction().execute(async (trx) => {+ let duplicated = 0;+ let skipped = 0;+ let overwritten = 0;++ for (const src of sourceOverrides) {+ const breaks = ((src.breaks as BreakRow[] | 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;+ }++ let parentId: string;++ if (existingId) {+ await trx+ .updateTable("customerItemPriceOverride")+ .set({+ active: src.active,+ applyRulesOnTop: src.applyRulesOnTop ?? true,+ notes: src.notes ?? null,+ validFrom: src.validFrom ?? null,+ validTo: src.validTo ?? null,+ customerId: target.customerId ?? null,+ customerTypeId: target.customerTypeId ?? null,+ itemId: src.itemId,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .where("id", "=", existingId)+ .where("companyId", "=", companyId)+ .execute();++ await trx+ .deleteFrom("customerItemPriceOverrideBreak")+ .where("customerItemPriceOverrideId", "=", existingId)+ .where("companyId", "=", companyId)+ .execute();++ parentId = existingId;+ overwritten++;+ } else {+ const [row] = await trx+ .insertInto("customerItemPriceOverride")+ .values({+ companyId,+ createdBy: userId,+ itemId: src.itemId,+ customerId: target.customerId ?? null,+ customerTypeId: target.customerTypeId ?? null,+ active: src.active,+ applyRulesOnTop: src.applyRulesOnTop ?? true,+ notes: src.notes ?? null,+ validFrom: src.validFrom ?? null,+ validTo: src.validTo ?? null+ })+ .returning("id")+ .execute();++ parentId = row.id;+ duplicated++;+ }++ await trx+ .insertInto("customerItemPriceOverrideBreak")+ .values(+ breaks.map((b) => ({+ customerItemPriceOverrideId: parentId,+ companyId,+ createdBy: userId,+ quantity: b.quantity,+ overridePrice: b.overridePrice,+ active: b.active+ }))+ )+ .execute();+ }++ return { duplicated, skipped, overwritten };+ });++ return { ...result, error: null };+ } catch (e) {+ return { duplicated: 0, skipped: 0, overwritten: 0, error: e };+ }+}diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 908c42717c..0670dc3f68 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -2248,6 +2248,8 @@ export async function resolvePriceList(scopeQuery = scopeQuery.eq("customerId", args.customerId);} else if (args.customerTypeId) {scopeQuery = scopeQuery.eq("customerTypeId", args.customerTypeId);+ } else {+ return { data: [], count: 0 };}const { data: scopedOverrides } = await scopeQuery;@@ -2824,126 +2826,6 @@ 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.tsxindex 8d95493fb3..dce93eb955 100644--- a/apps/erp/app/modules/sales/ui/Pricing/DuplicatePriceListModal.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/DuplicatePriceListModal.tsx@@ -113,7 +113,15 @@ export function DuplicatePriceListModal({{scopeType === "customer" && (<>- <Customer name="targetCustomerId" label={t`Customer`} />+ <Customer+ name="targetCustomerId"+ label={t`Customer`}+ exclude={+ sourceScope.customerId+ ? [sourceScope.customerId]+ : undefined+ }+ /><Hidden name="targetCustomerTypeId" value="" /></>)}@@ -123,6 +131,11 @@ export function DuplicatePriceListModal({<CustomerTypename="targetCustomerTypeId"label={t`Customer Type`}+ exclude={+ sourceScope.customerTypeId+ ? [sourceScope.customerTypeId]+ : undefined+ }/><Hidden name="targetCustomerId" value="" /></>diff --git a/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsx b/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsxindex 5406add2cb..becaf6dd2e 100644--- a/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.duplicate.tsx@@ -1,9 +1,12 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { duplicatePriceOverrides } from "~/modules/sales";+import { z } from "zod";+import { duplicatePriceListValidator } from "~/modules/sales";+import { duplicatePriceOverrides } from "~/modules/sales/sales.server";import { getParams, path } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -13,34 +16,36 @@ export async function action({ request }: ActionFunctionArgs) {});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";+ const validation = await validator(duplicatePriceListValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ sourceCustomerId,+ sourceCustomerTypeId,+ targetCustomerId,+ targetCustomerTypeId,+ conflictStrategy+ } = validation.data;let overrideIds: string[] | undefined;- const overrideIdsRaw = formData.get("overrideIds") as string;- if (overrideIdsRaw) {+ if (validation.data.overrideIds) {try {- overrideIds = JSON.parse(overrideIdsRaw);+ const parsed = z+ .array(z.string())+ .parse(JSON.parse(validation.data.overrideIds));+ overrideIds = parsed.length ? parsed : undefined;} catch {- // ignore parse error+ return validationError({+ fieldErrors: { overrideIds: "Invalid override IDs" }+ });}}- 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,diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.tsindex c2ea8f09b4..d3c438bc4e 100644--- a/packages/database/src/audit.config.ts+++ b/packages/database/src/audit.config.ts@@ -270,11 +270,15 @@ export const auditConfig = {priceOverride: {label: "Price Override",tables: {- customerItemPriceOverride: { role: "root" }+ customerItemPriceOverride: { role: "root" },+ customerItemPriceOverrideBreak: {+ entityIdColumn: "customerItemPriceOverrideId"+ }}},+priceOverrideBreak: {- label: "Quantity Break",+ label: "Price Override Break",tables: {customerItemPriceOverrideBreak: { role: "root" }}