Skip to content

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

feat(purchasing): manage purchase order dates per line (#2052)

Naveen Kashyap25d2c33a19b4
diff --git a/.ai/playbooks/po-line-dates.md b/.ai/playbooks/po-line-dates.md
new file mode 100644
index 0000000000..929900cd10
--- /dev/null
+++ b/.ai/playbooks/po-line-dates.md
@@ -0,0 +1,62 @@
+# PO line dates (requested / promised / delivery per line)
+
+Last tested: 2026-10-27
+Routes: /x/purchase-order/<id>/details (summary + Shipping card),
+/x/purchase-order/<id>/<lineId>/details (line form)
+
+## Prerequisites
+- A dev company with a Draft PO and a To Receive PO, each with a line and no
+ header or line dates. Find them with
+ `select po.id, po."purchaseOrderId", po.status from "purchaseOrder" po` scoped
+ to your company; PO numbers differ between databases.
+- `SUPABASE_DB_URL` in `.env.local` for psql checks.
+
+## Steps
+### 1. Header dates reach the lines
+On a Draft PO's details page, in the Shipping card, click the "day" spinbutton of
+Requested Date and type `DDMMYYYY` with `agent-browser keyboard type`, same for
+Promised Date, then requestSubmit the card's form (find it via
+`input[name=receiptPromisedDate]`). Lines with an empty date (or the old order
+date) take the new ones; a line with its own date keeps it. Saving the card
+again without changing a date moves no line, so a line left empty stays empty.
+A Delivery Date reaches only lines that have received something.
+
+### 2. Summary pill
+Each non-indirect line shows "Promised" plus a pill under the price badges:
+calendar icon only when the line has no date, the date when it has one. Click
+`button[aria-label="Promised Date"]` (nth for nth line), pick a gridcell button by
+full label (`button "Friday, 20 November 2026"`); it saves on pick. Clear empties
+it and it stays empty after reload (no fallback to the order's date).
+
+### 3. Line form
+Sections: Details, Receiving, Dates, Tax & Shipping. Dates fields save outside the
+form's Save: a typed date saves on blur (Tab away), a calendar pick saves when the
+popover closes (Escape). Nothing is saved mid-typing. The form's Save leaves the
+line's dates alone.
+
+### 4. New line
+"Add Line Item" opens a modal; its Dates section starts on the order's Requested
+and Promised dates, and picking an item keeps them. Saved line carries them.
+
+### 5. Released order (To Receive)
+Line form: Requested Date disabled, Promised and Delivery enabled. Server refusal:
+`fetch('/x/purchase-order/<id>/<lineId>/date', {method:'POST', body})` with
+`field=requiredDate` answers `Cannot change the requested date of a confirmed
+purchase order.` The pill on a To Invoice order is disabled.
+
+## Selector Notes
+- Line Dates spinbuttons are named `day, Requested Date` / `day, Promised Date`.
+- Calendar toggles: `button "Toggle Promised Date"`; the popover's Clear is the
+ last `button "Clear"` in the snapshot.
+- Quantity in the line form is the textbox `Quantity Optional`.
+- Opening `/x/purchase-order/<id>/new` directly renders blank; use Add Line Item.
+
+## Cleanup
+Restore with SQL: header `receiptRequestedDate`/`receiptPromisedDate` null, line
+`requiredDate`/`promisedDate` null, delete any added line. Changing quantity can
+re-price the line from supplier price breaks; restore `supplierUnitPrice` too.
+
+## Common Failures
+- macOS may intermittently refuse the shell access to ~/Documents
+ ("Operation not permitted"); run agent-browser / psql from /private/tmp and
+ retry file access.
diff --git a/.ai/playbooks/po-promised-date-after-confirm.md b/.ai/playbooks/po-promised-date-after-confirm.md
new file mode 100644
index 0000000000..554e6db434
--- /dev/null
+++ b/.ai/playbooks/po-promised-date-after-confirm.md
@@ -0,0 +1,48 @@
+# PO Receipt Promised Date after confirmation
+
+Last tested: 2026-10-26
+Route: /x/purchase-order/<purchaseOrder.id>/details (properties panel, right side)
+
+## Prerequisites
+- A seeded dev company (`pnpm db:seed:dev`) has POs in every status: Draft, To Receive,
+ To Receive and Invoice, To Invoice, Completed, Closed. Find them with
+ `select po.id, po."purchaseOrderId", po.status from "purchaseOrder" po` scoped to
+ the test user's company.
+- Seeded POs have no promised dates and no line with its own date or received
+ complete. To test those line cases, set them with SQL on the local DB
+ (`purchaseOrderLine."promisedDate"`, `"receivedComplete"`) and restore after.
+
+## Steps
+### 1. Navigate
+Open the PO details page. In the snapshot the properties panel renders four
+"Calendar" buttons: Receipt Requested Date, Receipt Promised Date, Delivery Date,
+then others. Find the right one with
+`agent-browser snapshot | grep "Receipt Promised Date" -A4` (full snapshot, not -i).
+
+### 2. Pick a date
+Click that "Calendar" button, click "Next" to change month if needed, then click the
+gridcell button by its full label, e.g. `button "Tuesday, 10 November 2026"`. The
+date saves on selection (no Save button). Press Escape to close the popover.
+
+### 3. Verify
+Read `purchaseOrderDelivery."receiptPromisedDate"` and the order's
+`purchaseOrderLine."promisedDate"` rows with psql (`SUPABASE_DB_URL` in `.env.local`).
+
+### 4. Server refusal
+From the logged-in page, `fetch('/x/purchase-order/update', {method:'POST', body})`
+with FormData `ids`, `field=receiptPromisedDate`, `value=YYYY-MM-DD`. A To Invoice /
+Completed / Closed order answers
+`{"error":{"category":"rule","message":"Cannot change the promised date of a fully received purchase order."}}`.
+
+## Expected
+- To Receive / To Receive and Invoice / Draft: Receipt Promised Date enabled;
+ Receipt Requested Date disabled on the confirmed ones.
+- To Invoice / Completed / Closed: Receipt Promised Date disabled.
+- A new date moves lines whose date is empty or equal to the previous order date;
+ a line with its own date and a received-complete line keep theirs.
+- The Shipping card on the page stays fully disabled on confirmed orders (by design).
+
+## Common Failures
+- Login: after clicking Continue the buttons go disabled for ~10 s before the
+ redirect to /x; wait, don't retry.
+- `psql -c` with two statements prints only the last result; run them separately.
diff --git a/apps/erp/app/modules/purchasing/AGENTS.md b/apps/erp/app/modules/purchasing/AGENTS.md
index 0ff9665572..1240bba50a 100644
--- a/apps/erp/app/modules/purchasing/AGENTS.md
+++ b/apps/erp/app/modules/purchasing/AGENTS.md
@@ -85,7 +85,8 @@ cd apps/erp && pnpm exec vitest run app/modules/purchasing
Each is a `defineServiceFn` const in `purchasing.server.ts`. The route calls it as `api.purchasing.<name>(input)`; the API and MCP publish the ones tagged `@mcp` as `purchasing_<name>`. It holds every check the route made. Routes validate the request, call one, and answer with `respond(request, result).redirect(…)` (a flash) or the result.
-- Purchase orders — `updatePurchaseOrder` (the details form: header columns only, never `status`, refused on a finalized order), `updatePurchaseOrders` (one field of the properties panel, refused on a released order except `deliveryDate`), `deletePurchaseOrders` (Draft / Planned, or Needs Approval by its requester — `purchaseOrderDeleteRefusal` in `purchasing.models.ts`; cancels the pending approvals in the delete's transaction), `finalizePurchaseOrderAndNotify` (party contact and supplier approval rules, the approval rule or the planning bypass, then prices, the PDF document and the email; the email attaches the new PDF, the supplier interaction's files without the PDFs stored for its orders (`withoutStoredPurchaseOrderPdfs`: every order converted from one supplier quote shares the folder) and the default attachments, and the PO page's Finalize list shows the same files; an order that needs approval is never released: `submitPurchaseOrderForApproval` sets Needs Approval and opens the request in one transaction, and the approvers are notified after it commits), `decidePurchaseOrderApproval`, `reopenPurchaseOrder` (Draft / Planned, optionally as a revision; `delete` permission from a released status), `closePurchaseOrderAndApprovals`. The status route takes only Draft, Planned and Closed.
+- **Line dates** — every PO line keeps its own `requiredDate` (requested), `promisedDate` and `receivedDate` (delivery; receipt posting also sets it), mapped to the order's `receiptRequestedDate` / `receiptPromisedDate` / `deliveryDate` by `purchaseOrderLineDateOfOrderDate` (`purchasing.models.ts`). A new line starts on the order's requested and promised dates (`upsertPurchaseOrderLine` fills them when absent; both line forms default them). A changed order date is copied by `cascadePurchaseOrderDateToLines` (`purchasing.service.ts`) to every line whose date is empty or still the order's previous one, in the transaction that writes the delivery row; a line given its own date keeps it, and received-complete lines keep their requested and promised dates. An order whose date is not changing moves no line, so saving the Shipping card fills no empty line. The delivery date is when the goods arrived (receipt posting sets the order's), so it reaches only lines with something received (`quantityReceived > 0`). Receipt posting also overwrites a line's `receivedDate` with the posting day on every receipt, so a hand-corrected delivery date lasts until the line's next receipt. Pinned by `apps/erp/test/database/purchase-order-line-dates.test.ts`. A saved line's dates save one at a time (`updatePurchaseOrderLineDate`), outside the line form's submit: the requested date is fixed once the order is released, the promised date once the line is received complete or the order fully received, and the delivery date stays correctable. The line page edits them in the form's Dates section (`PurchaseOrderLineDateFields`); the order summary edits each line's promised date in place (`PurchaseOrderLinePromisedDate`). The line details route drops the date fields from its update, because `updatePurchaseOrderLineRestatingCompletion` sanitizes a missing field to null.
+- Purchase orders — `updatePurchaseOrder` (the details form: header columns only, never `status`, refused on a finalized order), `updatePurchaseOrders` (one field of the properties panel, refused on a released order except `deliveryDate`, and `receiptPromisedDate` until the order is fully received: `isPurchaseOrderPromisedDateEditable`. A new requested, promised or delivery date also moves the order's lines — see Line dates), `updatePurchaseOrderDelivery` (the Shipping card, `$orderId.delivery.tsx`; refused on a released order; cascades its three dates the same way), `updatePurchaseOrderLineDate` (one date of one line, `$orderId.$lineId.date.tsx`; `purchaseOrderLineDateRefusal`), `deletePurchaseOrders` (Draft / Planned, or Needs Approval by its requester — `purchaseOrderDeleteRefusal` in `purchasing.models.ts`; cancels the pending approvals in the delete's transaction), `finalizePurchaseOrderAndNotify` (party contact and supplier approval rules, the approval rule or the planning bypass, then prices, the PDF document and the email; the email attaches the new PDF, the supplier interaction's files without the PDFs stored for its orders (`withoutStoredPurchaseOrderPdfs`: every order converted from one supplier quote shares the folder) and the default attachments, and the PO page's Finalize list shows the same files; an order that needs approval is never released: `submitPurchaseOrderForApproval` sets Needs Approval and opens the request in one transaction, and the approvers are notified after it commits), `decidePurchaseOrderApproval`, `reopenPurchaseOrder` (Draft / Planned, optionally as a revision; `delete` permission from a released status), `closePurchaseOrderAndApprovals`. The status route takes only Draft, Planned and Closed.
- Return orders — `updateReturnOrders`, `confirmReturnOrder` (stores the PDF; a failed PDF is a `warning`), `cancelReturnOrder`, `reopenReturnOrder`, `addReturnOrderLine` (Draft only), `updateReturnOrderLine` (post-confirm locks: `lockedReturnLineField`).
- RFQs — `createPurchasingRfq`, `updatePurchasingRfqs`, `cancelPurchasingRfq` (cancels the linked supplier quotes), `finalizePurchasingRfqAndNotify` (`service.finalizePurchasingRfq`, ported from `finalize-purchasing-rfq`, then the emails: the RFQ and line documents, and each line item's original CAD file from `getItemModelFiles` — attached in line order while the total stays under `PO_EMAIL_ATTACHMENT_LIMIT_MB` (`splitRfqModelAttachments`), the rest signed for 7 days and listed as links in the body; a model with no known size goes as a link, one whose attachment cannot be signed falls back to a link, and one with no link either is named in the body).
- Supplier quotes — `updateSupplierQuotes`, `finalizeSupplierQuoteWithLink`, `sendSupplierQuoteToSupplier`; `submitDigitalSupplierQuote` / `declineDigitalSupplierQuote` / `updateDigitalSupplierQuoteLineNotes` / `recordSupplierQuoteLinkVisit` (system only, not published: the supplier's share link runs them through `shareLinkContext`, `~/modules/service-context.server`; submit refuses a line that is not the quote's).
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
index 9c4407a2aa..ef1381ccd0 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
@@ -8,6 +8,7 @@ import {
canCreatePurchaseOrderRevision,
isPurchaseOrderBulkDeletable,
isPurchaseOrderLocked,
+ isPurchaseOrderPromisedDateEditable,
leaseDetailsValidator,
leaseDurationOf,
leaseEndDate,
@@ -21,6 +22,7 @@ import {
lockedReturnLineField,
PURCHASE_ORDER_LOCKED_STATUSES,
purchaseOrderDeleteRefusal,
+ purchaseOrderLineDateRefusal,
purchaseOrderStatusType,
purchaseOrderValidator,
resolveLeaseDates,
@@ -550,3 +552,68 @@ describe("splitRfqModelAttachments", () => {
expect(link.map((m) => m.id)).toEqual(["a"]);
});
});
+
+describe("isPurchaseOrderPromisedDateEditable", () => {
+ it("stays editable on a confirmed order until every line is received", () => {
+ const editable = purchaseOrderStatusType.filter(
+ isPurchaseOrderPromisedDateEditable
+ );
+ expect(editable).toEqual([
+ "Draft",
+ "Planned",
+ "Needs Approval",
+ "To Review",
+ "To Receive",
+ "To Receive and Invoice",
+ "Rejected"
+ ]);
+ });
+
+ it("is editable on an order with no status yet", () => {
+ expect(isPurchaseOrderPromisedDateEditable(null)).toBe(true);
+ });
+});
+
+describe("purchaseOrderLineDateRefusal", () => {
+ const editable = (
+ field: Parameters<typeof purchaseOrderLineDateRefusal>[0],
+ receivedComplete = false
+ ) =>
+ purchaseOrderStatusType.filter(
+ (status) =>
+ purchaseOrderLineDateRefusal(field, { status, receivedComplete }) ===
+ null
+ );
+
+ it("fixes the required date once the order is released", () => {
+ expect(editable("requiredDate")).toEqual([
+ "Draft",
+ "Planned",
+ "Needs Approval",
+ "To Review",
+ "Rejected"
+ ]);
+ });
+
+ it("keeps an open line's promised date editable until the order is fully received", () => {
+ expect(editable("promisedDate")).toEqual([
+ "Draft",
+ "Planned",
+ "Needs Approval",
+ "To Review",
+ "To Receive",
+ "To Receive and Invoice",
+ "Rejected"
+ ]);
+ });
+
+ it("fixes the promised date of a line received complete", () => {
+ expect(editable("promisedDate", true)).toEqual([]);
+ });
+
+ it("always lets the delivery date be corrected", () => {
+ expect(editable("receivedDate", true)).toEqual([
+ ...purchaseOrderStatusType
+ ]);
+ });
+});
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index 418747a030..cc994a094c 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -763,6 +763,90 @@ export function isPurchaseOrderBulkDeletable(
return status === "Draft" || status === "Planned";
}
+/** Statuses reached once every line is received; the promised date locks here. */
+export const PURCHASE_ORDER_RECEIVED_STATUSES = [
+ "To Invoice",
+ "Completed",
+ "Closed"
+] as const satisfies readonly (typeof purchaseOrderStatusType)[number][];
+
+export function isPurchaseOrderPromisedDateEditable(
+ status: (typeof purchaseOrderStatusType)[number] | string | null | undefined
+): boolean {
+ return !PURCHASE_ORDER_RECEIVED_STATUSES.some(
+ (received) => received === status
+ );
+}
+
+/** Why an order's status refuses a promised date, or null when it allows one.
+ * A Closed order may still have lines nothing was received on. */
+export function purchaseOrderPromisedDateRefusal(
+ status: (typeof purchaseOrderStatusType)[number] | string | null | undefined
+): string | null {
+ if (status === "Closed") {
+ return "Cannot change the promised date of a closed purchase order.";
+ }
+ return isPurchaseOrderPromisedDateEditable(status)
+ ? null
+ : "Cannot change the promised date of a fully received purchase order.";
+}
+
+/** A line's own dates. `receivedDate` is its delivery date. */
+export const purchaseOrderLineDateFields = [
+ "requiredDate",
+ "promisedDate",
+ "receivedDate"
+] as const;
+
+export type PurchaseOrderLineDateField =
+ (typeof purchaseOrderLineDateFields)[number];
+
+/** The order date each line date starts from. */
+export const purchaseOrderLineDateOfOrderDate = {
+ receiptRequestedDate: "requiredDate",
+ receiptPromisedDate: "promisedDate",
+ deliveryDate: "receivedDate"
+} as const satisfies Record<string, PurchaseOrderLineDateField>;
+
+export type PurchaseOrderDateField =
+ keyof typeof purchaseOrderLineDateOfOrderDate;
+
+export function isPurchaseOrderDateField(
+ field: string
+): field is PurchaseOrderDateField {
+ return field in purchaseOrderLineDateOfOrderDate;
+}
+
+/** Why a line date cannot change, or null when it can. */
+export function purchaseOrderLineDateRefusal(
+ field: PurchaseOrderLineDateField,
+ line: {
+ status: (typeof purchaseOrderStatusType)[number] | string | null;
+ receivedComplete: boolean;
+ }
+): string | null {
+ switch (field) {
+ case "requiredDate":
+ return isPurchaseOrderLocked(line.status)
+ ? "Cannot change the requested date of a confirmed purchase order."
+ : null;
+ case "promisedDate":
+ return (
+ purchaseOrderPromisedDateRefusal(line.status) ??
+ (line.receivedComplete
+ ? "Cannot change the promised date of a received line."
+ : null)
+ );
+ case "receivedDate":
+ return null;
+ }
+}
+
+export const purchaseOrderLineDateValidator = z.object({
+ field: z.enum(purchaseOrderLineDateFields),
+ value: zfd.text(z.string().optional())
+});
+
/**
* The PO statuses planning may change: Apply on a planning action, the order
* drawer's inline edits, and Cancel's line delete. An allowlist on purpose —
@@ -1200,7 +1284,7 @@ function isOnOrAfter(later: string, earlier: string): boolean {
/** A real calendar date written `YYYY-MM-DD` — what a DATE column takes and
* what the lease's month arithmetic parses. */
-function isIsoDate(value: string): boolean {
+export function isIsoDate(value: string): boolean {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
try {
return parseDate(value).toString() === value;
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index bf3fb44d5f..34acce0633 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -45,6 +45,7 @@ import {
groupBy,
PO_EMAIL_ATTACHMENT_LIMIT_MB,
SCALE,
+ sanitize,
taxableBase,
tiptapToHTML,
unchecked
@@ -65,7 +66,7 @@ import {
getCompany,
getCompanySettings
} from "~/modules/settings/settings.service";
-import { optionalTiptapDoc } from "~/modules/shared/shared.models";
+import { incoterms, optionalTiptapDoc } from "~/modules/shared/shared.models";
import {
getLocationTimeZone,
invokePosting,
@@ -78,6 +79,8 @@ import { fromServerFn } from "../shared/shared.service";
import {
canCreatePurchaseOrderRevision,
findPlanningPurchaseOrder,
+ isIsoDate,
+ isPurchaseOrderDateField,
isPurchaseOrderEditableFromPlanning,
isPurchaseOrderLocked,
isPurchaseReturnOrderLocked,
@@ -92,6 +95,9 @@ import {
plannedOrderValidator,
planningPurchaseOrderWeek,
purchaseOrderDeleteRefusal,
+ purchaseOrderLineDateFields,
+ purchaseOrderLineDateRefusal,
+ purchaseOrderPromisedDateRefusal,
purchaseOrderStatusType,
purchaseReturnOrderLineValidator,
purchasingRfqFinalizeValidator,
@@ -1842,9 +1848,11 @@ const purchaseOrderDeliveryFields = [
* (an empty `supplierId` changes nothing). A new `supplierId` on one order
* takes the supplier's currency and today's rate; a new `currencyCode` takes
* today's rate (refused when there is none). `receiptRequestedDate`,
- * `locationId` and `deliveryDate` are the delivery's. `receiptPromisedDate`
- * also fills every line that has no promised date of its own. Refused when
- * any order is released, except for `deliveryDate`.
+ * `receiptPromisedDate`, `locationId` and `deliveryDate` are the delivery's;
+ * a new date also moves the lines still on the order's previous one. Refused
+ * when any order is released, except for `deliveryDate`, and for
+ * `receiptPromisedDate` until the order is fully received (To Invoice,
+ * Completed or Closed).
*
* @mcp
*/
@@ -1870,7 +1878,14 @@ export const updatePurchaseOrders = defineServiceFn({
updatedAt: datetime.timestamp()
});
- if (field !== "deliveryDate") {
+ if (field === "receiptPromisedDate") {
+ const statuses = await service.statusesOf(ctx, "purchaseOrder", ids);
+ if (statuses instanceof CarbonError) return statuses;
+ const refusal = statuses
+ .map(purchaseOrderPromisedDateRefusal)
+ .find((message) => message !== null);
+ if (refusal) return ctx.error("rule", refusal);
+ } else if (field !== "deliveryDate") {
const statuses = await service.statusesOf(ctx, "purchaseOrder", ids);
if (statuses instanceof CarbonError) return statuses;
if (statuses.some(isPurchaseOrderLocked)) {
@@ -1881,20 +1896,31 @@ export const updatePurchaseOrders = defineServiceFn({
const failed = (error: unknown) =>
ctx.error("internal", "Failed to update the purchase order", error);
- if (field === "receiptPromisedDate") {
- const lines = await client
- .from("purchaseOrderLine")
- .update({ promisedDate: value ?? undefined, ...stamp() })
- .in("purchaseOrderId", ids)
- .eq("companyId", companyId)
- .is("promisedDate", null);
- if (lines.error) return failed(lines.error);
+ if (isPurchaseOrderDateField(field)) {
+ // One transaction: the lines compare against the order's previous date,
+ // so they are written before the delivery row changes it.
+ const saved = await ctx
+ .transaction(async (tx) => {
+ const db = tx.asSystem.pg;
+ await service.cascadePurchaseOrderDateToLines(db, {
+ companyId,
+ userId: ctx.auditUserId,
+ purchaseOrderIds: ids,
+ field,
+ value
+ });
+ await db
+ .updateTable("purchaseOrderDelivery")
+ .set({ [field]: value, ...stamp() })
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .execute();
+ })
+ .catch(failed);
+ return saved instanceof CarbonError ? saved : { ids };
}
- if (
- field === "receiptPromisedDate" ||
- (purchaseOrderDeliveryFields as readonly string[]).includes(field)
- ) {
+ if ((purchaseOrderDeliveryFields as readonly string[]).includes(field)) {
const delivery = await client
.from("purchaseOrderDelivery")
.update(unchecked({ [field]: value, ...stamp() }))
@@ -1937,6 +1963,136 @@ export const updatePurchaseOrders = defineServiceFn({
}
});
+/**
+ * Change one date of a purchase order line.
+ *
+ * @remarks
+ * The requested date is refused once the order is released, the promised date
+ * once the line or the order is received; the delivery date can always be
+ * corrected.
+ *
+ * @param lineId - The purchase order line's id.
+ * @param field - Which date: `requiredDate`, `promisedDate` or `receivedDate`.
+ * @param value - The date, `YYYY-MM-DD`, or null to clear it.
+ * @mcp
+ */
+export const updatePurchaseOrderLineDate = defineServiceFn({
+ input: z.object({
+ lineId: z.string().min(1),
+ field: z.enum(purchaseOrderLineDateFields),
+ value: z.string().refine(isIsoDate, "Use a YYYY-MM-DD date").nullable()
+ }),
+ permission: { update: "purchasing" },
+
+ async run(ctx, { lineId, field, value }) {
+ const companyId = ctx.company.id;
+ const db = ctx.asSystem.pg;
+ const failed = (error: unknown) =>
+ ctx.error("internal", "Failed to update the purchase order line", error);
+
+ const line = await db
+ .selectFrom("purchaseOrderLine")
+ .innerJoin("purchaseOrder", (join) =>
+ join
+ .onRef("purchaseOrder.id", "=", "purchaseOrderLine.purchaseOrderId")
+ .onRef("purchaseOrder.companyId", "=", "purchaseOrderLine.companyId")
+ )
+ .select(["purchaseOrderLine.receivedComplete", "purchaseOrder.status"])
+ .where("purchaseOrderLine.id", "=", lineId)
+ .where("purchaseOrderLine.companyId", "=", companyId)
+ .executeTakeFirst()
+ .catch(failed);
+ if (line instanceof CarbonError) return line;
+ if (!line) return ctx.error("notFound", "Purchase order line not found");
+
+ const refusal = purchaseOrderLineDateRefusal(field, line);
+ if (refusal) return ctx.error("rule", refusal);
+
+ const updated = await db
+ .updateTable("purchaseOrderLine")
+ .set({
+ [field]: value,
+ updatedBy: ctx.auditUserId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", lineId)
+ .where("companyId", "=", companyId)
+ .execute()
+ .catch(failed);
+ return updated instanceof CarbonError ? updated : { lineId };
+ }
+});
+
+/**
+ * Save a purchase order's Shipping card. Refused once the order is released.
+ * A new date also moves the lines still on the order's previous one.
+ */
+export const updatePurchaseOrderDelivery = defineServiceFn({
+ input: z.object({
+ id: z.string().min(1),
+ locationId: z.string().optional(),
+ shippingMethodId: z.string().optional(),
+ trackingNumber: z.string(),
+ deliveryDate: z.string().optional(),
+ receiptRequestedDate: z.string().optional(),
+ receiptPromisedDate: z.string().optional(),
+ dropShipment: z.boolean(),
+ customerId: z.string().optional(),
+ customerLocationId: z.string().optional(),
+ supplierShippingCost: z.number().optional(),
+ notes: z.string().optional(),
+ incoterm: z.enum(incoterms).optional(),
+ incotermLocation: z.string().optional(),
+ customFields: z.record(z.string(), z.unknown()).optional()
+ }),
+ permission: { update: "purchasing" },
+
+ async run(ctx, { id, customFields, ...delivery }) {
+ const companyId = ctx.company.id;
+ const statuses = await service.statusesOf(ctx, "purchaseOrder", [id]);
+ if (statuses instanceof CarbonError) return statuses;
+ if (statuses.length === 0) {
+ return ctx.error("notFound", "Purchase order not found");
+ }
+ if (statuses.some(isPurchaseOrderLocked)) {
+ return ctx.error("rule", "Cannot modify a confirmed purchase order.");
+ }
+
+ const saved = await ctx
+ .transaction(async (tx) => {
+ const db = tx.asSystem.pg;
+ for (const field of [
+ "receiptRequestedDate",
+ "receiptPromisedDate",
+ "deliveryDate"
+ ] as const) {
+ await service.cascadePurchaseOrderDateToLines(db, {
+ companyId,
+ userId: ctx.auditUserId,
+ purchaseOrderIds: [id],
+ field,
+ value: delivery[field] ?? null
+ });
+ }
+ await db
+ .updateTable("purchaseOrderDelivery")
+ .set({
+ ...sanitize(delivery),
+ customFields: (customFields ?? null) as Json,
+ updatedBy: ctx.auditUserId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .execute();
+ })
+ .catch((error: unknown) =>
+ ctx.error("internal", "Failed to update purchase order delivery", error)
+ );
+ return saved instanceof CarbonError ? saved : { id };
+ }
+});
+
/**
* Delete purchase orders.
*
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 8f20b69e04..bf69fcf005 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -191,8 +191,10 @@ import {
PLANNING_EDITABLE_PURCHASE_ORDER_STATUSES,
PURCHASE_ORDER_LOCKED_STATUSES,
type PURCHASE_ORDER_REOPEN_STATUSES,
+ type PurchaseOrderDateField,
planningLineCurrencyCode,
planningQuantityChange,
+ purchaseOrderLineDateOfOrderDate,
taxPairForQuantity
} from "./purchasing.models";
import { renderPurchaseOrderPdf } from "./purchasing.pdf";
@@ -2260,10 +2262,19 @@ export async function upsertPurchaseOrderLine(
return updatePurchaseOrderLineRestatingCompletion(client, companyId, line);
}
- const existing = await client
- .from("purchaseOrderLine")
- .select("sortOrder")
- .eq("purchaseOrderId", normalized.purchaseOrderId);
+ const [existing, delivery] = await Promise.all([
+ client
+ .from("purchaseOrderLine")
+ .select("sortOrder")
+ .eq("purchaseOrderId", normalized.purchaseOrderId),
+ client
+ .from("purchaseOrderDelivery")
+ .select("receiptRequestedDate, receiptPromisedDate")
+ .eq("id", normalized.purchaseOrderId)
+ .eq("companyId", normalized.companyId)
+ .maybeSingle()
+ ]);
+ if (delivery.error) return { data: null, error: delivery.error };
const maxSortOrder = (existing.data ?? []).reduce(
(max, row) => Math.max(max, row.sortOrder ?? 0),
@@ -2272,7 +2283,20 @@ export async function upsertPurchaseOrderLine(
return client
.from("purchaseOrderLine")
- .insert([{ ...normalized, sortOrder: maxSortOrder + 1 }])
+ .insert([
+ {
+ ...normalized,
+ requiredDate:
+ normalized.requiredDate ??
+ delivery.data?.receiptRequestedDate ??
+ undefined,
+ promisedDate:
+ normalized.promisedDate ??
+ delivery.data?.receiptPromisedDate ??
+ undefined,
+ sortOrder: maxSortOrder + 1
+ }
+ ])
.select("id")
.single();
}
@@ -3601,6 +3625,82 @@ export async function getDefaultAttachmentsForPO(
});
}
+/**
+ * Copies a changed order date to the lines that have no date or the order's
+ * current one. Run it before the delivery row changes, in the same
+ * transaction. The delivery date (when goods arrived) goes only to lines that
+ * received something; received-complete lines keep the other two.
+ *
+ * It locks the delivery rows first, so a concurrent save of the same order
+ * waits and then compares against the date this one commits.
+ */
+export async function cascadePurchaseOrderDateToLines(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ purchaseOrderIds: string[];
+ field: PurchaseOrderDateField;
+ value: string | null;
+ }
+) {
+ const { companyId, userId, purchaseOrderIds, field, value } = args;
+ if (!value || purchaseOrderIds.length === 0) return;
+ const lineField = purchaseOrderLineDateOfOrderDate[field];
+
+ await db
+ .selectFrom("purchaseOrderDelivery")
+ .select("id")
+ .where("companyId", "=", companyId)
+ .where("id", "in", purchaseOrderIds)
+ .orderBy("id")
+ .forUpdate()
+ .execute();
+
+ let update = db
+ .updateTable("purchaseOrderLine")
+ .set({
+ [lineField]: value,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("purchaseOrderLine.companyId", "=", companyId)
+ .where("purchaseOrderLine.purchaseOrderId", "in", purchaseOrderIds)
+ .where((eb) =>
+ eb.exists(
+ eb
+ .selectFrom("purchaseOrderDelivery")
+ .select(sql.lit(1).as("one"))
+ .whereRef(
+ "purchaseOrderDelivery.id",
+ "=",
+ "purchaseOrderLine.purchaseOrderId"
+ )
+ .whereRef(
+ "purchaseOrderDelivery.companyId",
+ "=",
+ "purchaseOrderLine.companyId"
+ )
+ .where(`purchaseOrderDelivery.${field}`, "is distinct from", value)
+ .where((delivery) =>
+ delivery.or([
+ delivery(`purchaseOrderLine.${lineField}`, "is", null),
+ delivery(
+ `purchaseOrderLine.${lineField}`,
+ "=",
+ delivery.ref(`purchaseOrderDelivery.${field}`)
+ )
+ ])
+ )
+ )
+ );
+ update =
+ field === "deliveryDate"
+ ? update.where("purchaseOrderLine.quantityReceived", ">", 0)
+ : update.where("purchaseOrderLine.receivedComplete", "=", false);
+ await update.execute();
+}
+
/**
* Apply a planning schedule/quantity change to a PO line.
* `purchaseQuantity` is in PURCHASE units — the caller converts from inventory
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index 60834005a4..cb6e358d8a 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@ -81,7 +81,11 @@ export default function PurchaseOrderExplorer() {
supplierTaxAmount: 0,
taxPercent: 0,
supplierShippingCost: 0,
- exchangeRate: purchaseOrderData?.purchaseOrder?.exchangeRate ?? 1
+ exchangeRate: purchaseOrderData?.purchaseOrder?.exchangeRate ?? 1,
+ requiredDate:
+ purchaseOrderData?.purchaseOrder?.receiptRequestedDate ?? undefined,
+ promisedDate:
+ purchaseOrderData?.purchaseOrder?.receiptPromisedDate ?? undefined
};
const newPurchaseOrderLineDisclosure = useDisclosure();
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineDates.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineDates.tsx
new file mode 100644
index 0000000000..4e50fbef11
--- /dev/null
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineDates.tsx
@@ -0,0 +1,286 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { TermId } from "@carbon/content/glossary";
+import { useAction } from "@carbon/query";
+import {
+ Button,
+ Calendar,
+ DatePicker as DatePickerBase,
+ FormControl,
+ FormLabel,
+ IconButton,
+ LabelWithHelp,
+ Popover,
+ PopoverContent,
+ PopoverFooter,
+ PopoverTrigger,
+ toast
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { parseDate, toCalendarDate } from "@internationalized/date";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import { useRef, useState } from "react";
+import { LuCalendarClock } from "react-icons/lu";
+import { usePermissions } from "~/hooks";
+import {
+ type PurchaseOrderLineDateField,
+ purchaseOrderLineDateRefusal
+} from "~/modules/purchasing/purchasing.models";
+import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.date";
+import { path } from "~/utils/path";
+import type { PurchaseOrder } from "../../types";
+
+type LineDates = {
+ id: string;
+ purchaseOrderId: string;
+ receivedComplete: boolean;
+} & Record<PurchaseOrderLineDateField, string | null>;
+
+type OrderStatus = Pick<PurchaseOrder, "status">;
+
+/**
+ * Saves one line date. A refused save is toasted and bumps that field's
+ * `failures`, which its control keys on to show the saved date again.
+ */
+export function useSavePurchaseOrderLineDate(line: {
+ id: string;
+ purchaseOrderId: string;
+}) {
+ const [refused, setRefused] = useState<
+ Partial<Record<PurchaseOrderLineDateField, number>>
+ >({});
+ const saving = useRef<PurchaseOrderLineDateField | null>(null);
+ const fetcher = useAction<typeof action>({
+ onError: (data) => {
+ if (data?.error) toast.error(data.error.message);
+ const field = saving.current;
+ if (field) {
+ setRefused((counts) => ({
+ ...counts,
+ [field]: (counts[field] ?? 0) + 1
+ }));
+ }
+ }
+ });
+
+ const save = (field: PurchaseOrderLineDateField, value: string | null) => {
+ saving.current = field;
+ const formData = new FormData();
+ formData.append("field", field);
+ formData.append("value", value ?? "");
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.purchaseOrderLineDate(line.purchaseOrderId, line.id)
+ });
+ };
+
+ const failures = (field: PurchaseOrderLineDateField) => refused[field] ?? 0;
+
+ return { save, failures };
+}
+
+export function PurchaseOrderLinePromisedDate({
+ line,
+ order
+}: {
+ line: Pick<LineDates, "id" | "purchaseOrderId" | "receivedComplete"> & {
+ promisedDate: string | null;
+ };
+ order: OrderStatus | undefined;
+}) {
+ const permissions = usePermissions();
+ const { save, failures } = useSavePurchaseOrderLineDate(line);
+ const value = line.promisedDate;
+ const isDisabled =
+ !permissions.can("update", "purchasing") ||
+ purchaseOrderLineDateRefusal("promisedDate", {
+ status: order?.status ?? null,
+ receivedComplete: line.receivedComplete
+ }) !== null;
+
+ return (
+ // The summary row toggles open on click; picking a date must not. The
+ // pill's 1px shadow ring sits outside it, so pad it in from the edge.
+ <div
+ className="flex shrink-0 items-center gap-2 pr-px text-sm whitespace-nowrap"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <span className="text-muted-foreground whitespace-nowrap">
+ <Trans>Promised</Trans>
+ </span>
+ <DatePill
+ key={`${value ?? ""}:${failures("promisedDate")}`}
+ value={value}
+ isDisabled={isDisabled}
+ onChange={(date) => {
+ if (date === value) return;
+ save("promisedDate", date);
+ }}
+ />
+ </div>
+ );
+}
+
+function DatePill({
+ value,
+ isDisabled,
+ onChange
+}: {
+ value: string | null;
+ isDisabled: boolean;
+ onChange: (date: string | null) => void;
+}) {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ // What was picked, shown until the saved date comes back with the page.
+ const [picked, setPicked] = useState<string | null | undefined>(undefined);
+ const shown = picked === undefined ? value : picked;
+
+ const [open, setOpen] = useState(false);
+
+ const pick = (next: string | null) => {
+ setOpen(false);
+ setPicked(next);
+ onChange(next);
+ };
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ {shown ? (
+ <Button
+ variant="secondary"
+ size="sm"
+ isDisabled={isDisabled}
+ rightIcon={<LuCalendarClock />}
+ aria-label={t`Promised Date`}
+ >
+ <span className="tabular-nums">
+ {formatDate(shown, undefined, locale)}
+ </span>
+ </Button>
+ ) : (
+ <IconButton
+ variant="secondary"
+ size="sm"
+ isDisabled={isDisabled}
+ icon={<LuCalendarClock />}
+ aria-label={t`Promised Date`}
+ />
+ )}
+ </PopoverTrigger>
+ <PopoverContent align="end">
+ <Calendar
+ value={shown ? parseDate(shown) : null}
+ onChange={(date) => pick(toCalendarDate(date).toString())}
+ />
+ <PopoverFooter>
+ <Button variant="secondary" onClick={() => pick(null)}>
+ <Trans>Clear</Trans>
+ </Button>
+ </PopoverFooter>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * A saved line's dates. Each saves when picked, outside the form's submit,
+ * because the promised date stays editable after the line is locked.
+ */
+export function PurchaseOrderLineDateFields({
+ line,
+ order
+}: {
+ line: LineDates;
+ order: OrderStatus | undefined;
+}) {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const canUpdate = permissions.can("update", "purchasing");
+ const { save, failures } = useSavePurchaseOrderLineDate(line);
+ const fields: {
+ field: PurchaseOrderLineDateField;
+ label: string;
+ termId?: TermId;
+ }[] = [
+ {
+ field: "requiredDate",
+ label: t`Requested Date`,
+ termId: "purchase-order-line-required-date"
+ },
+ { field: "promisedDate", label: t`Promised Date` },
+ { field: "receivedDate", label: t`Delivery Date` }
+ ];
+
+ return (
+ <>
+ {fields.map(({ field, label, termId }) => {
+ const value = line[field];
+ const refusal = purchaseOrderLineDateRefusal(field, {
+ status: order?.status ?? null,
+ receivedComplete: line.receivedComplete
+ });
+ return (
+ <LineDateField
+ key={`${field}:${value ?? ""}:${failures(field)}`}
+ label={label}
+ termId={termId}
+ value={value}
+ isDisabled={!canUpdate || refusal !== null}
+ onChange={(date) => save(field, date)}
+ />
+ );
+ })}
+ </>
+ );
+}
+
+/**
+ * Not a form field, so the line form's submit and lock skip it. A typed date
+ * saves when the field loses focus, not on each keystroke: the picker reports
+ * a complete date while the year is still being typed.
+ */
+function LineDateField({
+ label,
+ termId,
+ value,
+ isDisabled,
+ onChange
+}: {
+ label: string;
+ termId?: TermId;
+ value: string | null;
+ isDisabled: boolean;
+ onChange: (date: string | null) => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const committed = useRef(value);
+
+ const commit = () => {
+ if (draft === committed.current) return;
+ committed.current = draft;
+ onChange(draft);
+ };
+
+ return (
+ <FormControl>
+ <FormLabel isOptional>
+ <LabelWithHelp termId={termId}>{label}</LabelWithHelp>
+ </FormLabel>
+ <DatePickerBase
+ aria-label={label}
+ value={draft ? parseDate(draft) : null}
+ isDisabled={isDisabled}
+ onChange={(date) => setDraft(date ? date.toString() : null)}
+ onBlur={commit}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) commit();
+ }}
+ />
+ </FormControl>
+ );
+}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index 9e87a0a28f..bfb12d1a80 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -46,7 +46,7 @@ import {
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useMemo, useState } from "react";
+import { type ReactNode, useMemo, useState } from "react";
import { LuBox, LuChevronRight, LuLandmark, LuReceipt } from "react-icons/lu";
import { useFetcher, useParams } from "react-router";
import type { z } from "zod";
@@ -95,18 +95,26 @@ import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.detail
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";
+import { PurchaseOrderLineDateFields } from "./PurchaseOrderLineDates";
type PurchaseOrderLineFormProps = {
initialValues: z.infer<typeof purchaseOrderLineValidator> & {
assetReadableId?: string;
assetName?: string;
};
+ lineDates?: {
+ receivedComplete: boolean;
+ requiredDate: string | null;
+ promisedDate: string | null;
+ receivedDate: string | null;
+ };
type?: "card" | "modal";
onClose?: () => void;
};
const PurchaseOrderLineForm = ({
initialValues,
+ lineDates,
type,
onClose
}: PurchaseOrderLineFormProps) => {
@@ -149,6 +157,25 @@ const PurchaseOrderLineForm = ({
// selected item.
const [itemFilter, setItemFilter] = useState<ItemType | "Item">("Item");
const isService = lineType === "Service";
+ const hasUnitOfMeasure = [
+ "Item",
+ "Part",
+ "Material",
+ "Consumable",
+ "Tool",
+ "Fixture"
+ ].includes(lineType);
+ // Outside processing is not received into a location.
+ const isReceivedToLocation =
+ [
+ "Item",
+ "Part",
+ "Service",
+ "Material",
+ "Tool",
+ "Consumable",
+ "Fixture"
+ ].includes(lineType) && !isOutsideProcessing;
const [locationId, setLocationId] = useState(initialValues.locationId);
const [itemData, setItemData] = useState<{
itemId: string;
@@ -369,7 +396,7 @@ const PurchaseOrderLineForm = ({
pricing: null,
purchaseQuantity: 1,
purchaseUom: "",
- requiredDate: null,
+ requiredDate: routeData?.purchaseOrder?.receiptRequestedDate ?? null,
storageUnitId: "",
supplierPartId: "",
supplierShippingCost: 0,
@@ -470,9 +497,10 @@ const PurchaseOrderLineForm = ({
itemReplenishment?.conversionFactor ??
1),
requiredDate:
- leadTime === 0
+ routeData?.purchaseOrder?.receiptRequestedDate ??
+ (leadTime === 0
? null
- : today(getLocalTimeZone()).add({ days: leadTime }).toString(),
+ : today(getLocalTimeZone()).add({ days: leadTime }).toString()),
storageUnitId: inventory.data?.defaultStorageUnitId ?? null,
supplierPartId: supplierPart?.data?.supplierPartId ?? "",
supplierTaxAmount: 0,
@@ -516,6 +544,20 @@ const PurchaseOrderLineForm = ({
const collapsedTaxPercent = initialValues?.taxPercent ?? 0;
+ const savedLineDates =
+ isEditing && lineDates ? (
+ <FormSection title={t`Dates`}>
+ <PurchaseOrderLineDateFields
+ line={{
+ id: initialValues.id!,
+ purchaseOrderId: orderId,
+ ...lineDates
+ }}
+ order={routeData?.purchaseOrder}
+ />
+ </FormSection>
+ ) : null;
+
const lineSubtitle = isFixedAsset
? initialValues.assetName || indirectData.description
: isGLAccount
@@ -672,8 +714,8 @@ const PurchaseOrderLineForm = ({
<Hidden name="conversionFactor" value={1} />
</>
)}
- <VStack>
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <VStack spacing={4}>
+ <FormSection title={t`Details`}>
<Item
autoFocus={!isEditing}
name="itemId"
@@ -713,23 +755,6 @@ const PurchaseOrderLineForm = ({
}
/>
- {isOutsideProcessing && (
- <JobOperationSelect jobId={initialValues.jobId} />
- )}
-
- <DatePicker
- name="requiredDate"
- label={t`Required Date`}
- termId="purchase-order-line-required-date"
- value={itemData?.requiredDate ?? undefined}
- onChange={(date) => {
- setItemData((d) => ({
- ...d,
- requiredDate: date
- }));
- }}
- />
-
<NumberControlled
minValue={itemData.minimumOrderQuantity}
name="purchaseQuantity"
@@ -749,42 +774,20 @@ const PurchaseOrderLineForm = ({
}}
/>
- {[
- "Item",
- "Part",
- "Material",
- "Consumable",
- "Tool",
- "Fixture"
- ].includes(lineType) && (
- <>
- <UnitOfMeasure
- name="purchaseUnitOfMeasureCode"
- label={t`Unit of Measure`}
- value={itemData.purchaseUom}
- onChange={(newValue) => {
- if (newValue) {
- setItemData((d) => ({
- ...d,
- purchaseUom: newValue?.value as string
- }));
- }
- }}
- />
- <ConversionFactor
- name="conversionFactor"
- termId="conversion-factor"
- purchasingCode={itemData.purchaseUom}
- inventoryCode={itemData.inventoryUom}
- value={itemData.conversionFactor}
- onChange={(value) => {
+ {hasUnitOfMeasure && (
+ <UnitOfMeasure
+ name="purchaseUnitOfMeasureCode"
+ label={t`Unit of Measure`}
+ value={itemData.purchaseUom}
+ onChange={(newValue) => {
+ if (newValue) {
setItemData((d) => ({
...d,
- conversionFactor: value
+ purchaseUom: newValue?.value as string
}));
- }}
- />
- </>
+ }
+ }}
+ />
)}
<NumberControlled
name="supplierUnitPrice"
@@ -801,33 +804,40 @@ const PurchaseOrderLineForm = ({
}))
}
/>
- {[
- "Item",
- "Part",
- "Service",
- "Material",
- "Tool",
- "Consumable",
- "Fixture"
- ].includes(lineType) &&
- !isOutsideProcessing && (
- <Location
- name="locationId"
- label={t`Delivery Location`}
- termId="purchase-order-line-delivery-location"
- value={locationId}
- onChange={onLocationChange}
+ {hasUnitOfMeasure && (
+ // Its own row, one column wide.
+ <div className="col-span-full grid grid-cols-1 lg:grid-cols-3 gap-x-8">
+ <ConversionFactor
+ name="conversionFactor"
+ termId="conversion-factor"
+ purchasingCode={itemData.purchaseUom}
+ inventoryCode={itemData.inventoryUom}
+ value={itemData.conversionFactor}
+ onChange={(value) => {
+ setItemData((d) => ({
+ ...d,
+ conversionFactor: value
+ }));
+ }}
/>
- )}
- {[
- "Item",
- "Part",
- "Material",
- "Tool",
- "Consumable",
- "Fixture"
- ].includes(lineType) &&
- !isOutsideProcessing && (
+ </div>
+ )}
+ {isOutsideProcessing && (
+ <JobOperationSelect jobId={initialValues.jobId} />
+ )}
+ <CustomFormFields table="purchaseOrderLine" />
+ </FormSection>
+
+ {isReceivedToLocation && (
+ <FormSection title={t`Receiving`}>
+ <Location
+ name="locationId"
+ label={t`Delivery Location`}
+ termId="purchase-order-line-delivery-location"
+ value={locationId}
+ onChange={onLocationChange}
+ />
+ {lineType !== "Service" && (
<StorageUnit
name="storageUnitId"
label={t`Storage Unit`}
@@ -844,11 +854,21 @@ const PurchaseOrderLineForm = ({
}}
/>
)}
+ </FormSection>
+ )}
- <CustomFormFields table="purchaseOrderLine" />
- </div>
+ {isEditing ? (
+ savedLineDates
+ ) : (
+ <NewLineDates
+ requiredDate={itemData.requiredDate}
+ onRequiredDateChange={(date) =>
+ setItemData((d) => ({ ...d, requiredDate: date }))
+ }
+ />
+ )}
- <div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 mt-4">
+ <div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
className="w-full justify-between cursor-pointer"
onClick={costsDisclosure.onToggle}
@@ -931,8 +951,8 @@ const PurchaseOrderLineForm = ({
name="description"
value={indirectData.description}
/>
- <VStack>
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <VStack spacing={4}>
+ <FormSection title={t`Details`}>
{activeTab === "gl-account" ? (
<>
<Account
@@ -1001,18 +1021,6 @@ const PurchaseOrderLineForm = ({
}
/>
</FormControl>
- <DatePicker
- name="requiredDate"
- label={t`Required Date`}
- termId="purchase-order-line-required-date"
- value={indirectData.requiredDate ?? undefined}
- onChange={(date) => {
- setIndirectData((d) => ({
- ...d,
- requiredDate: date
- }));
- }}
- />
<NumberControlled
name="purchaseQuantity"
label={t`Quantity`}
@@ -1047,9 +1055,21 @@ const PurchaseOrderLineForm = ({
}
/>
<CustomFormFields table="purchaseOrderLine" />
- </div>
+ </FormSection>
- <div className="h-4" />
+ {isEditing ? (
+ savedLineDates
+ ) : (
+ <NewLineDates
+ requiredDate={indirectData.requiredDate}
+ onRequiredDateChange={(date) =>
+ setIndirectData((d) => ({
+ ...d,
+ requiredDate: date
+ }))
+ }
+ />
+ )}
<div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
<HStack
@@ -1208,3 +1228,46 @@ function JobOperationSelect(initialValues: { jobId?: string }) {
</>
);
}
+
+function FormSection({
+ title,
+ children
+}: {
+ title: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <Label>{title}</Label>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ {children}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A new line's dates, sent with the form. A saved line's dates save on their
+ * own (PurchaseOrderLineDateFields).
+ */
+function NewLineDates({
+ requiredDate,
+ onRequiredDateChange
+}: {
+ requiredDate: string | null;
+ onRequiredDateChange: (date: string | null) => void;
+}) {
+ const { t } = useLingui();
+ return (
+ <FormSection title={t`Dates`}>
+ <DatePicker
+ name="requiredDate"
+ label={t`Requested Date`}
+ termId="purchase-order-line-required-date"
+ value={requiredDate ?? undefined}
+ onChange={onRequiredDateChange}
+ />
+ <DatePicker name="promisedDate" label={t`Promised Date`} />
+ </FormSection>
+ );
+}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx
index e263445cba..29a8be6eaf 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx
@@ -58,7 +58,10 @@ import type { action } from "~/routes/x+/items+/update";
import type { action as exchangeRateAction } from "~/routes/x+/purchase-order+/$orderId.exchange-rate";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
-import { isPurchaseOrderLocked } from "../../purchasing.models";
+import {
+ isPurchaseOrderLocked,
+ isPurchaseOrderPromisedDateEditable
+} from "../../purchasing.models";
import type { PurchaseOrder, SupplierQuote } from "../../types";
const PurchaseOrderProperties = () => {
@@ -137,6 +140,10 @@ const PurchaseOrderProperties = () => {
const canUpdate = permissions.can("update", "purchasing");
const isLocked = isPurchaseOrderLocked(routeData?.purchaseOrder?.status);
const isDisabled = !canUpdate || isLocked;
+ // The promise moves with the supplier until everything is received.
+ const isPromisedDateDisabled =
+ !canUpdate ||
+ !isPurchaseOrderPromisedDateEditable(routeData?.purchaseOrder?.status);
return (
<VStack
@@ -384,7 +391,7 @@ const PurchaseOrderProperties = () => {
name="receiptPromisedDate"
label={t`Receipt Promised Date`}
inline
- isDisabled={isDisabled}
+ isDisabled={isPromisedDateDisabled}
onChange={(date) => {
onUpdate("receiptPromisedDate", date);
}}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
index 97a75466d5..738c4f28e7 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
@@ -52,6 +52,7 @@ import type {
PurchaseOrderLine,
Supplier
} from "../../types";
+import { PurchaseOrderLinePromisedDate } from "./PurchaseOrderLineDates";
const LineItems = ({
currencyCode,
@@ -59,9 +60,11 @@ const LineItems = ({
formatter,
locale,
lines,
+ order,
shouldConvertCurrency
}: {
currencyCode: string;
+ order: PurchaseOrder | undefined;
presentationCurrencyFormatter: Intl.NumberFormat;
formatter: Intl.NumberFormat;
locale: string;
@@ -246,6 +249,17 @@ const LineItems = ({
</Badge>
) : null}
</div>
+ {!isIndirect && (
+ <PurchaseOrderLinePromisedDate
+ line={{
+ id: line.id,
+ purchaseOrderId: orderId,
+ receivedComplete: line.receivedComplete ?? false,
+ promisedDate: line.promisedDate
+ }}
+ order={order}
+ />
+ )}
</VStack>
</div>
</div>
@@ -560,6 +574,7 @@ const PurchaseOrderSummary = ({
formatter={formatter}
locale={locale}
lines={routeData?.lines ?? []}
+ order={routeData?.purchaseOrder}
shouldConvertCurrency={shouldConvertCurrency}
/>
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index d34c4582a5..d0241bc652 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1619,
+ "totalTools": 1620,
"modules": 14,
"tools": [
{"name":"accounting_closePeriod","classification":"WRITE","schema":"7e5905ac5974","response":"7e5905ac5974","permission":"accounting:update","paginates":false},
@@ -1025,6 +1025,7 @@
{"name":"purchasing_updatePurchaseOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderFavorite","classification":"WRITE","schema":"ff73dc321969","response":"bcde375ebd4c","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderLine","classification":"WRITE","schema":"1b3bb1270d43","response":"3797626bd17e","permission":"purchasing:update","paginates":false},
+ {"name":"purchasing_updatePurchaseOrderLineDate","classification":"WRITE","schema":"f319f45db0d0","response":"063a6777d378","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrderLineOrder","classification":"WRITE","schema":"33aad0d0c2bb","response":"none","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchaseOrders","classification":"WRITE","schema":"c182f3099a0b","response":"0eb0c2be01ed","permission":"purchasing:update","paginates":false},
{"name":"purchasing_updatePurchasingRFQLine","classification":"WRITE","schema":"886a79ee22a8","response":"3797626bd17e","permission":"purchasing:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.date.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.date.tsx
new file mode 100644
index 0000000000..93c02ff1e0
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.date.tsx
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { carbon } from "@carbon/api/carbon.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { purchaseOrderLineDateValidator } from "~/modules/purchasing/purchasing.models";
+
+export async function action(args: ActionFunctionArgs) {
+ const input = await validator(purchaseOrderLineDateValidator).request(args, {
+ params: ["lineId"]
+ });
+ if ("invalid" in input) return input.invalid;
+
+ const api = await carbon(args.request);
+ return api.purchasing.updatePurchaseOrderLineDate({
+ lineId: input.params.lineId,
+ field: input.data.field,
+ value: input.data.value ?? null
+ });
+}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
index 65bd7dfe9a..64678563f5 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx
@@ -133,8 +133,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- const { id, ...d } = validation.data;
+ // Dates save on their own (the Dates section); sent empty here, the
+ // update would clear them.
+ const {
+ id: _id,
+ requiredDate: _requiredDate,
+ promisedDate: _promisedDate,
+ ...d
+ } = validation.data;
const updatePurchaseOrderLine = await upsertPurchaseOrderLine(client, {
id: lineId,
@@ -189,7 +195,6 @@ export default function EditPurchaseOrderLineRoute() {
locationId: line?.locationId ?? "",
purchaseQuantity: line?.purchaseQuantity ?? 1,
purchaseUnitOfMeasureCode: line?.purchaseUnitOfMeasureCode ?? "",
- requiredDate: line?.requiredDate ?? undefined,
storageUnitId: line?.storageUnitId ?? "",
supplierPartId: line?.supplierPartId ?? "",
supplierShippingCost: line?.supplierShippingCost ?? 0,
@@ -207,6 +212,12 @@ export default function EditPurchaseOrderLineRoute() {
<PurchaseOrderLineForm
key={initialValues.id}
initialValues={initialValues}
+ lineDates={{
+ receivedComplete: line.receivedComplete ?? false,
+ requiredDate: line.requiredDate,
+ promisedDate: line.promisedDate,
+ receivedDate: line.receivedDate
+ }}
/>
<SupplierInteractionLineNotes
id={line?.id ?? ""}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.delivery.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.delivery.tsx
index 8e4736433f..c756b3d064 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delivery.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delivery.tsx
@@ -2,90 +2,29 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { assertIsPost, 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 { redirect } from "@carbon/utils";
+import { carbon, respond } from "@carbon/api/carbon.server";
+import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
-import {
- isPurchaseOrderLocked,
- purchaseOrderDeliveryValidator
-} from "~/modules/purchasing/purchasing.models";
-import {
- getPurchaseOrder,
- upsertPurchaseOrderDelivery
-} from "~/modules/purchasing/purchasing.service";
+import { purchaseOrderDeliveryValidator } from "~/modules/purchasing/purchasing.models";
import { setCustomFields } from "~/utils/form";
-import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
-
- const { orderId } = params;
- if (!orderId) throw new Error("Could not find orderId");
-
- // First check with view permission to get PO status
- const { client: viewClient } = await requirePermissions(request, {
- view: "purchasing"
- });
-
- const purchaseOrder = await getPurchaseOrder(viewClient, orderId);
- if (purchaseOrder.error) {
- throw redirect(
- path.to.purchaseOrderDetails(orderId),
- await flash(
- request,
- error(purchaseOrder.error, "Failed to load purchase order")
- )
- );
- }
-
- await requireUnlocked({
- request,
- isLocked: isPurchaseOrderLocked(purchaseOrder.data?.status),
- redirectTo: path.to.purchaseOrderDetails(orderId),
- message: "Cannot modify a confirmed purchase order."
+export async function action(args: ActionFunctionArgs) {
+ const input = await validator(purchaseOrderDeliveryValidator).request(args, {
+ params: ["orderId"]
});
-
- const { client, userId } = await requirePermissions(request, {
- update: "purchasing"
+ if ("invalid" in input) return input.invalid;
+ const { orderId } = input.params;
+
+ const api = await carbon(args.request);
+ const result = await api.purchasing.updatePurchaseOrderDelivery({
+ ...input.data,
+ id: orderId,
+ customFields: input.formData ? setCustomFields(input.formData) : undefined
});
- const formData = await request.formData();
- const validation = await validator(purchaseOrderDeliveryValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const updatePurchaseOrderDelivery = await upsertPurchaseOrderDelivery(
- client,
- {
- ...validation.data,
- id: orderId,
- updatedBy: userId,
- customFields: setCustomFields(formData)
- }
- );
- if (updatePurchaseOrderDelivery.error) {
- throw redirect(
- path.to.purchaseOrderDetails(orderId),
- await flash(
- request,
- error(
- updatePurchaseOrderDelivery.error,
- "Failed to update purchase order delivery"
- )
- )
- );
- }
-
- throw redirect(
+ return respond(args.request, result).redirect(
path.to.purchaseOrderDetails(orderId),
- await flash(request, success("Updated purchase order delivery"))
+ { message: "Updated purchase order delivery" }
);
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
index c64fc61eaf..50f2dbbfcf 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
@@ -10,6 +10,7 @@ import { validationError, validator } from "@carbon/form";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { useParams } from "react-router";
+import { useRouteData } from "~/hooks";
import { getUnreleasedChangeOrderIssue } from "~/modules/items/items.service";
import {
isPurchaseOrderLocked,
@@ -19,6 +20,7 @@ import {
getPurchaseOrder,
upsertPurchaseOrderLine
} from "~/modules/purchasing/purchasing.service";
+import type { PurchaseOrder } from "~/modules/purchasing/types";
import { PurchaseOrderLineForm } from "~/modules/purchasing/ui/PurchaseOrder";
import type { MethodItemType } from "~/modules/shared/types";
import { setCustomFields } from "~/utils/form";
@@ -113,6 +115,10 @@ export default function NewPurchaseOrderLineRoute() {
if (!orderId) throw new Error("Could not find purchase order id");
+ const routeData = useRouteData<{ purchaseOrder: PurchaseOrder }>(
+ path.to.purchaseOrder(orderId)
+ );
+
const initialValues = {
conversionFactor: 1,
exchangeRate: 1,
@@ -124,7 +130,8 @@ export default function NewPurchaseOrderLineRoute() {
purchaseOrderLineType: "Part" as MethodItemType,
purchaseQuantity: 1,
purchaseUnitOfMeasureCode: "",
- requiredDate: undefined,
+ requiredDate: routeData?.purchaseOrder?.receiptRequestedDate ?? undefined,
+ promisedDate: routeData?.purchaseOrder?.receiptPromisedDate ?? undefined,
setupPrice: 0,
storageUnitId: "",
supplierShippingCost: 0,
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 919ae00432..d6544c06d0 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -2092,6 +2092,8 @@ export const path = {
generatePath(`${x}/purchase-order/${id}/finalize`),
purchaseOrderLine: (orderId: string, id: string) =>
generatePath(`${x}/purchase-order/${orderId}/${id}/details`),
+ purchaseOrderLineDate: (orderId: string, id: string) =>
+ generatePath(`${x}/purchase-order/${orderId}/${id}/date`),
purchaseOrderLineOrder: (orderId: string) =>
generatePath(`${x}/purchase-order/${orderId}/line-order`),
purchaseOrderLineReceiving: (orderId: string, id: string) =>
diff --git a/apps/erp/test/database/purchase-order-line-dates.test.ts b/apps/erp/test/database/purchase-order-line-dates.test.ts
new file mode 100644
index 0000000000..b9ec7fc14a
--- /dev/null
+++ b/apps/erp/test/database/purchase-order-line-dates.test.ts
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { expect } from "vitest";
+import { cascadePurchaseOrderDateToLines } from "../../app/modules/purchasing/purchasing.service";
+import {
+ alwaysPostFixture,
+ type Fixture,
+ seed,
+ USER
+} from "./fixtures/always-post";
+import { databaseTest } from "./fixtures/local-database";
+
+type LineSeed = {
+ key: string;
+ requiredDate?: string | null;
+ receivedDate?: string | null;
+ quantityReceived?: number;
+ receivedComplete?: boolean;
+};
+
+async function purchaseOrder(
+ f: Fixture,
+ delivery: { receiptRequestedDate?: string; deliveryDate?: string },
+ lines: LineSeed[]
+): Promise<string> {
+ const purchaseOrderId = `${f.prefix}-po-dates`;
+ await seed(f, async (trx) => {
+ const interaction = await trx
+ .insertInto("supplierInteraction")
+ .values({ supplierId: f.supplierId, companyId: f.companyId })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("purchaseOrder")
+ .values({
+ id: purchaseOrderId,
+ purchaseOrderId: "PO-DATES",
+ supplierId: f.supplierId,
+ supplierInteractionId: interaction.id,
+ currencyCode: "USD",
+ exchangeRate: 1,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("purchaseOrderDelivery")
+ .values({
+ id: purchaseOrderId,
+ locationId: f.locationId,
+ companyId: f.companyId,
+ ...delivery
+ })
+ .execute();
+ await trx
+ .insertInto("purchaseOrderLine")
+ .values(
+ lines.map((line) => ({
+ id: `${f.prefix}-pol-${line.key}`,
+ purchaseOrderId,
+ purchaseOrderLineType: "Part" as const,
+ itemId: f.partId,
+ purchaseQuantity: 10,
+ quantityReceived: line.quantityReceived ?? 0,
+ receivedComplete: line.receivedComplete ?? false,
+ requiredDate: line.requiredDate ?? null,
+ receivedDate: line.receivedDate ?? null,
+ supplierUnitPrice: 10,
+ exchangeRate: 1,
+ conversionFactor: 1,
+ inventoryUnitOfMeasureCode: "EA",
+ locationId: f.locationId,
+ companyId: f.companyId,
+ createdBy: USER
+ }))
+ )
+ .execute();
+ });
+ return purchaseOrderId;
+}
+
+async function lineDates(f: Fixture, purchaseOrderId: string) {
+ const rows = await f.db
+ .selectFrom("purchaseOrderLine")
+ .select(["id", "requiredDate", "receivedDate"])
+ .where("purchaseOrderId", "=", purchaseOrderId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ return Object.fromEntries(
+ rows.map((row) => [row.id.slice(`${f.prefix}-pol-`.length), row])
+ );
+}
+
+databaseTest(
+ "a new requested date moves the lines on the old date or none, and leaves the rest",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const purchaseOrderId = await purchaseOrder(
+ f,
+ { receiptRequestedDate: "2026-11-01" },
+ [
+ { key: "empty" },
+ { key: "following", requiredDate: "2026-11-01" },
+ { key: "own", requiredDate: "2026-11-15" },
+ {
+ key: "received",
+ requiredDate: "2026-11-01",
+ quantityReceived: 10,
+ receivedComplete: true
+ }
+ ]
+ );
+
+ await cascadePurchaseOrderDateToLines(f.db, {
+ companyId: f.companyId,
+ userId: USER,
+ purchaseOrderIds: [purchaseOrderId],
+ field: "receiptRequestedDate",
+ value: "2026-11-20"
+ });
+
+ const lines = await lineDates(f, purchaseOrderId);
+ expect(lines.empty?.requiredDate).toBe("2026-11-20");
+ expect(lines.following?.requiredDate).toBe("2026-11-20");
+ expect(lines.own?.requiredDate).toBe("2026-11-15");
+ expect(lines.received?.requiredDate).toBe("2026-11-01");
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "an order date that does not change leaves a line with no date empty",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const purchaseOrderId = await purchaseOrder(
+ f,
+ { receiptRequestedDate: "2026-11-01" },
+ [{ key: "empty" }]
+ );
+
+ await cascadePurchaseOrderDateToLines(f.db, {
+ companyId: f.companyId,
+ userId: USER,
+ purchaseOrderIds: [purchaseOrderId],
+ field: "receiptRequestedDate",
+ value: "2026-11-01"
+ });
+
+ const lines = await lineDates(f, purchaseOrderId);
+ expect(lines.empty?.requiredDate).toBeNull();
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "the delivery date goes only to lines that have received something",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const purchaseOrderId = await purchaseOrder(f, {}, [
+ { key: "partly", quantityReceived: 4 },
+ { key: "nothing" }
+ ]);
+
+ await cascadePurchaseOrderDateToLines(f.db, {
+ companyId: f.companyId,
+ userId: USER,
+ purchaseOrderIds: [purchaseOrderId],
+ field: "deliveryDate",
+ value: "2026-11-05"
+ });
+
+ const lines = await lineDates(f, purchaseOrderId);
+ expect(lines.partly?.receivedDate).toBe("2026-11-05");
+ expect(lines.nothing?.receivedDate).toBeNull();
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/docs/content/docs/reference/purchase-orders.mdx b/docs/content/docs/reference/purchase-orders.mdx
index e5548c1152..dd2a8da311 100644
--- a/docs/content/docs/reference/purchase-orders.mdx
+++ b/docs/content/docs/reference/purchase-orders.mdx
@@ -38,6 +38,26 @@ The status is computed from the state of its lines, never set by hand.
<Status name="Rejected" terminal>Sign-off was declined.</Status>
</StatusFlow>
+## Dates
+
+The order and every line carry three dates: the <Term id="purchase-order-delivery-requested-date">Requested Date</Term>, the <Term id="purchase-order-delivery-promised-date">Promised Date</Term> and the <Term id="purchase-order-delivery-actual-date">Delivery Date</Term>.
+
+The order's dates are set on the **Shipping** card and in the properties panel. A line's dates are set in the **Dates** section of the line page, and the order summary shows each line's promised date as a **Promised** pill you can change in place.
+
+A new line starts on the order's Requested and Promised dates. When you change an order date, every line whose date is empty or still the old order date takes the new one. A line you gave its own date keeps it.
+
+<Callout type="info" title="The Delivery Date only reaches lines that received goods">
+The Delivery Date records when goods arrived, so a new order Delivery Date moves only lines with a quantity received. Posting a receipt also sets each received line's Delivery Date to the day of the receipt, which replaces a date you corrected by hand.
+</Callout>
+
+Each date locks at a different point:
+
+- **Requested Date** locks once the order is confirmed (from **"To Receive and Invoice"** onward).
+- **Promised Date** stays editable until the order is fully received (**"To Invoice"**, **"Completed"** or **"Closed"**). A line's promised date also locks when the line is received complete, and such a line keeps its requested and promised dates when the order's dates change.
+- **Delivery Date** can always be corrected.
+
+<Screenshot label="Purchase order line page: the Dates section with Requested Date disabled and Promised Date and Delivery Date editable on a To Receive order" caption="A confirmed order keeps the requested date and lets the promise move." />
+
## Related
<Cards>
@@ -76,6 +96,12 @@ The line is already fully received; there's nothing left to short-close. Reopen
### "Receiving is already closed for this line" / "Receiving is not closed for this line"
The close/reopen action was applied twice. The line is already in the requested state — refresh the page to see the current state.
+### "Cannot change the requested date of a confirmed purchase order."
+A line's Requested Date (`purchaseOrderLine.requiredDate`) locks at the same statuses as the order. Reopen the order to change it, or record the supplier's new date as the Promised Date.
+
+### "Cannot change the promised date of a received line." / "…of a fully received purchase order." / "…of a closed purchase order."
+The line is received complete, the order is at "To Invoice" or "Completed", or the order was closed (a Closed order may still have lines with nothing received; reopen it to change the date). Line dates save one at a time through `updatePurchaseOrderLineDate`; the order's Receipt Promised Date through `updatePurchaseOrders`.
+
### "Failed to finalize purchase order"
Generic wrapper. Common underlying causes: no PO number sequence configured for the company, or a PDF/email step failing (separate "Failed to generate PDF" / "Failed to send email" messages). Ask for the full error text and check the supplier contact's email if sending failed.
</AgentContext>
diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.ts
index 5922de5a06..ab34cc7849 100644
--- a/docs/content/src/glossary/terms.ts
+++ b/docs/content/src/glossary/terms.ts
@@ -1725,8 +1725,8 @@ export const terms = {
definition: msg`The specific operation on the job above that this PO line is purchasing; only operations marked outside-processing are selectable.`
},
"purchase-order-line-required-date": {
- term: msg`Required Date`,
- definition: msg`When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling.`
+ term: msg`Requested Date`,
+ definition: msg`When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling.`
},
"purchase-order-line-delivery-location": {
term: msg`Delivery Location`,
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 1fe6002aec..2d345be3ce 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Wann Lieferantenreaktionen erwartet werden; Lieferanten sehen dieses Dat
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Wenn der Einkäufer die Ware anforderte; der Lieferant kann am Zugesagten Termin etwas anderes zusagen und am Liefertermin wieder etwas anderes liefern."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Wenn der Einkäufer diese Positionsware auf der Rampe benötigt; die Planung verwendet dieses Datum für Bestandsverfügbarkeit und Fremdbearbeitung-Planung."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Wann der Einkäufer die Ware dieser Position an der Laderampe benötigt. Eine neue Position übernimmt den Wunschtermin des Auftrags; die Planung verwendet dieses Datum für die Terminierung von Lagerverfügbarkeit und Fremdbearbeitung."
msgid "When the contract runs and what happens when it completes."
msgstr "Wenn der Vertrag läuft und was beim Abschluss passiert."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 37069a0d85..e29a97f99b 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -26630,8 +26630,8 @@ msgstr "When supplier responses are expected back; suppliers see this date on th
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
msgid "When the contract runs and what happens when it completes."
msgstr "When the contract runs and what happens when it completes."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index e2b2948b8b..a27addc201 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Cuándo se espera que respondan los proveedores; los proveedores ven est
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Cuándo el comprador solicitó los bienes; el proveedor puede prometer algo diferente en la Fecha Prometida y contabilizar algo diferente nuevamente en la Fecha de Entrega."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Cuándo el comprador necesita los bienes de esta línea en el muelle; la planificación utiliza esta fecha para disponibilidad de existencias y programación de procesamiento externo."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Cuándo necesita el comprador la mercancía de esta línea en el muelle. Una nueva línea empieza en la fecha solicitada del pedido; la planificación usa esta fecha para programar la disponibilidad de stock y los procesos subcontratados."
msgid "When the contract runs and what happens when it completes."
msgstr "Cuándo corre el contrato y qué ocurre cuando se completa."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 830eec3f5f..b6688f5cdc 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Quand les réponses des fournisseurs sont attendues ; les fournisseurs v
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Quand l'acheteur a demandé les marchandises ; le fournisseur peut promettre quelque chose d'autre à la Date Promise et contabiliser quelque chose d'autre à nouveau à la Date de Livraison."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Quand l'acheteur a besoin des marchandises de cette ligne au quai ; la planification utilise cette date pour la disponibilité des stocks et l'ordonnancement du traitement externe."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Date à laquelle l'acheteur a besoin des marchandises de cette ligne sur le quai. Une nouvelle ligne démarre à la Date demandée de la commande ; la planification utilise cette date pour programmer la disponibilité des stocks et la sous-traitance."
msgid "When the contract runs and what happens when it completes."
msgstr "Quand le contrat s'exécute et ce qui se passe quand il s'achève."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 6eed3c55f7..31195c4e2b 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -26630,8 +26630,8 @@ msgstr "जब आपूर्तिकर्ता प्रतिक्रि
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "जब क्रेता ने माल के लिए अनुरोध किया; आपूर्तिकर्ता वादा की गई तिथि पर कुछ और वादा कर सकता है और डिलीवरी तिथि पर फिर से कुछ और पोस्ट कर सकता है।"
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "जब क्रेता को इस पंक्ति के माल की डॉक पर आवश्यकता हो; योजना स्टॉक-उपलब्धता और बाहरी प्रसंस्करण शेड्यूलिंग के लिए इस तिथि का उपयोग करती है।"
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "क्रेता को इस पंक्ति का माल डॉक पर कब चाहिए। नई पंक्ति ऑर्डर की अनुरोधित तिथि से शुरू होती है; योजना इस तिथि का उपयोग स्टॉक उपलब्धता और बाहरी प्रसंस्करण की शेड्यूलिंग के लिए करती है।"
msgid "When the contract runs and what happens when it completes."
msgstr "जब अनुबंध चलता है और जब वह पूर्ण होता है तो क्या होता है।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index aa68686ca3..d9f394d0a8 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Quando si prevede che i fornitori rispondano; i fornitori vedono questa
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Quando il buyer ha richiesto la merce; il fornitore può promettere qualcosa di diverso sulla data promessa e consegnare qualcosa di diverso di nuovo sulla data di consegna."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Quando il Buyer ha bisogno dei beni di questa riga sulla banchina; la pianificazione utilizza questa data per la disponibilità della giacenza e la pianificazione della lavorazione esterna."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Quando il Buyer richiede la merce di questa riga in banchina. Una nuova riga parte dalla Data richiesta dell'ordine; la Pianificazione usa questa data per la verifica della disponibilità di magazzino e per la programmazione delle lavorazioni esterne."
msgid "When the contract runs and what happens when it completes."
msgstr "Quando il contratto è in corso e cosa accade al completamento."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index ad2bf606a3..798d812287 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -26630,8 +26630,8 @@ msgstr "仕入先の回答が返信予定の日付。仕入先は見積依頼ポ
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "購買担当者が商品をリクエストした日付。仕入先は回答納期に異なる日付を約束し、納期に再び別の日付を記録することができます。"
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "購買担当者がこの明細の商品をドックに必要とする日付。計画はこの日付を在庫可用性と外注加工スケジュール用に使用します。"
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "購買担当者がこの明細の品物を受入ドックに必要とする日です。新しい明細は、オーダーの希望納期が初期値になります。計画では、この日付を在庫可否および外注工程のスケジュール設定に使用します。"
msgid "When the contract runs and what happens when it completes."
msgstr "契約の実行期間と完了時のアクション。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index c5f01bd72a..175c6c0c44 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -26630,8 +26630,8 @@ msgstr "공급업체 응답이 도착할 것으로 예상되는 시점입니다.
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "구매 담당자가 물품을 요청한 시점; 공급업체는 약속일에 다른 것을 약속할 수 있으며 납기일에 다시 다른 것을 전기할 수 있습니다."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "구매 담당자가 이 라인의 물품을 도크에서 필요로 할 때; 계획은 이 날짜를 재고 가용성 및 외주 처리 스케줄링에 사용합니다."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "구매 담당자가 이 라인의 품목을 하역장(도크)에서 받기를 원하는 날짜입니다. 새 라인은 주문의 요청일로 시작하며, 계획에서는 이 날짜를 재고 가용성 및 외주 공정 일정 산정에 사용합니다."
msgid "When the contract runs and what happens when it completes."
msgstr "계약이 실행되는 시간과 완료되면 어떻게 되는가"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 30621045f0..6467643bfc 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Kiedy oczekuje się odpowiedzi dostawców; dostawcy widzą tę datę w p
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Gdy kupiec poprosił o towar; dostawca może obiecać coś innego w polu Data potwierdzona i dostarczyć coś innego w polu Data dostawy."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Gdy kupiec potrzebuje towaru z tej pozycji na doku; planowanie wykorzystuje tę datę do dostępności zapasu i planowania kooperacji."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Termin, w którym kupiec potrzebuje towaru z tej pozycji na rampie przyjęć. Nowa pozycja jest domyślnie ustawiana na datę żądaną zamówienia; planowanie wykorzystuje tę datę do harmonogramowania dostępności zapasów i obróbki zewnętrznej."
msgid "When the contract runs and what happens when it completes."
msgstr "Kiedy umowa działa i co się dzieje po jej zakończeniu."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index e77772e729..dcd4ad3aff 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Quando se espera que os fornecedores respondam; os fornecedores veem est
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Quando o comprador solicitou os bens; o fornecedor pode prometer algo diferente na Data Prometida e contabilizar algo diferente novamente na Data de Entrega."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Quando o comprador precisa dos bens desta linha no cais; o planejamento usa esta data para disponibilidade de estoque e agendamento de processamento externo."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Quando o comprador precisa que as mercadorias desta linha estejam na doca de recebimento. Uma nova linha começa na Data solicitada do pedido; o Planejamento usa esta data para o agendamento de disponibilidade de estoque e de processamento externo."
msgid "When the contract runs and what happens when it completes."
msgstr "Quando o contrato é executado e o que acontece quando é concluído."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index ef5af1033a..042ad67b50 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Когда ожидается ответ поставщиков; пос
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Когда закупщик запросил товары; поставщик может обещать что-то другое по дате подтверждения и провести что-то другое в дату поставки."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Когда закупщику нужны товары этой строки на причале; планирование использует эту дату для проверки наличия запаса и планирования кооперации."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Когда закупщику нужны товары по этой строке на складе приёмки. Новая строка начинается с запрошенной даты заказа; планирование использует эту дату для проверки наличия на складе и планирования внешней обработки."
msgid "When the contract runs and what happens when it completes."
msgstr "Когда контракт вступает в действие и что происходит при его завершении."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b9d7774383..1def5eb361 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -26630,8 +26630,8 @@ msgstr "Tedarikçi yanıtlarının ne zaman beklenmesi gerektiği; tedarikçiler
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "Satın almacının malları istediği zaman; tedarikçi Taahhüt tarihinde başka bir şey taahhüt edebilir ve Teslim tarihinde yine başka bir şey muhasebeleştirebilir."
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "Satın almacının bu satırın mallarına rampa üzerinde ihtiyaç duyduğu zaman; planlama bu tarihi stok uygunluğu ve fason işlem planlaması için kullanır."
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "Satın almacının bu satırdaki malları rıhtımda istediği tarih. Yeni bir satır, siparişin Talep edilen tarihinde başlar; planlama bu tarihi stok uygunluğu ve dış işlem çizelgelemesi için kullanır."
msgid "When the contract runs and what happens when it completes."
msgstr "Sözleşme ne zaman çalıştırılır ve tamamlandığında ne olur."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 6ddcbb97b9..32db003bec 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -26630,8 +26630,8 @@ msgstr "何时预期供应商回复;供应商在RFQ门户上看到该日期,Carb
msgid "When the buyer asked for the goods; the supplier may promise something else on Promised Date and post something else again on Delivery Date."
msgstr "当采购员要求货物时;供应商可能在承诺日期承诺其他内容,在交货日期再过账其他内容。"
-msgid "When the buyer needs this line's goods on the dock; planning uses this date for stock-availability and outside-processing scheduling."
-msgstr "当采购员需要此行的货物在码头时;计划使用此日期进行库存可用性和委外加工调度。"
+msgid "When the buyer needs this line's goods on the dock. A new line starts on the order's Requested Date; planning uses this date for stock-availability and outside-processing scheduling."
+msgstr "采购员需要本行物料到货的日期。新增行默认从订单的要求日期开始;计划根据此日期安排库存可用性和外协加工的排程。"
msgid "When the contract runs and what happens when it completes."
msgstr "当合同运行时以及完成时会发生什么。"