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.

fix: bug fixes

Brad Barbin4d0ee1092b84
diff --git a/apps/erp/app/components/Agent/Agent.ee.tsx b/apps/erp/app/components/Agent/Agent.ee.tsx
index 89dd249485..977c11503e 100644
--- a/apps/erp/app/components/Agent/Agent.ee.tsx
+++ b/apps/erp/app/components/Agent/Agent.ee.tsx
@@ -21,7 +21,6 @@ import {
useMount,
useShortcutKeys,
} from "@carbon/react";
-import { FunctionRegion } from "@supabase/supabase-js";
import type { LanguageModelV1Prompt } from "ai";
import { Fragment, useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
@@ -193,7 +192,6 @@ export function Agent() {
"x-company-id": companyId,
"x-user-id": userId,
},
- region: FunctionRegion.UsEast1,
});
if (!tools?.data?.result) {
@@ -315,7 +313,6 @@ export function Agent() {
inputFormat: "messages",
temperature: 1,
}),
- region: FunctionRegion.UsEast1,
});
if (response?.error) {
@@ -362,7 +359,6 @@ export function Agent() {
"x-company-id": companyId,
"x-user-id": userId,
},
- region: FunctionRegion.UsEast1,
});
const response = toolResponse?.data;
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 98ff24cc56..c94b0b3af6 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -373,7 +373,8 @@ const OrderDrawer = memo(
setOrders(selectedItem, []);
onClose();
}
- }, [fetcher.data, onClose, selectedItem, setOrders]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.data?.success]);
const supplierDisclosure = useDisclosure();
@@ -802,19 +803,6 @@ const PlanningTable = memo(
}
);
- useEffect(() => {
- if (
- bulkUpdateFetcher.data?.success === false &&
- bulkUpdateFetcher?.data?.message
- ) {
- toast.error(bulkUpdateFetcher.data.message);
- }
-
- if (bulkUpdateFetcher.data?.success === true) {
- toast.success("Orders submitted");
- }
- }, [bulkUpdateFetcher.data]);
-
const isDisabled =
!permissions.can("create", "production") ||
bulkUpdateFetcher.state !== "idle" ||
@@ -1255,5 +1243,5 @@ PlanningTable.displayName = "PlanningTable";
export default PlanningTable;
function getLocationPath(locationId: string) {
- return `${path.to.productionPlanning}?location=${locationId}`;
+ return `${path.to.purchasingPlanning}?location=${locationId}`;
}
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index b596876fd3..0d2d23eea2 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -28,12 +28,25 @@ export async function action({ request }: ActionFunctionArgs) {
});
const { items, action, locationId } = await request.json();
+
if (typeof locationId !== "string") {
- return json({ success: false, message: "Location is required" });
+ return json(
+ {
+ success: false,
+ message: "Location ID is required and must be a valid string",
+ },
+ { status: 500 }
+ );
}
if (typeof action !== "string") {
- return json({ success: false, message: "Invalid form data" });
+ return json(
+ {
+ success: false,
+ message: "Action parameter is required and must be a valid string",
+ },
+ { status: 500 }
+ );
}
switch (action) {
@@ -41,12 +54,51 @@ export async function action({ request }: ActionFunctionArgs) {
const parsedItems = itemsValidator.safeParse(items);
if (!parsedItems.success) {
- return json({ success: false, message: "Invalid form data" });
+ const errorMessages = parsedItems.error.errors.map((error) => {
+ const path = error.path;
+ const field = path[path.length - 1];
+
+ // Create more readable error messages based on the field and context
+ if (field === "orders" && path.length === 2) {
+ return "No orders provided for item";
+ }
+ if (field === "quantity") {
+ return "Invalid quantity specified";
+ }
+ if (field === "periodId") {
+ return "No period specified";
+ }
+ if (field === "startDate") {
+ return "Invalid start date";
+ }
+ if (field === "dueDate") {
+ return "Invalid due date";
+ }
+
+ // Fallback to original message for unhandled cases
+ return error.message;
+ });
+
+ console.error("Validation errors:", parsedItems.error.errors);
+ return json(
+ {
+ success: false,
+ message: `Validation failed: ${errorMessages.join(", ")}`,
+ errors: errorMessages,
+ },
+ { status: 500 }
+ );
}
const itemsToOrder = parsedItems.data;
if (itemsToOrder.length === 0) {
- return json({ success: false, message: "No items to order" });
+ return json(
+ {
+ success: false,
+ message: "No items were provided to create production orders",
+ },
+ { status: 500 }
+ );
}
try {
@@ -62,6 +114,9 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: string;
}> = [];
+ let processedItems = 0;
+ let errors: string[] = [];
+
for (const item of itemsToOrder) {
const orders = item.orders;
const jobIds: string[] = [];
@@ -77,25 +132,28 @@ export async function action({ request }: ActionFunctionArgs) {
.single();
if (manufacturing.error) {
- console.error(
- `Failed to get manufacturing data for item ${item.id}:`,
- manufacturing.error
- );
+ const errorMsg = `Failed to retrieve manufacturing data for item ${item.id}: ${manufacturing.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
if (manufacturing.data?.manufacturingBlocked) {
- console.warn(`Manufacturing is blocked for item ${item.id}`);
+ const errorMsg = `Manufacturing is blocked for item ${item.id}`;
+ console.warn(errorMsg);
+ errors.push(errorMsg);
continue;
}
if (manufacturing.data?.requiresConfiguration) {
- console.warn(
- `Manufacturing requires configuration for item ${item.id}`
- );
+ const errorMsg = `Manufacturing requires configuration for item ${item.id}`;
+ console.warn(errorMsg);
+ errors.push(errorMsg);
continue;
}
+ let itemProcessed = false;
+
// Process each order for this item
for (const order of orders) {
if (!order.existingId) {
@@ -106,16 +164,17 @@ export async function action({ request }: ActionFunctionArgs) {
companyId
);
if (nextSequence.error) {
- console.error(
- `Failed to get next sequence for item ${item.id}:`,
- nextSequence.error
- );
+ const errorMsg = `Failed to generate job sequence for item ${item.id}: ${nextSequence.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
const jobId = nextSequence.data;
if (!jobId) {
- console.error(`Failed to get job ID for item ${item.id}`);
+ const errorMsg = `Failed to generate job ID for item ${item.id}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
@@ -140,18 +199,17 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (createJob.error) {
- console.error(
- `Failed to create job for item ${item.id}:`,
- createJob.error
- );
+ const errorMsg = `Failed to create job for item ${item.id}: ${createJob.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
const id = createJob.data?.id;
if (!id) {
- console.error(
- `Failed to get created job ID for item ${item.id}`
- );
+ const errorMsg = `Job was not returned after creation for item ${item.id}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
@@ -163,14 +221,14 @@ export async function action({ request }: ActionFunctionArgs) {
});
if (upsertMethod.error) {
- console.error(
- `Failed to create job method for item ${item.id}:`,
- upsertMethod.error
- );
+ const errorMsg = `Failed to create job method for item ${item.id}: ${upsertMethod.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
jobIds.push(id);
+ itemProcessed = true;
} else {
// Update existing job
jobIds.push(order.existingId);
@@ -191,12 +249,13 @@ export async function action({ request }: ActionFunctionArgs) {
.eq("id", order.existingId);
if (updateJob.error) {
- console.error(
- `Failed to update job ${order.existingId}:`,
- updateJob.error
- );
+ const errorMsg = `Failed to update job ${order.existingId} for item ${item.id}: ${updateJob.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
+
+ itemProcessed = true;
}
// Track supply forecast by period
@@ -206,24 +265,27 @@ export async function action({ request }: ActionFunctionArgs) {
(order.quantity - (order.existingQuantity ?? 0));
}
- // Add job IDs to the overall list
- allJobIds.push(...jobIds);
-
- // Add supply forecasts for this item
- Object.entries(supplyForecastByPeriod).forEach(
- ([periodId, quantity]) => {
- allSupplyForecasts.push({
- itemId: item.id,
- locationId,
- sourceType: "Production Order" as const,
- forecastQuantity: quantity,
- periodId,
- companyId,
- createdBy: userId,
- updatedBy: userId,
- });
- }
- );
+ if (itemProcessed) {
+ processedItems++;
+ // Add job IDs to the overall list
+ allJobIds.push(...jobIds);
+
+ // Add supply forecasts for this item
+ Object.entries(supplyForecastByPeriod).forEach(
+ ([periodId, quantity]) => {
+ allSupplyForecasts.push({
+ itemId: item.id,
+ locationId,
+ sourceType: "Production Order" as const,
+ forecastQuantity: quantity,
+ periodId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ );
+ }
}
// Insert all supply forecasts
@@ -233,10 +295,9 @@ export async function action({ request }: ActionFunctionArgs) {
.insert(allSupplyForecasts);
if (insertForecasts.error) {
- console.error(
- "Failed to insert supply forecasts:",
- insertForecasts.error
- );
+ const errorMsg = `Failed to insert supply forecasts: ${insertForecasts.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
}
}
@@ -251,21 +312,57 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ if (errors.length > 0 && processedItems === 0) {
+ return json(
+ {
+ success: false,
+ message: `Failed to process any items. Errors: ${errors
+ .slice(0, 3)
+ .join("; ")}${
+ errors.length > 3 ? ` and ${errors.length - 3} more...` : ""
+ }`,
+ errors: errors,
+ },
+ { status: 500 }
+ );
+ }
+
+ const message =
+ processedItems === itemsToOrder.length
+ ? `Successfully processed all ${processedItems} items with ${allJobIds.length} jobs`
+ : `Processed ${processedItems} of ${itemsToOrder.length} items. ${
+ errors.length
+ } errors occurred: ${errors.slice(0, 2).join("; ")}${
+ errors.length > 2 ? "..." : ""
+ }`;
+
return json({
- success: true,
- message: `Successfully processed ${itemsToOrder.length} items with ${allJobIds.length} jobs`,
+ success: processedItems > 0,
+ message,
+ processedItems,
+ totalItems: itemsToOrder.length,
+ errors: errors.length > 0 ? errors : undefined,
});
} catch (error) {
- console.error("Error processing production orders:", error);
- return json({
- success: false,
- message: `Error processing production orders: ${
- error instanceof Error ? error.message : "Unknown error"
- }`,
- });
+ console.error("Unexpected error processing production orders:", error);
+ return json(
+ {
+ success: false,
+ message: `Unexpected error occurred while processing production orders: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ },
+ { status: 500 }
+ );
}
default:
- return json({ success: false, message: "Invalid field" });
+ return json(
+ {
+ success: false,
+ message: `Unknown action '${action}'. Expected action: 'order'`,
+ },
+ { status: 500 }
+ );
}
}
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index e1822d1869..ab69af9414 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -31,11 +31,23 @@ export async function action({ request }: ActionFunctionArgs) {
const { items, action, locationId } = await request.json();
if (typeof locationId !== "string") {
- return json({ success: false, message: "Location is required" });
+ return json(
+ {
+ success: false,
+ message: "Location ID is required and must be a valid string",
+ },
+ { status: 500 }
+ );
}
if (typeof action !== "string") {
- return json({ success: false, message: "Invalid form data" });
+ return json(
+ {
+ success: false,
+ message: "Action parameter is required and must be a valid string",
+ },
+ { status: 500 }
+ );
}
switch (action) {
@@ -43,15 +55,54 @@ export async function action({ request }: ActionFunctionArgs) {
const parsedItems = itemsValidator.safeParse(items);
if (!parsedItems.success) {
- parsedItems.error.errors.forEach((error) => {
- console.error(error);
+ const errorMessages = parsedItems.error.errors.map((error) => {
+ const path = error.path;
+ const field = path[path.length - 1];
+
+ // Create more readable error messages based on the field and context
+ if (field === "orders" && path.length === 2) {
+ return "No orders provided for item";
+ }
+ if (field === "supplierId" || field === "suppliers") {
+ return "No suppliers provided";
+ }
+ if (field === "quantity") {
+ return "Invalid quantity specified";
+ }
+ if (field === "unitPrice") {
+ return "Invalid unit price specified";
+ }
+ if (field === "periodId") {
+ return "No period specified";
+ }
+ if (field === "deliveryDate") {
+ return "Invalid delivery date";
+ }
+
+ // Fallback to original message for unhandled cases
+ return error.message;
});
- return json({ success: false, message: "Invalid form data" });
+
+ console.error("Validation errors:", parsedItems.error.errors);
+ return json(
+ {
+ success: false,
+ message: `Validation failed: ${errorMessages.join(", ")}`,
+ errors: errorMessages,
+ },
+ { status: 500 }
+ );
}
const itemsToOrder = parsedItems.data;
if (itemsToOrder.length === 0) {
- return json({ success: false, message: "No items to order" });
+ return json(
+ {
+ success: false,
+ message: "No items were provided to create purchase orders",
+ },
+ { status: 500 }
+ );
}
try {
@@ -98,12 +149,60 @@ export async function action({ request }: ActionFunctionArgs) {
.single(),
]);
+ if (suppliers.error) {
+ console.error("Failed to fetch suppliers:", suppliers.error);
+ return json(
+ {
+ success: false,
+ message: "Failed to retrieve supplier information from database",
+ },
+ { status: 500 }
+ );
+ }
+
+ if (supplierParts.error) {
+ console.error("Failed to fetch supplier parts:", supplierParts.error);
+ return json(
+ {
+ success: false,
+ message:
+ "Failed to retrieve supplier part information from database",
+ },
+ { status: 500 }
+ );
+ }
+
+ if (periods.error) {
+ console.error("Failed to fetch periods:", periods.error);
+ return json(
+ {
+ success: false,
+ message: "Failed to retrieve period information from database",
+ },
+ { status: 500 }
+ );
+ }
+
+ if (company.error) {
+ console.error("Failed to fetch company:", company.error);
+ return json(
+ {
+ success: false,
+ message: "Failed to retrieve company information from database",
+ },
+ { status: 500 }
+ );
+ }
+
const suppliersById = new Map(
suppliers.data?.map((supplier) => [supplier.id, supplier]) ?? []
);
const baseCurrencyCode = company.data?.baseCurrencyCode ?? "USD";
+ let processedItems = 0;
+ let errors: string[] = [];
+
for (const item of itemsToOrder) {
const orders = item.orders;
const supplier = suppliersById.get(orders[0]?.supplierId ?? "");
@@ -121,20 +220,21 @@ export async function action({ request }: ActionFunctionArgs) {
.single();
if (purchasing.error) {
- console.error(
- `Failed to get purchasing data for item ${item.id}:`,
- purchasing.error
- );
+ const errorMsg = `Failed to retrieve purchasing data for item ${item.id}: ${purchasing.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
if (purchasing.data?.purchasingBlocked) {
- console.warn(`Purchasing is blocked for item ${item.id}`);
+ const errorMsg = `Purchasing is blocked for item ${item.id}`;
+ console.warn(errorMsg);
+ errors.push(errorMsg);
continue;
}
// Get existing purchase orders for this supplier
- const { data: existingPurchaseOrders } = await client
+ const { data: existingPurchaseOrders, error: poError } = await client
.from("purchaseOrder")
.select(
"id, purchaseOrderId, orderDate, status, purchaseOrderDelivery(receiptRequestedDate, receiptPromisedDate)"
@@ -142,6 +242,13 @@ export async function action({ request }: ActionFunctionArgs) {
.eq("supplierId", supplier?.id ?? "")
.in("status", ["Draft", "Planned"]);
+ if (poError) {
+ const errorMsg = `Failed to retrieve existing purchase orders for supplier ${supplier?.id}: ${poError.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
+ continue;
+ }
+
const existingPOs =
existingPurchaseOrders?.map((order) => {
const dueDate =
@@ -182,9 +289,13 @@ export async function action({ request }: ActionFunctionArgs) {
return order;
});
+ let itemProcessed = false;
+
for (const order of ordersMappedToExistingPOs) {
if (!order.supplierId) {
- console.error(`Supplier ID is required for item ${item.id}`);
+ const errorMsg = `Supplier ID is missing for item ${item.id}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
@@ -195,18 +306,17 @@ export async function action({ request }: ActionFunctionArgs) {
companyId
);
if (nextSequence.error) {
- console.error(
- `Failed to get next sequence for item ${item.id}:`,
- nextSequence.error
- );
+ const errorMsg = `Failed to generate purchase order sequence for item ${item.id}: ${nextSequence.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
const purchaseOrderId = nextSequence.data;
if (!purchaseOrderId) {
- console.error(
- `Failed to get purchase order ID for item ${item.id}`
- );
+ const errorMsg = `Failed to generate purchase order ID for item ${item.id}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
@@ -218,6 +328,13 @@ export async function action({ request }: ActionFunctionArgs) {
supplier?.currencyCode ?? baseCurrencyCode
);
+ if (currency.error) {
+ const errorMsg = `Failed to retrieve exchange rate for currency ${supplier?.currencyCode}: ${currency.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
+ continue;
+ }
+
if (currency.data) {
exchangeRate = currency.data.exchangeRate ?? 1;
}
@@ -239,18 +356,17 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (createPurchaseOrder.error) {
- console.error(
- `Failed to create purchase order for item ${item.id}:`,
- createPurchaseOrder.error
- );
+ const errorMsg = `Failed to create purchase order for item ${item.id}: ${createPurchaseOrder.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
const purchaseOrder = createPurchaseOrder.data?.[0];
if (!purchaseOrder) {
- console.error(
- `Failed to get created purchase order for item ${item.id}`
- );
+ const errorMsg = `Purchase order was not returned after creation for item ${item.id}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
@@ -281,12 +397,13 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (createPurchaseOrderLine.error) {
- console.error(
- `Failed to create purchase order line for item ${item.id}:`,
- createPurchaseOrderLine.error
- );
+ const errorMsg = `Failed to create purchase order line for item ${item.id}: ${createPurchaseOrderLine.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
+
+ itemProcessed = true;
} else {
if (order.existingLineId) {
const updatePurchaseOrderLine = await upsertPurchaseOrderLine(
@@ -317,10 +434,9 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (updatePurchaseOrderLine.error) {
- console.error(
- `Failed to update purchase order line ${order.existingLineId}:`,
- updatePurchaseOrderLine.error
- );
+ const errorMsg = `Failed to update purchase order line ${order.existingLineId} for item ${item.id}: ${updatePurchaseOrderLine.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
continue;
}
} else {
@@ -351,18 +467,27 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (insertPurchaseOrderLine.error) {
- console.error(
- `Failed to insert purchase order line for item ${item.id}:`,
- insertPurchaseOrderLine.error
- );
+ const errorMsg = `Failed to add purchase order line for item ${item.id}: ${insertPurchaseOrderLine.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
+ continue;
}
}
- await updatePurchaseOrder(client, {
+ const updateResult = await updatePurchaseOrder(client, {
id: order.existingId,
status: "Planned" as const,
updatedBy: userId,
});
+
+ if (updateResult.error) {
+ const errorMsg = `Failed to update purchase order status for item ${item.id}: ${updateResult.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
+ continue;
+ }
+
+ itemProcessed = true;
}
const periodId = order.periodId;
@@ -371,20 +496,23 @@ export async function action({ request }: ActionFunctionArgs) {
(order.quantity - (order.existingQuantity ?? 0));
}
- Object.entries(supplyForecastByPeriod).forEach(
- ([periodId, quantity]) => {
- allSupplyForecasts.push({
- itemId: item.id,
- locationId,
- sourceType: "Purchase Order" as const,
- forecastQuantity: quantity,
- periodId,
- companyId,
- createdBy: userId,
- updatedBy: userId,
- });
- }
- );
+ if (itemProcessed) {
+ processedItems++;
+ Object.entries(supplyForecastByPeriod).forEach(
+ ([periodId, quantity]) => {
+ allSupplyForecasts.push({
+ itemId: item.id,
+ locationId,
+ sourceType: "Purchase Order" as const,
+ forecastQuantity: quantity,
+ periodId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ );
+ }
}
if (allSupplyForecasts.length > 0) {
@@ -393,28 +521,63 @@ export async function action({ request }: ActionFunctionArgs) {
.insert(allSupplyForecasts);
if (insertForecasts.error) {
- console.error(
- "Failed to insert supply forecasts:",
- insertForecasts.error
- );
+ const errorMsg = `Failed to insert supply forecasts: ${insertForecasts.error.message}`;
+ console.error(errorMsg);
+ errors.push(errorMsg);
}
}
+ if (errors.length > 0 && processedItems === 0) {
+ return json(
+ {
+ success: false,
+ message: `Failed to process any items. Errors: ${errors
+ .slice(0, 3)
+ .join("; ")}${
+ errors.length > 3 ? ` and ${errors.length - 3} more...` : ""
+ }`,
+ errors: errors,
+ },
+ { status: 500 }
+ );
+ }
+
+ const message =
+ processedItems === itemsToOrder.length
+ ? `Successfully processed all ${processedItems} items`
+ : `Processed ${processedItems} of ${itemsToOrder.length} items. ${
+ errors.length
+ } errors occurred: ${errors.slice(0, 2).join("; ")}${
+ errors.length > 2 ? "..." : ""
+ }`;
+
return json({
- success: true,
- message: `Successfully processed ${itemsToOrder.length} items`,
+ success: processedItems > 0,
+ message,
+ processedItems,
+ totalItems: itemsToOrder.length,
+ errors: errors.length > 0 ? errors : undefined,
});
} catch (error) {
- console.error("Error processing purchase orders:", error);
- return json({
- success: false,
- message: `Error processing purchase orders: ${
- error instanceof Error ? error.message : "Unknown error"
- }`,
- });
+ console.error("Unexpected error processing purchase orders:", error);
+ return json(
+ {
+ success: false,
+ message: `Unexpected error occurred while processing purchase orders: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ },
+ { status: 500 }
+ );
}
default:
- return json({ success: false, message: "Invalid field" });
+ return json(
+ {
+ success: false,
+ message: `Unknown action '${action}'. Expected action: 'order'`,
+ },
+ { status: 500 }
+ );
}
}
diff --git a/llm/cache/quote-discount-system.md b/llm/cache/quote-discount-system.md
index 23cc354d04..8ebb43b9e6 100644
--- a/llm/cache/quote-discount-system.md
+++ b/llm/cache/quote-discount-system.md
@@ -60,7 +60,33 @@ The `QuotationPrice` type (from `sales.service.ts` exports) includes:
- `shippingCost`: number
- `exchangeRate`: number | null
+## Sales Order and Invoice Integration
+
+### Sales Order Lines
+- The `salesOrderLine` table does NOT contain discount fields
+- The `salesOrderLines` view (created in `20240412224648_sales-orders.sql`) includes:
+ - Basic sales order line fields
+ - Customer ID from the parent sales order
+ - Item name and description via joins
+ - **No discount information is included in this view**
+
+### Sales Invoice Lines
+- The `salesInvoiceLine` table does NOT contain discount fields
+- The `salesInvoiceLines` view (created in `20250507143421_sales-invoice.sql`) includes:
+ - Basic invoice line fields
+ - Item details (name, description, thumbnail)
+ - Unit cost from `itemCost` table
+ - Customer part ID
+ - **No discount information is included in this view**
+
+### Quote to Sales Order/Invoice Flow
+- Sales orders and invoices were originally designed to reference quotes (via `quoteId`)
+- This relationship appears to have been removed/commented out in the migrations
+- Currently, there is no direct link between quote line prices (with discounts) and sales order/invoice lines
+- Discount information from quotes is NOT automatically propagated to sales orders or invoices
+
## Notes
- Discounts are applied at the price level per quantity, not at the quote or line level
- The system calculates net prices dynamically based on unit price and discount percent
-- No global quote-level discount exists; all discounts are line-item and quantity-specific
\ No newline at end of file
+- No global quote-level discount exists; all discounts are line-item and quantity-specific
+- **Important**: Discount information exists only in the `quoteLinePrice` table and is not available in sales order or invoice views
\ No newline at end of file
diff --git a/packages/database/supabase/functions/chat/index.ts b/packages/database/supabase/functions/chat/index.ts
index d1ea657bab..502138ee52 100644
--- a/packages/database/supabase/functions/chat/index.ts
+++ b/packages/database/supabase/functions/chat/index.ts
@@ -4,8 +4,8 @@ import { APICallError, LanguageModelV1CallOptions } from "npm:ai";
import { z } from "npm:zod";
import { corsHeaders } from "../lib/headers.ts";
-import { getAuthFromAPIKey, getSupabase } from "../lib/supabase.ts";
import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";
+import { getAuthFromAPIKey, getSupabase } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
const model = createAnthropic({
@@ -69,7 +69,7 @@ serve(async (req: Request) => {
} catch (error) {
console.error(error);
if (error instanceof APICallError) {
- throw new Response(
+ return new Response(
JSON.stringify({
message: "API call error",
}),