@open-mercato/core 0.6.6-develop.6524.1.a78cc4694e → 0.6.6-develop.6526.1.6df9b3dd84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/sales/commands/documents.js +44 -0
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/dist/modules/sales/commands/returns.js +2 -27
- package/dist/modules/sales/commands/returns.js.map +2 -2
- package/dist/modules/sales/components/documents/ItemsSection.js +1 -0
- package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
- package/dist/modules/sales/components/documents/LineItemDialog.js +9 -0
- package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
- package/dist/modules/sales/lib/shipments/snapshots.js +27 -1
- package/dist/modules/sales/lib/shipments/snapshots.js.map +2 -2
- package/dist/modules/workflows/lib/graph-utils.js +3 -3
- package/dist/modules/workflows/lib/graph-utils.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/sales/commands/documents.ts +65 -0
- package/src/modules/sales/commands/returns.ts +2 -32
- package/src/modules/sales/components/documents/ItemsSection.tsx +5 -0
- package/src/modules/sales/components/documents/LineItemDialog.tsx +10 -0
- package/src/modules/sales/i18n/de.json +4 -0
- package/src/modules/sales/i18n/en.json +4 -0
- package/src/modules/sales/i18n/es.json +4 -0
- package/src/modules/sales/i18n/pl.json +4 -0
- package/src/modules/sales/lib/shipments/snapshots.ts +30 -0
- package/src/modules/workflows/lib/graph-utils.ts +9 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "crypto";
|
|
2
|
-
import { SalesOrderLine, SalesShipmentItem } from "../../data/entities.js";
|
|
2
|
+
import { SalesOrderLine, SalesShipment, SalesShipmentItem } from "../../data/entities.js";
|
|
3
3
|
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
4
4
|
const cloneJson = (value) => {
|
|
5
5
|
if (value === null || value === void 0) return value;
|
|
@@ -84,9 +84,35 @@ const refreshShipmentItemsSnapshot = async (em, shipment, options) => {
|
|
|
84
84
|
shipment.itemsSnapshot = snapshot.length ? snapshot : null;
|
|
85
85
|
return snapshot;
|
|
86
86
|
};
|
|
87
|
+
const loadShippedQuantityByLine = async (em, orderId, scope) => {
|
|
88
|
+
const shipments = await findWithDecryption(
|
|
89
|
+
em,
|
|
90
|
+
SalesShipment,
|
|
91
|
+
{ order: orderId, deletedAt: null },
|
|
92
|
+
{},
|
|
93
|
+
scope
|
|
94
|
+
);
|
|
95
|
+
const shippedByLine = /* @__PURE__ */ new Map();
|
|
96
|
+
if (!shipments.length) return shippedByLine;
|
|
97
|
+
const items = await findWithDecryption(
|
|
98
|
+
em,
|
|
99
|
+
SalesShipmentItem,
|
|
100
|
+
{ shipment: { $in: shipments.map((shipment) => shipment.id) } },
|
|
101
|
+
{},
|
|
102
|
+
scope
|
|
103
|
+
);
|
|
104
|
+
items.forEach((item) => {
|
|
105
|
+
const orderLineId = typeof item.orderLine === "string" ? item.orderLine : item.orderLine?.id ?? null;
|
|
106
|
+
if (!orderLineId) return;
|
|
107
|
+
const next = (shippedByLine.get(orderLineId) ?? 0) + coerceShipmentQuantity(item.quantity);
|
|
108
|
+
shippedByLine.set(orderLineId, next);
|
|
109
|
+
});
|
|
110
|
+
return shippedByLine;
|
|
111
|
+
};
|
|
87
112
|
export {
|
|
88
113
|
buildShipmentItemSnapshots,
|
|
89
114
|
coerceShipmentQuantity,
|
|
115
|
+
loadShippedQuantityByLine,
|
|
90
116
|
readShipmentItemsSnapshot,
|
|
91
117
|
refreshShipmentItemsSnapshot
|
|
92
118
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/sales/lib/shipments/snapshots.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { SalesOrderLine, SalesShipment, SalesShipmentItem } from '../../data/entities'\nimport type { ShipmentItemSnapshot } from './types'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst cloneJson = <T>(value: T): T => {\n if (value === null || value === undefined) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport const coerceShipmentQuantity = (value: unknown): number => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (!Number.isNaN(parsed)) return parsed\n }\n return 0\n}\n\nconst extractOrderLineId = (entry: SalesShipmentItem): string | null => {\n const raw =\n typeof entry.orderLine === 'string'\n ? entry.orderLine\n : entry.orderLine?.id ?? (entry as any).orderLineId ?? null\n return typeof raw === 'string' ? raw : null\n}\n\nconst ensureLineMap = async ( // NOSONAR \u2014 returns same Map ref but populated from DB between early return and final return\n em: EntityManager,\n items: SalesShipmentItem[],\n lineMap?: Map<string, SalesOrderLine>\n): Promise<Map<string, SalesOrderLine>> => {\n const map = lineMap ?? new Map<string, SalesOrderLine>()\n const missing: string[] = []\n items.forEach((item) => {\n const lineId = extractOrderLineId(item)\n if (!lineId || map.has(lineId)) return\n missing.push(lineId)\n })\n if (!missing.length) return map\n const lines = await em.find(SalesOrderLine, { id: { $in: missing } })\n lines.forEach((line) => map.set(line.id, line))\n return map\n}\n\nexport const buildShipmentItemSnapshots = (\n items: SalesShipmentItem[],\n options?: { lineMap?: Map<string, SalesOrderLine> }\n): ShipmentItemSnapshot[] => {\n const map = options?.lineMap ?? new Map<string, SalesOrderLine>()\n return items\n .map((item) => {\n const orderLineId = extractOrderLineId(item)\n if (!orderLineId) return null\n const line = map.get(orderLineId) ?? null\n const id = typeof item.id === 'string' ? item.id : randomUUID()\n const quantity = coerceShipmentQuantity(item.quantity)\n const metadata =\n item.metadata && typeof item.metadata === 'object' ? cloneJson(item.metadata) : null\n return {\n id,\n orderLineId,\n orderLineName: line?.name ?? null,\n orderLineNumber: line?.lineNumber ?? null,\n quantity,\n metadata,\n } satisfies ShipmentItemSnapshot\n })\n .filter((entry): entry is ShipmentItemSnapshot => Boolean(entry))\n}\n\nexport const readShipmentItemsSnapshot = (raw: unknown): ShipmentItemSnapshot[] => {\n if (!Array.isArray(raw)) return []\n return raw\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null\n const orderLineId =\n typeof (entry as any).orderLineId === 'string'\n ? (entry as any).orderLineId\n : typeof (entry as any).order_line_id === 'string'\n ? (entry as any).order_line_id\n : null\n if (!orderLineId) return null\n const quantity = coerceShipmentQuantity((entry as any).quantity)\n const orderLineNumberRaw = (entry as any).orderLineNumber ?? (entry as any).order_line_number\n const orderLineNumber =\n typeof orderLineNumberRaw === 'number' && Number.isFinite(orderLineNumberRaw)\n ? orderLineNumberRaw\n : typeof orderLineNumberRaw === 'string' && orderLineNumberRaw.trim().length\n ? Number(orderLineNumberRaw)\n : null\n const metadata =\n (entry as any).metadata && typeof (entry as any).metadata === 'object'\n ? cloneJson((entry as any).metadata as Record<string, unknown>)\n : null\n const orderLineName =\n typeof (entry as any).orderLineName === 'string'\n ? (entry as any).orderLineName\n : typeof (entry as any).order_line_name === 'string'\n ? (entry as any).order_line_name\n : null\n const id =\n typeof (entry as any).id === 'string' && (entry as any).id.length\n ? (entry as any).id\n : randomUUID()\n return {\n id,\n orderLineId,\n orderLineName,\n orderLineNumber: Number.isFinite(orderLineNumber) ? Number(orderLineNumber) : null,\n quantity,\n metadata,\n } satisfies ShipmentItemSnapshot\n })\n .filter((entry): entry is ShipmentItemSnapshot => Boolean(entry))\n}\n\nexport const refreshShipmentItemsSnapshot = async (\n em: EntityManager,\n shipment: SalesShipment,\n options?: { items?: SalesShipmentItem[]; lineMap?: Map<string, SalesOrderLine> }\n): Promise<ShipmentItemSnapshot[]> => {\n const items =\n options?.items ??\n (await findWithDecryption(\n em,\n SalesShipmentItem,\n { shipment },\n { populate: ['orderLine'] },\n { tenantId: shipment.tenantId ?? null, organizationId: shipment.organizationId ?? null },\n ))\n const map = await ensureLineMap(em, items, options?.lineMap)\n const snapshot = buildShipmentItemSnapshots(items, { lineMap: map })\n shipment.itemsSnapshot = snapshot.length ? snapshot : null\n return snapshot\n}\n\nexport type { ShipmentItemSnapshot } from './types'\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { SalesOrderLine, SalesShipment, SalesShipmentItem } from '../../data/entities'\nimport type { ShipmentItemSnapshot } from './types'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst cloneJson = <T>(value: T): T => {\n if (value === null || value === undefined) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport const coerceShipmentQuantity = (value: unknown): number => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (!Number.isNaN(parsed)) return parsed\n }\n return 0\n}\n\nconst extractOrderLineId = (entry: SalesShipmentItem): string | null => {\n const raw =\n typeof entry.orderLine === 'string'\n ? entry.orderLine\n : entry.orderLine?.id ?? (entry as any).orderLineId ?? null\n return typeof raw === 'string' ? raw : null\n}\n\nconst ensureLineMap = async ( // NOSONAR \u2014 returns same Map ref but populated from DB between early return and final return\n em: EntityManager,\n items: SalesShipmentItem[],\n lineMap?: Map<string, SalesOrderLine>\n): Promise<Map<string, SalesOrderLine>> => {\n const map = lineMap ?? new Map<string, SalesOrderLine>()\n const missing: string[] = []\n items.forEach((item) => {\n const lineId = extractOrderLineId(item)\n if (!lineId || map.has(lineId)) return\n missing.push(lineId)\n })\n if (!missing.length) return map\n const lines = await em.find(SalesOrderLine, { id: { $in: missing } })\n lines.forEach((line) => map.set(line.id, line))\n return map\n}\n\nexport const buildShipmentItemSnapshots = (\n items: SalesShipmentItem[],\n options?: { lineMap?: Map<string, SalesOrderLine> }\n): ShipmentItemSnapshot[] => {\n const map = options?.lineMap ?? new Map<string, SalesOrderLine>()\n return items\n .map((item) => {\n const orderLineId = extractOrderLineId(item)\n if (!orderLineId) return null\n const line = map.get(orderLineId) ?? null\n const id = typeof item.id === 'string' ? item.id : randomUUID()\n const quantity = coerceShipmentQuantity(item.quantity)\n const metadata =\n item.metadata && typeof item.metadata === 'object' ? cloneJson(item.metadata) : null\n return {\n id,\n orderLineId,\n orderLineName: line?.name ?? null,\n orderLineNumber: line?.lineNumber ?? null,\n quantity,\n metadata,\n } satisfies ShipmentItemSnapshot\n })\n .filter((entry): entry is ShipmentItemSnapshot => Boolean(entry))\n}\n\nexport const readShipmentItemsSnapshot = (raw: unknown): ShipmentItemSnapshot[] => {\n if (!Array.isArray(raw)) return []\n return raw\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null\n const orderLineId =\n typeof (entry as any).orderLineId === 'string'\n ? (entry as any).orderLineId\n : typeof (entry as any).order_line_id === 'string'\n ? (entry as any).order_line_id\n : null\n if (!orderLineId) return null\n const quantity = coerceShipmentQuantity((entry as any).quantity)\n const orderLineNumberRaw = (entry as any).orderLineNumber ?? (entry as any).order_line_number\n const orderLineNumber =\n typeof orderLineNumberRaw === 'number' && Number.isFinite(orderLineNumberRaw)\n ? orderLineNumberRaw\n : typeof orderLineNumberRaw === 'string' && orderLineNumberRaw.trim().length\n ? Number(orderLineNumberRaw)\n : null\n const metadata =\n (entry as any).metadata && typeof (entry as any).metadata === 'object'\n ? cloneJson((entry as any).metadata as Record<string, unknown>)\n : null\n const orderLineName =\n typeof (entry as any).orderLineName === 'string'\n ? (entry as any).orderLineName\n : typeof (entry as any).order_line_name === 'string'\n ? (entry as any).order_line_name\n : null\n const id =\n typeof (entry as any).id === 'string' && (entry as any).id.length\n ? (entry as any).id\n : randomUUID()\n return {\n id,\n orderLineId,\n orderLineName,\n orderLineNumber: Number.isFinite(orderLineNumber) ? Number(orderLineNumber) : null,\n quantity,\n metadata,\n } satisfies ShipmentItemSnapshot\n })\n .filter((entry): entry is ShipmentItemSnapshot => Boolean(entry))\n}\n\nexport const refreshShipmentItemsSnapshot = async (\n em: EntityManager,\n shipment: SalesShipment,\n options?: { items?: SalesShipmentItem[]; lineMap?: Map<string, SalesOrderLine> }\n): Promise<ShipmentItemSnapshot[]> => {\n const items =\n options?.items ??\n (await findWithDecryption(\n em,\n SalesShipmentItem,\n { shipment },\n { populate: ['orderLine'] },\n { tenantId: shipment.tenantId ?? null, organizationId: shipment.organizationId ?? null },\n ))\n const map = await ensureLineMap(em, items, options?.lineMap)\n const snapshot = buildShipmentItemSnapshots(items, { lineMap: map })\n shipment.itemsSnapshot = snapshot.length ? snapshot : null\n return snapshot\n}\n\nexport const loadShippedQuantityByLine = async (\n em: EntityManager,\n orderId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<Map<string, number>> => {\n const shipments = await findWithDecryption(\n em,\n SalesShipment,\n { order: orderId, deletedAt: null },\n {},\n scope,\n )\n const shippedByLine = new Map<string, number>()\n if (!shipments.length) return shippedByLine\n const items = await findWithDecryption(\n em,\n SalesShipmentItem,\n { shipment: { $in: shipments.map((shipment) => shipment.id) } },\n {},\n scope,\n )\n items.forEach((item) => {\n const orderLineId = typeof item.orderLine === 'string' ? item.orderLine : (item.orderLine?.id ?? null)\n if (!orderLineId) return\n const next = (shippedByLine.get(orderLineId) ?? 0) + coerceShipmentQuantity(item.quantity)\n shippedByLine.set(orderLineId, next)\n })\n return shippedByLine\n}\n\nexport type { ShipmentItemSnapshot } from './types'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,gBAAgB,eAAe,yBAAyB;AAEjE,SAAS,0BAA0B;AAEnC,MAAM,YAAY,CAAI,UAAgB;AACpC,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEO,MAAM,yBAAyB,CAAC,UAA2B;AAChE,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK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;AAAA,IACX,EAAE,UAAU,CAAC,WAAW,EAAE;AAAA,IAC1B,EAAE,UAAU,SAAS,YAAY,MAAM,gBAAgB,SAAS,kBAAkB,KAAK;AAAA,EACzF;AACF,QAAM,MAAM,MAAM,cAAc,IAAI,OAAO,SAAS,OAAO;AAC3D,QAAM,WAAW,2BAA2B,OAAO,EAAE,SAAS,IAAI,CAAC;AACnE,WAAS,gBAAgB,SAAS,SAAS,WAAW;AACtD,SAAO;AACT;AAEO,MAAM,4BAA4B,OACvC,IACA,SACA,UACiC;AACjC,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,IACA,EAAE,OAAO,SAAS,WAAW,KAAK;AAAA,IAClC,CAAC;AAAA,IACD;AAAA,EACF;AACA,QAAM,gBAAgB,oBAAI,IAAoB;AAC9C,MAAI,CAAC,UAAU,OAAQ,QAAO;AAC9B,QAAM,QAAQ,MAAM;AAAA,IAClB;AAAA,IACA;AAAA,IACA,EAAE,UAAU,EAAE,KAAK,UAAU,IAAI,CAAC,aAAa,SAAS,EAAE,EAAE,EAAE;AAAA,IAC9D,CAAC;AAAA,IACD;AAAA,EACF;AACA,QAAM,QAAQ,CAAC,SAAS;AACtB,UAAM,cAAc,OAAO,KAAK,cAAc,WAAW,KAAK,YAAa,KAAK,WAAW,MAAM;AACjG,QAAI,CAAC,YAAa;AAClB,UAAM,QAAQ,cAAc,IAAI,WAAW,KAAK,KAAK,uBAAuB,KAAK,QAAQ;AACzF,kBAAc,IAAI,aAAa,IAAI;AAAA,EACrC,CAAC;AACD,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -240,9 +240,9 @@ function calculateSmartLayout(steps, transitions, spacing) {
|
|
|
240
240
|
while (queue.length > 0) {
|
|
241
241
|
const { id, level } = queue.shift();
|
|
242
242
|
const currentLevel = levels.get(id);
|
|
243
|
-
if (currentLevel
|
|
244
|
-
|
|
245
|
-
|
|
243
|
+
if (currentLevel !== void 0 && level <= currentLevel) continue;
|
|
244
|
+
levels.set(id, level);
|
|
245
|
+
if (level > steps.length) continue;
|
|
246
246
|
const children = outgoing.get(id) || [];
|
|
247
247
|
for (const child of children) {
|
|
248
248
|
queue.push({ id: child, level: level + 1 });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/workflows/lib/graph-utils.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Node, Edge } from '@xyflow/react'\nimport type { WorkflowDefinition } from '../data/entities'\n\n/**\n * Graph Utilities for Visual Workflow Editor\n *\n * Converts between ReactFlow graph representation and workflow definition JSON\n */\n\nexport interface GraphToDefinitionOptions {\n includePositions?: boolean\n}\n\nexport interface DefinitionToGraphOptions {\n autoLayout?: boolean\n layoutSpacing?: { vertical: number; horizontal: number }\n}\n\n/**\n * Convert ReactFlow graph (nodes + edges) to workflow definition JSON\n */\nexport function graphToDefinition(\n nodes: Node[],\n edges: Edge[],\n options: GraphToDefinitionOptions = {}\n): WorkflowDefinition['definition'] {\n // Extract steps from nodes\n const steps = nodes.map((node) => {\n const step: any = {\n stepId: node.id,\n stepName: node.data.label || node.id,\n stepType: mapNodeTypeToStepType(node.type || 'automated'),\n }\n\n // Add step-specific configuration\n if (node.data.description) {\n step.description = node.data.description\n }\n\n // Add timeout if present\n if (node.data.timeout) {\n step.timeout = node.data.timeout\n }\n\n // Add retryPolicy if present\n if (node.data.retryPolicy) {\n step.retryPolicy = node.data.retryPolicy\n }\n\n // Add generic config if present\n if (node.data.config) {\n step.config = node.data.config\n }\n\n // User task configuration\n if (node.type === 'userTask' && node.data) {\n step.userTaskConfig = {\n assignedTo: node.data.assignedTo,\n assignedToRoles: node.data.assignedToRoles || [],\n formKey: node.data.formKey,\n allowedActions: node.data.allowedActions || ['complete', 'cancel'],\n }\n\n // Add form schema if present\n if ((node.data as any).formSchema || (node.data as any).userTaskConfig?.formSchema) {\n step.userTaskConfig.formSchema = (node.data as any).formSchema || (node.data as any).userTaskConfig.formSchema\n }\n\n // Add advanced fields if present\n if ((node.data as any).assignmentRule || (node.data as any).userTaskConfig?.assignmentRule) {\n step.userTaskConfig.assignmentRule = (node.data as any).assignmentRule || (node.data as any).userTaskConfig.assignmentRule\n }\n\n if ((node.data as any).slaDuration || (node.data as any).userTaskConfig?.slaDuration) {\n step.userTaskConfig.slaDuration = (node.data as any).slaDuration || (node.data as any).userTaskConfig.slaDuration\n }\n\n if ((node.data as any).escalationRules || (node.data as any).userTaskConfig?.escalationRules) {\n step.userTaskConfig.escalationRules = (node.data as any).escalationRules || (node.data as any).userTaskConfig.escalationRules\n }\n }\n\n // Wait for signal configuration\n if (node.type === 'waitForSignal' && node.data.signalConfig) {\n step.signalConfig = node.data.signalConfig\n }\n\n // Step activities (for AUTOMATED steps)\n if (node.type === 'automated' && node.data.activities) {\n step.activities = node.data.activities\n }\n\n // Pre-conditions (for START steps)\n if (node.type === 'start' && (node.data as any).preConditions && (node.data as any).preConditions.length > 0) {\n step.preConditions = (node.data as any).preConditions\n }\n\n // Store position for visual editor\n if (options.includePositions && node.position) {\n step._editorPosition = {\n x: node.position.x,\n y: node.position.y,\n }\n }\n\n return step\n })\n\n // Extract transitions from edges\n const transitions = edges.map((edge) => {\n const edgeData = edge.data as any\n const transition: any = {\n transitionId: edge.id,\n fromStepId: edge.source,\n toStepId: edge.target,\n trigger: edgeData?.trigger || 'auto',\n }\n\n // Add transition name if present\n if (edgeData?.transitionName) {\n transition.transitionName = edgeData.transitionName\n }\n\n // Add priority if present (default 0)\n if (edgeData?.priority !== undefined) {\n transition.priority = edgeData.priority\n }\n\n // Add continueOnActivityFailure if present (default false)\n if (edgeData?.continueOnActivityFailure !== undefined) {\n transition.continueOnActivityFailure = edgeData.continueOnActivityFailure\n }\n\n // Add conditions if present\n if (edgeData?.preConditions && edgeData.preConditions.length > 0) {\n transition.preConditions = edgeData.preConditions\n }\n\n if (edgeData?.postConditions && edgeData.postConditions.length > 0) {\n transition.postConditions = edgeData.postConditions\n }\n\n // Add activities if present in edge data\n if (edgeData?.activities && edgeData.activities.length > 0) {\n transition.activities = edgeData.activities.map((activity: any) => ({\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n config: activity.config || {},\n // Include all optional fields\n ...(activity.async !== undefined && { async: activity.async }),\n ...(activity.timeout && { timeout: activity.timeout }),\n ...(activity.retryPolicy && { retryPolicy: activity.retryPolicy }),\n ...(activity.compensate !== undefined && { compensate: activity.compensate }),\n }))\n } else {\n // Check if source node is automated and has activity data\n // If so, place the activity in this transition\n const sourceNode = nodes.find(n => n.id === edge.source)\n if (sourceNode && sourceNode.type === 'automated' && sourceNode.data) {\n if (sourceNode.data.activityType || sourceNode.data.activityId) {\n const activity: any = {\n activityId: sourceNode.data.activityId || `activity_${sourceNode.id}`,\n activityName: sourceNode.data.activityName || sourceNode.data.label || 'Automated Activity',\n activityType: sourceNode.data.activityType || 'CALL_API',\n config: sourceNode.data.activityConfig || {},\n }\n // Include optional activity fields from node data\n if ((sourceNode.data as any).activityAsync !== undefined) {\n activity.async = (sourceNode.data as any).activityAsync\n }\n if ((sourceNode.data as any).activityTimeout) {\n activity.timeout = (sourceNode.data as any).activityTimeout\n }\n if ((sourceNode.data as any).activityRetryPolicy) {\n activity.retryPolicy = (sourceNode.data as any).activityRetryPolicy\n }\n if ((sourceNode.data as any).activityCompensate !== undefined) {\n activity.compensate = (sourceNode.data as any).activityCompensate\n }\n transition.activities = [activity]\n }\n }\n }\n\n // Add label if present (legacy field, transitionName is preferred)\n if (edgeData?.label && !transition.transitionName) {\n transition.transitionName = edgeData.label\n }\n\n return transition\n })\n\n return {\n steps,\n transitions,\n activities: [], // Global activities can be added later\n }\n}\n\n/**\n * Convert workflow definition JSON to ReactFlow graph (nodes + edges)\n */\nexport function definitionToGraph(\n definition: WorkflowDefinition['definition'],\n options: DefinitionToGraphOptions = {}\n): { nodes: Node[]; edges: Edge[] } {\n const { autoLayout = true, layoutSpacing = { vertical: 200, horizontal: 300 } } = options\n\n // Build step map for quick lookup\n const stepMap = new Map(definition.steps.map(step => [step.stepId, step]))\n\n // Calculate smart layout positions if autoLayout is enabled\n const positions = autoLayout\n ? calculateSmartLayout(definition.steps, definition.transitions, layoutSpacing)\n : null\n\n // Convert steps to nodes\n const nodes: Node[] = definition.steps.map((step, index) => {\n // Determine position\n let position = positions?.get(step.stepId) || { x: 250, y: 50 + index * layoutSpacing.vertical }\n\n // Use stored position if available and not auto-layouting\n if (!autoLayout && (step as any)._editorPosition) {\n position = (step as any)._editorPosition\n }\n\n // Map step type to node type\n const nodeType = mapStepTypeToNodeType(step.stepType)\n\n // Build node data\n const nodeData: any = {\n label: step.stepName,\n description: (step as any).description,\n stepNumber: index > 0 ? index : undefined,\n }\n\n // Add timeout if present\n if ((step as any).timeout) {\n nodeData.timeout = (step as any).timeout\n }\n\n // Add retryPolicy if present\n if ((step as any).retryPolicy) {\n nodeData.retryPolicy = (step as any).retryPolicy\n }\n\n // Add generic config if present\n if ((step as any).config) {\n nodeData.config = (step as any).config\n }\n\n // Add user task data\n if (step.stepType === 'USER_TASK' && step.userTaskConfig) {\n nodeData.assignedTo = step.userTaskConfig.assignedTo\n nodeData.assignedToRoles = step.userTaskConfig.assignedToRoles || []\n nodeData.formKey = step.userTaskConfig.formKey\n nodeData.allowedActions = step.userTaskConfig.allowedActions\n\n // Store full userTaskConfig for advanced fields\n nodeData.userTaskConfig = step.userTaskConfig\n\n // Add form schema if present\n if (step.userTaskConfig.formSchema) {\n nodeData.formSchema = step.userTaskConfig.formSchema\n }\n\n // Add advanced fields if present\n if (step.userTaskConfig.assignmentRule) {\n nodeData.assignmentRule = step.userTaskConfig.assignmentRule\n }\n\n if (step.userTaskConfig.slaDuration) {\n nodeData.slaDuration = step.userTaskConfig.slaDuration\n }\n\n if (step.userTaskConfig.escalationRules) {\n nodeData.escalationRules = step.userTaskConfig.escalationRules\n }\n }\n\n // Add wait for signal data\n if (step.stepType === 'WAIT_FOR_SIGNAL' && (step as any).signalConfig) {\n nodeData.signalConfig = (step as any).signalConfig\n }\n\n // Add step activities data (for AUTOMATED steps)\n if (step.stepType === 'AUTOMATED' && (step as any).activities) {\n nodeData.activities = (step as any).activities\n }\n\n // Add pre-conditions data (for START steps)\n if (step.stepType === 'START' && (step as any).preConditions) {\n nodeData.preConditions = (step as any).preConditions\n }\n\n // Set badge based on type\n nodeData.badge = getBadgeForNodeType(nodeType)\n\n // Default status is pending\n nodeData.status = 'pending'\n\n return {\n id: step.stepId,\n type: nodeType,\n position,\n data: nodeData,\n }\n })\n\n // Convert transitions to edges\n const edges: Edge[] = definition.transitions.map((transition) => {\n return {\n id: transition.transitionId,\n source: transition.fromStepId,\n target: transition.toStepId,\n type: 'workflowTransition',\n data: {\n trigger: transition.trigger,\n transitionName: (transition as any).transitionName,\n priority: (transition as any).priority !== undefined ? (transition as any).priority : 0,\n continueOnActivityFailure: (transition as any).continueOnActivityFailure !== undefined\n ? (transition as any).continueOnActivityFailure\n : false,\n preConditions: transition.preConditions || [],\n postConditions: transition.postConditions || [],\n activities: transition.activities || [],\n label: (transition as any).transitionName || (transition as any).label, // Backward compat\n state: (transition as any).state || 'pending', // Default edge state\n },\n }\n })\n\n return { nodes, edges }\n}\n\n/**\n * Calculate smart layout positions for workflow nodes\n * Uses a layered/hierarchical layout algorithm that:\n * 1. Assigns levels (ranks) to nodes based on graph topology\n * 2. Spreads sibling nodes horizontally at the same level\n * 3. Centers merge points below their incoming nodes\n */\nfunction calculateSmartLayout(\n steps: any[],\n transitions: any[],\n spacing: { vertical: number; horizontal: number }\n): Map<string, { x: number; y: number }> {\n const positions = new Map<string, { x: number; y: number }>()\n\n if (steps.length === 0) return positions\n\n // Build adjacency lists\n const outgoing = new Map<string, string[]>() // node -> children\n const incoming = new Map<string, string[]>() // node -> parents\n\n for (const step of steps) {\n outgoing.set(step.stepId, [])\n incoming.set(step.stepId, [])\n }\n\n for (const t of transitions) {\n const children = outgoing.get(t.fromStepId) || []\n children.push(t.toStepId)\n outgoing.set(t.fromStepId, children)\n\n const parents = incoming.get(t.toStepId) || []\n parents.push(t.fromStepId)\n incoming.set(t.toStepId, parents)\n }\n\n // Find start node(s) - nodes with no incoming edges\n const startNodes = steps.filter(s => (incoming.get(s.stepId) || []).length === 0)\n if (startNodes.length === 0) {\n // Fallback: use first step as start\n startNodes.push(steps[0])\n }\n\n // Assign levels using BFS (longest path from start)\n const levels = new Map<string, number>()\n const queue: Array<{ id: string; level: number }> = []\n\n for (const start of startNodes) {\n queue.push({ id: start.stepId, level: 0 })\n }\n\n while (queue.length > 0) {\n const { id, level } = queue.shift()!\n const currentLevel = levels.get(id)\n\n // Take the maximum level (longest path)\n if (currentLevel === undefined || level > currentLevel) {\n levels.set(id, level)\n }\n\n const children = outgoing.get(id) || []\n for (const child of children) {\n queue.push({ id: child, level: level + 1 })\n }\n }\n\n // Group nodes by level\n const nodesByLevel = new Map<number, string[]>()\n for (const [nodeId, level] of levels) {\n const nodesAtLevel = nodesByLevel.get(level) || []\n nodesAtLevel.push(nodeId)\n nodesByLevel.set(level, nodesAtLevel)\n }\n\n // Calculate positions\n const centerX = 400 // Center line for the graph\n const startY = 50\n\n for (const [level, nodeIds] of nodesByLevel) {\n const count = nodeIds.length\n const y = startY + level * spacing.vertical\n\n if (count === 1) {\n // Single node at this level - center it\n positions.set(nodeIds[0], { x: centerX, y })\n } else {\n // Multiple nodes at this level - spread them horizontally\n const totalWidth = (count - 1) * spacing.horizontal\n const startX = centerX - totalWidth / 2\n\n // Sort nodes by their parent's position for consistent ordering\n nodeIds.sort((a, b) => {\n const parentsA = incoming.get(a) || []\n const parentsB = incoming.get(b) || []\n const parentPosA = parentsA.length > 0 ? (positions.get(parentsA[0])?.x || 0) : 0\n const parentPosB = parentsB.length > 0 ? (positions.get(parentsB[0])?.x || 0) : 0\n return parentPosA - parentPosB\n })\n\n nodeIds.forEach((nodeId, idx) => {\n positions.set(nodeId, { x: startX + idx * spacing.horizontal, y })\n })\n }\n }\n\n return positions\n}\n\n/**\n * Map node type to step type (for graph \u2192 definition)\n */\nfunction mapNodeTypeToStepType(nodeType: string): string {\n const mapping: Record<string, string> = {\n start: 'START',\n end: 'END',\n userTask: 'USER_TASK',\n automated: 'AUTOMATED',\n decision: 'DECISION',\n waitForSignal: 'WAIT_FOR_SIGNAL',\n waitForTimer: 'WAIT_FOR_TIMER',\n }\n return mapping[nodeType] || 'AUTOMATED'\n}\n\n/**\n * Map step type to node type (for definition \u2192 graph)\n */\nfunction mapStepTypeToNodeType(stepType: string): string {\n const mapping: Record<string, string> = {\n START: 'start',\n END: 'end',\n USER_TASK: 'userTask',\n AUTOMATED: 'automated',\n DECISION: 'decision',\n WAIT_FOR_SIGNAL: 'waitForSignal',\n WAIT_FOR_TIMER: 'waitForTimer',\n }\n return mapping[stepType] || 'automated'\n}\n\n/**\n * Get badge text for node type\n */\nfunction getBadgeForNodeType(nodeType: string): string {\n const badges: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'User Task',\n automated: 'Automated',\n decision: 'Decision',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n }\n return badges[nodeType] || 'Task'\n}\n\n/**\n * Validate workflow graph\n */\nexport interface ValidationError {\n type: 'error' | 'warning'\n message: string\n nodeId?: string\n edgeId?: string\n}\n\nexport function validateWorkflowGraph(nodes: Node[], edges: Edge[]): ValidationError[] {\n const errors: ValidationError[] = []\n\n // Check for at least one start node\n const startNodes = nodes.filter((n) => n.type === 'start')\n if (startNodes.length === 0) {\n errors.push({\n type: 'error',\n message: 'Workflow must have at least one START node',\n })\n }\n if (startNodes.length > 1) {\n errors.push({\n type: 'warning',\n message: 'Workflow has multiple START nodes',\n })\n }\n\n // Check for at least one end node\n const endNodes = nodes.filter((n) => n.type === 'end')\n if (endNodes.length === 0) {\n errors.push({\n type: 'error',\n message: 'Workflow must have at least one END node',\n })\n }\n\n // Check for orphan nodes (no incoming or outgoing edges)\n for (const node of nodes) {\n if (node.type === 'start') continue // Start nodes don't need incoming edges\n if (node.type === 'end') continue // End nodes don't need outgoing edges\n\n const hasIncoming = edges.some((e) => e.target === node.id)\n const hasOutgoing = edges.some((e) => e.source === node.id)\n\n if (!hasIncoming && !hasOutgoing) {\n errors.push({\n type: 'error',\n message: `Node \"${node.data.label}\" is disconnected`,\n nodeId: node.id,\n })\n } else if (!hasIncoming) {\n errors.push({\n type: 'warning',\n message: `Node \"${node.data.label}\" has no incoming connections`,\n nodeId: node.id,\n })\n } else if (!hasOutgoing) {\n errors.push({\n type: 'warning',\n message: `Node \"${node.data.label}\" has no outgoing connections`,\n nodeId: node.id,\n })\n }\n }\n\n // Check for cycles (simple detection)\n const hasCycle = detectCycle(nodes, edges)\n if (hasCycle) {\n errors.push({\n type: 'warning',\n message: 'Workflow contains cycles (loops)',\n })\n }\n\n // Check for duplicate step IDs\n const stepIds = new Set<string>()\n for (const node of nodes) {\n if (stepIds.has(node.id)) {\n errors.push({\n type: 'error',\n message: `Duplicate step ID: ${node.id}`,\n nodeId: node.id,\n })\n }\n stepIds.add(node.id)\n }\n\n return errors\n}\n\n/**\n * Simple cycle detection using DFS\n */\nfunction detectCycle(nodes: Node[], edges: Edge[]): boolean {\n const adjList = new Map<string, string[]>()\n\n // Build adjacency list\n for (const node of nodes) {\n adjList.set(node.id, [])\n }\n for (const edge of edges) {\n const neighbors = adjList.get(edge.source) || []\n neighbors.push(edge.target)\n adjList.set(edge.source, neighbors)\n }\n\n const visited = new Set<string>()\n const recStack = new Set<string>()\n\n function dfs(nodeId: string): boolean {\n visited.add(nodeId)\n recStack.add(nodeId)\n\n const neighbors = adjList.get(nodeId) || []\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n if (dfs(neighbor)) return true\n } else if (recStack.has(neighbor)) {\n return true // Cycle detected\n }\n }\n\n recStack.delete(nodeId)\n return false\n }\n\n for (const node of nodes) {\n if (!visited.has(node.id)) {\n if (dfs(node.id)) return true\n }\n }\n\n return false\n}\n\n/**\n * Sanitize ID to match schema regex: /^[a-z0-9_-]+$/\n * Converts to lowercase, replaces invalid characters with underscores\n */\nexport function sanitizeId(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, '_')\n .replace(/_{2,}/g, '_') // Replace multiple underscores with single\n .replace(/(?:^_|_$)/g, '') // Remove leading/trailing underscores\n}\n\n/**\n * Validate ID matches schema regex: /^[a-z0-9_-]+$/\n */\nexport function validateId(id: string): boolean {\n return /^[a-z0-9_-]+$/.test(id)\n}\n\n/**\n * Generate unique step ID\n */\nexport function generateStepId(prefix: string = 'step'): string {\n const id = `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`\n return sanitizeId(id)\n}\n\n/**\n * Generate unique transition ID\n */\nexport function generateTransitionId(fromStepId: string, toStepId: string): string {\n const id = `e_${fromStepId}_${toStepId}`\n return sanitizeId(id)\n}\n\n/**\n * Append a new edge to the list, skipping duplicate connections.\n *\n * A plain-data replacement for React Flow's `addEdge` so the visual editor\n * page does not pull the `@xyflow/react` runtime out of its lazy boundary\n * (#3169). Mirrors `addEdge`'s dedup rule: an edge is dropped when one with\n * the same source/target endpoints (and handles) already exists.\n */\nexport function appendWorkflowEdge(edges: Edge[], edge: Edge): Edge[] {\n const isDuplicate = edges.some(\n (existing) =>\n existing.source === edge.source &&\n existing.target === edge.target &&\n // Match addEdge: empty-string and nullish handles are equivalent.\n (existing.sourceHandle || null) === (edge.sourceHandle || null) &&\n (existing.targetHandle || null) === (edge.targetHandle || null),\n )\n return isDuplicate ? edges : [...edges, edge]\n}\n"],
|
|
5
|
-
"mappings": "AAqBO,SAAS,kBACd,OACA,OACA,UAAoC,CAAC,GACH;AAElC,QAAM,QAAQ,MAAM,IAAI,CAAC,SAAS;AAChC,UAAM,OAAY;AAAA,MAChB,QAAQ,KAAK;AAAA,MACb,UAAU,KAAK,KAAK,SAAS,KAAK;AAAA,MAClC,UAAU,sBAAsB,KAAK,QAAQ,WAAW;AAAA,IAC1D;AAGA,QAAI,KAAK,KAAK,aAAa;AACz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AAQ,IAAI,QAAQ,GAAG;AAC1B,YAAI,IAAI,QAAQ,EAAG,QAAO;AAAA,MAC5B,WAAW,SAAS,IAAI,QAAQ,GAAG;AACjC,eAAO;AAAA,MACT;AAAA,IACF;AAEA,aAAS,OAAO,MAAM;AACtB,WAAO;AAAA,EACT;AAEA,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,QAAQ,IAAI,KAAK,EAAE,GAAG;AACzB,UAAI,IAAI,KAAK,EAAE,EAAG,QAAO;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,WAAW,OAAuB;AAChD,SAAO,MACJ,YAAY,EACZ,QAAQ,gBAAgB,GAAG,EAC3B,QAAQ,UAAU,GAAG,EACrB,QAAQ,cAAc,EAAE;AAC7B;AAKO,SAAS,WAAW,IAAqB;AAC9C,SAAO,gBAAgB,KAAK,EAAE;AAChC;AAKO,SAAS,eAAe,SAAiB,QAAgB;AAC9D,QAAM,KAAK,GAAG,MAAM,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC7E,SAAO,WAAW,EAAE;AACtB;AAKO,SAAS,qBAAqB,YAAoB,UAA0B;AACjF,QAAM,KAAK,KAAK,UAAU,IAAI,QAAQ;AACtC,SAAO,WAAW,EAAE;AACtB;AAUO,SAAS,mBAAmB,OAAe,MAAoB;AACpE,QAAM,cAAc,MAAM;AAAA,IACxB,CAAC,aACC,SAAS,WAAW,KAAK,UACzB,SAAS,WAAW,KAAK;AAAA,KAExB,SAAS,gBAAgB,WAAW,KAAK,gBAAgB,UACzD,SAAS,gBAAgB,WAAW,KAAK,gBAAgB;AAAA,EAC9D;AACA,SAAO,cAAc,QAAQ,CAAC,GAAG,OAAO,IAAI;AAC9C;",
|
|
4
|
+
"sourcesContent": ["import type { Node, Edge } from '@xyflow/react'\nimport type { WorkflowDefinition } from '../data/entities'\n\n/**\n * Graph Utilities for Visual Workflow Editor\n *\n * Converts between ReactFlow graph representation and workflow definition JSON\n */\n\nexport interface GraphToDefinitionOptions {\n includePositions?: boolean\n}\n\nexport interface DefinitionToGraphOptions {\n autoLayout?: boolean\n layoutSpacing?: { vertical: number; horizontal: number }\n}\n\n/**\n * Convert ReactFlow graph (nodes + edges) to workflow definition JSON\n */\nexport function graphToDefinition(\n nodes: Node[],\n edges: Edge[],\n options: GraphToDefinitionOptions = {}\n): WorkflowDefinition['definition'] {\n // Extract steps from nodes\n const steps = nodes.map((node) => {\n const step: any = {\n stepId: node.id,\n stepName: node.data.label || node.id,\n stepType: mapNodeTypeToStepType(node.type || 'automated'),\n }\n\n // Add step-specific configuration\n if (node.data.description) {\n step.description = node.data.description\n }\n\n // Add timeout if present\n if (node.data.timeout) {\n step.timeout = node.data.timeout\n }\n\n // Add retryPolicy if present\n if (node.data.retryPolicy) {\n step.retryPolicy = node.data.retryPolicy\n }\n\n // Add generic config if present\n if (node.data.config) {\n step.config = node.data.config\n }\n\n // User task configuration\n if (node.type === 'userTask' && node.data) {\n step.userTaskConfig = {\n assignedTo: node.data.assignedTo,\n assignedToRoles: node.data.assignedToRoles || [],\n formKey: node.data.formKey,\n allowedActions: node.data.allowedActions || ['complete', 'cancel'],\n }\n\n // Add form schema if present\n if ((node.data as any).formSchema || (node.data as any).userTaskConfig?.formSchema) {\n step.userTaskConfig.formSchema = (node.data as any).formSchema || (node.data as any).userTaskConfig.formSchema\n }\n\n // Add advanced fields if present\n if ((node.data as any).assignmentRule || (node.data as any).userTaskConfig?.assignmentRule) {\n step.userTaskConfig.assignmentRule = (node.data as any).assignmentRule || (node.data as any).userTaskConfig.assignmentRule\n }\n\n if ((node.data as any).slaDuration || (node.data as any).userTaskConfig?.slaDuration) {\n step.userTaskConfig.slaDuration = (node.data as any).slaDuration || (node.data as any).userTaskConfig.slaDuration\n }\n\n if ((node.data as any).escalationRules || (node.data as any).userTaskConfig?.escalationRules) {\n step.userTaskConfig.escalationRules = (node.data as any).escalationRules || (node.data as any).userTaskConfig.escalationRules\n }\n }\n\n // Wait for signal configuration\n if (node.type === 'waitForSignal' && node.data.signalConfig) {\n step.signalConfig = node.data.signalConfig\n }\n\n // Step activities (for AUTOMATED steps)\n if (node.type === 'automated' && node.data.activities) {\n step.activities = node.data.activities\n }\n\n // Pre-conditions (for START steps)\n if (node.type === 'start' && (node.data as any).preConditions && (node.data as any).preConditions.length > 0) {\n step.preConditions = (node.data as any).preConditions\n }\n\n // Store position for visual editor\n if (options.includePositions && node.position) {\n step._editorPosition = {\n x: node.position.x,\n y: node.position.y,\n }\n }\n\n return step\n })\n\n // Extract transitions from edges\n const transitions = edges.map((edge) => {\n const edgeData = edge.data as any\n const transition: any = {\n transitionId: edge.id,\n fromStepId: edge.source,\n toStepId: edge.target,\n trigger: edgeData?.trigger || 'auto',\n }\n\n // Add transition name if present\n if (edgeData?.transitionName) {\n transition.transitionName = edgeData.transitionName\n }\n\n // Add priority if present (default 0)\n if (edgeData?.priority !== undefined) {\n transition.priority = edgeData.priority\n }\n\n // Add continueOnActivityFailure if present (default false)\n if (edgeData?.continueOnActivityFailure !== undefined) {\n transition.continueOnActivityFailure = edgeData.continueOnActivityFailure\n }\n\n // Add conditions if present\n if (edgeData?.preConditions && edgeData.preConditions.length > 0) {\n transition.preConditions = edgeData.preConditions\n }\n\n if (edgeData?.postConditions && edgeData.postConditions.length > 0) {\n transition.postConditions = edgeData.postConditions\n }\n\n // Add activities if present in edge data\n if (edgeData?.activities && edgeData.activities.length > 0) {\n transition.activities = edgeData.activities.map((activity: any) => ({\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n config: activity.config || {},\n // Include all optional fields\n ...(activity.async !== undefined && { async: activity.async }),\n ...(activity.timeout && { timeout: activity.timeout }),\n ...(activity.retryPolicy && { retryPolicy: activity.retryPolicy }),\n ...(activity.compensate !== undefined && { compensate: activity.compensate }),\n }))\n } else {\n // Check if source node is automated and has activity data\n // If so, place the activity in this transition\n const sourceNode = nodes.find(n => n.id === edge.source)\n if (sourceNode && sourceNode.type === 'automated' && sourceNode.data) {\n if (sourceNode.data.activityType || sourceNode.data.activityId) {\n const activity: any = {\n activityId: sourceNode.data.activityId || `activity_${sourceNode.id}`,\n activityName: sourceNode.data.activityName || sourceNode.data.label || 'Automated Activity',\n activityType: sourceNode.data.activityType || 'CALL_API',\n config: sourceNode.data.activityConfig || {},\n }\n // Include optional activity fields from node data\n if ((sourceNode.data as any).activityAsync !== undefined) {\n activity.async = (sourceNode.data as any).activityAsync\n }\n if ((sourceNode.data as any).activityTimeout) {\n activity.timeout = (sourceNode.data as any).activityTimeout\n }\n if ((sourceNode.data as any).activityRetryPolicy) {\n activity.retryPolicy = (sourceNode.data as any).activityRetryPolicy\n }\n if ((sourceNode.data as any).activityCompensate !== undefined) {\n activity.compensate = (sourceNode.data as any).activityCompensate\n }\n transition.activities = [activity]\n }\n }\n }\n\n // Add label if present (legacy field, transitionName is preferred)\n if (edgeData?.label && !transition.transitionName) {\n transition.transitionName = edgeData.label\n }\n\n return transition\n })\n\n return {\n steps,\n transitions,\n activities: [], // Global activities can be added later\n }\n}\n\n/**\n * Convert workflow definition JSON to ReactFlow graph (nodes + edges)\n */\nexport function definitionToGraph(\n definition: WorkflowDefinition['definition'],\n options: DefinitionToGraphOptions = {}\n): { nodes: Node[]; edges: Edge[] } {\n const { autoLayout = true, layoutSpacing = { vertical: 200, horizontal: 300 } } = options\n\n // Build step map for quick lookup\n const stepMap = new Map(definition.steps.map(step => [step.stepId, step]))\n\n // Calculate smart layout positions if autoLayout is enabled\n const positions = autoLayout\n ? calculateSmartLayout(definition.steps, definition.transitions, layoutSpacing)\n : null\n\n // Convert steps to nodes\n const nodes: Node[] = definition.steps.map((step, index) => {\n // Determine position\n let position = positions?.get(step.stepId) || { x: 250, y: 50 + index * layoutSpacing.vertical }\n\n // Use stored position if available and not auto-layouting\n if (!autoLayout && (step as any)._editorPosition) {\n position = (step as any)._editorPosition\n }\n\n // Map step type to node type\n const nodeType = mapStepTypeToNodeType(step.stepType)\n\n // Build node data\n const nodeData: any = {\n label: step.stepName,\n description: (step as any).description,\n stepNumber: index > 0 ? index : undefined,\n }\n\n // Add timeout if present\n if ((step as any).timeout) {\n nodeData.timeout = (step as any).timeout\n }\n\n // Add retryPolicy if present\n if ((step as any).retryPolicy) {\n nodeData.retryPolicy = (step as any).retryPolicy\n }\n\n // Add generic config if present\n if ((step as any).config) {\n nodeData.config = (step as any).config\n }\n\n // Add user task data\n if (step.stepType === 'USER_TASK' && step.userTaskConfig) {\n nodeData.assignedTo = step.userTaskConfig.assignedTo\n nodeData.assignedToRoles = step.userTaskConfig.assignedToRoles || []\n nodeData.formKey = step.userTaskConfig.formKey\n nodeData.allowedActions = step.userTaskConfig.allowedActions\n\n // Store full userTaskConfig for advanced fields\n nodeData.userTaskConfig = step.userTaskConfig\n\n // Add form schema if present\n if (step.userTaskConfig.formSchema) {\n nodeData.formSchema = step.userTaskConfig.formSchema\n }\n\n // Add advanced fields if present\n if (step.userTaskConfig.assignmentRule) {\n nodeData.assignmentRule = step.userTaskConfig.assignmentRule\n }\n\n if (step.userTaskConfig.slaDuration) {\n nodeData.slaDuration = step.userTaskConfig.slaDuration\n }\n\n if (step.userTaskConfig.escalationRules) {\n nodeData.escalationRules = step.userTaskConfig.escalationRules\n }\n }\n\n // Add wait for signal data\n if (step.stepType === 'WAIT_FOR_SIGNAL' && (step as any).signalConfig) {\n nodeData.signalConfig = (step as any).signalConfig\n }\n\n // Add step activities data (for AUTOMATED steps)\n if (step.stepType === 'AUTOMATED' && (step as any).activities) {\n nodeData.activities = (step as any).activities\n }\n\n // Add pre-conditions data (for START steps)\n if (step.stepType === 'START' && (step as any).preConditions) {\n nodeData.preConditions = (step as any).preConditions\n }\n\n // Set badge based on type\n nodeData.badge = getBadgeForNodeType(nodeType)\n\n // Default status is pending\n nodeData.status = 'pending'\n\n return {\n id: step.stepId,\n type: nodeType,\n position,\n data: nodeData,\n }\n })\n\n // Convert transitions to edges\n const edges: Edge[] = definition.transitions.map((transition) => {\n return {\n id: transition.transitionId,\n source: transition.fromStepId,\n target: transition.toStepId,\n type: 'workflowTransition',\n data: {\n trigger: transition.trigger,\n transitionName: (transition as any).transitionName,\n priority: (transition as any).priority !== undefined ? (transition as any).priority : 0,\n continueOnActivityFailure: (transition as any).continueOnActivityFailure !== undefined\n ? (transition as any).continueOnActivityFailure\n : false,\n preConditions: transition.preConditions || [],\n postConditions: transition.postConditions || [],\n activities: transition.activities || [],\n label: (transition as any).transitionName || (transition as any).label, // Backward compat\n state: (transition as any).state || 'pending', // Default edge state\n },\n }\n })\n\n return { nodes, edges }\n}\n\n/**\n * Calculate smart layout positions for workflow nodes\n * Uses a layered/hierarchical layout algorithm that:\n * 1. Assigns levels (ranks) to nodes based on graph topology\n * 2. Spreads sibling nodes horizontally at the same level\n * 3. Centers merge points below their incoming nodes\n */\nfunction calculateSmartLayout(\n steps: any[],\n transitions: any[],\n spacing: { vertical: number; horizontal: number }\n): Map<string, { x: number; y: number }> {\n const positions = new Map<string, { x: number; y: number }>()\n\n if (steps.length === 0) return positions\n\n // Build adjacency lists\n const outgoing = new Map<string, string[]>() // node -> children\n const incoming = new Map<string, string[]>() // node -> parents\n\n for (const step of steps) {\n outgoing.set(step.stepId, [])\n incoming.set(step.stepId, [])\n }\n\n for (const t of transitions) {\n const children = outgoing.get(t.fromStepId) || []\n children.push(t.toStepId)\n outgoing.set(t.fromStepId, children)\n\n const parents = incoming.get(t.toStepId) || []\n parents.push(t.fromStepId)\n incoming.set(t.toStepId, parents)\n }\n\n // Find start node(s) - nodes with no incoming edges\n const startNodes = steps.filter(s => (incoming.get(s.stepId) || []).length === 0)\n if (startNodes.length === 0) {\n // Fallback: use first step as start\n startNodes.push(steps[0])\n }\n\n // Assign levels using BFS (longest path from start)\n const levels = new Map<string, number>()\n const queue: Array<{ id: string; level: number }> = []\n\n for (const start of startNodes) {\n queue.push({ id: start.stepId, level: 0 })\n }\n\n while (queue.length > 0) {\n const { id, level } = queue.shift()!\n const currentLevel = levels.get(id)\n\n // Only propagate when this path improves the node's level (longest path).\n // Without this guard a cyclic graph (renegotiation/revision loops) keeps\n // re-enqueuing children forever and freezes the browser (script timeout).\n if (currentLevel !== undefined && level <= currentLevel) continue\n levels.set(id, level)\n\n // Safety cap: in a DAG a node's level is bounded by the node count; a\n // higher value means we are walking a cycle, so stop descending.\n if (level > steps.length) continue\n\n const children = outgoing.get(id) || []\n for (const child of children) {\n queue.push({ id: child, level: level + 1 })\n }\n }\n\n // Group nodes by level\n const nodesByLevel = new Map<number, string[]>()\n for (const [nodeId, level] of levels) {\n const nodesAtLevel = nodesByLevel.get(level) || []\n nodesAtLevel.push(nodeId)\n nodesByLevel.set(level, nodesAtLevel)\n }\n\n // Calculate positions\n const centerX = 400 // Center line for the graph\n const startY = 50\n\n for (const [level, nodeIds] of nodesByLevel) {\n const count = nodeIds.length\n const y = startY + level * spacing.vertical\n\n if (count === 1) {\n // Single node at this level - center it\n positions.set(nodeIds[0], { x: centerX, y })\n } else {\n // Multiple nodes at this level - spread them horizontally\n const totalWidth = (count - 1) * spacing.horizontal\n const startX = centerX - totalWidth / 2\n\n // Sort nodes by their parent's position for consistent ordering\n nodeIds.sort((a, b) => {\n const parentsA = incoming.get(a) || []\n const parentsB = incoming.get(b) || []\n const parentPosA = parentsA.length > 0 ? (positions.get(parentsA[0])?.x || 0) : 0\n const parentPosB = parentsB.length > 0 ? (positions.get(parentsB[0])?.x || 0) : 0\n return parentPosA - parentPosB\n })\n\n nodeIds.forEach((nodeId, idx) => {\n positions.set(nodeId, { x: startX + idx * spacing.horizontal, y })\n })\n }\n }\n\n return positions\n}\n\n/**\n * Map node type to step type (for graph \u2192 definition)\n */\nfunction mapNodeTypeToStepType(nodeType: string): string {\n const mapping: Record<string, string> = {\n start: 'START',\n end: 'END',\n userTask: 'USER_TASK',\n automated: 'AUTOMATED',\n decision: 'DECISION',\n waitForSignal: 'WAIT_FOR_SIGNAL',\n waitForTimer: 'WAIT_FOR_TIMER',\n }\n return mapping[nodeType] || 'AUTOMATED'\n}\n\n/**\n * Map step type to node type (for definition \u2192 graph)\n */\nfunction mapStepTypeToNodeType(stepType: string): string {\n const mapping: Record<string, string> = {\n START: 'start',\n END: 'end',\n USER_TASK: 'userTask',\n AUTOMATED: 'automated',\n DECISION: 'decision',\n WAIT_FOR_SIGNAL: 'waitForSignal',\n WAIT_FOR_TIMER: 'waitForTimer',\n }\n return mapping[stepType] || 'automated'\n}\n\n/**\n * Get badge text for node type\n */\nfunction getBadgeForNodeType(nodeType: string): string {\n const badges: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'User Task',\n automated: 'Automated',\n decision: 'Decision',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n }\n return badges[nodeType] || 'Task'\n}\n\n/**\n * Validate workflow graph\n */\nexport interface ValidationError {\n type: 'error' | 'warning'\n message: string\n nodeId?: string\n edgeId?: string\n}\n\nexport function validateWorkflowGraph(nodes: Node[], edges: Edge[]): ValidationError[] {\n const errors: ValidationError[] = []\n\n // Check for at least one start node\n const startNodes = nodes.filter((n) => n.type === 'start')\n if (startNodes.length === 0) {\n errors.push({\n type: 'error',\n message: 'Workflow must have at least one START node',\n })\n }\n if (startNodes.length > 1) {\n errors.push({\n type: 'warning',\n message: 'Workflow has multiple START nodes',\n })\n }\n\n // Check for at least one end node\n const endNodes = nodes.filter((n) => n.type === 'end')\n if (endNodes.length === 0) {\n errors.push({\n type: 'error',\n message: 'Workflow must have at least one END node',\n })\n }\n\n // Check for orphan nodes (no incoming or outgoing edges)\n for (const node of nodes) {\n if (node.type === 'start') continue // Start nodes don't need incoming edges\n if (node.type === 'end') continue // End nodes don't need outgoing edges\n\n const hasIncoming = edges.some((e) => e.target === node.id)\n const hasOutgoing = edges.some((e) => e.source === node.id)\n\n if (!hasIncoming && !hasOutgoing) {\n errors.push({\n type: 'error',\n message: `Node \"${node.data.label}\" is disconnected`,\n nodeId: node.id,\n })\n } else if (!hasIncoming) {\n errors.push({\n type: 'warning',\n message: `Node \"${node.data.label}\" has no incoming connections`,\n nodeId: node.id,\n })\n } else if (!hasOutgoing) {\n errors.push({\n type: 'warning',\n message: `Node \"${node.data.label}\" has no outgoing connections`,\n nodeId: node.id,\n })\n }\n }\n\n // Check for cycles (simple detection)\n const hasCycle = detectCycle(nodes, edges)\n if (hasCycle) {\n errors.push({\n type: 'warning',\n message: 'Workflow contains cycles (loops)',\n })\n }\n\n // Check for duplicate step IDs\n const stepIds = new Set<string>()\n for (const node of nodes) {\n if (stepIds.has(node.id)) {\n errors.push({\n type: 'error',\n message: `Duplicate step ID: ${node.id}`,\n nodeId: node.id,\n })\n }\n stepIds.add(node.id)\n }\n\n return errors\n}\n\n/**\n * Simple cycle detection using DFS\n */\nfunction detectCycle(nodes: Node[], edges: Edge[]): boolean {\n const adjList = new Map<string, string[]>()\n\n // Build adjacency list\n for (const node of nodes) {\n adjList.set(node.id, [])\n }\n for (const edge of edges) {\n const neighbors = adjList.get(edge.source) || []\n neighbors.push(edge.target)\n adjList.set(edge.source, neighbors)\n }\n\n const visited = new Set<string>()\n const recStack = new Set<string>()\n\n function dfs(nodeId: string): boolean {\n visited.add(nodeId)\n recStack.add(nodeId)\n\n const neighbors = adjList.get(nodeId) || []\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n if (dfs(neighbor)) return true\n } else if (recStack.has(neighbor)) {\n return true // Cycle detected\n }\n }\n\n recStack.delete(nodeId)\n return false\n }\n\n for (const node of nodes) {\n if (!visited.has(node.id)) {\n if (dfs(node.id)) return true\n }\n }\n\n return false\n}\n\n/**\n * Sanitize ID to match schema regex: /^[a-z0-9_-]+$/\n * Converts to lowercase, replaces invalid characters with underscores\n */\nexport function sanitizeId(input: string): string {\n return input\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, '_')\n .replace(/_{2,}/g, '_') // Replace multiple underscores with single\n .replace(/(?:^_|_$)/g, '') // Remove leading/trailing underscores\n}\n\n/**\n * Validate ID matches schema regex: /^[a-z0-9_-]+$/\n */\nexport function validateId(id: string): boolean {\n return /^[a-z0-9_-]+$/.test(id)\n}\n\n/**\n * Generate unique step ID\n */\nexport function generateStepId(prefix: string = 'step'): string {\n const id = `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`\n return sanitizeId(id)\n}\n\n/**\n * Generate unique transition ID\n */\nexport function generateTransitionId(fromStepId: string, toStepId: string): string {\n const id = `e_${fromStepId}_${toStepId}`\n return sanitizeId(id)\n}\n\n/**\n * Append a new edge to the list, skipping duplicate connections.\n *\n * A plain-data replacement for React Flow's `addEdge` so the visual editor\n * page does not pull the `@xyflow/react` runtime out of its lazy boundary\n * (#3169). Mirrors `addEdge`'s dedup rule: an edge is dropped when one with\n * the same source/target endpoints (and handles) already exists.\n */\nexport function appendWorkflowEdge(edges: Edge[], edge: Edge): Edge[] {\n const isDuplicate = edges.some(\n (existing) =>\n existing.source === edge.source &&\n existing.target === edge.target &&\n // Match addEdge: empty-string and nullish handles are equivalent.\n (existing.sourceHandle || null) === (edge.sourceHandle || null) &&\n (existing.targetHandle || null) === (edge.targetHandle || null),\n )\n return isDuplicate ? edges : [...edges, edge]\n}\n"],
|
|
5
|
+
"mappings": "AAqBO,SAAS,kBACd,OACA,OACA,UAAoC,CAAC,GACH;AAElC,QAAM,QAAQ,MAAM,IAAI,CAAC,SAAS;AAChC,UAAM,OAAY;AAAA,MAChB,QAAQ,KAAK;AAAA,MACb,UAAU,KAAK,KAAK,SAAS,KAAK;AAAA,MAClC,UAAU,sBAAsB,KAAK,QAAQ,WAAW;AAAA,IAC1D;AAGA,QAAI,KAAK,KAAK,aAAa;AACzB,WAAK,cAAc,KAAK,KAAK;AAAA,IAC/B;AAGA,QAAI,KAAK,KAAK,SAAS;AACrB,WAAK,UAAU,KAAK,KAAK;AAAA,IAC3B;AAGA,QAAI,KAAK,KAAK,aAAa;AACzB,WAAK,cAAc,KAAK,KAAK;AAAA,IAC/B;AAGA,QAAI,KAAK,KAAK,QA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EA,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,QAAQ,IAAI,KAAK,EAAE,GAAG;AACzB,UAAI,IAAI,KAAK,EAAE,EAAG,QAAO;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,WAAW,OAAuB;AAChD,SAAO,MACJ,YAAY,EACZ,QAAQ,gBAAgB,GAAG,EAC3B,QAAQ,UAAU,GAAG,EACrB,QAAQ,cAAc,EAAE;AAC7B;AAKO,SAAS,WAAW,IAAqB;AAC9C,SAAO,gBAAgB,KAAK,EAAE;AAChC;AAKO,SAAS,eAAe,SAAiB,QAAgB;AAC9D,QAAM,KAAK,GAAG,MAAM,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC7E,SAAO,WAAW,EAAE;AACtB;AAKO,SAAS,qBAAqB,YAAoB,UAA0B;AACjF,QAAM,KAAK,KAAK,UAAU,IAAI,QAAQ;AACtC,SAAO,WAAW,EAAE;AACtB;AAUO,SAAS,mBAAmB,OAAe,MAAoB;AACpE,QAAM,cAAc,MAAM;AAAA,IACxB,CAAC,aACC,SAAS,WAAW,KAAK,UACzB,SAAS,WAAW,KAAK;AAAA,KAExB,SAAS,gBAAgB,WAAW,KAAK,gBAAgB,UACzD,SAAS,gBAAgB,WAAW,KAAK,gBAAgB;AAAA,EAC9D;AACA,SAAO,cAAc,QAAQ,CAAC,GAAG,OAAO,IAAI;AAC9C;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.6.6-develop.
|
|
3
|
+
"version": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -253,16 +253,16 @@
|
|
|
253
253
|
"zod": "^4.4.3"
|
|
254
254
|
},
|
|
255
255
|
"peerDependencies": {
|
|
256
|
-
"@open-mercato/ai-assistant": "0.6.6-develop.
|
|
257
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
258
|
-
"@open-mercato/ui": "0.6.6-develop.
|
|
256
|
+
"@open-mercato/ai-assistant": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
257
|
+
"@open-mercato/shared": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
258
|
+
"@open-mercato/ui": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
259
259
|
"react": "^19.0.0",
|
|
260
260
|
"react-dom": "^19.0.0"
|
|
261
261
|
},
|
|
262
262
|
"devDependencies": {
|
|
263
|
-
"@open-mercato/ai-assistant": "0.6.6-develop.
|
|
264
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
265
|
-
"@open-mercato/ui": "0.6.6-develop.
|
|
263
|
+
"@open-mercato/ai-assistant": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
264
|
+
"@open-mercato/shared": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
265
|
+
"@open-mercato/ui": "0.6.6-develop.6526.1.6df9b3dd84",
|
|
266
266
|
"@testing-library/dom": "^10.4.1",
|
|
267
267
|
"@testing-library/jest-dom": "^6.9.1",
|
|
268
268
|
"@testing-library/react": "^16.3.1",
|
|
@@ -125,6 +125,7 @@ import {
|
|
|
125
125
|
type SalesLineCalculationResult,
|
|
126
126
|
type SalesDocumentCalculationResult,
|
|
127
127
|
} from "../lib/types";
|
|
128
|
+
import { loadShippedQuantityByLine } from "../lib/shipments/snapshots";
|
|
128
129
|
import { resolveDictionaryEntryValue } from "../lib/dictionaries";
|
|
129
130
|
import { resolveStatusEntryIdByValue } from "../lib/statusHelpers";
|
|
130
131
|
import { SalesDocumentNumberGenerator } from "../services/salesDocumentNumberGenerator";
|
|
@@ -6521,6 +6522,69 @@ const quoteAdjustmentDeleteSchema = z.object({
|
|
|
6521
6522
|
quoteId: z.string().uuid(),
|
|
6522
6523
|
});
|
|
6523
6524
|
|
|
6525
|
+
const SHIPPED_QUANTITY_TOLERANCE = 1e-6;
|
|
6526
|
+
|
|
6527
|
+
const hasNumericChange = (
|
|
6528
|
+
next: number | null | undefined,
|
|
6529
|
+
previous: number | null | undefined,
|
|
6530
|
+
): boolean => {
|
|
6531
|
+
if (next === undefined || next === null) return false;
|
|
6532
|
+
if (previous === undefined || previous === null) return true;
|
|
6533
|
+
return Math.abs(next - previous) > SHIPPED_QUANTITY_TOLERANCE;
|
|
6534
|
+
};
|
|
6535
|
+
|
|
6536
|
+
const hasUnitChange = (
|
|
6537
|
+
next: string | null | undefined,
|
|
6538
|
+
previous: string | null | undefined,
|
|
6539
|
+
): boolean => {
|
|
6540
|
+
if (next === undefined || next === null) return false;
|
|
6541
|
+
const normalizedPrevious = (previous ?? "").trim().toLowerCase();
|
|
6542
|
+
if (!normalizedPrevious) return false;
|
|
6543
|
+
return next.trim().toLowerCase() !== normalizedPrevious;
|
|
6544
|
+
};
|
|
6545
|
+
|
|
6546
|
+
async function assertShippedOrderLineEditable(
|
|
6547
|
+
em: EntityManager,
|
|
6548
|
+
order: SalesOrder,
|
|
6549
|
+
existingSnapshot: SalesLineSnapshot | null,
|
|
6550
|
+
parsed: z.infer<typeof orderLineUpsertSchema>,
|
|
6551
|
+
): Promise<void> {
|
|
6552
|
+
const lineId = existingSnapshot?.id;
|
|
6553
|
+
if (!existingSnapshot || !lineId) return;
|
|
6554
|
+
const shippedByLine = await loadShippedQuantityByLine(em, order.id, {
|
|
6555
|
+
tenantId: order.tenantId,
|
|
6556
|
+
organizationId: order.organizationId,
|
|
6557
|
+
});
|
|
6558
|
+
const shippedQuantity = shippedByLine.get(lineId) ?? 0;
|
|
6559
|
+
if (shippedQuantity <= 0) return;
|
|
6560
|
+
|
|
6561
|
+
const { translate } = await resolveTranslations();
|
|
6562
|
+
const nextQuantity = parsed.quantity ?? existingSnapshot.quantity;
|
|
6563
|
+
if (nextQuantity < shippedQuantity - SHIPPED_QUANTITY_TOLERANCE) {
|
|
6564
|
+
throw new CrudHttpError(409, {
|
|
6565
|
+
error: translate(
|
|
6566
|
+
"sales.documents.items.errorQuantityBelowShipped",
|
|
6567
|
+
"You cannot lower the quantity below the {{shipped}} already shipped.",
|
|
6568
|
+
{ shipped: shippedQuantity },
|
|
6569
|
+
),
|
|
6570
|
+
});
|
|
6571
|
+
}
|
|
6572
|
+
|
|
6573
|
+
const pricingChanged =
|
|
6574
|
+
hasNumericChange(parsed.unitPriceNet, existingSnapshot.unitPriceNet) ||
|
|
6575
|
+
hasNumericChange(parsed.unitPriceGross, existingSnapshot.unitPriceGross) ||
|
|
6576
|
+
hasNumericChange(parsed.taxRate, existingSnapshot.taxRate) ||
|
|
6577
|
+
hasUnitChange(parsed.quantityUnit, existingSnapshot.quantityUnit);
|
|
6578
|
+
if (pricingChanged) {
|
|
6579
|
+
throw new CrudHttpError(409, {
|
|
6580
|
+
error: translate(
|
|
6581
|
+
"sales.documents.items.errorPriceShipped",
|
|
6582
|
+
"You cannot change the price or unit of a line that has shipped items.",
|
|
6583
|
+
),
|
|
6584
|
+
});
|
|
6585
|
+
}
|
|
6586
|
+
}
|
|
6587
|
+
|
|
6524
6588
|
const orderLineUpsertCommand: CommandHandler<
|
|
6525
6589
|
{ body?: Record<string, unknown>; query?: Record<string, unknown> },
|
|
6526
6590
|
{ orderId: string; lineId: string }
|
|
@@ -6565,6 +6629,7 @@ const orderLineUpsertCommand: CommandHandler<
|
|
|
6565
6629
|
const existingSnapshot = parsed.id
|
|
6566
6630
|
? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)
|
|
6567
6631
|
: null;
|
|
6632
|
+
await assertShippedOrderLineEditable(em, order, existingSnapshot, parsed);
|
|
6568
6633
|
const priceMode =
|
|
6569
6634
|
parsed.priceMode === "gross"
|
|
6570
6635
|
? "gross"
|
|
@@ -15,8 +15,8 @@ import type { SalesCalculationService } from '../services/salesCalculationServic
|
|
|
15
15
|
import type { SalesAdjustmentDraft, SalesLineSnapshot, SalesDocumentCalculationResult } from '../lib/types'
|
|
16
16
|
import { cloneJson, deriveLineNetFromGross, ensureOrganizationScope, ensureSameScope, ensureTenantScope, extractUndoPayload, toNumericString, enforceSalesDocumentOptimisticLock, SALES_RESOURCE_KIND_ORDER, SALES_RESOURCE_KIND_RETURN } from './shared'
|
|
17
17
|
import { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'
|
|
18
|
-
import { SalesOrder, SalesOrderAdjustment, SalesOrderLine, SalesReturn, SalesReturnLine
|
|
19
|
-
import {
|
|
18
|
+
import { SalesOrder, SalesOrderAdjustment, SalesOrderLine, SalesReturn, SalesReturnLine } from '../data/entities'
|
|
19
|
+
import { loadShippedQuantityByLine } from '../lib/shipments/snapshots'
|
|
20
20
|
import { computeAvailableReturnQuantity } from '../lib/returnQuantity'
|
|
21
21
|
import {
|
|
22
22
|
returnCreateSchema,
|
|
@@ -581,36 +581,6 @@ async function restoreReturnEffects(
|
|
|
581
581
|
return createdLines
|
|
582
582
|
}
|
|
583
583
|
|
|
584
|
-
async function loadShippedQuantityByLine(
|
|
585
|
-
em: EntityManager,
|
|
586
|
-
orderId: string,
|
|
587
|
-
scope: { tenantId: string; organizationId: string },
|
|
588
|
-
): Promise<Map<string, number>> {
|
|
589
|
-
const shipments = await findWithDecryption(
|
|
590
|
-
em,
|
|
591
|
-
SalesShipment,
|
|
592
|
-
{ order: orderId, deletedAt: null },
|
|
593
|
-
{},
|
|
594
|
-
scope,
|
|
595
|
-
)
|
|
596
|
-
const shippedByLine = new Map<string, number>()
|
|
597
|
-
if (!shipments.length) return shippedByLine
|
|
598
|
-
const items = await findWithDecryption(
|
|
599
|
-
em,
|
|
600
|
-
SalesShipmentItem,
|
|
601
|
-
{ shipment: { $in: shipments.map((shipment) => shipment.id) } },
|
|
602
|
-
{},
|
|
603
|
-
scope,
|
|
604
|
-
)
|
|
605
|
-
items.forEach((item) => {
|
|
606
|
-
const orderLineId = typeof item.orderLine === 'string' ? item.orderLine : item.orderLine?.id ?? null
|
|
607
|
-
if (!orderLineId) return
|
|
608
|
-
const next = (shippedByLine.get(orderLineId) ?? 0) + coerceShipmentQuantity(item.quantity)
|
|
609
|
-
shippedByLine.set(orderLineId, next)
|
|
610
|
-
})
|
|
611
|
-
return shippedByLine
|
|
612
|
-
}
|
|
613
|
-
|
|
614
584
|
function normalizeLinesInput(lines: ReturnCreateInput['lines']): ReturnLineInput[] {
|
|
615
585
|
const seen = new Set<string>()
|
|
616
586
|
const result: ReturnLineInput[] = []
|
|
@@ -817,6 +817,11 @@ export function SalesDocumentItemsSection({
|
|
|
817
817
|
organizationId={resolvedOrganizationId}
|
|
818
818
|
tenantId={resolvedTenantId}
|
|
819
819
|
initialLine={lineForEdit}
|
|
820
|
+
shippedQuantity={
|
|
821
|
+
lineForEdit
|
|
822
|
+
? Math.max(0, shippedTotals.get(lineForEdit.id) ?? 0)
|
|
823
|
+
: 0
|
|
824
|
+
}
|
|
820
825
|
onSaved={async () => {
|
|
821
826
|
await loadItems();
|
|
822
827
|
emitSalesDocumentTotalsRefresh({ documentId, kind });
|
|
@@ -278,6 +278,7 @@ type SalesLineDialogProps = {
|
|
|
278
278
|
organizationId: string | null;
|
|
279
279
|
tenantId: string | null;
|
|
280
280
|
initialLine?: SalesLineRecord | null;
|
|
281
|
+
shippedQuantity?: number;
|
|
281
282
|
onOpenChange: (open: boolean) => void;
|
|
282
283
|
onSaved?: () => Promise<void> | void;
|
|
283
284
|
};
|
|
@@ -472,6 +473,7 @@ export function LineItemDialog({
|
|
|
472
473
|
organizationId,
|
|
473
474
|
tenantId,
|
|
474
475
|
initialLine,
|
|
476
|
+
shippedQuantity = 0,
|
|
475
477
|
onOpenChange,
|
|
476
478
|
onSaved,
|
|
477
479
|
}: SalesLineDialogProps) {
|
|
@@ -1326,6 +1328,14 @@ export function LineItemDialog({
|
|
|
1326
1328
|
},
|
|
1327
1329
|
);
|
|
1328
1330
|
}
|
|
1331
|
+
if (shippedQuantity > 0 && qtyNumber < shippedQuantity) {
|
|
1332
|
+
const message = t(
|
|
1333
|
+
"sales.documents.items.errorQuantityBelowShipped",
|
|
1334
|
+
"You cannot lower the quantity below the {{shipped}} already shipped.",
|
|
1335
|
+
{ shipped: shippedQuantity },
|
|
1336
|
+
);
|
|
1337
|
+
throw createCrudFormError(message, { quantity: message });
|
|
1338
|
+
}
|
|
1329
1339
|
const resolvedQuantityUnit = (() => {
|
|
1330
1340
|
const entered = normalizeUnitCode(values.quantityUnit);
|
|
1331
1341
|
if (isCustomLine) return entered;
|
|
@@ -638,8 +638,10 @@
|
|
|
638
638
|
"sales.documents.detail.items.errorDelete": "Position konnte nicht gelöscht werden.",
|
|
639
639
|
"sales.documents.detail.items.errorDeleteShipped": "Positionen mit versandten Artikeln können nicht gelöscht werden.",
|
|
640
640
|
"sales.documents.detail.items.errorLoad": "Positionen konnten nicht geladen werden.",
|
|
641
|
+
"sales.documents.detail.items.errorPriceShipped": "Preis oder Einheit einer Position mit versandten Artikeln können nicht geändert werden.",
|
|
641
642
|
"sales.documents.detail.items.errorProductRequired": "Wähle ein Produkt aus, um fortzufahren.",
|
|
642
643
|
"sales.documents.detail.items.errorQuantity": "Die Menge muss größer als 0 sein.",
|
|
644
|
+
"sales.documents.detail.items.errorQuantityBelowShipped": "Die Menge kann nicht unter die bereits versandten {{shipped}} gesenkt werden.",
|
|
643
645
|
"sales.documents.detail.items.errorSave": "Position konnte nicht gespeichert werden.",
|
|
644
646
|
"sales.documents.detail.items.errorUnitPrice": "Der Stückpreis muss größer als 0 sein.",
|
|
645
647
|
"sales.documents.detail.items.errorVariantRequired": "Wähle eine Variante aus, um fortzufahren.",
|
|
@@ -950,8 +952,10 @@
|
|
|
950
952
|
"sales.documents.items.errorDeleteShipped": "Positionen mit versandten Artikeln können nicht gelöscht werden.",
|
|
951
953
|
"sales.documents.items.errorLoad": "Positionen konnten nicht geladen werden.",
|
|
952
954
|
"sales.documents.items.errorNameRequired": "Name ist für benutzerdefinierte Positionen erforderlich.",
|
|
955
|
+
"sales.documents.items.errorPriceShipped": "Preis oder Einheit einer Position mit versandten Artikeln können nicht geändert werden.",
|
|
953
956
|
"sales.documents.items.errorProductRequired": "Wähle ein Produkt aus, um fortzufahren.",
|
|
954
957
|
"sales.documents.items.errorQuantity": "Die Menge muss größer als 0 sein.",
|
|
958
|
+
"sales.documents.items.errorQuantityBelowShipped": "Die Menge kann nicht unter die bereits versandten {{shipped}} gesenkt werden.",
|
|
955
959
|
"sales.documents.items.errorSave": "Position konnte nicht gespeichert werden.",
|
|
956
960
|
"sales.documents.items.errorScope": "Organisation und Mandant sind erforderlich.",
|
|
957
961
|
"sales.documents.items.errorUnitPrice": "Der Stückpreis muss größer als 0 sein.",
|
|
@@ -638,8 +638,10 @@
|
|
|
638
638
|
"sales.documents.detail.items.errorDelete": "Failed to delete line.",
|
|
639
639
|
"sales.documents.detail.items.errorDeleteShipped": "You cannot delete a line that has shipped items.",
|
|
640
640
|
"sales.documents.detail.items.errorLoad": "Failed to load items.",
|
|
641
|
+
"sales.documents.detail.items.errorPriceShipped": "You cannot change the price or unit of a line that has shipped items.",
|
|
641
642
|
"sales.documents.detail.items.errorProductRequired": "Select a product to continue.",
|
|
642
643
|
"sales.documents.detail.items.errorQuantity": "Quantity must be greater than 0.",
|
|
644
|
+
"sales.documents.detail.items.errorQuantityBelowShipped": "You cannot lower the quantity below the {{shipped}} already shipped.",
|
|
643
645
|
"sales.documents.detail.items.errorSave": "Failed to save line.",
|
|
644
646
|
"sales.documents.detail.items.errorUnitPrice": "Unit price must be greater than 0.",
|
|
645
647
|
"sales.documents.detail.items.errorVariantRequired": "Select a variant to continue.",
|
|
@@ -950,8 +952,10 @@
|
|
|
950
952
|
"sales.documents.items.errorDeleteShipped": "You cannot delete a line that has shipped items.",
|
|
951
953
|
"sales.documents.items.errorLoad": "Failed to load items.",
|
|
952
954
|
"sales.documents.items.errorNameRequired": "Name is required for custom lines.",
|
|
955
|
+
"sales.documents.items.errorPriceShipped": "You cannot change the price or unit of a line that has shipped items.",
|
|
953
956
|
"sales.documents.items.errorProductRequired": "Select a product to continue.",
|
|
954
957
|
"sales.documents.items.errorQuantity": "Quantity must be greater than 0.",
|
|
958
|
+
"sales.documents.items.errorQuantityBelowShipped": "You cannot lower the quantity below the {{shipped}} already shipped.",
|
|
955
959
|
"sales.documents.items.errorSave": "Failed to save line.",
|
|
956
960
|
"sales.documents.items.errorScope": "Organization and tenant are required.",
|
|
957
961
|
"sales.documents.items.errorUnitPrice": "Unit price must be greater than 0.",
|
|
@@ -638,8 +638,10 @@
|
|
|
638
638
|
"sales.documents.detail.items.errorDelete": "No se pudo eliminar la línea.",
|
|
639
639
|
"sales.documents.detail.items.errorDeleteShipped": "No puedes eliminar una línea que ya tiene envíos.",
|
|
640
640
|
"sales.documents.detail.items.errorLoad": "No se pudieron cargar los artículos.",
|
|
641
|
+
"sales.documents.detail.items.errorPriceShipped": "No puedes cambiar el precio ni la unidad de una línea que ya tiene envíos.",
|
|
641
642
|
"sales.documents.detail.items.errorProductRequired": "Selecciona un producto para continuar.",
|
|
642
643
|
"sales.documents.detail.items.errorQuantity": "La cantidad debe ser mayor que 0.",
|
|
644
|
+
"sales.documents.detail.items.errorQuantityBelowShipped": "No puedes reducir la cantidad por debajo de las {{shipped}} ya enviadas.",
|
|
643
645
|
"sales.documents.detail.items.errorSave": "No se pudo guardar la línea.",
|
|
644
646
|
"sales.documents.detail.items.errorUnitPrice": "El precio unitario debe ser mayor que 0.",
|
|
645
647
|
"sales.documents.detail.items.errorVariantRequired": "Selecciona una variante para continuar.",
|
|
@@ -950,8 +952,10 @@
|
|
|
950
952
|
"sales.documents.items.errorDeleteShipped": "No puedes eliminar una línea que ya tiene envíos.",
|
|
951
953
|
"sales.documents.items.errorLoad": "No se pudieron cargar los artículos.",
|
|
952
954
|
"sales.documents.items.errorNameRequired": "El nombre es obligatorio para líneas personalizadas.",
|
|
955
|
+
"sales.documents.items.errorPriceShipped": "No puedes cambiar el precio ni la unidad de una línea que ya tiene envíos.",
|
|
953
956
|
"sales.documents.items.errorProductRequired": "Selecciona un producto para continuar.",
|
|
954
957
|
"sales.documents.items.errorQuantity": "La cantidad debe ser mayor que 0.",
|
|
958
|
+
"sales.documents.items.errorQuantityBelowShipped": "No puedes reducir la cantidad por debajo de las {{shipped}} ya enviadas.",
|
|
955
959
|
"sales.documents.items.errorSave": "No se pudo guardar la línea.",
|
|
956
960
|
"sales.documents.items.errorScope": "Se requieren organización e inquilino.",
|
|
957
961
|
"sales.documents.items.errorUnitPrice": "El precio unitario debe ser mayor que 0.",
|
|
@@ -638,8 +638,10 @@
|
|
|
638
638
|
"sales.documents.detail.items.errorDelete": "Nie udało się usunąć pozycji.",
|
|
639
639
|
"sales.documents.detail.items.errorDeleteShipped": "Nie można usunąć pozycji, która ma wysłane sztuki.",
|
|
640
640
|
"sales.documents.detail.items.errorLoad": "Nie udało się wczytać pozycji.",
|
|
641
|
+
"sales.documents.detail.items.errorPriceShipped": "Nie można zmienić ceny ani jednostki pozycji, która ma wysłane sztuki.",
|
|
641
642
|
"sales.documents.detail.items.errorProductRequired": "Wybierz produkt, aby kontynuować.",
|
|
642
643
|
"sales.documents.detail.items.errorQuantity": "Ilość musi być większa niż 0.",
|
|
644
|
+
"sales.documents.detail.items.errorQuantityBelowShipped": "Nie można obniżyć ilości poniżej {{shipped}} już wysłanych.",
|
|
643
645
|
"sales.documents.detail.items.errorSave": "Nie udało się zapisać pozycji.",
|
|
644
646
|
"sales.documents.detail.items.errorUnitPrice": "Cena jednostkowa musi być większa niż 0.",
|
|
645
647
|
"sales.documents.detail.items.errorVariantRequired": "Wybierz wariant, aby kontynuować.",
|
|
@@ -950,8 +952,10 @@
|
|
|
950
952
|
"sales.documents.items.errorDeleteShipped": "Nie można usunąć pozycji, która ma wysłane sztuki.",
|
|
951
953
|
"sales.documents.items.errorLoad": "Nie udało się załadować pozycji.",
|
|
952
954
|
"sales.documents.items.errorNameRequired": "Nazwa jest wymagana dla niestandardowych pozycji.",
|
|
955
|
+
"sales.documents.items.errorPriceShipped": "Nie można zmienić ceny ani jednostki pozycji, która ma wysłane sztuki.",
|
|
953
956
|
"sales.documents.items.errorProductRequired": "Wybierz produkt, aby kontynuować.",
|
|
954
957
|
"sales.documents.items.errorQuantity": "Ilość musi być większa niż 0.",
|
|
958
|
+
"sales.documents.items.errorQuantityBelowShipped": "Nie można obniżyć ilości poniżej {{shipped}} już wysłanych.",
|
|
955
959
|
"sales.documents.items.errorSave": "Nie udało się zapisać pozycji.",
|
|
956
960
|
"sales.documents.items.errorScope": "Wymagane są organizacja i najemca.",
|
|
957
961
|
"sales.documents.items.errorUnitPrice": "Cena jednostkowa musi być większa niż 0.",
|
|
@@ -136,4 +136,34 @@ export const refreshShipmentItemsSnapshot = async (
|
|
|
136
136
|
return snapshot
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
export const loadShippedQuantityByLine = async (
|
|
140
|
+
em: EntityManager,
|
|
141
|
+
orderId: string,
|
|
142
|
+
scope: { tenantId: string; organizationId: string },
|
|
143
|
+
): Promise<Map<string, number>> => {
|
|
144
|
+
const shipments = await findWithDecryption(
|
|
145
|
+
em,
|
|
146
|
+
SalesShipment,
|
|
147
|
+
{ order: orderId, deletedAt: null },
|
|
148
|
+
{},
|
|
149
|
+
scope,
|
|
150
|
+
)
|
|
151
|
+
const shippedByLine = new Map<string, number>()
|
|
152
|
+
if (!shipments.length) return shippedByLine
|
|
153
|
+
const items = await findWithDecryption(
|
|
154
|
+
em,
|
|
155
|
+
SalesShipmentItem,
|
|
156
|
+
{ shipment: { $in: shipments.map((shipment) => shipment.id) } },
|
|
157
|
+
{},
|
|
158
|
+
scope,
|
|
159
|
+
)
|
|
160
|
+
items.forEach((item) => {
|
|
161
|
+
const orderLineId = typeof item.orderLine === 'string' ? item.orderLine : (item.orderLine?.id ?? null)
|
|
162
|
+
if (!orderLineId) return
|
|
163
|
+
const next = (shippedByLine.get(orderLineId) ?? 0) + coerceShipmentQuantity(item.quantity)
|
|
164
|
+
shippedByLine.set(orderLineId, next)
|
|
165
|
+
})
|
|
166
|
+
return shippedByLine
|
|
167
|
+
}
|
|
168
|
+
|
|
139
169
|
export type { ShipmentItemSnapshot } from './types'
|