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.

Reorder line items (#776)

Gaurav Bhattcf184bcfe047
diff --git a/.claude/skills/database-transactions/SKILL.md b/.claude/skills/database-transactions/SKILL.md
new file mode 100644
index 0000000000..b92e1f804a
--- /dev/null
+++ b/.claude/skills/database-transactions/SKILL.md
@@ -0,0 +1,77 @@
+---
+name: database-transactions
+description: Use when writing service functions that perform multi-row database writes, bulk updates, reordering, or any operation that must succeed or fail atomically. Triggers on Kysely transactions, sortOrder updates, bulk inserts/updates, multi-table writes, and service functions with array/loop writes.
+---
+
+# Database Transactions in Carbon
+
+## When to use Kysely transactions
+
+When a service function writes to **multiple rows** — whether by mapping over an array, looping, or chaining several inserts/updates that must succeed or fail together — wrap the writes in a Postgres transaction via **Kysely**, not a `Promise.all` of independent Supabase calls.
+
+**Why:** every `client.from(...).update(...)` is a separate HTTP roundtrip to PostgREST. With `Promise.all`, three of five rows can commit and the rest fail, leaving the data in a half-applied state with no rollback. Kysely opens one PG transaction, runs every write inside it, and rolls everything back on any error.
+
+**Use transactions when:**
+- Bulk reorder / sortOrder updates across N rows.
+- Writes that span multiple tables and need to be all-or-nothing (e.g. parent + child rows, denormalized counters).
+- Anything where partial application would be a real bug, not a cosmetic glitch.
+
+**Don't use transactions when:**
+- A single write (already atomic).
+- Reads only — keep using the Supabase client (`client.from(...).select(...)`), Kysely has no auth/RLS context.
+- Throwaway/idempotent fan-out where partial failure is fine and retry is cheap.
+
+## The Carbon transaction pattern
+
+Service function takes `db: Kysely<KyselyDatabase>` and wraps writes in `db.transaction().execute(async (trx) => { ... })`. The route handler injects the connection via `getDatabaseClient()` from `~/services/database.server`. Real precedents to copy from: `items.service.ts -> upsertPickMethodWithShelfLife`, `production.service.ts -> updateProcedureStepOrder` (older `Promise.all` version — do not mirror), and all of the `update<Entity>LineOrder` functions across `purchasing`, `sales`, `invoicing` services.
+
+### Service function example
+
+```ts
+// apps/erp/app/modules/purchasing/purchasing.service.ts
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+
+export async function updatePurchaseOrderLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("purchaseOrderLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+```
+
+### Route handler example
+
+```ts
+// apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
+import { getDatabaseClient } from "~/services/database.server";
+import { updatePurchaseOrderLineOrder } from "~/modules/purchasing";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { userId } = await requirePermissions(request, { update: "purchasing" });
+ // ... build `updates` from formData ...
+ try {
+ await updatePurchaseOrderLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+ return { success: true };
+}
+```
+
+## Key notes
+
+- **`Kysely<KyselyDatabase>` is the first arg by convention.** The route passes `getDatabaseClient()`.
+- Kysely throws on rollback — wrap the call in `try/catch`, don't expect an `{ error }` return.
+- Kysely auto-quotes reserved column names (e.g. `order`), so `.set({ order: sortOrder })` is safe.
+- Kysely uses a connection pool and the Postgres role — **it bypasses RLS.** Enforce auth at the route via `requirePermissions(...)`, and when in doubt scope queries by `companyId` inside the transaction.
diff --git a/apps/erp/app/components/LineReorder/ReorderEditBar.tsx b/apps/erp/app/components/LineReorder/ReorderEditBar.tsx
new file mode 100644
index 0000000000..d1aef86fda
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/ReorderEditBar.tsx
@@ -0,0 +1,39 @@
+import { Button } from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+
+type ReorderEditBarProps = {
+ isSaving: boolean;
+ isDirty: boolean;
+ onSave: () => void;
+ onCancel: () => void;
+};
+
+export function ReorderEditBar({
+ isSaving,
+ isDirty,
+ onSave,
+ onCancel
+}: ReorderEditBarProps) {
+ return (
+ <div className="flex gap-1 flex-1">
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onCancel}
+ isDisabled={isSaving}
+ className="flex-1 h-8 text-xs"
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={onSave}
+ isDisabled={!isDirty || isSaving}
+ className="flex-1 h-8 text-xs"
+ >
+ {isSaving ? <Trans>Saving...</Trans> : <Trans>Save</Trans>}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/erp/app/components/LineReorder/ReorderableLineList.tsx b/apps/erp/app/components/LineReorder/ReorderableLineList.tsx
new file mode 100644
index 0000000000..907915cea4
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/ReorderableLineList.tsx
@@ -0,0 +1,109 @@
+import { ClientOnly, cn, VStack } from "@carbon/react";
+import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core";
+import {
+ closestCenter,
+ DndContext,
+ DragOverlay,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors
+} from "@dnd-kit/core";
+import {
+ SortableContext,
+ useSortable,
+ verticalListSortingStrategy
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import type { ReactNode } from "react";
+import { createPortal } from "react-dom";
+import type { DragHandleBindings, ReorderableLine } from "./types";
+
+type ReorderableLineListProps<T extends ReorderableLine> = {
+ lines: T[];
+ activeLine: T | null;
+ onDragStart: (event: DragStartEvent) => void;
+ onDragEnd: (event: DragEndEvent) => void;
+ renderRow: (line: T, dragHandle: DragHandleBindings) => ReactNode;
+ renderOverlay: (line: T) => ReactNode;
+};
+
+export function ReorderableLineList<T extends ReorderableLine>({
+ lines,
+ activeLine,
+ onDragStart,
+ onDragEnd,
+ renderRow,
+ renderOverlay
+}: ReorderableLineListProps<T>) {
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(KeyboardSensor)
+ );
+
+ return (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ >
+ <SortableContext
+ items={lines.map((l) => l.id!)}
+ strategy={verticalListSortingStrategy}
+ >
+ <VStack spacing={0} className="w-full">
+ {lines.map((line) => (
+ <SortableLineRow key={line.id} line={line} renderRow={renderRow} />
+ ))}
+ </VStack>
+ </SortableContext>
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay dropAnimation={null}>
+ {activeLine && renderOverlay(activeLine)}
+ </DragOverlay>,
+ document.body
+ )
+ }
+ </ClientOnly>
+ </DndContext>
+ );
+}
+
+function SortableLineRow<T extends ReorderableLine>({
+ line,
+ renderRow
+}: {
+ line: T;
+ renderRow: (line: T, dragHandle: DragHandleBindings) => ReactNode;
+}) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging
+ } = useSortable({ id: line.id! });
+
+ const style = {
+ transform: CSS.Translate.toString(transform),
+ transition: transition ?? undefined
+ };
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ "w-full border-b border-border/60 bg-card",
+ "transition-[opacity,background-color] duration-150 ease",
+ isDragging && "opacity-40 bg-muted/30"
+ )}
+ >
+ {renderRow(line, { attributes, listeners })}
+ </div>
+ );
+}
diff --git a/apps/erp/app/components/LineReorder/ReorderableRow.tsx b/apps/erp/app/components/LineReorder/ReorderableRow.tsx
new file mode 100644
index 0000000000..534d30b445
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/ReorderableRow.tsx
@@ -0,0 +1,47 @@
+import { cn, HStack } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import type { ReactNode } from "react";
+import { LuGripVertical } from "react-icons/lu";
+import type { DragHandleBindings } from "./types";
+
+type ReorderableRowProps = {
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+ children: ReactNode;
+};
+
+export function ReorderableRow({
+ dragHandle,
+ isOverlay,
+ children
+}: ReorderableRowProps) {
+ const { t } = useLingui();
+ return (
+ <HStack
+ spacing={0}
+ className={cn(
+ "w-full items-center relative",
+ isOverlay &&
+ "bg-card rounded-md shadow-[0_0_0_1px_hsl(var(--border)),0_4px_12px_rgba(0,0,0,0.08),0_12px_32px_rgba(0,0,0,0.06)]"
+ )}
+ >
+ {dragHandle && (
+ <button
+ type="button"
+ aria-label={t`Drag to reorder`}
+ className={cn(
+ "relative flex items-center justify-center w-10 h-10 shrink-0",
+ "text-muted-foreground/50 hover:text-foreground",
+ "cursor-grab active:cursor-grabbing active:scale-[0.96]",
+ "transition-[color,transform] duration-150 ease"
+ )}
+ {...dragHandle.attributes}
+ {...dragHandle.listeners}
+ >
+ <LuGripVertical className="w-4 h-4" />
+ </button>
+ )}
+ {children}
+ </HStack>
+ );
+}
diff --git a/apps/erp/app/components/LineReorder/index.ts b/apps/erp/app/components/LineReorder/index.ts
new file mode 100644
index 0000000000..d8e8e1642f
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/index.ts
@@ -0,0 +1,5 @@
+export { ReorderableLineList } from "./ReorderableLineList";
+export { ReorderableRow } from "./ReorderableRow";
+export { ReorderEditBar } from "./ReorderEditBar";
+export type { DragHandleBindings, ReorderableLine } from "./types";
+export { useLineOrderEditMode } from "./useLineOrderEditMode";
diff --git a/apps/erp/app/components/LineReorder/types.ts b/apps/erp/app/components/LineReorder/types.ts
new file mode 100644
index 0000000000..517a227d45
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/types.ts
@@ -0,0 +1,10 @@
+import type { useSortable } from "@dnd-kit/sortable";
+
+export type ReorderableLine = {
+ id: string | null | undefined;
+};
+
+export type DragHandleBindings = {
+ attributes: ReturnType<typeof useSortable>["attributes"];
+ listeners: ReturnType<typeof useSortable>["listeners"];
+};
diff --git a/apps/erp/app/components/LineReorder/useLineOrderEditMode.ts b/apps/erp/app/components/LineReorder/useLineOrderEditMode.ts
new file mode 100644
index 0000000000..b41542e28b
--- /dev/null
+++ b/apps/erp/app/components/LineReorder/useLineOrderEditMode.ts
@@ -0,0 +1,132 @@
+import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core";
+import { arrayMove } from "@dnd-kit/sortable";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useFetcher } from "react-router";
+import type { ReorderableLine } from "./types";
+
+type Options<T extends ReorderableLine> = {
+ actionPath: string;
+ lines: T[];
+ /** How to read the sort position off a line. Defaults to `line.sortOrder`. */
+ getSortOrder?: (line: T) => number;
+};
+
+/**
+ * Edit-mode state for drag-to-reorder line lists.
+ *
+ * Owns the draft order while the user reorders, debounceless save via a
+ * react-router fetcher, Esc to cancel, and a `submittedRef` guard so a
+ * leftover `fetcher.data.success` from a prior save doesn't auto-close a
+ * fresh re-entry to edit mode.
+ */
+export function useLineOrderEditMode<T extends ReorderableLine>({
+ actionPath,
+ lines,
+ getSortOrder = defaultGetSortOrder as (line: T) => number
+}: Options<T>) {
+ const fetcher = useFetcher<{ success?: boolean }>();
+
+ const [isEditing, setIsEditing] = useState(false);
+ const [draft, setDraft] = useState<T[]>([]);
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const submittedRef = useRef(false);
+
+ const isSaving = fetcher.state !== "idle";
+
+ const original = useMemo(
+ () => [...lines].sort((a, b) => getSortOrder(a) - getSortOrder(b)),
+ [lines, getSortOrder]
+ );
+
+ const isDirty = useMemo(() => {
+ if (draft.length !== original.length) return false;
+ return draft.some((d, i) => d.id !== original[i]?.id);
+ }, [draft, original]);
+
+ const enterEditMode = useCallback(() => {
+ setDraft(original.map((l) => ({ ...l })));
+ setIsEditing(true);
+ }, [original]);
+
+ const cancelEditMode = useCallback(() => {
+ setDraft([]);
+ setActiveId(null);
+ setIsEditing(false);
+ }, []);
+
+ const handleDragStart = useCallback((event: DragStartEvent) => {
+ setActiveId(String(event.active.id));
+ }, []);
+
+ const handleDragEnd = useCallback((event: DragEndEvent) => {
+ setActiveId(null);
+ const { active, over } = event;
+ if (!over || active.id === over.id) return;
+
+ setDraft((prev) => {
+ const oldIndex = prev.findIndex((l) => l.id === active.id);
+ const newIndex = prev.findIndex((l) => l.id === over.id);
+ if (oldIndex === -1 || newIndex === -1) return prev;
+ return arrayMove(prev, oldIndex, newIndex);
+ });
+ }, []);
+
+ const save = useCallback(() => {
+ if (!isDirty) return;
+ const updates: Record<string, number> = {};
+ draft.forEach((line, index) => {
+ if (line.id) updates[line.id] = index + 1;
+ });
+ const formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ submittedRef.current = true;
+ fetcher.submit(formData, { method: "post", action: actionPath });
+ }, [actionPath, draft, fetcher, isDirty]);
+
+ // Close edit mode once OUR save resolves. The ref makes sure we ignore
+ // fetcher.data left over from a previous submission when re-entering edit mode.
+ useEffect(() => {
+ if (
+ submittedRef.current &&
+ fetcher.state === "idle" &&
+ fetcher.data?.success
+ ) {
+ submittedRef.current = false;
+ setDraft([]);
+ setActiveId(null);
+ setIsEditing(false);
+ }
+ }, [fetcher.data, fetcher.state]);
+
+ // Esc cancels edit mode.
+ useEffect(() => {
+ if (!isEditing) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") cancelEditMode();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [isEditing, cancelEditMode]);
+
+ const activeLine = useMemo(
+ () => (activeId ? (draft.find((l) => l.id === activeId) ?? null) : null),
+ [activeId, draft]
+ );
+
+ return {
+ isEditing,
+ isSaving,
+ isDirty,
+ draft,
+ activeLine,
+ enterEditMode,
+ cancelEditMode,
+ handleDragStart,
+ handleDragEnd,
+ save
+ };
+}
+
+function defaultGetSortOrder(line: { sortOrder?: number | null }): number {
+ return line.sortOrder ?? 0;
+}
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 83ed7d0274..a9ad196128 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -1,4 +1,5 @@
import type { Database, Json } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { getLocalTimeZone, now, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
@@ -205,6 +206,7 @@ export async function getPurchaseInvoiceLines(
.from("purchaseInvoiceLines")
.select("*")
.eq("invoiceId", purchaseInvoiceId)
+ .order("sortOrder", { ascending: true })
.order("createdAt", { ascending: true });
}
@@ -287,6 +289,7 @@ export async function getSalesInvoiceLines(
.from("salesInvoiceLines")
.select("*")
.eq("invoiceId", salesInvoiceId)
+ .order("sortOrder", { ascending: true })
.order("createdAt", { ascending: true });
}
@@ -541,13 +544,38 @@ export async function upsertPurchaseInvoiceLine(
.single();
}
+ const existing = await client
+ .from("purchaseInvoiceLine")
+ .select("sortOrder")
+ .eq("invoiceId", purchaseInvoiceLine.invoiceId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
return client
.from("purchaseInvoiceLine")
- .insert([purchaseInvoiceLine])
+ .insert([{ ...purchaseInvoiceLine, sortOrder: maxSortOrder + 1 }])
.select("id")
.single();
}
+export async function updatePurchaseInvoiceLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("purchaseInvoiceLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
export async function upsertSalesInvoice(
client: SupabaseClient<Database>,
salesInvoice:
@@ -711,9 +739,34 @@ export async function upsertSalesInvoiceLine(
.single();
}
+ const existing = await client
+ .from("salesInvoiceLine")
+ .select("sortOrder")
+ .eq("invoiceId", salesInvoiceLine.invoiceId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
return client
.from("salesInvoiceLine")
- .insert([salesInvoiceLine])
+ .insert([{ ...salesInvoiceLine, sortOrder: maxSortOrder + 1 }])
.select("id")
.single();
}
+
+export async function updateSalesInvoiceLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("salesInvoiceLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
index 05e15ac29e..30e62a9148 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
@@ -20,9 +20,21 @@ import {
import { getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useParams } from "react-router";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import {
useOptimisticLocation,
usePermissions,
@@ -90,6 +102,15 @@ export default function PurchaseInvoiceExplorer() {
}
});
+ const lines = purchaseInvoiceData?.purchaseInvoiceLines ?? [];
+ const canReorder =
+ !isDisabled && permissions.can("update", "invoicing") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<PurchaseInvoiceLine>({
+ actionPath: path.to.purchaseInvoiceLineOrder(invoiceId),
+ lines
+ });
+
return (
<>
<VStack className="w-full h-[calc(100dvh-99px)] justify-between">
@@ -97,15 +118,33 @@ export default function PurchaseInvoiceExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {purchaseInvoiceData?.purchaseInvoiceLines?.length ? (
- purchaseInvoiceData.purchaseInvoiceLines.map((line) => (
- <PurchaseInvoiceLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line}
- onDelete={onDeleteLine}
+ {lines.length > 0 ? (
+ editMode.isEditing ? (
+ <ReorderableLineList<PurchaseInvoiceLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <PurchaseInvoiceLineBody
+ line={line}
+ dragHandle={dragHandle}
+ />
+ )}
+ renderOverlay={(line) => (
+ <PurchaseInvoiceLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <PurchaseInvoiceLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -121,29 +160,51 @@ export default function PurchaseInvoiceExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newPurchaseInvoiceLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newPurchaseInvoiceLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newPurchaseInvoiceLineDisclosure.isOpen && (
@@ -163,6 +224,37 @@ export default function PurchaseInvoiceExplorer() {
);
}
+function PurchaseInvoiceLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: PurchaseInvoiceLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ const [items] = useItems();
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.invoiceLineType === "G/L Account"
+ ? line.description || "Indirect Expense"
+ : getItemReadableId(items, line.itemId)}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.invoiceLineType === "G/L Account"
+ ? "G/L Account"
+ : line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type PurchaseInvoiceLineItemProps = {
line: PurchaseInvoiceLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index 043ad289c5..a39f6552e9 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -20,9 +20,21 @@ import {
import { getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useParams } from "react-router";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import {
useOptimisticLocation,
usePermissions,
@@ -94,6 +106,15 @@ export default function SalesInvoiceExplorer() {
}
});
+ const lines = salesInvoiceData?.salesInvoiceLines ?? [];
+ const canReorder =
+ !isDisabled && permissions.can("update", "invoicing") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<SalesInvoiceLine>({
+ actionPath: path.to.salesInvoiceLineOrder(invoiceId),
+ lines
+ });
+
return (
<>
<VStack className="w-full h-[calc(100dvh-99px)] justify-between">
@@ -101,15 +122,30 @@ export default function SalesInvoiceExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {salesInvoiceData?.salesInvoiceLines?.length ? (
- salesInvoiceData.salesInvoiceLines.map((line) => (
- <SalesInvoiceLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line}
- onDelete={onDeleteLine}
+ {lines.length > 0 ? (
+ editMode.isEditing ? (
+ <ReorderableLineList<SalesInvoiceLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <SalesInvoiceLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <SalesInvoiceLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <SalesInvoiceLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -125,29 +161,51 @@ export default function SalesInvoiceExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newSalesInvoiceLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newSalesInvoiceLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newSalesInvoiceLineDisclosure.isOpen && (
@@ -165,6 +223,33 @@ export default function SalesInvoiceExplorer() {
);
}
+function SalesInvoiceLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: SalesInvoiceLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ const [items] = useItems();
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {getItemReadableId(items, line.itemId) ?? ""}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type SalesInvoiceLineItemProps = {
line: SalesInvoiceLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 55d4a90004..7fe3f3ac48 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { getPurchaseOrderStatus } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import type {
@@ -282,6 +283,7 @@ export async function getPurchaseOrderLines(
.from("purchaseOrderLines")
.select("*")
.eq("purchaseOrderId", purchaseOrderId)
+ .order("sortOrder", { ascending: true })
.order("createdAt", { ascending: true });
}
@@ -730,7 +732,8 @@ export async function getSupplierQuoteLines(
return client
.from("supplierQuoteLines")
.select("*")
- .eq("supplierQuoteId", supplierQuoteId);
+ .eq("supplierQuoteId", supplierQuoteId)
+ .order("sortOrder", { ascending: true });
}
export async function getSupplierQuoteLinePrices(
@@ -1466,13 +1469,39 @@ export async function upsertPurchaseOrderLine(
.select("id")
.single();
}
+
+ const existing = await client
+ .from("purchaseOrderLine")
+ .select("sortOrder")
+ .eq("purchaseOrderId", purchaseOrderLine.purchaseOrderId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
return client
.from("purchaseOrderLine")
- .insert([purchaseOrderLine])
+ .insert([{ ...purchaseOrderLine, sortOrder: maxSortOrder + 1 }])
.select("id")
.single();
}
+export async function updatePurchaseOrderLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("purchaseOrderLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
export async function upsertPurchaseOrderPayment(
client: SupabaseClient<Database>,
purchaseOrderPayment:
@@ -1719,15 +1748,45 @@ export async function upsertSupplierQuoteLine(
.select("id")
.single();
}
+
+ const existing = await client
+ .from("supplierQuoteLine")
+ .select("sortOrder")
+ .eq("supplierQuoteId", supplierQuoteLine.supplierQuoteId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
return client
.from("supplierQuoteLine")
.insert([
- { ...supplierQuoteLine, description: supplierQuoteLine.description ?? "" }
+ {
+ ...supplierQuoteLine,
+ description: supplierQuoteLine.description ?? "",
+ sortOrder: maxSortOrder + 1
+ }
])
.select("id")
.single();
}
+export async function updateSupplierQuoteLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("supplierQuoteLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
export async function upsertSupplierType(
client: SupabaseClient<Database>,
supplierType:
@@ -1915,6 +1974,21 @@ export async function upsertPurchasingRFQLine(
.single();
}
+export async function updatePurchasingRFQLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("purchasingRfqLine")
+ .set({ order: sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
export async function upsertPurchasingRFQSuppliers(
client: SupabaseClient<Database>,
purchasingRfqId: string,
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index 9a1c3dc37c..71a7e4185d 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@ -20,10 +20,22 @@ import {
} from "@carbon/react";
import { getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import { useMemo, useRef, useState } from "react";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useParams } from "react-router";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import {
useOptimisticLocation,
usePermissions,
@@ -68,16 +80,26 @@ export default function PurchaseOrderExplorer() {
const deleteLineDisclosure = useDisclosure();
const [deleteLine, setDeleteLine] = useState<PurchaseOrderLine | null>(null);
- // Check if PO is in a locked state (finalized/approved)
const isLocked = isPurchaseOrderLocked(
purchaseOrderData?.purchaseOrder?.status
);
- // Adding new lines is NOT allowed on locked POs (would increase total)
- // For unlocked POs, only Draft status allows adding new lines
const isDisabled = isLocked
- ? true // No new lines on locked POs
+ ? true
: purchaseOrderData?.purchaseOrder?.status !== "Draft";
+ const lines = useMemo(
+ () => purchaseOrderData?.lines ?? [],
+ [purchaseOrderData]
+ );
+
+ const canReorder =
+ !isDisabled && permissions.can("update", "purchasing") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<PurchaseOrderLine>({
+ actionPath: path.to.purchaseOrderLineOrder(orderId),
+ lines
+ });
+
const onDeleteLine = (line: PurchaseOrderLine) => {
setDeleteLine(line);
deleteLineDisclosure.onOpen();
@@ -103,15 +125,30 @@ export default function PurchaseOrderExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {purchaseOrderData?.lines && purchaseOrderData?.lines?.length > 0 ? (
- purchaseOrderData?.lines.map((line) => (
- <PurchaseOrderLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line}
- onDelete={onDeleteLine}
+ {lines.length > 0 ? (
+ editMode.isEditing ? (
+ <ReorderableLineList<PurchaseOrderLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <PurchaseOrderLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <PurchaseOrderLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <PurchaseOrderLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -127,29 +164,51 @@ export default function PurchaseOrderExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newPurchaseOrderLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newPurchaseOrderLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newPurchaseOrderLineDisclosure.isOpen && (
@@ -166,6 +225,37 @@ export default function PurchaseOrderExplorer() {
);
}
+function PurchaseOrderLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: PurchaseOrderLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ const [items] = useItems();
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.purchaseOrderLineType === "G/L Account"
+ ? line.description || "Indirect Expense"
+ : getItemReadableId(items, line.itemId)}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.purchaseOrderLineType === "G/L Account"
+ ? "G/L Account"
+ : line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type PurchaseOrderLineItemProps = {
line: PurchaseOrderLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQExplorer.tsx
index e1cfdf435b..82ccda4ddd 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQExplorer.tsx
@@ -19,9 +19,21 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useParams } from "react-router";
import { Empty, ItemThumbnail } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import { usePermissions, useRouteData } from "~/hooks";
import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
@@ -78,6 +90,15 @@ export default function PurchasingRFQExplorer() {
const lines = purchasingRfqData?.lines ?? [];
+ const canReorder =
+ !isDisabled && permissions.can("update", "purchasing") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<PurchasingRFQLine>({
+ actionPath: path.to.purchasingRfqLineOrder(rfqId),
+ lines,
+ getSortOrder: (line) => line.order ?? 0
+ });
+
return (
<div data-purchasing-rfq-explorer>
<VStack className="w-full h-[calc(100dvh-99px)] justify-between">
@@ -86,14 +107,29 @@ export default function PurchasingRFQExplorer() {
spacing={0}
>
{lines.length > 0 ? (
- lines.map((line) => (
- <PurchasingRFQLineItem
- key={line.id}
- line={line}
- isDisabled={isDisabled}
- onDelete={onDeleteLine}
+ editMode.isEditing ? (
+ <ReorderableLineList<PurchasingRFQLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <PurchasingRFQLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <PurchasingRFQLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <PurchasingRFQLineItem
+ key={line.id}
+ line={line}
+ isDisabled={isDisabled}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "purchasing") && (
@@ -109,31 +145,51 @@ export default function PurchasingRFQExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={
- isDisabled || !permissions.can("update", "purchasing")
- }
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newPurchasingRFQLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "purchasing")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newPurchasingRFQLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newPurchasingRFQLineDisclosure.isOpen && (
@@ -150,6 +206,35 @@ export default function PurchasingRFQExplorer() {
);
}
+function PurchasingRFQLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: PurchasingRFQLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail
+ thumbnailPath={line.thumbnailPath}
+ type={line.itemType as MethodItemType}
+ />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.itemReadableId || line.description || "Item"}
+ </span>
+ <span className="font-medium text-muted-foreground text-xs line-clamp-1">
+ {line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type PurchasingRFQLineItemProps = {
line: PurchasingRFQLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
index 1b54973dab..a6148fd906 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
@@ -21,9 +21,21 @@ import {
import { getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useParams } from "react-router";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared";
@@ -82,6 +94,15 @@ export default function SupplierQuoteExplorer() {
}
});
+ const lines = routeData?.lines ?? [];
+ const canReorder =
+ !isDisabled && permissions.can("update", "purchasing") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<SupplierQuoteLine>({
+ actionPath: path.to.supplierQuoteLineOrder(id),
+ lines
+ });
+
return (
<>
<VStack className="w-full h-[calc(100dvh-99px)] justify-between">
@@ -89,15 +110,30 @@ export default function SupplierQuoteExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {routeData?.lines && routeData?.lines?.length > 0 ? (
- routeData?.lines.map((line) => (
- <SupplierQuoteLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line}
- onDelete={onDeleteLine}
+ {lines.length > 0 ? (
+ editMode.isEditing ? (
+ <ReorderableLineList<SupplierQuoteLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <SupplierQuoteLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <SupplierQuoteLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <SupplierQuoteLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -113,29 +149,51 @@ export default function SupplierQuoteExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newSupplierQuoteLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newSupplierQuoteLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newSupplierQuoteLineDisclosure.isOpen && (
@@ -158,6 +216,37 @@ export default function SupplierQuoteExplorer() {
);
}
+function SupplierQuoteLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: SupplierQuoteLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ const [items] = useItems();
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.supplierQuoteLineType === "G/L Account"
+ ? line.description || "Indirect Expense"
+ : getItemReadableId(items, line.itemId)}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.supplierQuoteLineType === "G/L Account"
+ ? "G/L Account"
+ : line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type SupplierQuoteLineItemProps = {
line: SupplierQuoteLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 514de51692..d1c134c995 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import type { PickPartial } from "@carbon/utils";
import { getLocalTimeZone, now, today } from "@internationalized/date";
import type {
@@ -1318,6 +1319,7 @@ export async function getQuoteLines(
.from("quoteLines")
.select("*")
.eq("quoteId", quoteId)
+ .order("sortOrder", { ascending: true })
.order("itemReadableId", { ascending: true });
}
@@ -1684,6 +1686,7 @@ export async function getSalesOrderLines(
.from("salesOrderLines")
.select("*")
.eq("salesOrderId", salesOrderId)
+ .order("sortOrder", { ascending: true })
.order("itemReadableId", { ascending: true });
}
@@ -1812,6 +1815,7 @@ export async function getSalesRFQLines(
.from("salesRfqLines")
.select("*")
.eq("salesRfqId", salesRfqId)
+ .order("order", { ascending: true })
.order("customerPartId", { ascending: true });
}
@@ -3085,20 +3089,6 @@ export async function updateSalesRFQFavorite(
}
}
-export async function updateSalesRFQLineOrder(
- client: SupabaseClient<Database>,
- updates: {
- id: string;
- order: number;
- updatedBy: string;
- }[]
-) {
- const updatePromises = updates.map(({ id, order, updatedBy }) =>
- client.from("salesRfqLine").update({ order, updatedBy }).eq("id", id)
- );
- return Promise.all(updatePromises);
-}
-
export async function updateQuoteExchangeRate(
client: SupabaseClient<Database>,
data: {
@@ -3503,7 +3493,37 @@ export async function upsertQuoteLine(
.select("id")
.single();
}
- return client.from("quoteLine").insert([quotationLine]).select("*").single();
+
+ const existing = await client
+ .from("quoteLine")
+ .select("sortOrder")
+ .eq("quoteId", quotationLine.quoteId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
+ return client
+ .from("quoteLine")
+ .insert([{ ...quotationLine, sortOrder: maxSortOrder + 1 }])
+ .select("*")
+ .single();
+}
+
+export async function updateQuoteLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("quoteLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
}
export async function upsertQuoteLineAdditionalCharges(
@@ -4853,15 +4873,44 @@ export async function upsertSalesOrderLine(
const salesOrder = await getSalesOrder(client, salesOrderLine.salesOrderId);
if (salesOrder.error) return salesOrder;
+ const existing = await client
+ .from("salesOrderLine")
+ .select("sortOrder")
+ .eq("salesOrderId", salesOrderLine.salesOrderId);
+
+ const maxSortOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.sortOrder ?? 0),
+ 0
+ );
+
return client
.from("salesOrderLine")
.insert([
- { ...salesOrderLine, exchangeRate: salesOrder.data?.exchangeRate ?? 1 }
+ {
+ ...salesOrderLine,
+ exchangeRate: salesOrder.data?.exchangeRate ?? 1,
+ sortOrder: maxSortOrder + 1
+ }
])
.select("id")
.single();
}
+export async function updateSalesOrderLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("salesOrderLine")
+ .set({ sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
export async function upsertSalesOrderPayment(
client: SupabaseClient<Database>,
salesOrderPayment:
@@ -4974,9 +5023,19 @@ export async function upsertSalesRFQLine(
})
) {
if ("createdBy" in salesRfqLine) {
+ const existing = await client
+ .from("salesRfqLine")
+ .select("order")
+ .eq("salesRfqId", salesRfqLine.salesRfqId);
+
+ const maxOrder = (existing.data ?? []).reduce(
+ (max, row) => Math.max(max, row.order ?? 0),
+ 0
+ );
+
return client
.from("salesRfqLine")
- .insert([salesRfqLine])
+ .insert([{ ...salesRfqLine, order: maxOrder + 1 }])
.select("id")
.single();
}
@@ -4987,3 +5046,18 @@ export async function upsertSalesRFQLine(
.select("id")
.single();
}
+
+export async function updateSalesRFQLineOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("salesRfqLine")
+ .set({ order: sortOrder, updatedBy })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index 8d7416ca64..8a8ba77f3f 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -34,12 +34,20 @@ import {
LuDownload,
LuEllipsisVertical,
LuSearch,
+ LuSettings2,
LuTable,
LuTrash
} from "react-icons/lu";
import { Link, useFetchers, useNavigate, useParams } from "react-router";
import { Empty, ItemThumbnail, MethodItemTypeIcon } from "~/components";
import { QuoteLineStatusIcon } from "~/components/Icons";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import type { Tree } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
import {
@@ -137,9 +145,22 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
linesMap.set(pendingItem.itemId!, { ...pendingItem, quoteId });
}
- const linesToRender = Array.from(linesMap.values()).sort((a, b) =>
- (a.itemReadableId ?? "").localeCompare(b.itemReadableId ?? "")
- );
+ // Server already returns lines ordered by sortOrder; the Map preserves
+ // insertion order so we just take values as-is. Optimistic items (added
+ // via .set() in the loop above) trail at the end, which is fine — they
+ // don't have a sortOrder yet.
+ const linesToRender = Array.from(linesMap.values());
+
+ const realQuoteLines = (quoteData?.lines ?? []) as QuotationLine[];
+ const canReorder =
+ !isDisabled &&
+ permissions.can("update", "sales") &&
+ realQuoteLines.length > 1;
+
+ const editMode = useLineOrderEditMode<QuotationLine>({
+ actionPath: path.to.quoteLineOrder(quoteId),
+ lines: realQuoteLines
+ });
return (
<div
@@ -156,20 +177,35 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
spacing={0}
>
{linesToRender.length > 0 ? (
- linesToRender.map((line) =>
- !isQuoteLine(line) ? (
- <OptimisticQuoteLineItem
- key={line.itemId}
- line={line as OptimisticQuoteLine}
- />
- ) : (
- <DroppableQuoteLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line as QuotationLine}
- onDelete={onDeleteLine}
- methods={methods}
- />
+ editMode.isEditing ? (
+ <ReorderableLineList<QuotationLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <QuoteLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <QuoteLineBody line={line} isOverlay />
+ )}
+ />
+ ) : (
+ linesToRender.map((line) =>
+ !isQuoteLine(line) ? (
+ <OptimisticQuoteLineItem
+ key={line.itemId}
+ line={line as OptimisticQuoteLine}
+ />
+ ) : (
+ <DroppableQuoteLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line as QuotationLine}
+ onDelete={onDeleteLine}
+ methods={methods}
+ />
+ )
)
)
) : (
@@ -187,29 +223,51 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newQuoteLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newQuoteLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && realQuoteLines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newQuoteLineDisclosure.isOpen && (
@@ -226,6 +284,32 @@ export default function QuoteExplorer({ methods }: QuoteExplorerProps) {
);
}
+function QuoteLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: QuotationLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.itemReadableId || line.description || "Item"}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
function isQuoteLine(
line: QuotationLine | OptimisticQuoteLine
): line is QuotationLine {
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index 0817b0806a..5cfeacfe6a 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -31,6 +31,7 @@ import {
LuCirclePlus,
LuEllipsisVertical,
LuSearch,
+ LuSettings2,
LuTrash,
LuTruck
} from "react-icons/lu";
@@ -42,6 +43,13 @@ import {
MethodIcon,
MethodItemTypeIcon
} from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import { LevelLine } from "~/components/TreeView";
import {
useOptimisticLocation,
@@ -176,6 +184,15 @@ export default function SalesOrderExplorer() {
}
});
+ const lines = salesOrderData?.lines ?? [];
+ const canReorder =
+ !isDisabled && permissions.can("update", "sales") && lines.length > 1;
+
+ const editMode = useLineOrderEditMode<SalesOrderLine>({
+ actionPath: path.to.salesOrderLineOrder(orderId),
+ lines
+ });
+
return (
<>
<VStack className="w-full h-[calc(100dvh-99px)] justify-between">
@@ -183,15 +200,30 @@ export default function SalesOrderExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {salesOrderData?.lines && salesOrderData?.lines?.length > 0 ? (
- salesOrderData?.lines.map((line) => (
- <SalesOrderLineItem
- key={line.id}
- isDisabled={isDisabled}
- line={line}
- onDelete={onDeleteLine}
+ {lines.length > 0 ? (
+ editMode.isEditing ? (
+ <ReorderableLineList<SalesOrderLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <SalesOrderLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <SalesOrderLineBody line={line} isOverlay />
+ )}
/>
- ))
+ ) : (
+ lines.map((line) => (
+ <SalesOrderLineItem
+ key={line.id}
+ isDisabled={isDisabled}
+ line={line}
+ onDelete={onDeleteLine}
+ />
+ ))
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -207,29 +239,51 @@ export default function SalesOrderExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newSalesOrderLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newSalesOrderLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && lines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newSalesOrderLineDisclosure.isOpen && (
@@ -246,6 +300,33 @@ export default function SalesOrderExplorer() {
);
}
+function SalesOrderLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: SalesOrderLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ const [items] = useItems();
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail thumbnailPath={line.thumbnailPath} type="Part" />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {getItemReadableId(items, line.itemId)}
+ </span>
+ <span className="text-muted-foreground text-xs truncate line-clamp-1">
+ {line.description}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type SalesOrderLineItemProps = {
line: SalesOrderLine;
isDisabled: boolean;
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index 3f4ff38781..29693579da 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -21,10 +21,22 @@ import {
import { useDroppable } from "@dnd-kit/core";
import { Trans } from "@lingui/react/macro";
import { useRef, useState } from "react";
-import { LuCirclePlus, LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import {
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuSettings2,
+ LuTrash
+} from "react-icons/lu";
import { Link, useFetchers, useParams } from "react-router";
import type { z } from "zod";
import { Empty, ItemThumbnail } from "~/components";
+import type { DragHandleBindings } from "~/components/LineReorder";
+import {
+ ReorderableLineList,
+ ReorderableRow,
+ ReorderEditBar,
+ useLineOrderEditMode
+} from "~/components/LineReorder";
import { usePermissions, useRealtime, useRouteData } from "~/hooks";
import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
@@ -104,6 +116,16 @@ export default function SalesRFQExplorer() {
}
const lines = Array.from(linesByCustomerPartId.values());
+ const realLines = (salesRfqData?.lines ?? []) as SalesRFQLine[];
+
+ const canReorder =
+ !isDisabled && permissions.can("update", "sales") && realLines.length > 1;
+
+ const editMode = useLineOrderEditMode<SalesRFQLine>({
+ actionPath: path.to.salesRfqLineOrder(rfqId),
+ lines: realLines,
+ getSortOrder: (line) => line.order ?? 0
+ });
return (
<div
@@ -121,19 +143,34 @@ export default function SalesRFQExplorer() {
>
{(salesRfqData?.lines && salesRfqData?.lines?.length > 0) ||
lines.length > 0 ? (
- lines.map((line) =>
- !isSalesRFQLine(line) ? (
- <OptimisticSalesRFQLineItem
- key={line.id}
- line={line as z.infer<typeof salesRfqDragValidator>}
- />
- ) : (
- <DroppableSalesRFQLineItem
- key={line.id}
- line={line as SalesRFQLine}
- isDisabled={isDisabled}
- onDelete={onDeleteLine}
- />
+ editMode.isEditing ? (
+ <ReorderableLineList<SalesRFQLine>
+ lines={editMode.draft}
+ activeLine={editMode.activeLine}
+ onDragStart={editMode.handleDragStart}
+ onDragEnd={editMode.handleDragEnd}
+ renderRow={(line, dragHandle) => (
+ <SalesRFQLineBody line={line} dragHandle={dragHandle} />
+ )}
+ renderOverlay={(line) => (
+ <SalesRFQLineBody line={line} isOverlay />
+ )}
+ />
+ ) : (
+ lines.map((line) =>
+ !isSalesRFQLine(line) ? (
+ <OptimisticSalesRFQLineItem
+ key={line.id}
+ line={line as z.infer<typeof salesRfqDragValidator>}
+ />
+ ) : (
+ <DroppableSalesRFQLineItem
+ key={line.id}
+ line={line as SalesRFQLine}
+ isDisabled={isDisabled}
+ onDelete={onDeleteLine}
+ />
+ )
)
)
) : (
@@ -151,29 +188,51 @@ export default function SalesRFQExplorer() {
</Empty>
)}
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newButtonRef}
- className="w-full"
- isDisabled={isDisabled || !permissions.can("update", "sales")}
- leftIcon={<LuCirclePlus />}
- variant="secondary"
- onClick={newSalesRFQLineDisclosure.onOpen}
- >
- <Trans>Add Line Item</Trans>
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <HStack>
- <span>
- <Trans>New Line Item</Trans>
- </span>
- <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
- </HStack>
- </TooltipContent>
- </Tooltip>
+ <div className="w-full flex border-t border-border p-4 gap-2">
+ {editMode.isEditing ? (
+ <ReorderEditBar
+ isSaving={editMode.isSaving}
+ isDirty={editMode.isDirty}
+ onSave={editMode.save}
+ onCancel={editMode.cancelEditMode}
+ />
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger className="flex-1">
+ <Button
+ ref={newButtonRef}
+ className="w-full"
+ isDisabled={
+ isDisabled || !permissions.can("update", "sales")
+ }
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={newSalesRFQLineDisclosure.onOpen}
+ >
+ <Trans>Add Line Item</Trans>
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <HStack>
+ <span>
+ <Trans>New Line Item</Trans>
+ </span>
+ <Kbd>{prettifyShortcut("Command+Shift+l")}</Kbd>
+ </HStack>
+ </TooltipContent>
+ </Tooltip>
+ {canReorder && realLines.length > 0 && (
+ <IconButton
+ aria-label="Reorder lines"
+ icon={<LuSettings2 />}
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={editMode.enterEditMode}
+ />
+ )}
+ </>
+ )}
</div>
</VStack>
{newSalesRFQLineDisclosure.isOpen && (
@@ -196,6 +255,36 @@ function isSalesRFQLine(
return "id" in line && "order" in line && "unitOfMeasureCode" in line;
}
+function SalesRFQLineBody({
+ line,
+ dragHandle,
+ isOverlay
+}: {
+ line: SalesRFQLine;
+ dragHandle?: DragHandleBindings;
+ isOverlay?: boolean;
+}) {
+ return (
+ <ReorderableRow dragHandle={dragHandle} isOverlay={isOverlay}>
+ <HStack spacing={2} className="flex-grow min-w-0 p-2 pr-10">
+ <ItemThumbnail
+ thumbnailPath={line.thumbnailPath}
+ type={line.itemType as MethodItemType}
+ />
+ <VStack spacing={0} className="min-w-0">
+ <span className="font-semibold line-clamp-1">
+ {line.customerPartId}
+ {line.customerPartRevision && `-${line.customerPartRevision}`}
+ </span>
+ <span className="font-medium text-muted-foreground text-xs line-clamp-1">
+ {line.itemReadableId}
+ </span>
+ </VStack>
+ </HStack>
+ </ReorderableRow>
+ );
+}
+
type DroppableSalesRFQLineItemProps = {
line: SalesRFQLine;
isDisabled: boolean;
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 90c91d45dc..70e2b2ee29 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -79,6 +79,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
GOOGLE_PLACES_API_KEY,
JIRA_CLIENT_ID,
MES_URL,
+ NODE_ENV,
NOVU_APPLICATION_ID,
NOVU_API_URL,
ONSHAPE_CLIENT_ID,
@@ -108,6 +109,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
GOOGLE_PLACES_API_KEY,
JIRA_CLIENT_ID,
MES_URL,
+ NODE_ENV,
NOVU_APPLICATION_ID,
NOVU_API_URL,
ONSHAPE_CLIENT_ID,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index e15282425a..53795cf470 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-05-15T14:00:49.014Z",
+ "generated": "2026-05-16T02:11:25.747Z",
"totalTools": 1075,
"modules": 15,
"tools": [
@@ -13049,7 +13049,7 @@
"description": "update sales r f q line order",
"paramCount": 3,
"serviceParams": [
- "client",
+ "db",
"updates"
],
"injectAuth": [
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx
new file mode 100644
index 0000000000..f29c3b35e4
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updatePurchaseInvoiceLineOrder } from "~/modules/invoicing";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "invoicing"
+ });
+
+ if (!params.invoiceId) throw new Error("Could not find invoiceId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updatePurchaseInvoiceLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
new file mode 100644
index 0000000000..7e5acbbe7b
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updatePurchaseOrderLineOrder } from "~/modules/purchasing";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "purchasing"
+ });
+
+ if (!params.orderId) throw new Error("Could not find orderId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updatePurchaseOrderLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx
new file mode 100644
index 0000000000..99b4a7f573
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$id.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updatePurchasingRFQLineOrder } from "~/modules/purchasing";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "purchasing"
+ });
+
+ if (!params.id) throw new Error("Could not find id");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updatePurchasingRFQLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx
new file mode 100644
index 0000000000..325ba3c1d4
--- /dev/null
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateQuoteLineOrder } from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "sales"
+ });
+
+ if (!params.quoteId) throw new Error("Could not find quoteId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateQuoteLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx
new file mode 100644
index 0000000000..fba5c58168
--- /dev/null
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateSalesInvoiceLineOrder } from "~/modules/invoicing";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "invoicing"
+ });
+
+ if (!params.invoiceId) throw new Error("Could not find invoiceId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateSalesInvoiceLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx
new file mode 100644
index 0000000000..8d300f198b
--- /dev/null
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateSalesOrderLineOrder } from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "sales"
+ });
+
+ if (!params.orderId) throw new Error("Could not find orderId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateSalesOrderLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx
new file mode 100644
index 0000000000..9a175ea88c
--- /dev/null
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateSalesRFQLineOrder } from "~/modules/sales";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "sales"
+ });
+
+ if (!params.rfqId) throw new Error("Could not find rfqId");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateSalesRFQLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx
new file mode 100644
index 0000000000..1d1eb59af0
--- /dev/null
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.line-order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateSupplierQuoteLineOrder } from "~/modules/purchasing";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "purchasing"
+ });
+
+ if (!params.id) throw new Error("Could not find id");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateSupplierQuoteLineOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index be02760bd9..19a8d9de26 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1318,6 +1318,8 @@ export const path = {
generatePath(`${x}/purchase-invoice/${id}/exchange-rate`),
purchaseInvoiceLine: (invoiceId: string, id: string) =>
generatePath(`${x}/purchase-invoice/${invoiceId}/${id}/details`),
+ purchaseInvoiceLineOrder: (invoiceId: string) =>
+ generatePath(`${x}/purchase-invoice/${invoiceId}/line-order`),
purchaseInvoicePost: (id: string) =>
generatePath(`${x}/purchase-invoice/${id}/post`),
purchaseInvoiceRoot: `${x}/purchase-invoice`,
@@ -1338,6 +1340,8 @@ export const path = {
purchaseOrderFavorite: `${x}/purchasing/orders/favorite`,
purchaseOrderLine: (orderId: string, id: string) =>
generatePath(`${x}/purchase-order/${orderId}/${id}/details`),
+ purchaseOrderLineOrder: (orderId: string) =>
+ generatePath(`${x}/purchase-order/${orderId}/line-order`),
purchaseOrderPayment: (id: string) =>
generatePath(`${x}/purchase-order/${id}/payment`),
purchaseOrderFinalize: (id: string) =>
@@ -1380,6 +1384,8 @@ export const path = {
generatePath(`${x}/quote/${id}/internal`),
quoteLine: (quoteId: string, id: string) =>
generatePath(`${x}/quote/${quoteId}/${id}/details`),
+ quoteLineOrder: (quoteId: string) =>
+ generatePath(`${x}/quote/${quoteId}/line-order`),
quoteLineConfigure: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/${quoteId}/${lineId}/configure`),
quoteLineMakeMethod: (
@@ -1448,6 +1454,8 @@ export const path = {
generatePath(`${x}/sales-invoice/${id}/exchange-rate`),
salesInvoiceLine: (id: string, lineId: string) =>
generatePath(`${x}/sales-invoice/${id}/${lineId}/details`),
+ salesInvoiceLineOrder: (id: string) =>
+ generatePath(`${x}/sales-invoice/${id}/line-order`),
salesInvoicePost: (id: string) =>
generatePath(`${x}/sales-invoice/${id}/post`),
salesInvoiceShipment: (id: string) =>
@@ -1473,6 +1481,8 @@ export const path = {
generatePath(`${x}/sales-order/${id}/internal`),
salesOrderLine: (orderId: string, id: string) =>
generatePath(`${x}/sales-order/${orderId}/${id}/details`),
+ salesOrderLineOrder: (orderId: string) =>
+ generatePath(`${x}/sales-order/${orderId}/line-order`),
salesOrderLineToJob: (orderId: string, lineId: string) =>
generatePath(`${x}/sales-order/${orderId}/${lineId}/job`),
salesOrderLinesToJobs: (orderId: string) =>
@@ -1504,8 +1514,8 @@ export const path = {
salesRfqFavorite: `${x}/sales/rfqs/favorite`,
salesRfqLine: (id: string, lineId: string) =>
generatePath(`${x}/sales-rfq/${id}/${lineId}/details`),
- salesRfqLinesOrder: (id: string) =>
- generatePath(`${x}/sales-rfq/${id}/lines/order`),
+ salesRfqLineOrder: (id: string) =>
+ generatePath(`${x}/sales-rfq/${id}/line-order`),
salesRfqRoot: `${x}/sales-rfq`,
salesRfqStatus: (id: string) => generatePath(`${x}/sales-rfq/${id}/status`),
salesRfqs: `${x}/sales/rfqs`,
@@ -1518,6 +1528,8 @@ export const path = {
purchasingRfqFavorite: `${x}/purchasing/rfqs/favorite`,
purchasingRfqLine: (id: string, lineId: string) =>
generatePath(`${x}/purchasing-rfq/${id}/${lineId}/details`),
+ purchasingRfqLineOrder: (id: string) =>
+ generatePath(`${x}/purchasing-rfq/${id}/line-order`),
purchasingRfqRoot: `${x}/purchasing-rfq`,
purchasingRfqStatus: (id: string) =>
generatePath(`${x}/purchasing-rfq/${id}/status`),
@@ -1640,6 +1652,8 @@ export const path = {
generatePath(`${x}/supplier-quote/${id}/exchange-rate`),
supplierQuoteLine: (id: string, lineId: string) =>
generatePath(`${x}/supplier-quote/${id}/${lineId}/details`),
+ supplierQuoteLineOrder: (id: string) =>
+ generatePath(`${x}/supplier-quote/${id}/line-order`),
supplierQuoteFinalize: (id: string) =>
generatePath(`${x}/supplier-quote/${id}/finalize`),
supplierQuoteSend: (id: string) =>
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index e0dbc41dd4..c3a66a1969 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -70,6 +70,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
CONTROLLED_ENVIRONMENT,
ERP_URL,
MES_URL,
+ NODE_ENV,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
SUPABASE_URL,
@@ -90,6 +91,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
CONTROLLED_ENVIRONMENT,
ERP_URL,
MES_URL,
+ NODE_ENV,
POSTHOG_API_HOST,
POSTHOG_PROJECT_PUBLIC_KEY,
SUPABASE_URL,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1774a972ca..9fb8a4104b 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -26620,6 +26620,7 @@ export type Database = {
requiredDate: string | null
serviceId: string | null
shippingCost: number | null
+ sortOrder: number
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierShippingCost: number
@@ -26662,6 +26663,7 @@ export type Database = {
requiredDate?: string | null
serviceId?: string | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -26704,6 +26706,7 @@ export type Database = {
requiredDate?: string | null
serviceId?: string | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -27848,6 +27851,7 @@ export type Database = {
requiresInspection: boolean
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierShippingCost: number
@@ -27899,6 +27903,7 @@ export type Database = {
requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -27950,6 +27955,7 @@ export type Database = {
requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -30380,6 +30386,7 @@ export type Database = {
quantity: number[] | null
quoteId: string
quoteRevisionId: number
+ sortOrder: number
status: Database["public"]["Enums"]["quoteLineStatus"]
tags: string[] | null
taxPercent: number
@@ -30412,6 +30419,7 @@ export type Database = {
quantity?: number[] | null
quoteId: string
quoteRevisionId?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["quoteLineStatus"]
tags?: string[] | null
taxPercent?: number
@@ -30444,6 +30452,7 @@ export type Database = {
quantity?: number[] | null
quoteId?: string
quoteRevisionId?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["quoteLineStatus"]
tags?: string[] | null
taxPercent?: number
@@ -33564,6 +33573,7 @@ export type Database = {
salesOrderLineId: string | null
setupPrice: number
shippingCost: number
+ sortOrder: number
storageUnitId: string | null
taxPercent: number
unitOfMeasureCode: string
@@ -33602,6 +33612,7 @@ export type Database = {
salesOrderLineId?: string | null
setupPrice?: number
shippingCost?: number
+ sortOrder?: number
storageUnitId?: string | null
taxPercent?: number
unitOfMeasureCode: string
@@ -33640,6 +33651,7 @@ export type Database = {
salesOrderLineId?: string | null
setupPrice?: number
shippingCost?: number
+ sortOrder?: number
storageUnitId?: string | null
taxPercent?: number
unitOfMeasureCode?: string
@@ -34516,6 +34528,7 @@ export type Database = {
sentDate: string | null
setupPrice: number | null
shippingCost: number
+ sortOrder: number
status: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId: string | null
taxPercent: number
@@ -34562,6 +34575,7 @@ export type Database = {
sentDate?: string | null
setupPrice?: number | null
shippingCost?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId?: string | null
taxPercent?: number
@@ -34608,6 +34622,7 @@ export type Database = {
sentDate?: string | null
setupPrice?: number | null
shippingCost?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId?: string | null
taxPercent?: number
@@ -36092,7 +36107,7 @@ export type Database = {
},
]
}
- searchIndex_7BqMC5eK9CZo1FTcT3LJUR: {
+ searchIndex_CYj9v111oXXm6PX9ZD6Yn2: {
Row: {
createdAt: string
description: string | null
@@ -40488,6 +40503,7 @@ export type Database = {
purchaseUnitOfMeasureCode: string | null
quantity: number[] | null
requiredDate: string | null
+ sortOrder: number
supplierPartId: string | null
supplierPartRevision: string | null
supplierQuoteId: string
@@ -40514,6 +40530,7 @@ export type Database = {
purchaseUnitOfMeasureCode?: string | null
quantity?: number[] | null
requiredDate?: string | null
+ sortOrder?: number
supplierPartId?: string | null
supplierPartRevision?: string | null
supplierQuoteId: string
@@ -40540,6 +40557,7 @@ export type Database = {
purchaseUnitOfMeasureCode?: string | null
quantity?: number[] | null
requiredDate?: string | null
+ sortOrder?: number
supplierPartId?: string | null
supplierPartRevision?: string | null
supplierQuoteId?: string
@@ -51836,6 +51854,7 @@ export type Database = {
jobOperationId: string | null
locationId: string | null
modelUploadId: string | null
+ ownerId: string | null
purchaseOrderId: string | null
purchaseOrderLineId: string | null
purchaseUnitOfMeasureCode: string | null
@@ -51843,6 +51862,7 @@ export type Database = {
requiredDate: string | null
serviceId: string | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierPartId: string | null
@@ -51923,6 +51943,41 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "purchaseInvoiceLine_storageUnitId_fkey"
columns: ["storageUnitId"]
@@ -52468,6 +52523,7 @@ export type Database = {
modelPath: string | null
modelSize: number | null
modelUploadId: string | null
+ ownerId: string | null
promisedDate: string | null
purchaseOrderId: string | null
purchaseOrderLineType:
@@ -52486,6 +52542,7 @@ export type Database = {
requiresInspection: boolean | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierPartId: string | null
@@ -52670,6 +52727,41 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -54178,9 +54270,12 @@ export type Database = {
modelSize: number | null
modelUploadId: string | null
noQuoteReason: string | null
+ priceTrace: Json | null
+ pricingRuleId: string | null
quantity: number[] | null
quoteId: string | null
quoteRevisionId: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
tags: string[] | null
taxPercent: number | null
@@ -54360,6 +54455,13 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "quoteLine_pricingRuleId_fkey"
+ columns: ["pricingRuleId"]
+ isOneToOne: false
+ referencedRelation: "pricingRule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -55883,6 +55985,7 @@ export type Database = {
salesOrderLineId: string | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
taxPercent: number | null
thumbnailPath: string | null
@@ -56188,7 +56291,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -56202,7 +56305,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -56531,6 +56634,7 @@ export type Database = {
sentDate: string | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["salesOrderLineStatus"] | null
storageUnitId: string | null
taxPercent: number | null
@@ -58549,9 +58653,11 @@ export type Database = {
itemId: string | null
itemReadableId: string | null
itemType: Database["public"]["Enums"]["itemType"] | null
+ ownerId: string | null
purchaseUnitOfMeasureCode: string | null
quantity: number[] | null
requiredDate: string | null
+ sortOrder: number | null
supplierPartId: string | null
supplierPartRevision: string | null
supplierQuoteId: string | null
@@ -58697,6 +58803,41 @@ export type Database = {
referencedRelation: "tools"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "supplierQuoteLine_purchaseUnitOfMeasureCode_fkey"
columns: ["purchaseUnitOfMeasureCode", "companyId"]
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index b4e53251ff..57795ad8a3 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -367,6 +367,7 @@ serve(async (req: Request) => {
conversionFactor: line.conversionFactor,
exchangeRate: line.exchangeRate ?? 1,
jobOperationId: line.jobOperationId,
+ sortOrder: line.sortOrder ?? 1,
companyId,
createdBy: userId,
}));
@@ -549,6 +550,7 @@ serve(async (req: Request) => {
exchangeRate: quote.data.exchangeRate ?? 1,
taxPercent: line.taxPercent,
shippingCost: selectedLines![line.id!].shippingCost,
+ sortOrder: line.sortOrder ?? 1,
};
});
@@ -775,6 +777,7 @@ serve(async (req: Request) => {
taxPercent: line.taxPercent ?? 0,
unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
exchangeRate: line.exchangeRate ?? 1,
+ sortOrder: line.sortOrder ?? 1,
companyId,
createdBy: userId,
});
@@ -1074,6 +1077,8 @@ serve(async (req: Request) => {
quantity: line.quantity,
status: "Not Started",
unitOfMeasureCode: line.unitOfMeasureCode,
+ // Sales RFQ uses "order" column; map it to quoteLine.sortOrder
+ sortOrder: line.order ?? 1,
companyId,
createdBy: userId,
}));
@@ -1347,6 +1352,7 @@ serve(async (req: Request) => {
taxPercent: line.taxPercent ?? 0,
unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
exchangeRate: line.exchangeRate ?? 1,
+ sortOrder: line.sortOrder ?? 1,
companyId,
createdBy: userId,
});
@@ -1529,6 +1535,7 @@ serve(async (req: Request) => {
supplierShippingCost:
selectedLines![line.id!].supplierShippingCost,
supplierTaxAmount: selectedLines![line.id!].supplierTaxAmount,
+ sortOrder: line.sortOrder ?? 1,
createdBy: userId,
companyId,
};
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 1774a972ca..9fb8a4104b 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -26620,6 +26620,7 @@ export type Database = {
requiredDate: string | null
serviceId: string | null
shippingCost: number | null
+ sortOrder: number
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierShippingCost: number
@@ -26662,6 +26663,7 @@ export type Database = {
requiredDate?: string | null
serviceId?: string | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -26704,6 +26706,7 @@ export type Database = {
requiredDate?: string | null
serviceId?: string | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -27848,6 +27851,7 @@ export type Database = {
requiresInspection: boolean
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierShippingCost: number
@@ -27899,6 +27903,7 @@ export type Database = {
requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -27950,6 +27955,7 @@ export type Database = {
requiresInspection?: boolean
setupPrice?: number | null
shippingCost?: number | null
+ sortOrder?: number
storageUnitId?: string | null
supplierExtendedPrice?: number | null
supplierShippingCost?: number
@@ -30380,6 +30386,7 @@ export type Database = {
quantity: number[] | null
quoteId: string
quoteRevisionId: number
+ sortOrder: number
status: Database["public"]["Enums"]["quoteLineStatus"]
tags: string[] | null
taxPercent: number
@@ -30412,6 +30419,7 @@ export type Database = {
quantity?: number[] | null
quoteId: string
quoteRevisionId?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["quoteLineStatus"]
tags?: string[] | null
taxPercent?: number
@@ -30444,6 +30452,7 @@ export type Database = {
quantity?: number[] | null
quoteId?: string
quoteRevisionId?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["quoteLineStatus"]
tags?: string[] | null
taxPercent?: number
@@ -33564,6 +33573,7 @@ export type Database = {
salesOrderLineId: string | null
setupPrice: number
shippingCost: number
+ sortOrder: number
storageUnitId: string | null
taxPercent: number
unitOfMeasureCode: string
@@ -33602,6 +33612,7 @@ export type Database = {
salesOrderLineId?: string | null
setupPrice?: number
shippingCost?: number
+ sortOrder?: number
storageUnitId?: string | null
taxPercent?: number
unitOfMeasureCode: string
@@ -33640,6 +33651,7 @@ export type Database = {
salesOrderLineId?: string | null
setupPrice?: number
shippingCost?: number
+ sortOrder?: number
storageUnitId?: string | null
taxPercent?: number
unitOfMeasureCode?: string
@@ -34516,6 +34528,7 @@ export type Database = {
sentDate: string | null
setupPrice: number | null
shippingCost: number
+ sortOrder: number
status: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId: string | null
taxPercent: number
@@ -34562,6 +34575,7 @@ export type Database = {
sentDate?: string | null
setupPrice?: number | null
shippingCost?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId?: string | null
taxPercent?: number
@@ -34608,6 +34622,7 @@ export type Database = {
sentDate?: string | null
setupPrice?: number | null
shippingCost?: number
+ sortOrder?: number
status?: Database["public"]["Enums"]["salesOrderLineStatus"]
storageUnitId?: string | null
taxPercent?: number
@@ -36092,7 +36107,7 @@ export type Database = {
},
]
}
- searchIndex_7BqMC5eK9CZo1FTcT3LJUR: {
+ searchIndex_CYj9v111oXXm6PX9ZD6Yn2: {
Row: {
createdAt: string
description: string | null
@@ -40488,6 +40503,7 @@ export type Database = {
purchaseUnitOfMeasureCode: string | null
quantity: number[] | null
requiredDate: string | null
+ sortOrder: number
supplierPartId: string | null
supplierPartRevision: string | null
supplierQuoteId: string
@@ -40514,6 +40530,7 @@ export type Database = {
purchaseUnitOfMeasureCode?: string | null
quantity?: number[] | null
requiredDate?: string | null
+ sortOrder?: number
supplierPartId?: string | null
supplierPartRevision?: string | null
supplierQuoteId: string
@@ -40540,6 +40557,7 @@ export type Database = {
purchaseUnitOfMeasureCode?: string | null
quantity?: number[] | null
requiredDate?: string | null
+ sortOrder?: number
supplierPartId?: string | null
supplierPartRevision?: string | null
supplierQuoteId?: string
@@ -51836,6 +51854,7 @@ export type Database = {
jobOperationId: string | null
locationId: string | null
modelUploadId: string | null
+ ownerId: string | null
purchaseOrderId: string | null
purchaseOrderLineId: string | null
purchaseUnitOfMeasureCode: string | null
@@ -51843,6 +51862,7 @@ export type Database = {
requiredDate: string | null
serviceId: string | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierPartId: string | null
@@ -51923,6 +51943,41 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "purchaseInvoiceLine_storageUnitId_fkey"
columns: ["storageUnitId"]
@@ -52468,6 +52523,7 @@ export type Database = {
modelPath: string | null
modelSize: number | null
modelUploadId: string | null
+ ownerId: string | null
promisedDate: string | null
purchaseOrderId: string | null
purchaseOrderLineType:
@@ -52486,6 +52542,7 @@ export type Database = {
requiresInspection: boolean | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
supplierExtendedPrice: number | null
supplierPartId: string | null
@@ -52670,6 +52727,41 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "purchaseOrderLine_purchaseOrderId_fkey"
columns: ["purchaseOrderId"]
@@ -54178,9 +54270,12 @@ export type Database = {
modelSize: number | null
modelUploadId: string | null
noQuoteReason: string | null
+ priceTrace: Json | null
+ pricingRuleId: string | null
quantity: number[] | null
quoteId: string | null
quoteRevisionId: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
tags: string[] | null
taxPercent: number | null
@@ -54360,6 +54455,13 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "quoteLine_pricingRuleId_fkey"
+ columns: ["pricingRuleId"]
+ isOneToOne: false
+ referencedRelation: "pricingRule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -55883,6 +55985,7 @@ export type Database = {
salesOrderLineId: string | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
storageUnitId: string | null
taxPercent: number | null
thumbnailPath: string | null
@@ -56188,7 +56291,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -56202,7 +56305,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -56531,6 +56634,7 @@ export type Database = {
sentDate: string | null
setupPrice: number | null
shippingCost: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["salesOrderLineStatus"] | null
storageUnitId: string | null
taxPercent: number | null
@@ -58549,9 +58653,11 @@ export type Database = {
itemId: string | null
itemReadableId: string | null
itemType: Database["public"]["Enums"]["itemType"] | null
+ ownerId: string | null
purchaseUnitOfMeasureCode: string | null
quantity: number[] | null
requiredDate: string | null
+ sortOrder: number | null
supplierPartId: string | null
supplierPartRevision: string | null
supplierQuoteId: string | null
@@ -58697,6 +58803,41 @@ export type Database = {
referencedRelation: "tools"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierQuoteLine_ownerId_fkey"
+ columns: ["ownerId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
{
foreignKeyName: "supplierQuoteLine_purchaseUnitOfMeasureCode_fkey"
columns: ["purchaseUnitOfMeasureCode", "companyId"]
diff --git a/packages/database/supabase/migrations/20260513120000_line-item-sort-order.sql b/packages/database/supabase/migrations/20260513120000_line-item-sort-order.sql
new file mode 100644
index 0000000000..626627a3b7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260513120000_line-item-sort-order.sql
@@ -0,0 +1,264 @@
+-- Add a sortOrder column to every line-item table that didn't already have
+-- one, backfill per parent, and rebuild the joined views so the new column
+-- flows through `<table>.*` expansion. RFQ tables (`purchasingRfqLine`,
+-- `salesRfqLine`) already have an `order` column and are intentionally
+-- omitted.
+
+----------------------------------------------------------------------------
+-- purchaseOrderLine
+----------------------------------------------------------------------------
+ALTER TABLE "purchaseOrderLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "purchaseOrderId" ORDER BY "createdAt"
+ ) AS rn
+ FROM "purchaseOrderLine"
+)
+UPDATE "purchaseOrderLine" pl
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE pl."id" = ranked."id";
+
+DROP VIEW IF EXISTS "purchaseOrderLines";
+CREATE OR REPLACE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT DISTINCT ON (pl.id)
+ pl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i.name as "itemName",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.description as "itemDescription",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ sp."supplierPartId",
+ jo."description" as "jobOperationDescription",
+ a."name" as "accountName"
+ FROM "purchaseOrderLine" pl
+ INNER JOIN "purchaseOrder" so ON so.id = pl."purchaseOrderId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = so."supplierId" AND sp."itemId" = i.id
+ LEFT JOIN "jobOperation" jo ON jo."id" = pl."jobOperationId"
+ LEFT JOIN "account" a ON a.id = pl."accountId"
+);
+
+----------------------------------------------------------------------------
+-- salesOrderLine
+----------------------------------------------------------------------------
+ALTER TABLE "salesOrderLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "salesOrderId" ORDER BY "createdAt"
+ ) AS rn
+ FROM "salesOrderLine"
+)
+UPDATE "salesOrderLine" sl
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE sl."id" = ranked."id";
+
+DROP VIEW IF EXISTS "salesOrderLines";
+CREATE OR REPLACE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ sl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ cp."customerPartId",
+ cp."customerPartRevision",
+ so."orderDate",
+ so."customerId",
+ so."salesOrderId" as "salesOrderReadableId"
+ FROM "salesOrderLine" sl
+ INNER JOIN "salesOrder" so ON so.id = sl."salesOrderId"
+ LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = sl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "customerPartToItem" cp ON cp."customerId" = so."customerId" AND cp."itemId" = i.id
+);
+
+----------------------------------------------------------------------------
+-- quoteLine (no createdAt; xid() ids sort chronologically)
+----------------------------------------------------------------------------
+ALTER TABLE "quoteLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "quoteId" ORDER BY "id"
+ ) AS rn
+ FROM "quoteLine"
+)
+UPDATE "quoteLine" ql
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE ql."id" = ranked."id";
+
+DROP VIEW IF EXISTS "quoteLines";
+CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost"
+ FROM "quoteLine" ql
+ LEFT JOIN "modelUpload" mu ON ql."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+);
+
+----------------------------------------------------------------------------
+-- supplierQuoteLine (no createdAt; xid() ids sort chronologically)
+----------------------------------------------------------------------------
+ALTER TABLE "supplierQuoteLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "supplierQuoteId" ORDER BY "id"
+ ) AS rn
+ FROM "supplierQuoteLine"
+)
+UPDATE "supplierQuoteLine" sq
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE sq."id" = ranked."id";
+
+DROP VIEW IF EXISTS "supplierQuoteLines";
+CREATE OR REPLACE VIEW "supplierQuoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ i."type" as "itemType",
+ COALESCE(i."thumbnailPath", mu."thumbnailPath") as "thumbnailPath",
+ ic."unitCost" as "unitCost",
+ a."name" as "accountName"
+ FROM "supplierQuoteLine" ql
+ LEFT JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "account" a ON a.id = ql."accountId"
+);
+
+----------------------------------------------------------------------------
+-- purchaseInvoiceLine
+----------------------------------------------------------------------------
+ALTER TABLE "purchaseInvoiceLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "invoiceId" ORDER BY "createdAt"
+ ) AS rn
+ FROM "purchaseInvoiceLine"
+)
+UPDATE "purchaseInvoiceLine" pl
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE pl."id" = ranked."id";
+
+DROP VIEW IF EXISTS "purchaseInvoiceLines";
+CREATE OR REPLACE VIEW "purchaseInvoiceLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ pl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.name as "itemName",
+ i.description as "itemDescription",
+ ic."unitCost" as "unitCost",
+ sp."supplierPartId",
+ a."name" as "accountName"
+ FROM "purchaseInvoiceLine" pl
+ INNER JOIN "purchaseInvoice" pi ON pi.id = pl."invoiceId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = pi."supplierId" AND sp."itemId" = i.id
+ LEFT JOIN "account" a ON a.id = pl."accountId"
+);
+
+----------------------------------------------------------------------------
+-- salesInvoiceLine
+----------------------------------------------------------------------------
+ALTER TABLE "salesInvoiceLine"
+ ADD COLUMN "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+WITH ranked AS (
+ SELECT "id",
+ ROW_NUMBER() OVER (
+ PARTITION BY "invoiceId" ORDER BY "createdAt"
+ ) AS rn
+ FROM "salesInvoiceLine"
+)
+UPDATE "salesInvoiceLine" sl
+SET "sortOrder" = ranked.rn
+FROM ranked
+WHERE sl."id" = ranked."id";
+
+DROP VIEW IF EXISTS "salesInvoiceLines";
+CREATE OR REPLACE VIEW "salesInvoiceLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ sl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i.name as "itemName",
+ i.description as "itemDescription",
+ ic."unitCost" as "unitCost",
+ (SELECT cp."customerPartId"
+ FROM "customerPartToItem" cp
+ WHERE cp."customerId" = si."customerId" AND cp."itemId" = i.id
+ LIMIT 1) as "customerPartId"
+ FROM "salesInvoiceLine" sl
+ INNER JOIN "salesInvoice" si ON si.id = sl."invoiceId"
+ LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = sl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+);
diff --git a/packages/dev/src/commands/remove.ts b/packages/dev/src/commands/remove.ts
index ae675a100b..dcfc370aa3 100644
--- a/packages/dev/src/commands/remove.ts
+++ b/packages/dev/src/commands/remove.ts
@@ -15,6 +15,11 @@ import {
} from "../git.js";
import { confirmRemove } from "../prompts.js";
import { destroyProjectVolumes, flushDb } from "../services/compose.js";
+import {
+ branchToPrefix,
+ pruneStaleRoutes,
+ unregisterAliases
+} from "../services/portless.js";
import { getSlot, listSlugs, removeSlot } from "../worktree.js";
export async function removeWorktreeCmd() {
@@ -65,14 +70,28 @@ export async function removeWorktreeCmd() {
}
const slotInfo = slug ? getSlot(slug) : null;
+ const branchPrefix = slug ? branchToPrefix(target.branch, slug) : null;
+
await tasks([
+ ...(branchPrefix
+ ? [
+ {
+ title: "Unregister portless aliases",
+ task: async () => {
+ await unregisterAliases(targetPath, branchPrefix);
+ pruneStaleRoutes(branchPrefix);
+ return "network stopped";
+ }
+ }
+ ]
+ : []),
...(slug
? [
{
title: `docker compose down -v · ${projectLabel}`,
task: async () => {
await destroyProjectVolumes(targetPath, projectLabel);
- return "stack removed";
+ return "stack and volumes removed";
}
}
]
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index dc373166c2..0b5c19b177 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -10,6 +10,7 @@ declare global {
CLOUDFLARE_TURNSTILE_SITE_KEY: string;
CONTROLLED_ENVIRONMENT: string;
ERP_URL: string;
+ NODE_ENV: string;
JIRA_CLIENT_ID: string;
MES_URL: string;
NOVU_APPLICATION_ID: string;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 7e1a2fe565..54a5c4b7bb 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Ziehen Sie eine Bestellungs-PDF hierher, oder klicken Sie, um eine Datei
msgid "Drag handle"
msgstr "Ziehgriff"
+msgid "Drag to reorder"
+msgstr "Zum Neuordnen ziehen"
+
msgid "Drop Shipment"
msgstr "Direktversand"
@@ -6419,6 +6422,9 @@ msgstr "Methode speichern"
msgid "Save View"
msgstr "Ansicht speichern"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Scannen"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index df303d336d..1e342fed2c 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Drag and drop a Purchase Order PDF here, or click to select a file"
msgid "Drag handle"
msgstr "Drag handle"
+msgid "Drag to reorder"
+msgstr "Drag to reorder"
+
msgid "Drop Shipment"
msgstr "Drop Shipment"
@@ -6419,6 +6422,9 @@ msgstr "Save Method"
msgid "Save View"
msgstr "Save View"
+msgid "Saving..."
+msgstr "Saving..."
+
msgid "Scan"
msgstr "Scan"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 8438ff1d5b..f0ee8a55c5 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Arrastra y suelta un PDF de Orden de Compra aquí, o haz
msgid "Drag handle"
msgstr "Controlador de arrastre"
+msgid "Drag to reorder"
+msgstr "Arrastra para reordenar"
+
msgid "Drop Shipment"
msgstr "Envío Directo"
@@ -6419,6 +6422,9 @@ msgstr "Guardar Método"
msgid "Save View"
msgstr "Guardar Vista"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Escanear"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 5e550b8690..3d2a57fad6 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Glissez-déposez un PDF de bon de commande ici, ou cliqu
msgid "Drag handle"
msgstr "Poignée de déplacement"
+msgid "Drag to reorder"
+msgstr "Glisser pour réorganiser"
+
msgid "Drop Shipment"
msgstr "Expédition directe"
@@ -6419,6 +6422,9 @@ msgstr "Enregistrer la méthode"
msgid "Save View"
msgstr "Enregistrer la vue"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Numériser"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index b5b61e7d70..52a44a2188 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -2502,6 +2502,9 @@ msgstr "यहà¤Ã
msgid "Drag handle"
msgstr "ड्रैग हैंडल"
+msgid "Drag to reorder"
+msgstr "पुनः व्यवस्थित करने के लिए खींचें"
+
msgid "Drop Shipment"
msgstr "ड्रॉप शिपमेंट"
@@ -6419,6 +6422,9 @@ msgstr "विà¤Ã
msgid "Save View"
msgstr "दृश्य सहेजें"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "स्कैन करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 136e637e76..db64021d3d 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Trascina e rilascia un PDF di ordine di acquisto qui, oppure fai clic pe
msgid "Drag handle"
msgstr "Maniglia di trascinamento"
+msgid "Drag to reorder"
+msgstr "Trascina per riordinare"
+
msgid "Drop Shipment"
msgstr "Spedizione Diretta"
@@ -6419,6 +6422,9 @@ msgstr "Salva Metodo"
msgid "Save View"
msgstr "Salva Vista"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Scansiona"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 64ecb5400f..5caa09aa22 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -2502,6 +2502,9 @@ msgstr "購入çââ
msgid "Drag handle"
msgstr "ドラッグハンドル"
+msgid "Drag to reorder"
+msgstr "ドラッグして並べ替え"
+
msgid "Drop Shipment"
msgstr "ドロップシップメント"
@@ -6419,6 +6422,9 @@ msgstr "メソãÃ
msgid "Save View"
msgstr "ビューを保存"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "スキャン"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index fb08d1e187..854d87ba32 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -2502,6 +2502,9 @@ msgstr "PrzeciÄ…gnij i upuÅ›Ã
msgid "Drag handle"
msgstr "Uchwyt do przeciÄ…gania"
+msgid "Drag to reorder"
+msgstr "Przeciągnij, aby zmienić kolejność"
+
msgid "Drop Shipment"
msgstr "Wysyłka bezpośrednia"
@@ -6419,6 +6422,9 @@ msgstr "Zapisz metodÄ™"
msgid "Save View"
msgstr "Zapisz Widok"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Skanuj"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 9da4064c73..e97c9ff6cb 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -2502,6 +2502,9 @@ msgstr "Arraste e solte um PDF de Ordem de Compra aqui, ou clique para seleciona
msgid "Drag handle"
msgstr "Puxador de arrasto"
+msgid "Drag to reorder"
+msgstr "Arrastar para reordenar"
+
msgid "Drop Shipment"
msgstr "Envio Direto"
@@ -6419,6 +6422,9 @@ msgstr "Salvar Método"
msgid "Save View"
msgstr "Guardar Visualização"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Digitalizar"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 32e3ad3b2f..1edce5e034 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -2502,6 +2502,9 @@ msgstr "ПерÐÃ
msgid "Drag handle"
msgstr "Ручка перетаскивания"
+msgid "Drag to reorder"
+msgstr "Перетащите для переупорядочивания"
+
msgid "Drop Shipment"
msgstr "Прямая поставка"
@@ -6419,6 +6422,9 @@ msgstr "СохÑ
msgid "Save View"
msgstr "Сохранить представление"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "Сканировать"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 050ae70005..2cd6ab51be 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -2502,6 +2502,9 @@ msgstr "将采Ã
msgid "Drag handle"
msgstr "拖动手柄"
+msgid "Drag to reorder"
+msgstr "拖动以重新排序"
+
msgid "Drop Shipment"
msgstr "直运"
@@ -6419,6 +6422,9 @@ msgstr "保存æâ€
msgid "Save View"
msgstr "保存视图"
+msgid "Saving..."
+msgstr ""
+
msgid "Scan"
msgstr "扫描"
diff --git a/packages/react/package.json b/packages/react/package.json
index e76fb1b980..d844682678 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -2,6 +2,7 @@
"name": "@carbon/react",
"dependencies": {
"@carbon/database": "workspace:*",
+ "@carbon/env": "workspace:*",
"@carbon/tiptap": "workspace:*",
"@nanostores/react": "catalog:",
"@carbon/utils": "workspace:*",
diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/react/src/hooks/useRealtimeChannel.ts
index e834d362ff..9b76b9c1ef 100644
--- a/packages/react/src/hooks/useRealtimeChannel.ts
+++ b/packages/react/src/hooks/useRealtimeChannel.ts
@@ -1,3 +1,4 @@
+import { NODE_ENV } from "@carbon/env";
import type { RealtimeChannel, SupabaseClient } from "@supabase/supabase-js";
import { REALTIME_SUBSCRIBE_STATES } from "@supabase/supabase-js";
import { useCallback, useEffect, useRef } from "react";
@@ -40,7 +41,7 @@ export const useRealtimeChannel = <TDeps extends any[]>(
setup,
enabled = true,
dependencies = [],
- notifyOnSubscribeError = process.env.NODE_ENV === "development"
+ notifyOnSubscribeError = NODE_ENV === "development"
} = options;
const channelRef = useRef<RealtimeChannel | null>(null);
const isTearingDownRef = useRef(false);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 922a0199dc..d4b45261e0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2477,6 +2477,9 @@ importers:
'@carbon/database':
specifier: workspace:*
version: link:../database
+ '@carbon/env':
+ specifier: workspace:*
+ version: link:../env
'@carbon/tiptap':
specifier: workspace:*
version: link:../tiptap