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
fix(production): let a job re-link to a sales order line from the Target field (#1258)
Siddharth Gaikwada7533fa9cfa6
diff --git a/apps/erp/app/components/Form/JobSalesOrderLine.tsx b/apps/erp/app/components/Form/JobSalesOrderLine.tsxnew file mode 100644index 0000000000..75030db3b7--- /dev/null+++ b/apps/erp/app/components/Form/JobSalesOrderLine.tsx@@ -0,0 +1,108 @@+/**+ * `<JobSalesOrderLine>` — picks a sales order line to link a job to. Lists only+ * lines whose item matches the job's item, on sales orders that are still open+ * (not Completed/Invoiced/Cancelled/Closed). Backed by the per-job endpoint+ * `api/production/job/:jobId/sales-order-lines`.+ *+ * Form-bound like the other property selectors: render it inside a+ * `ValidatedForm` and give it a `name`.+ */++import type { ComboboxProps } from "@carbon/form";+import { Combobox, FieldEmptyState } from "@carbon/form";+import { useLingui } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { useEffect, useMemo } from "react";+import { useFetcher } from "react-router";+import type { getOpenSalesOrderLinesForItem } from "~/modules/sales";+import { useCustomers } from "~/stores";+import { path } from "~/utils/path";++type OpenSalesOrderLine = NonNullable<+ Awaited<ReturnType<typeof getOpenSalesOrderLinesForItem>>["data"]+>[number];++type JobSalesOrderLineProps = Omit<+ ComboboxProps,+ "options" | "onChange" | "inline"+> & {+ jobId: string;+ /** Render a compact inline preview (property panels) once a value is set. */+ inline?: boolean;+ onChange?: (line: OpenSalesOrderLine | null) => void;+};++const salesOrderLinePreview = (+ value: string,+ options: { value: string; label: ReactNode; helper?: string }[]+) => {+ const match = options.find((o) => o.value === value);+ return <span className="text-sm">{match?.label ?? ""}</span>;+};++const JobSalesOrderLine = ({+ jobId,+ inline,+ onChange,+ ...props+}: JobSalesOrderLineProps) => {+ const { t } = useLingui();+ const [customers] = useCustomers();++ const fetcher =+ useFetcher<Awaited<ReturnType<typeof getOpenSalesOrderLinesForItem>>>();++ // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity is stable+ useEffect(() => {+ if (jobId) fetcher.load(path.to.api.jobSalesOrderLines(jobId));+ }, [jobId]);++ const lines = fetcher.data?.data ?? [];++ const customerNameById = useMemo(() => {+ const map = new Map<string, string>();+ for (const customer of customers) map.set(customer.id, customer.name);+ return map;+ }, [customers]);++ const options = useMemo(+ () =>+ lines.map((line) => {+ const customerName = line.salesOrder?.customerId+ ? customerNameById.get(line.salesOrder.customerId)+ : undefined;+ const quantity =+ line.saleQuantity != null ? `Qty ${line.saleQuantity}` : undefined;+ const helper = [customerName, quantity].filter(Boolean).join(" · ");+ return {+ value: line.id,+ label: line.salesOrder?.salesOrderId ?? line.id,+ helper: helper || undefined+ };+ }),+ [lines, customerNameById]+ );++ return (+ <Combobox+ options={options}+ {...props}+ label={props.label ?? t`Target`}+ placeholder={props.placeholder ?? t`Link to sales order line`}+ emptyMessage={+ props.emptyMessage ?? (+ <FieldEmptyState+ title={t`No open sales order lines`}+ description={t`No open orders for this item are available to link.`}+ />+ )+ }+ inline={inline ? salesOrderLinePreview : undefined}+ onChange={(option) =>+ onChange?.(lines.find((line) => line.id === option?.value) ?? null)+ }+ />+ );+};++export default JobSalesOrderLine;diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.tsindex 3e4ebd3d6b..cc18726ade 100644--- a/apps/erp/app/components/Form/index.ts+++ b/apps/erp/app/components/Form/index.ts@@ -55,6 +55,7 @@ import InspectionDocument from "./InspectionDocument";import Item, { useConfigurableItems } from "./Item";import ItemPostingGroup from "./ItemPostingGroup";import Items from "./Items";+import JobSalesOrderLine from "./JobSalesOrderLine";import Location from "./Location";import MaterialType from "./MaterialType";import Part from "./Part";@@ -135,6 +136,7 @@ export {Item,ItemPostingGroup,Items,+ JobSalesOrderLine,useConfigurableItems,Location,MaterialType,diff --git a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsxindex 353c2605b9..b51dace527 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx@@ -41,6 +41,7 @@ import {import {Customer,Item,+ JobSalesOrderLine,Location,StorageUnit,Tags,@@ -324,26 +325,46 @@ const JobProperties = () => {</HStack></VStack>) : (- <ValidatedForm- defaultValues={{- storageUnitId: routeData?.job?.storageUnitId ?? undefined- }}- validator={z.object({- storageUnitId: zfd.text(z.string().optional())- })}- className="w-full"- >- <StorageUnit- label={t`Target`}- name="storageUnitId"- inline- locationId={routeData?.job?.locationId ?? undefined}- isReadOnly={isDisabled}- onChange={(value) => {- onUpdate("storageUnitId", value?.id ?? null);+ <>+ <ValidatedForm+ defaultValues={{ salesOrderLineId: undefined }}+ validator={z.object({+ salesOrderLineId: zfd.text(z.string().optional())+ })}+ className="w-full"+ >+ <JobSalesOrderLine+ jobId={jobId}+ name="salesOrderLineId"+ label={t`Target`}+ inline+ isReadOnly={isDisabled}+ onChange={(line) => {+ onUpdate("salesOrderLineId", line?.id ?? null);+ }}+ />+ </ValidatedForm>+ <ValidatedForm+ defaultValues={{+ storageUnitId: routeData?.job?.storageUnitId ?? undefined}}- />- </ValidatedForm>+ validator={z.object({+ storageUnitId: zfd.text(z.string().optional())+ })}+ className="w-full"+ >+ <StorageUnit+ label={t`Storage Unit`}+ name="storageUnitId"+ inline+ locationId={routeData?.job?.locationId ?? undefined}+ isReadOnly={isDisabled}+ onChange={(value) => {+ onUpdate("storageUnitId", value?.id ?? null);+ }}+ />+ </ValidatedForm>+ </>)}<Assigneediff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.mdindex 1fbfff1bed..411d5c0f96 100644--- a/apps/erp/app/modules/sales/AGENTS.md+++ b/apps/erp/app/modules/sales/AGENTS.md@@ -62,6 +62,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=sales- `closeSalesOrder` / `releaseSalesOrder` / `finalizeQuote` — status transitions- `getQuote` / `getQuoteLines` / `getQuoteLinePrices` / `getQuoteMaterials` / `getQuoteOperations` — quote reads- `getSalesOrder(s)` / `getSalesOrderLines` / `getExternalSalesOrderLines` — order reads+- `getOpenSalesOrderLinesForItem` — sales order lines a job can link to (open orders, matching item); `isSalesOrderClosed` / `OPEN_SALES_ORDER_STATUSES` gate eligibility- `getCustomer(s)` / `getCustomerContacts` / `getCustomerLocations` — customer reads- `getPricingRules` / `createPricingRule` / `duplicatePricingRule` — rule management- `getOpportunity` / `getOpportunityDocuments` — deal trackingdiff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex ad66a3a1fa..d213a46333 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -684,6 +684,31 @@ export const salesOrderStatusType = ["Closed"] as const;+// Sales orders in these statuses can still receive/fulfill a job — i.e. a job+// may be linked to one of their lines. The terminal statuses (Completed,+// Invoiced, Cancelled, Closed) are excluded. Used when offering sales order+// lines to link a job to (see getOpenSalesOrderLinesForItem).+export const OPEN_SALES_ORDER_STATUSES = [+ "Draft",+ "Needs Approval",+ "Confirmed",+ "In Progress",+ "To Ship and Invoice",+ "To Ship",+ "To Invoice"+] as const;++/**+ * True for terminal statuses (Completed, Invoiced, Cancelled, Closed) — and for+ * null/unknown — i.e. sales orders a job should not be (re)linked to. Inverse of+ * OPEN_SALES_ORDER_STATUSES.+ */+export function isSalesOrderClosed(status: string | null | undefined): boolean {+ return !OPEN_SALES_ORDER_STATUSES.includes(+ status as (typeof OPEN_SALES_ORDER_STATUSES)[number]+ );+}+export const salesConfirmValidator = z.object({notification: z.enum(["Email", "None"]).optional(),diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 4728daa501..b07d6e316e 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -56,7 +56,7 @@ import type {salesRfqValidator,selectedLinesValidator} from "./sales.models";-import { costCategoryKeys } from "./sales.models";+import { costCategoryKeys, OPEN_SALES_ORDER_STATUSES } from "./sales.models";import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";import type {MatchedRule,@@ -1739,6 +1739,28 @@ export async function getSalesOrderLinesByItemId(.order("createdAt", { ascending: false });}+/**+ * Sales order lines eligible for a job to link to: lines whose item matches the+ * job's item, on sales orders that are still open (not Completed/Invoiced/+ * Cancelled/Closed). Joins the base salesOrder header so we can filter on its+ * status (the salesOrderLines view only exposes the line-level status).+ */+export async function getOpenSalesOrderLinesForItem(+ client: SupabaseClient<Database>,+ companyId: string,+ itemId: string+) {+ return client+ .from("salesOrderLine")+ .select(+ "id, saleQuantity, salesOrderLineType, salesOrder!inner(id, salesOrderId, customerId, status)"+ )+ .eq("companyId", companyId)+ .eq("itemId", itemId)+ .in("salesOrder.status", [...OPEN_SALES_ORDER_STATUSES])+ .order("createdAt", { ascending: false });+}+export async function getSalesOrderLinesByItemIds(client: SupabaseClient<Database>,itemIds: string[]diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsxindex bccbdb71f2..bd7ab14828 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx@@ -4,13 +4,7 @@ import { Combobox, ValidatedForm } from "@carbon/form";import {Badge,Select as CarbonSelect,- CardAction,cn,- DropdownMenu,- DropdownMenuContent,- DropdownMenuIcon,- DropdownMenuItem,- DropdownMenuTrigger,FormControl,FormLabel,HStack,@@ -43,13 +37,11 @@ import {import { getItemReadableId } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useState } from "react";-import { BsThreeDotsVertical } from "react-icons/bs";import {LuBox,LuChevronRight,LuLandmark,LuPlus,- LuTrash,LuTruck} from "react-icons/lu";import { useParams } from "react-router";@@ -86,11 +78,9 @@ import {import type {PriceTraceStep,SalesOrder,- SalesOrderLine,SalesOrderLineType} from "../../types";import { PriceTracePopover } from "../Pricing/PriceTracePopover";-import DeleteSalesOrderLine from "./DeleteSalesOrderLine";type SalesOrderLineFormProps = {initialValues: z.infer<typeof salesOrderLineValidator> & {@@ -425,7 +415,6 @@ const SalesOrderLineForm = ({const costsDisclosure = useDisclosure();const assetCostsDisclosure = useDisclosure();- const deleteDisclosure = useDisclosure();return (<>@@ -545,30 +534,6 @@ const SalesOrderLineForm = ({</TabsTrigger></TabsList>)}- {isEditing &&- permissions.can("update", "sales") &&- !isLocked && (- <CardAction>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- icon={<BsThreeDotsVertical />}- aria-label={t`More`}- variant="ghost"- />- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- destructive- onClick={deleteDisclosure.onOpen}- >- <DropdownMenuIcon icon={<LuTrash />} />- <Trans>Delete Line</Trans>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </CardAction>- )}</div></HStack><ModalCardBody>@@ -1093,12 +1058,6 @@ const SalesOrderLineForm = ({</ModalCard></ModalCardProvider></Tabs>- {isEditing && deleteDisclosure.isOpen && (- <DeleteSalesOrderLine- line={initialValues as SalesOrderLine}- onCancel={deleteDisclosure.onClose}- />- )}</>);};diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 07b714bda4..ea69fad33c 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-07-28T08:32:59.708Z",+ "generated": "2026-07-28T19:19:08.201Z","totalTools": 1397,"modules": 15,"tools": [@@ -35613,6 +35613,32 @@]}},+ {+ "name": "sales_getOpenSalesOrderLinesForItem",+ "module": "sales",+ "classification": "READ",+ "description": "get open sales order lines for item",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "itemId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "itemId": {+ "type": "string"+ }+ },+ "required": [+ "itemId"+ ]+ }+ },{"name": "sales_getSalesOrderLinesByItemIds","module": "sales",diff --git a/apps/erp/app/routes/api+/production.job.$jobId.sales-order-lines.ts b/apps/erp/app/routes/api+/production.job.$jobId.sales-order-lines.tsnew file mode 100644index 0000000000..53d2505061--- /dev/null+++ b/apps/erp/app/routes/api+/production.job.$jobId.sales-order-lines.ts@@ -0,0 +1,62 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getOpenSalesOrderLinesForItem } from "~/modules/sales";++/**+ * Sales order lines a job can be linked to: open/draft orders whose line item+ * matches this job's item. Consumed by the JobSalesOrderLine picker.+ *+ * A genuinely absent or item-less job returns an empty list, but real query+ * failures are surfaced via flash (never masked as "no lines"), and the payload+ * never leaks the raw PostgREST error.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "production"+ });++ const { jobId } = params;+ if (!jobId) {+ return { data: [], error: null };+ }++ const job = await client+ .from("job")+ .select("itemId")+ .eq("id", jobId)+ .eq("companyId", companyId)+ .maybeSingle();++ if (job.error) {+ return data(+ { data: [], error: null },+ await flash(request, error(job.error, "Failed to load job"))+ );+ }++ // Job genuinely absent or item-less: there is nothing to link to.+ if (!job.data?.itemId) {+ return { data: [], error: null };+ }++ const lines = await getOpenSalesOrderLinesForItem(+ client,+ companyId,+ job.data.itemId+ );++ if (lines.error) {+ return data(+ { data: [], error: null },+ await flash(+ request,+ error(lines.error, "Failed to get sales order lines")+ )+ );+ }++ return lines;+}diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsxindex 2b559d3b33..ed25a77e67 100644--- a/apps/erp/app/routes/x+/job+/update.tsx+++ b/apps/erp/app/routes/x+/job+/update.tsx@@ -9,6 +9,7 @@ import {recalculateJobRequirements,upsertJobMethod} from "~/modules/production";+import { isSalesOrderClosed } from "~/modules/sales";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";const logger = getLogger("erp", "update");@@ -244,17 +245,61 @@ export async function action({ request }: ActionFunctionArgs) {case "salesOrderId":case "salesOrderLineId":if (!value) {+ // Unlink: clear the sales order + line (customerId is left as-is).return await client.from("job")- .update({ salesOrderId: null, salesOrderLineId: null })+ .update({+ salesOrderId: null,+ salesOrderLineId: null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ }).in("id", ids as string[]).eq("companyId", companyId);- } else {+ }++ // Linking is done via the line — resolve its order + customer from it.+ if (field !== "salesOrderLineId") {return {error: { message: `Invalid value: ${value} for field: ${field}` },data: null};}++ const salesOrderLine = await client+ .from("salesOrderLine")+ .select("id, salesOrderId, salesOrder(customerId, status)")+ .eq("id", value)+ .eq("companyId", companyId)+ .single();++ if (salesOrderLine.error || !salesOrderLine.data) {+ return {+ error: { message: "Sales order line not found" },+ data: null+ };+ }++ if (isSalesOrderClosed(salesOrderLine.data.salesOrder?.status)) {+ return {+ error: {+ message: "Cannot link a job to a completed or cancelled sales order"+ },+ data: null+ };+ }++ return await client+ .from("job")+ .update({+ salesOrderId: salesOrderLine.data.salesOrderId,+ salesOrderLineId: salesOrderLine.data.id,+ customerId: salesOrderLine.data.salesOrder?.customerId ?? null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[])+ .eq("companyId", companyId);default:return {error: { message: `Invalid field: ${field}` },diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex f6f394382e..8ba8c56977 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -120,6 +120,8 @@ export const path = {generatePath(`${api}/production/methods/${id}/bom.csv?withOperations=${withOperations}`),+ jobSalesOrderLines: (jobId: string) =>+ generatePath(`${api}/production/job/${jobId}/sales-order-lines`),jobs: `${api}/production/jobs`,kanban: (id: string) => generatePath(`${api}/kanban/${id}`),kanbanCollision: (id: string) =>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex c437f6b135..d01d840f8a 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -100058,7 +100058,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -100107,7 +100107,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 5ad6dbceb2..59aee79e71 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -66142,14 +66142,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69535,14 +69535,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70089,14 +70089,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 5ad6dbceb2..59aee79e71 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -66142,14 +66142,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69535,14 +69535,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -70089,14 +70089,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex be88ecdfc8..5fd062fca4 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -7213,6 +7213,9 @@ msgstr "Jira-Problem verknüpfen"msgid "Link Linear Issue"msgstr "Linear-Problem verknüpfen"+msgid "Link to sales order line"+msgstr "Mit Verkaufsauftragszeile verknüpfen"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Keine Notizen"msgid "No open invoices"msgstr "Keine offenen Rechnungen"+msgid "No open orders for this item are available to link."+msgstr "Für diesen Artikel sind keine offenen Bestellungen zum Verknüpfen verfügbar."++msgid "No open sales order lines"+msgstr "Keine offenen Verkaufsbestellpositionen"+msgid "No operations require picking at this location"msgstr "Keine Operationen erfordern Kommissionierung an diesem Standort"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Gelegenheit"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Optimiert für schnelle Vorschau — Downloads liefern immer die ursprüngliche hochgeladene Datei"msgid "Optional"msgstr "Optional"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Wechselkurs aktualisieren"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Miniaturansicht aus dem 3D-Modell neu generieren"msgid "Regenerating thumbnail…"msgstr "Miniaturansicht wird neu generiert…"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 52ba299ed0..8b9b6fc11e 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -7213,6 +7213,9 @@ msgstr "Link Jira Issue"msgid "Link Linear Issue"msgstr "Link Linear Issue"+msgid "Link to sales order line"+msgstr "Link to sales order line"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "No notes"msgid "No open invoices"msgstr "No open invoices"+msgid "No open orders for this item are available to link."+msgstr "No open orders for this item are available to link."++msgid "No open sales order lines"+msgstr "No open sales order lines"+msgid "No operations require picking at this location"msgstr "No operations require picking at this location"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex a2f2d702a6..09d6630a88 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -7213,6 +7213,9 @@ msgstr "Vincular problema de Jira"msgid "Link Linear Issue"msgstr "Vincular problema de Linear"+msgid "Link to sales order line"+msgstr "Vincular a una línea de orden de venta"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Sin notas"msgid "No open invoices"msgstr "Sin facturas abiertas"+msgid "No open orders for this item are available to link."+msgstr "No hay pedidos abiertos disponibles para este artículo."++msgid "No open sales order lines"+msgstr "Sin líneas de pedido de venta abiertas"+msgid "No operations require picking at this location"msgstr "No se requieren operaciones de picking en esta ubicación"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Oportunidad"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Optimizado para vistas previas rápidas — las descargas siempre sirven el archivo original cargado"msgid "Optional"msgstr "Opcional"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Actualizar tipo de cambio"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Regenerar miniatura del modelo 3D"msgid "Regenerating thumbnail…"msgstr "Regenerando miniatura…"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 4c94922cf2..151c52b0f4 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -7213,6 +7213,9 @@ msgstr "Lier un problème Jira"msgid "Link Linear Issue"msgstr "Lier un problème Linear"+msgid "Link to sales order line"+msgstr "Lier à la ligne de commande client"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Aucune note"msgid "No open invoices"msgstr "Aucune facture ouverte"+msgid "No open orders for this item are available to link."+msgstr "Aucune commande ouverte pour cet article n'est disponible pour la liaison."++msgid "No open sales order lines"+msgstr "Aucune ligne de commande client ouverte"+msgid "No operations require picking at this location"msgstr "Aucune opération ne nécessite de prélèvement à cet endroit"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Opportunité"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Optimisé pour les aperçus rapides — les téléchargements servent toujours le fichier d'origine téléchargé"msgid "Optional"msgstr "Facultatif"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Actualiser le taux de change"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Régénérer la miniature à partir du modèle 3D"msgid "Regenerating thumbnail…"msgstr "Régénération de la miniature en cours…"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 1cceaf5668..4a86924022 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -7213,6 +7213,9 @@ msgstr "Jira समस्या को लिंक करें"msgid "Link Linear Issue"msgstr "Linear समस्या को लिंक करें"+msgid "Link to sales order line"+msgstr "बिक्रय आदेश पंक्ति से लिंक करें"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "कोई नोट नहीं"msgid "No open invoices"msgstr "कोई खुले चालान नहीं"+msgid "No open orders for this item are available to link."+msgstr "इस आइटम के लिए लिंक करने के लिए कोई खुले ऑर्डर उपलब्ध नहीं हैं।"++msgid "No open sales order lines"+msgstr "कोई खुली बिक्रय ऑर्डर लाइनें नहीं"+msgid "No operations require picking at this location"msgstr "इस स्थान पर कोई भी ऑपरेशन पिकिंग की आवश्यकता नहीं है"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "अवसर"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "तेज़ पूर्वावलोकन के लिए अनुकूलित — डाउनलोड हमेशा मूल अपलोड की गई फ़ाइल देते हैं"msgid "Optional"msgstr "वैकल्पिक"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "विनिमय दर को ताज़ा करें"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "3D मॉडल से थंबनेल पुनः उत्पन्न करें"msgid "Regenerating thumbnail…"msgstr "थंबनेल को पुनः उत्पन्न किया जा रहा है…"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 6db617854a..bf5a72fd36 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -7213,6 +7213,9 @@ msgstr "Collega Problema Jira"msgid "Link Linear Issue"msgstr "Collega problema Linear"+msgid "Link to sales order line"+msgstr "Collega alla riga dell'ordine di vendita"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Nessuna nota"msgid "No open invoices"msgstr "Nessuna fattura aperta"+msgid "No open orders for this item are available to link."+msgstr "Nessun ordine aperto per questo articolo disponibile per il collegamento."++msgid "No open sales order lines"+msgstr "Nessuna riga di ordine di vendita aperta"+msgid "No operations require picking at this location"msgstr "Nessuna operazione richiede il prelievo in questa posizione"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Opportunità"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Ottimizzato per anteprime veloci — i download forniscono sempre il file originale caricato"msgid "Optional"msgstr "Facoltativo"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Aggiorna tasso di cambio"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Rigenerare la miniatura dal modello 3D"msgid "Regenerating thumbnail…"msgstr "Rigenerazione dell'anteprima…"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 60abbea595..f7f1ea9788 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -7213,6 +7213,9 @@ msgstr "Jira イシューをリンク"msgid "Link Linear Issue"msgstr "Linear イシューをリンク"+msgid "Link to sales order line"+msgstr "販売注文行へのリンク"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "ノートなし"msgid "No open invoices"msgstr "未処理の請求書がありません"+msgid "No open orders for this item are available to link."+msgstr "このアイテムにリンク可能なオープンオーダーはありません。"++msgid "No open sales order lines"+msgstr "オープンな販売注文行がありません"+msgid "No operations require picking at this location"msgstr "この場所でのピッキングが必要な操作はありません"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "機会"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "高速プレビューに最適化されています — ダウンロードは常にアップロードされたオリジナルファイルを提供します"msgid "Optional"msgstr "オプション"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "為替レートを更新"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "3Dモデルからサムネイルを再生成"msgid "Regenerating thumbnail…"msgstr "サムネイルを再生成中…"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex cc1f228f0b..935e9b8916 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -7213,6 +7213,9 @@ msgstr "Jira 이슈 연결"msgid "Link Linear Issue"msgstr "Linear 이슈 연결"+msgid "Link to sales order line"+msgstr "판매주문 라인에 연결"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "메모 없음"msgid "No open invoices"msgstr "미결 인보이스가 없습니다"+msgid "No open orders for this item are available to link."+msgstr "이 항목에 연결할 수 있는 미결 주문이 없습니다."++msgid "No open sales order lines"+msgstr "미결 판매주문 라인이 없습니다."+msgid "No operations require picking at this location"msgstr "이 위치에서 피킹이 필요한 공정작업이 없습니다"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "기회"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "빠른 미리보기에 최적화됨 — 다운로드는 항상 원본 업로드 파일을 제공합니다."msgid "Optional"msgstr "선택 사항"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "환율 새로고침"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "3D 모델에서 썸네일 재생성"msgid "Regenerating thumbnail…"msgstr "썸네일 재생성 중…"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex f530983520..c76b069566 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -7213,6 +7213,9 @@ msgstr "Połącz problem Jiry"msgid "Link Linear Issue"msgstr "Połącz problem Linear"+msgid "Link to sales order line"+msgstr "Połącz z linią zamówienia sprzedaży"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Brak notek"msgid "No open invoices"msgstr "Brak otwartych faktur"+msgid "No open orders for this item are available to link."+msgstr "Brak dostępnych otwartych zamówień dla tego produktu do powiązania."++msgid "No open sales order lines"+msgstr "Brak otwartych linii zamówień sprzedaży"+msgid "No operations require picking at this location"msgstr "Żadne operacje nie wymagają pobrania w tej lokalizacji"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Okazja"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Zoptymalizowane pod kątem szybkich podglądów — pobieranie zawsze dostarcza oryginalnie przesłany plik"msgid "Optional"msgstr "Opcjonalnie"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Odśwież kurs wymiany"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Ponownie wygeneruj miniaturę z modelu 3D"msgid "Regenerating thumbnail…"msgstr "Ponownie generowanie miniatury…"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 20e4ddaa1c..2c688a2e9c 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -7213,6 +7213,9 @@ msgstr "Vincular Problema do Jira"msgid "Link Linear Issue"msgstr "Vincular Problema Linear"+msgid "Link to sales order line"+msgstr "Vincular à linha do pedido de venda"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Sem notas"msgid "No open invoices"msgstr "Nenhuma fatura aberta"+msgid "No open orders for this item are available to link."+msgstr "Nenhum pedido aberto para este item está disponível para vincular."++msgid "No open sales order lines"+msgstr "Nenhuma linha de pedido de venda aberta"+msgid "No operations require picking at this location"msgstr "Nenhuma operação requer picking neste local"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Oportunidade"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Otimizado para visualizações rápidas — downloads sempre servem o arquivo original enviado"msgid "Optional"msgstr "Opcional"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Atualizar taxa de câmbio"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Regenerar miniatura do modelo 3D"msgid "Regenerating thumbnail…"msgstr "Regenerando miniatura…"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 7e44486bdb..29a5b4f424 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -7213,6 +7213,9 @@ msgstr "Связать проблему Jira"msgid "Link Linear Issue"msgstr "Связать проблему Linear"+msgid "Link to sales order line"+msgstr "Связать со строкой заказа на продажу"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Нет заметок"msgid "No open invoices"msgstr "Нет открытых счетов"+msgid "No open orders for this item are available to link."+msgstr "Нет открытых заказов для этого товара, доступных для связи."++msgid "No open sales order lines"+msgstr "Нет открытых строк заказа продажи"+msgid "No operations require picking at this location"msgstr "На этом месте нет операций, требующих комплектации"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Возможность"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Оптимизировано для быстрого предпросмотра — загрузки всегда предоставляют исходный загруженный файл"msgid "Optional"msgstr "Опционально"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Обновить курс обмена"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "Восстановить миниатюру из 3D модели"msgid "Regenerating thumbnail…"msgstr "Создание миниатюры…"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex d5b0657f26..9c80de0cea 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -7213,6 +7213,9 @@ msgstr "Jira Sorununu Bağla"msgid "Link Linear Issue"msgstr "Linear sorununu bağla"+msgid "Link to sales order line"+msgstr "Satış siparişi satırına bağla"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "Notlar yok"msgid "No open invoices"msgstr "Açık fatura yok"+msgid "No open orders for this item are available to link."+msgstr "Bu öğe için bağlanacak açık siparişler mevcut değil."++msgid "No open sales order lines"+msgstr "Açık satış sipariş satırı yok"+msgid "No operations require picking at this location"msgstr "Bu konumda toplama gerektiren işlem yok"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "Fırsat"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "Hızlı önizlemeler için optimize edildi — indirmeler her zaman yüklenen orijinal dosyayı sunar"msgid "Optional"msgstr "İsteğe bağlı"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "Döviz kurunu yenile"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "3D modelinden küçük resmi yeniden oluştur"msgid "Regenerating thumbnail…"msgstr "Küçük resim yenileniyor…"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex cffd866212..227aea4711 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -7213,6 +7213,9 @@ msgstr "关联 Jira 问题"msgid "Link Linear Issue"msgstr "关联 Linear 问题"+msgid "Link to sales order line"+msgstr "关联销售订单行"+#. placeholder {0}: r.linkedSum#. placeholder {1}: r.quantitymsgid "Linked entity quantity ({0}) does not match row quantity ({1})."@@ -8476,6 +8479,12 @@ msgstr "没有备注"msgid "No open invoices"msgstr "没有未结发票"+msgid "No open orders for this item are available to link."+msgstr "此项目没有可链接的未结订单。"++msgid "No open sales order lines"+msgstr "没有未结销售订单行"+msgid "No operations require picking at this location"msgstr "此位置不需要进行任何操作拣选"@@ -8927,7 +8936,7 @@ msgid "Opportunity"msgstr "机会"msgid "Optimized for fast previews — downloads always serve the original uploaded file"-msgstr ""+msgstr "针对快速预览优化 — 下载始终提供原始上载的文件"msgid "Optional"msgstr "可选"@@ -10310,7 +10319,7 @@ msgid "Refresh exchange rate"msgstr "刷新汇率"msgid "Regenerate thumbnail from the 3D model"-msgstr ""+msgstr "从 3D 模型重新生成缩略图"msgid "Regenerating thumbnail…"msgstr "正在重新生成缩略图…"diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsxindex fee342267f..abcfe11f6f 100644--- a/packages/react/src/Combobox.tsx+++ b/packages/react/src/Combobox.tsx@@ -81,8 +81,6 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(return [labelText, selectedOption.helper].filter(Boolean).join(" - ");}, [selectedOption]);const dropdownContentWidthCh = useMemo(() => {- if (options.length === 0) return undefined;-const maxOptionChars = options.reduce((longest, option) => {const labelText =typeof option.label === "string"@@ -95,6 +93,9 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(return Math.max(longest, combined.length);}, 0);+ // Keep a sensible minimum even for an empty list so the `emptyMessage`+ // has room. An inline "+" trigger is tiny, so falling back to the trigger+ // width would collapse the popover and wrap the message one word per line.return Math.min(72, Math.max(36, maxOptionChars + 8));}, [options]);@@ -160,9 +161,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(onTouchMove={(e) => e.stopPropagation()}className="min-w-[var(--radix-popover-trigger-width)] max-w-[min(560px,calc(100vw-2rem))] p-1"style={{- width: dropdownContentWidthCh- ? `min(560px, max(var(--radix-popover-trigger-width), ${dropdownContentWidthCh}ch))`- : "var(--radix-popover-trigger-width)"+ width: `min(560px, max(var(--radix-popover-trigger-width), ${dropdownContentWidthCh}ch))`}}>{emptyMessage && options.length === 0 ? (