Skip to content

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

feat: sales invoice routes and ui

Brad Barbin7db36a2d6c36
diff --git a/README.md b/README.md
index 2903778d74..0227eb1c6e 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,21 @@
Carbon is the open-source operating system for manufacturing.
-Technical highlights/roadmap:
+Features:
+
+- [x] ERP
+- [x] MES
+- [x] Custom Fields
+- [x] Nested BoM
+- [x] Traceability
+- [x] Configurator
+- [x] MCP Client/Server
+- [x] API
+- [x] Webhooks
+- [ ] Purchase Planning
+- [ ] Accounting
+
+Technical highlights:
- [x] Unified auth and permissions across apps
- [x] Full-stack type safety (Database → UI)
@@ -11,6 +25,7 @@ Technical highlights/roadmap:
- [x] Role-based access control (Customer, Supplier, Employee)
- [x] Row-level security (RLS)
- [x] Composable user groups
+- [x] Dependency graph for operations
- [x] Third-party integrations
## Techstack
@@ -172,9 +187,3 @@ $ npm run dev
```
4. Rename the `_migrations` folder back to `migrations`
-
-## Connecting to the MCP Server
-
-```bash
-$ npx opencontrol http://localhost:54321/functions/v1/mcp
-```
diff --git a/apps/erp/app/modules/documents/documents.models.ts b/apps/erp/app/modules/documents/documents.models.ts
index 8a3b92f0c5..4472bb130d 100644
--- a/apps/erp/app/modules/documents/documents.models.ts
+++ b/apps/erp/app/modules/documents/documents.models.ts
@@ -8,6 +8,8 @@ export const documentSourceTypes = [
"Quote",
"Request for Quote",
"Supplier Quote",
+ "Sales Order",
+ "Sales Invoice",
...methodItemType,
] as const;
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
index 409e4b74ba..84d1d1faad 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -622,6 +622,10 @@ function getDocumentLocation(
return path.to.quote(sourceDocumentId);
case "Request for Quote":
return path.to.salesRfq(sourceDocumentId);
+ case "Sales Order":
+ return path.to.salesOrder(sourceDocumentId);
+ case "Sales Invoice":
+ return path.to.salesInvoice(sourceDocumentId);
case "Supplier Quote":
return path.to.supplierQuote(sourceDocumentId);
case "Job":
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index c0b6e21778..47dd0d9edc 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -146,3 +146,80 @@ export const purchaseInvoiceLineValidator = z
// path: ["description"], // path of error
// }
// );
+
+export const salesInvoiceValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ invoiceId: zfd.text(z.string().optional()),
+ customerId: z.string().min(36, { message: "Customer is required" }),
+ customerReference: zfd.text(z.string().optional()),
+ paymentTermId: zfd.text(z.string().optional()),
+ currencyCode: zfd.text(z.string().optional()),
+ locationId: zfd.text(z.string().optional()),
+ invoiceCustomerId: zfd.text(z.string().optional()),
+ invoiceCustomerContactId: zfd.text(z.string().optional()),
+ invoiceCustomerLocationId: zfd.text(z.string().optional()),
+ dateIssued: zfd.text(z.string().optional()),
+ dateDue: zfd.text(z.string().optional()),
+ supplierShippingCost: zfd.numeric(z.number().optional()),
+ exchangeRate: zfd.numeric(z.number().optional()),
+ exchangeRateUpdatedAt: zfd.text(z.string().optional()),
+});
+
+export const salesInvoiceShipmentValidator = z.object({
+ id: z.string(),
+ locationId: zfd.text(z.string().optional()),
+ shippingMethodId: zfd.text(z.string().optional()),
+ shippingTermId: zfd.text(z.string().optional()),
+ shippingCost: zfd.numeric(z.number().optional().default(0)),
+ customFields: z.any().optional(),
+});
+
+export const salesInvoiceLineValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ invoiceId: z.string().min(20, { message: "Invoice is required" }),
+ invoiceLineType: z.enum(methodItemType, {
+ errorMap: (issue, ctx) => ({
+ message: "Type is required",
+ }),
+ }),
+ purchaseOrderId: zfd.text(z.string().optional()),
+ purchaseOrderLineId: zfd.text(z.string().optional()),
+ itemId: zfd.text(z.string().optional()),
+ itemReadableId: zfd.text(z.string().optional()),
+ accountNumber: zfd.text(z.string().optional()),
+ assetId: zfd.text(z.string().optional()),
+ description: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(z.number().optional()),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of measure is required" }),
+ unitPrice: zfd.numeric(z.number().optional()),
+ shippingCost: zfd.numeric(z.number().optional().default(0)),
+ taxPercent: zfd.numeric(z.number().optional().default(0)),
+ locationId: zfd.text(z.string().optional()),
+ shelfId: zfd.text(z.string().optional()),
+ exchangeRate: zfd.numeric(z.number().optional()),
+ })
+ .refine(
+ (data) =>
+ ["Part", "Service", "Material", "Tool", "Consumable"].includes(
+ data.invoiceLineType
+ )
+ ? data.itemId
+ : true,
+ {
+ message: "Item is required",
+ path: ["itemId"], // path of error
+ }
+ )
+ .refine(
+ (data) =>
+ ["Part", "Material", "Tool", "Consumable"].includes(data.invoiceLineType)
+ ? data.locationId
+ : true,
+ {
+ message: "Location is required",
+ path: ["locationId"], // path of error
+ }
+ );
diff --git a/apps/erp/app/modules/invoicing/invoicing.server.ts b/apps/erp/app/modules/invoicing/invoicing.server.ts
deleted file mode 100644
index 9f3cec500f..0000000000
--- a/apps/erp/app/modules/invoicing/invoicing.server.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { getCarbonServiceRole } from "@carbon/auth";
-
-export async function createPurchaseInvoiceFromPurchaseOrder(
- purchaseOrderId: string,
- companyId: string,
- userId: string
-) {
- const client = getCarbonServiceRole();
- return client.functions.invoke<{ id: string }>("convert", {
- body: {
- type: "purchaseOrderToPurchaseInvoice",
- id: purchaseOrderId,
- companyId,
- userId,
- },
- });
-}
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index c6c13019c1..8a6d3c743b 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -12,12 +12,51 @@ import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
import { getEmployeeJob } from "../people/people.service";
+import {
+ getCustomerPayment,
+ getCustomerShipping,
+} from "../sales/sales.service";
import type {
purchaseInvoiceDeliveryValidator,
purchaseInvoiceLineValidator,
purchaseInvoiceValidator,
+ salesInvoiceLineValidator,
+ salesInvoiceShipmentValidator,
+ salesInvoiceValidator,
} from "./invoicing.models";
+export async function createPurchaseInvoiceFromPurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string,
+ companyId: string,
+ userId: string
+) {
+ return client.functions.invoke<{ id: string }>("convert", {
+ body: {
+ type: "purchaseOrderToPurchaseInvoice",
+ id: purchaseOrderId,
+ companyId,
+ userId,
+ },
+ });
+}
+
+export async function createSalesInvoiceFromSalesOrder(
+ client: SupabaseClient<Database>,
+ salesOrderId: string,
+ companyId: string,
+ userId: string
+) {
+ return client.functions.invoke<{ id: string }>("convert", {
+ body: {
+ type: "salesOrderToSalesInvoice",
+ id: salesOrderId,
+ companyId,
+ userId,
+ },
+ });
+}
+
export async function deletePurchaseInvoice(
client: SupabaseClient<Database>,
purchaseInvoiceId: string
@@ -38,6 +77,23 @@ export async function deletePurchaseInvoiceLine(
.eq("id", purchaseInvoiceLineId);
}
+export async function deleteSalesInvoice(
+ client: SupabaseClient<Database>,
+ salesInvoiceId: string
+) {
+ // TODO: this should be a transaction that checks whether it is posted
+ // and then sets the status of the purchase order back to
+ // "To Receive and Invoice" | "To Invoice"
+ return client.from("salesInvoice").delete().eq("id", salesInvoiceId);
+}
+
+export async function deleteSalesInvoiceLine(
+ client: SupabaseClient<Database>,
+ salesInvoiceLineId: string
+) {
+ return client.from("salesInvoiceLine").delete().eq("id", salesInvoiceLineId);
+}
+
export async function getPurchaseInvoice(
client: SupabaseClient<Database>,
purchaseInvoiceId: string
@@ -180,6 +236,38 @@ export async function getSalesInvoiceLine(
.single();
}
+export async function updatePurchaseInvoiceExchangeRate(
+ client: SupabaseClient<Database>,
+ data: {
+ id: string;
+ exchangeRate: number;
+ }
+) {
+ const update = {
+ id: data.id,
+ exchangeRate: data.exchangeRate,
+ exchangeRateUpdatedAt: new Date().toISOString(),
+ };
+
+ return client.from("purchaseInvoice").update(update).eq("id", update.id);
+}
+
+export async function updateSalesInvoiceExchangeRate(
+ client: SupabaseClient<Database>,
+ data: {
+ id: string;
+ exchangeRate: number;
+ }
+) {
+ const update = {
+ id: data.id,
+ exchangeRate: data.exchangeRate,
+ exchangeRateUpdatedAt: new Date().toISOString(),
+ };
+
+ return client.from("salesInvoice").update(update).eq("id", update.id);
+}
+
export async function upsertPurchaseInvoice(
client: SupabaseClient<Database>,
purchaseInvoice:
@@ -338,3 +426,162 @@ export async function upsertPurchaseInvoiceLine(
.select("id")
.single();
}
+
+export async function upsertSalesInvoice(
+ client: SupabaseClient<Database>,
+ salesInvoice:
+ | (Omit<z.infer<typeof salesInvoiceValidator>, "id" | "invoiceId"> & {
+ invoiceId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof salesInvoiceValidator>, "id" | "invoiceId"> & {
+ id: string;
+ invoiceId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in salesInvoice) {
+ return client
+ .from("salesInvoice")
+ .update({
+ ...sanitize(salesInvoice),
+ updatedAt: today(getLocalTimeZone()).toString(),
+ })
+ .eq("id", salesInvoice.id)
+ .select("id, invoiceId");
+ }
+
+ const [opportunity, customerPayment, customerShipping, salesPerson] =
+ await Promise.all([
+ client
+ .from("opportunity")
+ .insert([{ companyId: salesInvoice.companyId }])
+ .select("id")
+ .single(),
+ getCustomerPayment(client, salesInvoice.customerId),
+ getCustomerShipping(client, salesInvoice.customerId),
+ getEmployeeJob(client, salesInvoice.createdBy, salesInvoice.companyId),
+ ]);
+
+ if (opportunity.error) return opportunity;
+ if (customerPayment.error) return customerPayment;
+ if (customerShipping.error) return customerShipping;
+
+ const { paymentTermId, invoiceCustomerId } = customerPayment.data;
+ const { shippingMethodId, shippingTermId } = customerShipping.data;
+
+ if (salesInvoice.currencyCode) {
+ const currency = await getCurrencyByCode(
+ client,
+ salesInvoice.companyId,
+ salesInvoice.currencyCode
+ );
+ if (currency.data) {
+ salesInvoice.exchangeRate = currency.data.exchangeRate ?? undefined;
+ salesInvoice.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+ } else {
+ salesInvoice.exchangeRate = 1;
+ salesInvoice.exchangeRateUpdatedAt = new Date().toISOString();
+ }
+
+ const locationId =
+ salesInvoice.locationId ?? salesPerson?.data?.locationId ?? null;
+
+ const invoice = await client
+ .from("salesInvoice")
+ .insert([
+ {
+ ...salesInvoice,
+ invoiceCustomerId: invoiceCustomerId ?? salesInvoice.customerId,
+ opportunityId: opportunity.data?.id,
+ currencyCode: salesInvoice.currencyCode ?? "USD",
+ paymentTermId: salesInvoice.paymentTermId ?? paymentTermId,
+ },
+ ])
+ .select("id, invoiceId");
+
+ if (invoice.error) return invoice;
+
+ const invoiceId = invoice.data[0].id;
+
+ const delivery = await client.from("salesInvoiceShipment").insert([
+ {
+ id: invoiceId,
+ locationId: locationId,
+ shippingMethodId: shippingMethodId,
+ shippingTermId: shippingTermId,
+ companyId: salesInvoice.companyId,
+ createdBy: salesInvoice.createdBy,
+ },
+ ]);
+
+ if (delivery.error) {
+ await client.from("salesInvoice").delete().eq("id", invoiceId);
+ return delivery;
+ }
+
+ return invoice;
+}
+
+export async function upsertSalesInvoiceShipment(
+ client: SupabaseClient<Database>,
+ salesInvoiceShipment:
+ | (z.infer<typeof salesInvoiceShipmentValidator> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (z.infer<typeof salesInvoiceShipmentValidator> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in salesInvoiceShipment) {
+ return client
+ .from("salesInvoiceShipment")
+ .update(sanitize(salesInvoiceShipment))
+ .eq("id", salesInvoiceShipment.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("salesInvoiceShipment")
+ .insert([salesInvoiceShipment])
+ .select("id")
+ .single();
+}
+
+export async function upsertSalesInvoiceLine(
+ client: SupabaseClient<Database>,
+ salesInvoiceLine:
+ | (Omit<z.infer<typeof salesInvoiceLineValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof salesInvoiceLineValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in salesInvoiceLine) {
+ return client
+ .from("salesInvoiceLine")
+ .update(sanitize(salesInvoiceLine))
+ .eq("id", salesInvoiceLine.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("salesInvoiceLine")
+ .insert([salesInvoiceLine])
+ .select("id")
+ .single();
+}
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
index 3c5d24960b..d43d0e546a 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx
@@ -107,7 +107,7 @@ const PurchaseInvoiceProperties = () => {
: routeData?.purchaseInvoice?.assignee;
const isDisabled =
- !permissions.can("update", "purchasing") ||
+ !permissions.can("update", "invoicing") ||
!["Draft", "To Review", "Overdue"].includes(
routeData?.purchaseInvoice?.status ?? ""
);
@@ -170,7 +170,7 @@ const PurchaseInvoiceProperties = () => {
table="purchaseInvoice"
value={assignee ?? ""}
variant="inline"
- isReadOnly={!permissions.can("update", "purchasing")}
+ isReadOnly={!permissions.can("update", "invoicing")}
/>
<ValidatedForm
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeletePurchaseInvoiceLine.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
similarity index 73%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/DeletePurchaseInvoiceLine.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
index 907113905d..ea21b4b1c2 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeletePurchaseInvoiceLine.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/DeleteSalesInvoiceLine.tsx
@@ -1,13 +1,13 @@
import { useParams } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { path } from "~/utils/path";
-import type { PurchaseInvoiceLine } from "../../types";
+import type { SalesInvoiceLine } from "../../types";
-export default function DeletePurchaseInvoiceLine({
+export default function DeleteSalesInvoiceLine({
line,
onCancel,
}: {
- line: PurchaseInvoiceLine;
+ line: SalesInvoiceLine;
onCancel: () => void;
}) {
const { invoiceId } = useParams();
@@ -16,7 +16,7 @@ export default function DeletePurchaseInvoiceLine({
return (
<ConfirmDelete
- action={path.to.deletePurchaseInvoiceLine(invoiceId, line.id)}
+ action={path.to.deleteSalesInvoiceLine(invoiceId, line.id)}
name={line.itemReadableId ?? "this line"}
text={`Are you sure you want to delete the line: ${line.itemReadableId}? This cannot be undone.`}
onCancel={onCancel}
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
similarity index 75%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceExplorer.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index d35e65b676..19ad3b30f9 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -32,43 +32,42 @@ import type { Supplier } from "~/modules/purchasing/types";
import type { MethodItemType } from "~/modules/shared";
import { methodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
-import type { PurchaseInvoice, PurchaseInvoiceLine } from "../../types";
-import DeletePurchaseInvoiceLine from "./DeletePurchaseInvoiceLine";
-import PurchaseInvoiceLineForm from "./PurchaseInvoiceLineForm";
+import type { SalesInvoice, SalesInvoiceLine } from "../../types";
+import DeleteSalesInvoiceLine from "./DeleteSalesInvoiceLine";
+import SalesInvoiceLineForm from "./SalesInvoiceLineForm";
-export default function PurchaseInvoiceExplorer() {
+export default function SalesInvoiceExplorer() {
const { defaults } = useUser();
const { invoiceId } = useParams();
if (!invoiceId) throw new Error("Could not find invoiceId");
- const purchaseInvoiceData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- purchaseInvoiceLines: PurchaseInvoiceLine[];
+ const salesInvoiceData = useRouteData<{
+ salesInvoice: SalesInvoice;
+ salesInvoiceLines: SalesInvoiceLine[];
supplier: Supplier;
- }>(path.to.purchaseInvoice(invoiceId));
+ }>(path.to.salesInvoice(invoiceId));
const permissions = usePermissions();
- const purchaseInvoiceLineInitialValues = {
+ const salesInvoiceLineInitialValues = {
invoiceId: invoiceId,
invoiceLineType: "Item" as MethodItemType,
- purchaseQuantity: 1,
+ quantity: 1,
locationId:
- purchaseInvoiceData?.purchaseInvoice?.locationId ??
- defaults.locationId ??
- "",
- supplierUnitPrice: 0,
- supplierShippingCost: 0,
- supplierTaxAmount: 0,
- exchangeRate: purchaseInvoiceData?.purchaseInvoice?.exchangeRate ?? 1,
+ salesInvoiceData?.salesInvoice?.locationId ?? defaults.locationId ?? "",
+ unitOfMeasureCode: "",
+ taxPercent: 0,
+ unitPrice: 0,
+ shippingCost: 0,
+ addOnCost: 0,
+ taxAmount: 0,
+ exchangeRate: salesInvoiceData?.salesInvoice?.exchangeRate ?? 1,
};
- const newPurchaseInvoiceLineDisclosure = useDisclosure();
+ const newSalesInvoiceLineDisclosure = useDisclosure();
const deleteLineDisclosure = useDisclosure();
- const [deleteLine, setDeleteLine] = useState<PurchaseInvoiceLine | null>(
- null
- );
- const isDisabled = purchaseInvoiceData?.purchaseInvoice?.status !== "Draft";
+ const [deleteLine, setDeleteLine] = useState<SalesInvoiceLine | null>(null);
+ const isDisabled = salesInvoiceData?.salesInvoice?.status !== "Draft";
- const onDeleteLine = (line: PurchaseInvoiceLine) => {
+ const onDeleteLine = (line: SalesInvoiceLine) => {
setDeleteLine(line);
deleteLineDisclosure.onOpen();
};
@@ -93,9 +92,9 @@ export default function PurchaseInvoiceExplorer() {
className="flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
spacing={0}
>
- {purchaseInvoiceData?.purchaseInvoiceLines?.length ? (
- purchaseInvoiceData.purchaseInvoiceLines.map((line) => (
- <PurchaseInvoiceLineItem
+ {salesInvoiceData?.salesInvoiceLines?.length ? (
+ salesInvoiceData.salesInvoiceLines.map((line) => (
+ <SalesInvoiceLineItem
key={line.id}
isDisabled={isDisabled}
line={line}
@@ -109,7 +108,7 @@ export default function PurchaseInvoiceExplorer() {
isDisabled={isDisabled}
leftIcon={<LuCirclePlus />}
variant="secondary"
- onClick={newPurchaseInvoiceLineDisclosure.onOpen}
+ onClick={newSalesInvoiceLineDisclosure.onOpen}
>
Add Line Item
</Button>
@@ -126,7 +125,7 @@ export default function PurchaseInvoiceExplorer() {
isDisabled={isDisabled || !permissions.can("update", "sales")}
leftIcon={<LuCirclePlus />}
variant="secondary"
- onClick={newPurchaseInvoiceLineDisclosure.onOpen}
+ onClick={newSalesInvoiceLineDisclosure.onOpen}
>
Add Line Item
</Button>
@@ -140,46 +139,43 @@ export default function PurchaseInvoiceExplorer() {
</Tooltip>
</div>
</VStack>
- {newPurchaseInvoiceLineDisclosure.isOpen && (
- <PurchaseInvoiceLineForm
- initialValues={purchaseInvoiceLineInitialValues}
+ {newSalesInvoiceLineDisclosure.isOpen && (
+ <SalesInvoiceLineForm
+ initialValues={salesInvoiceLineInitialValues}
type="modal"
- onClose={newPurchaseInvoiceLineDisclosure.onClose}
+ onClose={newSalesInvoiceLineDisclosure.onClose}
/>
)}
{deleteLineDisclosure.isOpen && (
- <DeletePurchaseInvoiceLine
- line={deleteLine!}
- onCancel={onDeleteCancel}
- />
+ <DeleteSalesInvoiceLine line={deleteLine!} onCancel={onDeleteCancel} />
)}
</>
);
}
-type PurchaseInvoiceLineItemProps = {
- line: PurchaseInvoiceLine;
+type SalesInvoiceLineItemProps = {
+ line: SalesInvoiceLine;
isDisabled: boolean;
- onDelete: (line: PurchaseInvoiceLine) => void;
+ onDelete: (line: SalesInvoiceLine) => void;
};
-function PurchaseInvoiceLineItem({
+function SalesInvoiceLineItem({
line,
isDisabled,
onDelete,
-}: PurchaseInvoiceLineItemProps) {
+}: SalesInvoiceLineItemProps) {
const { invoiceId } = useParams();
if (!invoiceId) throw new Error("Could not find invoiceId");
const permissions = usePermissions();
const location = useOptimisticLocation();
const isSelected =
- location.pathname === path.to.purchaseInvoiceLine(invoiceId, line.id!);
+ location.pathname === path.to.salesInvoiceLine(invoiceId, line.id!);
return (
<VStack spacing={0} className="border-b">
<Link
- to={path.to.purchaseInvoiceLine(invoiceId, line.id!)}
+ to={path.to.salesInvoiceLine(invoiceId, line.id!)}
prefetch="intent"
className="w-full"
>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
similarity index 52%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceForm.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
index 01a9462468..25c3508766 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
@@ -17,63 +17,63 @@ import type { z } from "zod";
import {
Currency,
CustomFormFields,
+ Customer,
+ CustomerContact,
+ CustomerLocation,
DatePicker,
Hidden,
Input,
Location,
Submit,
- Supplier,
- SupplierContact,
- SupplierLocation,
} from "~/components/Form";
import PaymentTerm from "~/components/Form/PaymentTerm";
import { usePermissions } from "~/hooks";
-import { purchaseInvoiceValidator } from "~/modules/invoicing";
+import { salesInvoiceValidator } from "~/modules/invoicing";
-type PurchaseInvoiceFormValues = z.infer<typeof purchaseInvoiceValidator>;
+type SalesInvoiceFormValues = z.infer<typeof salesInvoiceValidator>;
-type PurchaseInvoiceFormProps = {
- initialValues: PurchaseInvoiceFormValues;
+type SalesInvoiceFormProps = {
+ initialValues: SalesInvoiceFormValues;
};
-const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
+const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {
const permissions = usePermissions();
const { carbon } = useCarbon();
const isEditing = initialValues.id !== undefined;
- const [invoiceSupplier, setInvoiceSupplier] = useState<{
+ const [invoiceCustomer, setInvoiceCustomer] = useState<{
id: string | undefined;
- invoiceSupplierContactId: string | undefined;
- invoiceSupplierLocationId: string | undefined;
+ invoiceCustomerContactId: string | undefined;
+ invoiceCustomerLocationId: string | undefined;
currencyCode: string | undefined;
paymentTermId: string | undefined;
}>({
- id: initialValues.invoiceSupplierId,
- invoiceSupplierContactId: initialValues.invoiceSupplierContactId,
- invoiceSupplierLocationId: initialValues.invoiceSupplierLocationId,
+ id: initialValues.invoiceCustomerId,
+ invoiceCustomerContactId: initialValues.invoiceCustomerContactId,
+ invoiceCustomerLocationId: initialValues.invoiceCustomerLocationId,
currencyCode: initialValues.currencyCode,
paymentTermId: initialValues.paymentTermId,
});
- const [supplier, setSupplier] = useState<{
+ const [customer, setCustomer] = useState<{
id: string | undefined;
}>({
- id: initialValues.supplierId,
+ id: initialValues.customerId,
});
- const onSupplierChange = async (
+ const onCustomerChange = async (
newValue: {
value: string | undefined;
label: string;
} | null
) => {
- setSupplier({ id: newValue?.value });
- if (newValue?.value !== invoiceSupplier.id) {
- onInvoiceSupplierChange(newValue);
+ setCustomer({ id: newValue?.value });
+ if (newValue?.value !== invoiceCustomer.id) {
+ onInvoiceCustomerChange(newValue);
}
};
- const onInvoiceSupplierChange = async (
+ const onInvoiceCustomerChange = async (
newValue: {
value: string | undefined;
label: string;
@@ -86,50 +86,50 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
if (newValue?.value) {
flushSync(() => {
- // update the supplier immediately
- setInvoiceSupplier({
+ // update the customer immediately
+ setInvoiceCustomer({
id: newValue?.value,
currencyCode: undefined,
paymentTermId: undefined,
- invoiceSupplierContactId: undefined,
- invoiceSupplierLocationId: undefined,
+ invoiceCustomerContactId: undefined,
+ invoiceCustomerLocationId: undefined,
});
});
- const [supplierData, paymentTermData] = await Promise.all([
+ const [customerData, paymentTermData] = await Promise.all([
carbon
- ?.from("supplier")
+ ?.from("customer")
.select("currencyCode")
.eq("id", newValue.value)
.single(),
carbon
- ?.from("supplierPayment")
+ ?.from("customerPayment")
.select("*")
- .eq("supplierId", newValue.value)
+ .eq("customerId", newValue.value)
.single(),
]);
- if (supplierData.error || paymentTermData.error) {
- toast.error("Error fetching supplier data");
+ if (customerData.error || paymentTermData.error) {
+ toast.error("Error fetching customer data");
} else {
- setInvoiceSupplier((prev) => ({
+ setInvoiceCustomer((prev) => ({
...prev,
id: newValue.value,
- invoiceSupplierContactId:
- paymentTermData.data.invoiceSupplierContactId ?? undefined,
- invoiceSupplierLocationId:
- paymentTermData.data.invoiceSupplierLocationId ?? undefined,
- currencyCode: supplierData.data.currencyCode ?? undefined,
+ invoiceCustomerContactId:
+ paymentTermData.data.invoiceCustomerContactId ?? undefined,
+ invoiceCustomerLocationId:
+ paymentTermData.data.invoiceCustomerLocationId ?? undefined,
+ currencyCode: customerData.data.currencyCode ?? undefined,
paymentTermId: paymentTermData.data.paymentTermId ?? undefined,
}));
}
} else {
- setInvoiceSupplier({
+ setInvoiceCustomer({
id: undefined,
currencyCode: undefined,
paymentTermId: undefined,
- invoiceSupplierContactId: undefined,
- invoiceSupplierLocationId: undefined,
+ invoiceCustomerContactId: undefined,
+ invoiceCustomerLocationId: undefined,
});
}
};
@@ -137,18 +137,18 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
return (
<ValidatedForm
method="post"
- validator={purchaseInvoiceValidator}
+ validator={salesInvoiceValidator}
defaultValues={initialValues}
>
<Card>
<CardHeader>
<CardTitle>
- {isEditing ? "Purchase Invoice" : "New Purchase Invoice"}
+ {isEditing ? "Sales Invoice" : "New Sales Invoice"}
</CardTitle>
{!isEditing && (
<CardDescription>
- A purchase invoice is a document that specifies the products or
- services purchased by a customer and the corresponding cost.
+ A sales invoice is a document that specifies the products or
+ services sold to a customer and the corresponding cost.
</CardDescription>
)}
</CardHeader>
@@ -164,43 +164,43 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
: "grid-cols-1 md:grid-cols-2"
)}
>
- <Supplier
- name="supplierId"
- label="Supplier"
- onChange={onSupplierChange}
+ <Customer
+ name="customerId"
+ label="Customer"
+ onChange={onCustomerChange}
/>
- <Input name="supplierReference" label="Supplier Invoice Number" />
+ <Input name="customerReference" label="Customer Invoice Number" />
- <Supplier
- name="invoiceSupplierId"
- label="Invoice Supplier"
- value={invoiceSupplier.id}
- onChange={onInvoiceSupplierChange}
+ <Customer
+ name="invoiceCustomerId"
+ label="Invoice Customer"
+ value={invoiceCustomer.id}
+ onChange={onInvoiceCustomerChange}
/>
- <SupplierLocation
- name="invoiceSupplierLocationId"
- label="Invoice Supplier Location"
- supplier={supplier.id}
- value={invoiceSupplier.invoiceSupplierLocationId}
+ <CustomerLocation
+ name="invoiceCustomerLocationId"
+ label="Invoice Customer Location"
+ customer={customer.id}
+ value={invoiceCustomer.invoiceCustomerLocationId}
onChange={(newValue) => {
if (newValue?.id) {
- setInvoiceSupplier((prevSupplier) => ({
- ...prevSupplier,
- invoiceSupplierLocationId: newValue.id,
+ setInvoiceCustomer((prevCustomer) => ({
+ ...prevCustomer,
+ invoiceCustomerLocationId: newValue.id,
}));
}
}}
/>
- <SupplierContact
- name="invoiceSupplierContactId"
- label="Invoice Supplier Contact"
- supplier={supplier.id}
- value={invoiceSupplier.invoiceSupplierContactId}
+ <CustomerContact
+ name="invoiceCustomerContactId"
+ label="Invoice Customer Contact"
+ customer={customer.id}
+ value={invoiceCustomer.invoiceCustomerContactId}
onChange={(newValue) => {
if (newValue?.id) {
- setInvoiceSupplier((prevSupplier) => ({
- ...prevSupplier,
- invoiceSupplierContactId: newValue.id,
+ setInvoiceCustomer((prevCustomer) => ({
+ ...prevCustomer,
+ invoiceCustomerContactId: newValue.id,
}));
}
}}
@@ -212,11 +212,11 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
<PaymentTerm
name="paymentTermId"
label="Payment Terms"
- value={invoiceSupplier?.paymentTermId}
+ value={invoiceCustomer?.paymentTermId}
onChange={(newValue) => {
if (newValue?.value) {
- setInvoiceSupplier((prevSupplier) => ({
- ...prevSupplier,
+ setInvoiceCustomer((prevCustomer) => ({
+ ...prevCustomer,
paymentTermId: newValue.value,
}));
}
@@ -225,18 +225,18 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
<Currency
name="currencyCode"
label="Currency"
- value={invoiceSupplier?.currencyCode}
+ value={invoiceCustomer?.currencyCode}
onChange={(newValue) => {
if (newValue?.value) {
- setInvoiceSupplier((prevSupplier) => ({
- ...prevSupplier,
+ setInvoiceCustomer((prevCustomer) => ({
+ ...prevCustomer,
currencyCode: newValue.value,
}));
}
}}
/>
<Location name="locationId" label="Location" />
- <CustomFormFields table="purchaseInvoice" />
+ <CustomFormFields table="salesInvoice" />
</div>
</VStack>
</CardContent>
@@ -256,4 +256,4 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
);
};
-export default PurchaseInvoiceForm;
+export default SalesInvoiceForm;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
similarity index 59%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceHeader.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
index 2c65a0a0d0..ee03677511 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
@@ -22,18 +22,18 @@ import {
} from "react-icons/lu";
import { usePanels } from "~/components/Layout/Panels";
import { usePermissions, useRouteData } from "~/hooks";
-import type { PurchaseInvoice, PurchaseInvoiceLine } from "~/modules/invoicing";
-import { PurchaseInvoicingStatus } from "~/modules/invoicing";
+import type { SalesInvoice, SalesInvoiceLine } from "~/modules/invoicing";
import { path } from "~/utils/path";
-import PurchaseInvoicePostModal from "./PurchaseInvoicePostModal";
+import SalesInvoicePostModal from "./SalesInvoicePostModal";
+import SalesInvoiceStatus from "./SalesInvoiceStatus";
-const PurchaseInvoiceHeader = () => {
+const SalesInvoiceHeader = () => {
const permissions = usePermissions();
const { invoiceId } = useParams();
const postingModal = useDisclosure();
const { carbon } = useCarbon();
- const [linesNotAssociatedWithPO, setLinesNotAssociatedWithPO] = useState<
+ const [linesNotAssociatedWithSO, setLinesNotAssociatedWithSO] = useState<
{
itemId: string | null;
itemReadableId: string | null;
@@ -45,77 +45,77 @@ const PurchaseInvoiceHeader = () => {
if (!invoiceId) throw new Error("invoiceId not found");
const routeData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- purchaseInvoiceLines: PurchaseInvoiceLine[];
- }>(path.to.purchaseInvoice(invoiceId));
+ salesInvoice: SalesInvoice;
+ salesInvoiceLines: SalesInvoiceLine[];
+ }>(path.to.salesInvoice(invoiceId));
- if (!routeData?.purchaseInvoice) throw new Error("purchaseInvoice not found");
- const { purchaseInvoice } = routeData;
+ if (!routeData?.salesInvoice) throw new Error("salesInvoice not found");
+ const { salesInvoice } = routeData;
const { toggleExplorer, toggleProperties } = usePanels();
- const isPosted = purchaseInvoice.postingDate !== null;
+ const isPosted = salesInvoice.postingDate !== null;
const [relatedDocs, setRelatedDocs] = useState<{
- purchaseOrders: { id: string; readableId: string }[];
- receipts: { id: string; readableId: string }[];
- }>({ purchaseOrders: [], receipts: [] });
+ salesOrders: { id: string; readableId: string }[];
+ shipments: { id: string; readableId: string }[];
+ }>({ salesOrders: [], shipments: [] });
// Load related documents on mount
useEffect(() => {
async function loadRelatedDocs() {
- if (!carbon || !purchaseInvoice.supplierInteractionId) return;
+ if (!carbon || !salesInvoice.opportunityId) return;
- const [purchaseOrdersResult, receiptsResult] = await Promise.all([
+ const [salesOrdersResult, shipmentsResult] = await Promise.all([
carbon
- .from("purchaseOrder")
- .select("id, purchaseOrderId")
- .eq("supplierInteractionId", purchaseInvoice.supplierInteractionId),
+ .from("salesOrder")
+ .select("id, salesOrderId")
+ .eq("opportunityId", salesInvoice.opportunityId),
carbon
- .from("receipt")
- .select("id, receiptId")
- .eq("supplierInteractionId", purchaseInvoice.supplierInteractionId),
+ .from("shipment")
+ .select("id, shipmentId")
+ .eq("opportunityId", salesInvoice.opportunityId),
]);
- if (purchaseOrdersResult.error)
- throw new Error(purchaseOrdersResult.error.message);
- if (receiptsResult.error) throw new Error(receiptsResult.error.message);
+ if (salesOrdersResult.error)
+ throw new Error(salesOrdersResult.error.message);
+ if (shipmentsResult.error) throw new Error(shipmentsResult.error.message);
setRelatedDocs({
- purchaseOrders:
- purchaseOrdersResult.data?.map((po) => ({
+ salesOrders:
+ salesOrdersResult.data?.map((po) => ({
id: po.id,
- readableId: po.purchaseOrderId,
+ readableId: po.salesOrderId,
})) ?? [],
- receipts:
- receiptsResult.data?.map((r) => ({
+ shipments:
+ shipmentsResult.data?.map((r) => ({
id: r.id,
- readableId: r.receiptId,
+ readableId: r.shipmentId,
})) ?? [],
});
}
loadRelatedDocs();
- }, [carbon, purchaseInvoice.supplierInteractionId]);
+ }, [carbon, salesInvoice.opportunityId]);
const showPostModal = async () => {
// check if there are any lines that are not associated with a PO
if (!carbon) throw new Error("carbon not found");
const { data, error } = await carbon
- .from("purchaseInvoiceLine")
- .select("itemId, itemReadableId, description, quantity, conversionFactor")
+ .from("salesInvoiceLine")
+ .select("itemId, itemReadableId, description, quantity")
.eq("invoiceId", invoiceId)
.in("invoiceLineType", ["Part", "Material", "Tool", "Consumable"])
- .is("purchaseOrderLineId", null);
+ .is("salesOrderLineId", null);
if (error) throw new Error(error.message);
if (!data) return;
// so that we can ask the user if they want to receive those lines
flushSync(() =>
- setLinesNotAssociatedWithPO(
+ setLinesNotAssociatedWithSO(
data?.map((d) => ({
...d,
description: d.description ?? "",
- quantity: d.quantity * (d.conversionFactor ?? 1),
+ quantity: d.quantity,
})) ?? []
)
);
@@ -133,47 +133,43 @@ const PurchaseInvoiceHeader = () => {
onClick={toggleExplorer}
variant="ghost"
/>
- <Link to={path.to.purchaseInvoiceDetails(invoiceId)}>
+ <Link to={path.to.salesInvoiceDetails(invoiceId)}>
<Heading size="h4" className="flex items-center gap-2">
- <span>{routeData?.purchaseInvoice?.invoiceId}</span>
+ <span>{routeData?.salesInvoice?.invoiceId}</span>
</Heading>
</Link>
- <PurchaseInvoicingStatus
- status={routeData?.purchaseInvoice?.status}
- />
+ <SalesInvoiceStatus status={routeData?.salesInvoice?.status} />
</HStack>
<HStack>
- {relatedDocs.purchaseOrders.length === 1 && (
+ {relatedDocs.salesOrders.length === 1 && (
<Button variant="secondary" leftIcon={<LuShoppingCart />} asChild>
<Link
- to={path.to.purchaseOrderDetails(
- relatedDocs.purchaseOrders[0].id
- )}
+ to={path.to.salesOrderDetails(relatedDocs.salesOrders[0].id)}
>
- Purchase Order
+ Sales Order
</Link>
</Button>
)}
- {relatedDocs.receipts.length === 1 && (
+ {relatedDocs.shipments.length === 1 && (
<Button variant="secondary" leftIcon={<LuHandCoins />} asChild>
- <Link to={path.to.receipt(relatedDocs.receipts[0].id)}>
- Receipt
+ <Link to={path.to.shipment(relatedDocs.shipments[0].id)}>
+ Shipment
</Link>
</Button>
)}
- {relatedDocs.purchaseOrders.length > 1 && (
+ {relatedDocs.salesOrders.length > 1 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" leftIcon={<LuShoppingCart />}>
- Purchase Orders
+ Sales Orders
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
- {relatedDocs.purchaseOrders.map((po) => (
+ {relatedDocs.salesOrders.map((po) => (
<DropdownMenuItem key={po.id} asChild>
- <Link to={path.to.purchaseOrderDetails(po.id)}>
+ <Link to={path.to.salesOrderDetails(po.id)}>
{po.readableId}
</Link>
</DropdownMenuItem>
@@ -182,18 +178,18 @@ const PurchaseInvoiceHeader = () => {
</DropdownMenu>
)}
- {relatedDocs.receipts.length > 1 && (
+ {relatedDocs.shipments.length > 1 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" leftIcon={<LuHandCoins />}>
- Receipts
+ Shipments
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
- {relatedDocs.receipts.map((receipt) => (
- <DropdownMenuItem key={receipt.id} asChild>
- <Link to={path.to.receipt(receipt.id)}>
- {receipt.readableId}
+ {relatedDocs.shipments.map((shipment) => (
+ <DropdownMenuItem key={shipment.id} asChild>
+ <Link to={path.to.shipment(shipment.id)}>
+ {shipment.readableId}
</Link>
</DropdownMenuItem>
))}
@@ -203,14 +199,14 @@ const PurchaseInvoiceHeader = () => {
<Button
leftIcon={<LuCheckCheck />}
variant={
- routeData?.purchaseInvoice?.status === "Draft"
+ routeData?.salesInvoice?.status === "Draft"
? "primary"
: "secondary"
}
onClick={showPostModal}
isDisabled={
isPosted ||
- routeData?.purchaseInvoiceLines?.length === 0 ||
+ routeData?.salesInvoiceLines?.length === 0 ||
!permissions.can("update", "invoicing")
}
>
@@ -228,15 +224,15 @@ const PurchaseInvoiceHeader = () => {
</div>
{postingModal.isOpen && (
- <PurchaseInvoicePostModal
+ <SalesInvoicePostModal
invoiceId={invoiceId}
isOpen={postingModal.isOpen}
onClose={postingModal.onClose}
- linesToReceive={linesNotAssociatedWithPO}
+ linesToShip={linesNotAssociatedWithSO}
/>
)}
</>
);
};
-export default PurchaseInvoiceHeader;
+export default SalesInvoiceHeader;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
similarity index 67%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceLineForm.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
index 258ee57a88..1b7394b68b 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
@@ -20,35 +20,34 @@ import { useParams } from "@remix-run/react";
import { useEffect, useState } from "react";
import type { z } from "zod";
import {
- ConversionFactor,
CustomFormFields,
Hidden,
Item,
Location,
+ Number,
NumberControlled,
Shelf,
Submit,
- UnitOfMeasure,
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import type { PurchaseInvoice } from "~/modules/invoicing";
-import { purchaseInvoiceLineValidator } from "~/modules/invoicing";
+import type { SalesInvoice } from "~/modules/invoicing";
+import { salesInvoiceLineValidator } from "~/modules/invoicing";
import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
-type PurchaseInvoiceLineFormProps = {
- initialValues: z.infer<typeof purchaseInvoiceLineValidator> & {
+type SalesInvoiceLineFormProps = {
+ initialValues: z.infer<typeof salesInvoiceLineValidator> & {
taxPercent?: number;
};
type?: "card" | "modal";
onClose?: () => void;
};
-const PurchaseInvoiceLineForm = ({
+const SalesInvoiceLineForm = ({
initialValues,
type,
onClose,
-}: PurchaseInvoiceLineFormProps) => {
+}: SalesInvoiceLineFormProps) => {
const permissions = usePermissions();
const { carbon } = useCarbon();
@@ -58,12 +57,10 @@ const PurchaseInvoiceLineForm = ({
if (!invoiceId) throw new Error("invoiceId not found");
const routeData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- }>(path.to.purchaseInvoice(invoiceId));
+ salesInvoice: SalesInvoice;
+ }>(path.to.salesInvoice(invoiceId));
- const isEditable = ["Draft"].includes(
- routeData?.purchaseInvoice?.status ?? ""
- );
+ const isEditable = ["Draft"].includes(routeData?.salesInvoice?.status ?? "");
const [itemType, setItemType] = useState<MethodItemType>(
initialValues.invoiceLineType as MethodItemType
@@ -74,13 +71,10 @@ const PurchaseInvoiceLineForm = ({
itemReadableId: string;
description: string;
quantity: number;
- supplierUnitPrice: number;
- supplierShippingCost: number;
- purchaseUom: string;
- inventoryUom: string;
- conversionFactor: number;
+ unitPrice: number;
+ shippingCost: number;
+ unitOfMeasureCode: string;
shelfId: string | null;
- minimumOrderQuantity?: number;
taxAmount: number;
taxPercent: number;
}>({
@@ -88,22 +82,21 @@ const PurchaseInvoiceLineForm = ({
itemReadableId: initialValues.itemReadableId ?? "",
description: initialValues.description ?? "",
quantity: initialValues.quantity ?? 1,
- supplierUnitPrice: initialValues.supplierUnitPrice ?? 0,
- supplierShippingCost: initialValues.supplierShippingCost ?? 0,
- purchaseUom: initialValues.purchaseUnitOfMeasureCode ?? "",
- inventoryUom: initialValues.inventoryUnitOfMeasureCode ?? "",
- conversionFactor: initialValues.conversionFactor ?? 1,
+ unitPrice: initialValues.unitPrice ?? 0,
+ shippingCost: initialValues.shippingCost ?? 0,
+ unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "",
shelfId: initialValues.shelfId ?? "",
- minimumOrderQuantity: undefined,
- taxAmount: initialValues.supplierTaxAmount ?? 0,
+ taxAmount:
+ ((initialValues.unitPrice ?? 0) * (initialValues.quantity ?? 1) +
+ (initialValues.shippingCost ?? 0)) *
+ (initialValues.taxPercent ?? 0),
taxPercent: initialValues.taxPercent ?? 0,
});
// update tax amount when quantity or unit price changes
useEffect(() => {
const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
+ itemData.unitPrice * itemData.quantity + itemData.shippingCost;
if (itemData.taxPercent !== 0) {
setItemData((d) => ({
...d,
@@ -111,9 +104,9 @@ const PurchaseInvoiceLineForm = ({
}));
}
}, [
- itemData.supplierUnitPrice,
+ itemData.unitPrice,
itemData.quantity,
- itemData.supplierShippingCost,
+ itemData.shippingCost,
itemData.taxPercent,
]);
@@ -132,13 +125,10 @@ const PurchaseInvoiceLineForm = ({
itemReadableId: "",
description: "",
quantity: 1,
- supplierUnitPrice: 0,
- supplierShippingCost: 0,
- inventoryUom: "",
- purchaseUom: "",
- conversionFactor: 1,
+ unitPrice: 0,
+ shippingCost: 0,
+ unitOfMeasureCode: "",
shelfId: "",
- minimumOrderQuantity: undefined,
taxAmount: 0,
taxPercent: 0,
});
@@ -153,22 +143,15 @@ const PurchaseInvoiceLineForm = ({
case "Material":
case "Part":
case "Tool":
- const [item, supplierPart, inventory] = await Promise.all([
+ const [item, inventory] = await Promise.all([
carbon
.from("item")
.select(
- "name, readableId, type, unitOfMeasureCode, itemCost(unitCost), itemReplenishment(purchasingUnitOfMeasureCode, conversionFactor, purchasingLeadTime)"
+ "name, readableId, type, unitOfMeasureCode, itemCost(unitCost)"
)
.eq("id", itemId)
.eq("companyId", company.id)
.single(),
- carbon
- .from("supplierPart")
- .select("*")
- .eq("itemId", itemId)
- .eq("companyId", company.id)
- .eq("supplierId", routeData?.purchaseInvoice.supplierId!)
- .maybeSingle(),
carbon
.from("pickMethod")
.select("defaultShelfId")
@@ -179,31 +162,21 @@ const PurchaseInvoiceLineForm = ({
]);
const itemCost = item?.data?.itemCost?.[0];
- const itemReplenishment = item?.data?.itemReplenishment;
- setItemData({
+ setItemData((prev) => ({
+ ...prev,
itemId: itemId,
itemReadableId: item.data?.readableId ?? "",
description: item.data?.name ?? "",
- quantity: supplierPart?.data?.minimumOrderQuantity ?? 1,
- supplierUnitPrice:
- (supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0) /
- (routeData?.purchaseInvoice?.exchangeRate ?? 1),
- supplierShippingCost: 0,
- purchaseUom:
- supplierPart?.data?.supplierUnitOfMeasureCode ??
- itemReplenishment?.purchasingUnitOfMeasureCode ??
- item.data?.unitOfMeasureCode ??
- "EA",
- inventoryUom: item.data?.unitOfMeasureCode ?? "EA",
- conversionFactor:
- supplierPart?.data?.conversionFactor ??
- itemReplenishment?.conversionFactor ??
- 1,
+ unitPrice:
+ (itemCost?.unitCost ?? 0) /
+ (routeData?.salesInvoice?.exchangeRate ?? 1),
+ shippingCost: 0,
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
shelfId: inventory.data?.defaultShelfId ?? null,
taxAmount: 0,
taxPercent: 0,
- });
+ }));
if (item.data?.type) {
setItemType(item.data.type as MethodItemType);
@@ -244,12 +217,12 @@ const PurchaseInvoiceLineForm = ({
<ModalCardContent size="xxlarge">
<ValidatedForm
defaultValues={initialValues}
- validator={purchaseInvoiceLineValidator}
+ validator={salesInvoiceLineValidator}
method="post"
action={
isEditing
- ? path.to.purchaseInvoiceLine(invoiceId, initialValues.id!)
- : path.to.newPurchaseInvoiceLine(invoiceId)
+ ? path.to.salesInvoiceLine(invoiceId, initialValues.id!)
+ : path.to.newSalesInvoiceLine(invoiceId)
}
className="w-full"
onSubmit={() => {
@@ -266,12 +239,12 @@ const PurchaseInvoiceLineForm = ({
>
{isEditing
? itemData?.itemReadableId || "..."
- : "New Purchase Invoice Line"}
+ : "New Sales Invoice Line"}
</ModalCardTitle>
<ModalCardDescription>
{isEditing
? itemData?.description || itemType
- : "A purchase invoice line contains invoice details for a particular item"}
+ : "A sales invoice line contains invoice details for a particular item"}
</ModalCardDescription>
</ModalCardHeader>
<ModalCardBody>
@@ -282,11 +255,11 @@ const PurchaseInvoiceLineForm = ({
<Hidden name="description" value={itemData.description} />
<Hidden
name="exchangeRate"
- value={routeData?.purchaseInvoice?.exchangeRate ?? 1}
+ value={routeData?.salesInvoice?.exchangeRate ?? 1}
/>
<Hidden
- name="inventoryUnitOfMeasureCode"
- value={itemData?.inventoryUom}
+ name="unitOfMeasureCode"
+ value={itemData?.unitOfMeasureCode}
/>
<VStack>
@@ -296,7 +269,6 @@ const PurchaseInvoiceLineForm = ({
label={itemType}
// @ts-ignore
type={itemType}
- replenishmentSystem="Buy"
onChange={(value) => {
onItemChange(value?.value as string);
}}
@@ -321,7 +293,7 @@ const PurchaseInvoiceLineForm = ({
) && (
<>
<NumberControlled
- minValue={itemData.minimumOrderQuantity}
+ minValue={itemData.quantity}
name="quantity"
label="Quantity"
value={itemData.quantity}
@@ -333,82 +305,58 @@ const PurchaseInvoiceLineForm = ({
}}
/>
- <UnitOfMeasure
- name="purchaseUnitOfMeasureCode"
- label="Unit of Measure"
- value={itemData.purchaseUom}
- onChange={(newValue) => {
- if (newValue) {
- setItemData((d) => ({
- ...d,
- purchaseUom: newValue?.value as string,
- }));
- }
- }}
- />
- <ConversionFactor
- name="conversionFactor"
- purchasingCode={itemData.purchaseUom}
- inventoryCode={itemData.inventoryUom}
- value={itemData.conversionFactor}
- onChange={(value) => {
- setItemData((d) => ({
- ...d,
- conversionFactor: value,
- }));
- }}
- />
-
<NumberControlled
- name="supplierUnitPrice"
- label="Supplier Unit Price"
- value={itemData.supplierUnitPrice}
+ name="unitPrice"
+ label="Unit Price"
+ value={itemData.unitPrice}
formatOptions={{
style: "currency",
currency:
- routeData?.purchaseInvoice?.currencyCode ??
+ routeData?.salesInvoice?.currencyCode ??
company.baseCurrencyCode,
}}
onChange={(value) =>
setItemData((d) => ({
...d,
- supplierUnitPrice: value,
+ unitPrice: value,
}))
}
/>
<NumberControlled
- name="supplierShippingCost"
+ name="shippingCost"
label="Shipping"
- value={itemData.supplierShippingCost}
+ value={itemData.shippingCost}
minValue={0}
formatOptions={{
style: "currency",
currency:
- routeData?.purchaseInvoice?.currencyCode ??
+ routeData?.salesInvoice?.currencyCode ??
company.baseCurrencyCode,
}}
onChange={(value) =>
setItemData((d) => ({
...d,
- supplierShippingCost: value,
+ shippingCost: value,
}))
}
/>
+ <Number name="addOnCost" label="Add On Cost" />
+
<NumberControlled
- name="supplierTaxAmount"
+ name="taxAmount"
label="Tax"
value={itemData.taxAmount}
formatOptions={{
style: "currency",
currency:
- routeData?.purchaseInvoice?.currencyCode ??
+ routeData?.salesInvoice?.currencyCode ??
company.baseCurrencyCode,
}}
onChange={(value) => {
const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
+ itemData.unitPrice * itemData.quantity +
+ itemData.shippingCost;
setItemData((d) => ({
...d,
taxAmount: value,
@@ -453,8 +401,8 @@ const PurchaseInvoiceLineForm = ({
}}
onChange={(value) => {
const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
+ itemData.unitPrice * itemData.quantity +
+ itemData.shippingCost;
setItemData((d) => ({
...d,
taxPercent: value,
@@ -462,7 +410,7 @@ const PurchaseInvoiceLineForm = ({
}));
}}
/>
- <CustomFormFields table="purchaseInvoiceLine" />
+ <CustomFormFields table="salesInvoiceLine" />
</div>
</VStack>
</ModalCardBody>
@@ -478,4 +426,4 @@ const PurchaseInvoiceLineForm = ({
);
};
-export default PurchaseInvoiceLineForm;
+export default SalesInvoiceLineForm;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
similarity index 79%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoicePostModal.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
index 5d98b97d99..3271c54299 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoicePostModal.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx
@@ -17,14 +17,14 @@ import {
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
-import type { action } from "~/routes/x+/purchase-invoice+/$invoiceId.post";
+import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";
import { path } from "~/utils/path";
-type PurchaseInvoicePostModalProps = {
+type SalesInvoicePostModalProps = {
isOpen: boolean;
onClose: () => void;
invoiceId: string;
- linesToReceive: {
+ linesToShip: {
itemId: string | null;
itemReadableId: string | null;
description: string | null;
@@ -32,13 +32,13 @@ type PurchaseInvoicePostModalProps = {
}[];
};
-const PurchaseInvoicePostModal = ({
+const SalesInvoicePostModal = ({
isOpen,
onClose,
invoiceId,
- linesToReceive,
-}: PurchaseInvoicePostModalProps) => {
- const hasLinesToReceive = linesToReceive.length > 0;
+ linesToShip,
+}: SalesInvoicePostModalProps) => {
+ const hasLinesToShip = linesToShip.length > 0;
const fetcher = useFetcher<typeof action>();
return (
@@ -53,10 +53,10 @@ const PurchaseInvoicePostModal = ({
<ModalTitle>Post Invoice</ModalTitle>
</ModalHeader>
<ModalBody>
- {hasLinesToReceive ? (
+ {hasLinesToShip ? (
<div className="gap-4 w-full flex flex-col">
<p>
- Are you sure you want to post this invoice? A receipt will be
+ Are you sure you want to post this invoice? A shipment will be
automatically created and posted for:
</p>
<Table>
@@ -67,7 +67,7 @@ const PurchaseInvoicePostModal = ({
</Tr>
</Thead>
<Tbody>
- {linesToReceive.map((line) => (
+ {linesToShip.map((line) => (
<Tr key={line.itemId} className="text-sm">
<Td>
<VStack spacing={0}>
@@ -91,7 +91,7 @@ const PurchaseInvoicePostModal = ({
</ModalBody>
<ModalFooter>
<HStack>
- <Button variant="solid" onClick={onClose}>
+ <Button variant="secondary" onClick={onClose}>
Cancel
</Button>
<fetcher.Form
@@ -103,9 +103,7 @@ const PurchaseInvoicePostModal = ({
isLoading={fetcher.state !== "idle"}
type="submit"
>
- {hasLinesToReceive
- ? "Post and Receive Invoice"
- : "Post Invoice"}
+ {hasLinesToShip ? "Post and Ship Invoice" : "Post Invoice"}
</Button>
</fetcher.Form>
</HStack>
@@ -115,4 +113,4 @@ const PurchaseInvoicePostModal = ({
);
};
-export default PurchaseInvoicePostModal;
+export default SalesInvoicePostModal;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
similarity index 69%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceProperties.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
index 3c5d24960b..4879a34d25 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceProperties.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx
@@ -19,27 +19,27 @@ import { zfd } from "zod-form-data";
import { Assignee, useOptimisticAssignment } from "~/components";
import {
Currency,
+ Customer,
+ CustomerContact,
+ CustomerLocation,
Location,
PaymentTerm,
- Supplier,
- SupplierContact,
- SupplierLocation,
} from "~/components/Form";
import CustomFormInlineFields from "~/components/Form/CustomFormInlineFields";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import type { action as exchangeRateAction } from "~/routes/x+/purchase-invoice+/$invoiceId.exchange-rate";
-import type { action } from "~/routes/x+/purchase-invoice+/update";
+import type { action as exchangeRateAction } from "~/routes/x+/sales-invoice+/$invoiceId.exchange-rate";
+import type { action } from "~/routes/x+/sales-invoice+/update";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
-import type { PurchaseInvoice } from "../../types";
+import type { SalesInvoice } from "../../types";
-const PurchaseInvoiceProperties = () => {
+const SalesInvoiceProperties = () => {
const { invoiceId } = useParams();
if (!invoiceId) throw new Error("invoiceId not found");
const routeData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- }>(path.to.purchaseInvoice(invoiceId));
+ salesInvoice: SalesInvoice;
+ }>(path.to.salesInvoice(invoiceId));
const fetcher = useFetcher<typeof action>();
useEffect(() => {
@@ -61,8 +61,8 @@ const PurchaseInvoiceProperties = () => {
);
const onUpdate = useCallback(
- (field: keyof PurchaseInvoice, value: string | null) => {
- if (value === routeData?.purchaseInvoice[field]) {
+ (field: keyof SalesInvoice, value: string | null) => {
+ if (value === routeData?.salesInvoice[field]) {
return;
}
const formData = new FormData();
@@ -72,11 +72,11 @@ const PurchaseInvoiceProperties = () => {
formData.append("value", value ?? "");
fetcher.submit(formData, {
method: "post",
- action: path.to.bulkUpdatePurchaseInvoice,
+ action: path.to.bulkUpdateSalesInvoice,
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
- [invoiceId, routeData?.purchaseInvoice]
+ [invoiceId, routeData?.salesInvoice]
);
const onUpdateCustomFields = useCallback(
@@ -84,7 +84,7 @@ const PurchaseInvoiceProperties = () => {
const formData = new FormData();
formData.append("ids", invoiceId);
- formData.append("table", "purchaseInvoice");
+ formData.append("table", "salesInvoice");
formData.append("value", value);
fetcher.submit(formData, {
@@ -99,17 +99,17 @@ const PurchaseInvoiceProperties = () => {
const permissions = usePermissions();
const optimisticAssignment = useOptimisticAssignment({
id: invoiceId,
- table: "purchaseInvoice",
+ table: "salesInvoice",
});
const assignee =
optimisticAssignment !== undefined
? optimisticAssignment
- : routeData?.purchaseInvoice?.assignee;
+ : routeData?.salesInvoice?.assignee;
const isDisabled =
- !permissions.can("update", "purchasing") ||
+ !permissions.can("update", "invoicing") ||
!["Draft", "To Review", "Overdue"].includes(
- routeData?.purchaseInvoice?.status ?? ""
+ routeData?.salesInvoice?.status ?? ""
);
return (
@@ -131,7 +131,7 @@ const PurchaseInvoiceProperties = () => {
onClick={() =>
copyToClipboard(
window.location.origin +
- path.to.purchaseInvoiceDetails(invoiceId)
+ path.to.salesInvoiceDetails(invoiceId)
)
}
>
@@ -139,7 +139,7 @@ const PurchaseInvoiceProperties = () => {
</Button>
</TooltipTrigger>
<TooltipContent>
- <span>Copy link to Purchase Invoice</span>
+ <span>Copy link to Sales Invoice</span>
</TooltipContent>
</Tooltip>
<Tooltip>
@@ -150,43 +150,43 @@ const PurchaseInvoiceProperties = () => {
size="sm"
className="p-1"
onClick={() =>
- copyToClipboard(routeData?.purchaseInvoice?.invoiceId ?? "")
+ copyToClipboard(routeData?.salesInvoice?.invoiceId ?? "")
}
>
<LuCopy className="w-3 h-3" />
</Button>
</TooltipTrigger>
<TooltipContent>
- <span>Copy Purchase Invoice number</span>
+ <span>Copy Sales Invoice number</span>
</TooltipContent>
</Tooltip>
</HStack>
</HStack>
- <span className="text-sm">{routeData?.purchaseInvoice?.invoiceId}</span>
+ <span className="text-sm">{routeData?.salesInvoice?.invoiceId}</span>
</VStack>
<Assignee
id={invoiceId}
- table="purchaseInvoice"
+ table="salesInvoice"
value={assignee ?? ""}
variant="inline"
- isReadOnly={!permissions.can("update", "purchasing")}
+ isReadOnly={!permissions.can("update", "invoicing")}
/>
<ValidatedForm
- defaultValues={{ supplierId: routeData?.purchaseInvoice?.supplierId }}
+ defaultValues={{ customerId: routeData?.salesInvoice?.customerId }}
validator={z.object({
- supplierId: z.string().min(1, { message: "Supplier is required" }),
+ customerId: z.string().min(1, { message: "Customer is required" }),
})}
className="w-full"
>
- <Supplier
- name="supplierId"
+ <Customer
+ name="customerId"
inline
isReadOnly={isDisabled}
onChange={(value) => {
if (value?.value) {
- onUpdate("supplierId", value.value);
+ onUpdate("customerId", value.value);
}
}}
/>
@@ -194,68 +194,68 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- supplierReference:
- routeData?.purchaseInvoice?.supplierReference ?? undefined,
+ customerReference:
+ routeData?.salesInvoice?.customerReference ?? undefined,
}}
validator={z.object({
- supplierReference: zfd.text(z.string().optional()),
+ customerReference: zfd.text(z.string().optional()),
})}
className="w-full"
>
<InputControlled
- name="supplierReference"
- label="Supplier Ref. Number"
- value={routeData?.purchaseInvoice?.supplierReference ?? ""}
+ name="customerReference"
+ label="Customer Ref. Number"
+ value={routeData?.salesInvoice?.customerReference ?? ""}
size="sm"
inline
isReadOnly={isDisabled}
onBlur={(e) => {
- onUpdate("supplierReference", e.target.value);
+ onUpdate("customerReference", e.target.value);
}}
/>
</ValidatedForm>
<ValidatedForm
defaultValues={{
- invoiceSupplierId: routeData?.purchaseInvoice?.invoiceSupplierId,
+ invoiceCustomerId: routeData?.salesInvoice?.invoiceCustomerId,
}}
validator={z.object({
- invoiceSupplierId: z
+ invoiceCustomerId: z
.string()
- .min(1, { message: "Supplier is required" }),
+ .min(1, { message: "Customer is required" }),
})}
className="w-full"
>
- <Supplier
- name="invoiceSupplierId"
- label="Invoice Supplier"
+ <Customer
+ name="invoiceCustomerId"
+ label="Invoice Customer"
inline
isReadOnly={isDisabled}
onChange={(value) => {
if (value?.value) {
- onUpdate("invoiceSupplierId", value.value);
+ onUpdate("invoiceCustomerId", value.value);
}
}}
/>
</ValidatedForm>
<ValidatedForm
defaultValues={{
- invoiceSupplierLocationId:
- routeData?.purchaseInvoice?.invoiceSupplierLocationId ?? "",
+ invoiceCustomerLocationId:
+ routeData?.salesInvoice?.invoiceCustomerLocationId ?? "",
}}
validator={z.object({
- invoiceSupplierLocationId: zfd.text(z.string().optional()),
+ invoiceCustomerLocationId: zfd.text(z.string().optional()),
})}
className="w-full"
>
- <SupplierLocation
- name="invoiceSupplierLocationId"
- label="Invoice Supplier Location"
- supplier={routeData?.purchaseInvoice?.invoiceSupplierId ?? ""}
+ <CustomerLocation
+ name="invoiceCustomerLocationId"
+ label="Invoice Customer Location"
+ customer={routeData?.salesInvoice?.invoiceCustomerId ?? ""}
inline
isReadOnly={isDisabled}
- onChange={(supplierLocation) => {
- if (supplierLocation?.id) {
- onUpdate("invoiceSupplierLocationId", supplierLocation.id);
+ onChange={(customerLocation) => {
+ if (customerLocation?.id) {
+ onUpdate("invoiceCustomerLocationId", customerLocation.id);
}
}}
/>
@@ -263,23 +263,23 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- invoiceSupplierContactId:
- routeData?.purchaseInvoice?.invoiceSupplierContactId ?? "",
+ invoiceCustomerContactId:
+ routeData?.salesInvoice?.invoiceCustomerContactId ?? "",
}}
validator={z.object({
- invoiceSupplierContactId: zfd.text(z.string().optional()),
+ invoiceCustomerContactId: zfd.text(z.string().optional()),
})}
className="w-full"
>
- <SupplierContact
- name="invoiceSupplierContactId"
- label="Invoice Supplier Contact"
- supplier={routeData?.purchaseInvoice?.invoiceSupplierId ?? ""}
+ <CustomerContact
+ name="invoiceCustomerContactId"
+ label="Invoice Customer Contact"
+ customer={routeData?.salesInvoice?.invoiceCustomerId ?? ""}
inline
isReadOnly={isDisabled}
- onChange={(supplierContact) => {
- if (supplierContact?.id) {
- onUpdate("invoiceSupplierContactId", supplierContact.id);
+ onChange={(customerContact) => {
+ if (customerContact?.id) {
+ onUpdate("invoiceCustomerContactId", customerContact.id);
}
}}
/>
@@ -287,7 +287,7 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- dateIssued: routeData?.purchaseInvoice?.dateIssued ?? "",
+ dateIssued: routeData?.salesInvoice?.dateIssued ?? "",
}}
validator={z.object({
dateIssued: z
@@ -309,7 +309,7 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- dateDue: routeData?.purchaseInvoice?.dateDue ?? "",
+ dateDue: routeData?.salesInvoice?.dateDue ?? "",
}}
validator={z.object({
dateDue: zfd.text(z.string().optional()),
@@ -329,7 +329,7 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- datePaid: routeData?.purchaseInvoice?.datePaid ?? "",
+ datePaid: routeData?.salesInvoice?.datePaid ?? "",
}}
validator={z.object({
datePaid: zfd.text(z.string().optional()),
@@ -347,7 +347,7 @@ const PurchaseInvoiceProperties = () => {
</ValidatedForm>
<ValidatedForm
- defaultValues={{ locationId: routeData?.purchaseInvoice?.locationId }}
+ defaultValues={{ locationId: routeData?.salesInvoice?.locationId }}
validator={z.object({
locationId: z.string().min(1, { message: "Location is required" }),
})}
@@ -368,7 +368,7 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- paymentTermId: routeData?.purchaseInvoice?.paymentTermId,
+ paymentTermId: routeData?.salesInvoice?.paymentTermId,
}}
validator={z.object({
paymentTermId: z
@@ -392,7 +392,7 @@ const PurchaseInvoiceProperties = () => {
<ValidatedForm
defaultValues={{
- currencyCode: routeData?.purchaseInvoice?.currencyCode ?? undefined,
+ currencyCode: routeData?.salesInvoice?.currencyCode ?? undefined,
}}
validator={z.object({
currencyCode: zfd.text(z.string().optional()),
@@ -403,7 +403,7 @@ const PurchaseInvoiceProperties = () => {
name="currencyCode"
label="Currency"
inline
- value={routeData?.purchaseInvoice?.currencyCode ?? ""}
+ value={routeData?.salesInvoice?.currencyCode ?? ""}
isReadOnly={isDisabled}
onChange={(value) => {
if (value?.value) {
@@ -413,15 +413,14 @@ const PurchaseInvoiceProperties = () => {
/>
</ValidatedForm>
- {routeData?.purchaseInvoice?.currencyCode &&
- routeData?.purchaseInvoice?.currencyCode !==
- company.baseCurrencyCode && (
+ {routeData?.salesInvoice?.currencyCode &&
+ routeData?.salesInvoice?.currencyCode !== company.baseCurrencyCode && (
<VStack spacing={2}>
<HStack spacing={1}>
<span className="text-xs text-muted-foreground">
Exchange Rate
</span>
- {routeData?.purchaseInvoice?.exchangeRateUpdatedAt && (
+ {routeData?.salesInvoice?.exchangeRateUpdatedAt && (
<Tooltip>
<TooltipTrigger tabIndex={-1}>
<LuInfo className="w-4 h-4" />
@@ -430,7 +429,7 @@ const PurchaseInvoiceProperties = () => {
Last updated:{" "}
{formatter.format(
new Date(
- routeData?.purchaseInvoice?.exchangeRateUpdatedAt ?? ""
+ routeData?.salesInvoice?.exchangeRateUpdatedAt ?? ""
)
)}
</TooltipContent>
@@ -438,7 +437,7 @@ const PurchaseInvoiceProperties = () => {
)}
</HStack>
<HStack className="w-full justify-between">
- <span>{routeData?.purchaseInvoice?.exchangeRate}</span>
+ <span>{routeData?.salesInvoice?.exchangeRate}</span>
<IconButton
size="sm"
variant="secondary"
@@ -449,11 +448,11 @@ const PurchaseInvoiceProperties = () => {
const formData = new FormData();
formData.append(
"currencyCode",
- routeData?.purchaseInvoice?.currencyCode ?? ""
+ routeData?.salesInvoice?.currencyCode ?? ""
);
exchangeRateFetcher.submit(formData, {
method: "post",
- action: path.to.purchaseInvoiceExchangeRate(invoiceId),
+ action: path.to.salesInvoiceExchangeRate(invoiceId),
});
}}
/>
@@ -462,12 +461,9 @@ const PurchaseInvoiceProperties = () => {
)}
<CustomFormInlineFields
customFields={
- (routeData?.purchaseInvoice?.customFields ?? {}) as Record<
- string,
- Json
- >
+ (routeData?.salesInvoice?.customFields ?? {}) as Record<string, Json>
}
- table="purchaseInvoice"
+ table="salesInvoice"
tags={[]}
onUpdate={onUpdateCustomFields}
isDisabled={isDisabled}
@@ -476,4 +472,4 @@ const PurchaseInvoiceProperties = () => {
);
};
-export default PurchaseInvoiceProperties;
+export default SalesInvoiceProperties;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceDeliveryForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
similarity index 72%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceDeliveryForm.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
index 1d6e1e97c9..3e909be60b 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceDeliveryForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
@@ -18,24 +18,24 @@ import {
Submit,
} from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
-import type { PurchaseInvoice } from "~/modules/invoicing";
-import { purchaseInvoiceDeliveryValidator } from "~/modules/invoicing";
-import type { action } from "~/routes/x+/purchase-invoice+/$invoiceId.delivery";
+import type { SalesInvoice } from "~/modules/invoicing";
+import { salesInvoiceShipmentValidator } from "~/modules/invoicing";
+import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.shipment";
import { path } from "~/utils/path";
-type PurchaseInvoiceDeliveryFormProps = {
- initialValues: z.infer<typeof purchaseInvoiceDeliveryValidator>;
+type SalesInvoiceShipmentFormProps = {
+ initialValues: z.infer<typeof salesInvoiceShipmentValidator>;
currencyCode: string;
defaultCollapsed?: boolean;
};
-export type PurchaseInvoiceDeliveryFormRef = {
+export type SalesInvoiceShipmentFormRef = {
focusShippingCost: () => void;
};
-const PurchaseInvoiceDeliveryForm = forwardRef<
- PurchaseInvoiceDeliveryFormRef,
- PurchaseInvoiceDeliveryFormProps
+const SalesInvoiceShipmentForm = forwardRef<
+ SalesInvoiceShipmentFormRef,
+ SalesInvoiceShipmentFormProps
>(({ initialValues, currencyCode, defaultCollapsed = true }, ref) => {
const { invoiceId } = useParams();
if (!invoiceId) {
@@ -43,11 +43,11 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
}
const routeData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- }>(path.to.purchaseInvoice(invoiceId));
+ salesInvoice: SalesInvoice;
+ }>(path.to.salesInvoice(invoiceId));
const isEditable = ["Draft", "To Review"].includes(
- routeData?.purchaseInvoice?.status ?? ""
+ routeData?.salesInvoice?.status ?? ""
);
const permissions = usePermissions();
@@ -67,7 +67,7 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
},
}));
- const isSupplier = permissions.is("supplier");
+ const isCustomer = permissions.is("customer");
return (
<Card
@@ -79,8 +79,8 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
>
<ValidatedForm
method="post"
- action={path.to.purchaseInvoiceDelivery(invoiceId)}
- validator={purchaseInvoiceDeliveryValidator}
+ action={path.to.salesInvoiceShipment(invoiceId)}
+ validator={salesInvoiceShipmentValidator}
defaultValues={initialValues}
fetcher={fetcher}
>
@@ -102,12 +102,12 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
/>
<Location
name="locationId"
- label="Delivery Location"
- isReadOnly={isSupplier}
+ label="Shipment Location"
+ isReadOnly={isCustomer}
isClearable
/>
<ShippingMethod name="shippingMethodId" label="Shipping Method" />
- <CustomFormFields table="purchaseInvoiceDelivery" />
+ <CustomFormFields table="salesInvoiceShipment" />
</div>
</CardContent>
<CardFooter>
@@ -122,6 +122,6 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
);
});
-PurchaseInvoiceDeliveryForm.displayName = "PurchaseInvoiceDeliveryForm";
+SalesInvoiceShipmentForm.displayName = "SalesInvoiceShipmentForm";
-export default PurchaseInvoiceDeliveryForm;
+export default SalesInvoiceShipmentForm;
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceSummary.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
similarity index 75%
rename from apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceSummary.tsx
rename to apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
index 8d1be394b0..fdffd76f1a 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/PurchaseInvoiceSummary.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx
@@ -19,7 +19,7 @@ import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
import { useState } from "react";
import { LuChevronRight, LuImage } from "react-icons/lu";
-import { SupplierAvatar } from "~/components";
+import { CustomerAvatar } from "~/components";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import {
useCurrencyFormatter,
@@ -29,9 +29,9 @@ import {
} from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
import type {
- PurchaseInvoice,
- PurchaseInvoiceDelivery,
- PurchaseInvoiceLine,
+ SalesInvoice,
+ SalesInvoiceLine,
+ SalesInvoiceShipment,
} from "../../types";
const LineItems = ({
@@ -39,14 +39,14 @@ const LineItems = ({
presentationCurrencyFormatter,
formatter,
locale,
- purchaseInvoiceLines,
+ salesInvoiceLines,
shouldConvertCurrency,
}: {
currencyCode: string;
presentationCurrencyFormatter: Intl.NumberFormat;
formatter: Intl.NumberFormat;
locale: string;
- purchaseInvoiceLines: PurchaseInvoiceLine[];
+ salesInvoiceLines: SalesInvoiceLine[];
shouldConvertCurrency: boolean;
}) => {
const { invoiceId } = useParams();
@@ -64,18 +64,30 @@ const LineItems = ({
return (
<VStack spacing={8} className="w-full overflow-hidden">
- {purchaseInvoiceLines.map((line) => {
+ {salesInvoiceLines.map((line) => {
if (!line.id) return null;
- const lineTotal = (line.unitPrice ?? 0) * (line.quantity ?? 0);
- const supplierLineTotal =
- (line.supplierUnitPrice ?? 0) * (line.quantity ?? 0);
+ const lineSubtotal = (line.unitPrice ?? 0) * (line.quantity ?? 0);
+ const customerSubtotal =
+ (line.convertedUnitPrice ?? 0) * (line.quantity ?? 0);
const total =
- lineTotal + (line.taxAmount ?? 0) + (line.shippingCost ?? 0);
- const supplierTotal =
- supplierLineTotal +
- (line.supplierTaxAmount ?? 0) +
- (line.supplierShippingCost ?? 0);
+ (lineSubtotal + (line.addOnCost ?? 0) + (line.shippingCost ?? 0)) *
+ (1 + (line.taxPercent ?? 0));
+ const customerTotal =
+ (customerSubtotal +
+ (line.convertedAddOnCost ?? 0) +
+ (line.convertedShippingCost ?? 0)) *
+ (1 + (line.taxPercent ?? 0));
+
+ const lineTaxAmount =
+ (line.taxPercent ?? 0) *
+ (lineSubtotal + (line.addOnCost ?? 0) + (line.shippingCost ?? 0));
+
+ const customerLineTaxAmount =
+ (line.taxPercent ?? 0) *
+ (customerSubtotal +
+ (line.convertedAddOnCost ?? 0) +
+ (line.convertedShippingCost ?? 0));
return (
<motion.div
@@ -116,7 +128,7 @@ const LineItems = ({
className="text-muted-foreground flex-shrink-0"
>
<Link
- to={path.to.purchaseInvoiceLine(invoiceId, line.id!)}
+ to={path.to.salesInvoiceLine(invoiceId, line.id!)}
>
Edit
</Link>
@@ -130,7 +142,7 @@ const LineItems = ({
{shouldConvertCurrency && (
<span className="text-muted-foreground text-sm">
{presentationCurrencyFormatter.format(
- supplierTotal
+ customerTotal
)}
</span>
)}
@@ -173,24 +185,10 @@ const LineItems = ({
{line.quantity}{" "}
{
unitOfMeasures.find(
- (uom) =>
- uom.value === line.purchaseUnitOfMeasureCode
+ (uom) => uom.value === line.unitOfMeasureCode
)?.label
}
</span>
- {line.conversionFactor !== 1 && (
- <span className="text-muted-foreground text-xs">
- {(line.quantity ?? 0) *
- (line.conversionFactor ?? 1)}{" "}
- {
- unitOfMeasures.find(
- (uom) =>
- uom.value ===
- line.inventoryUnitOfMeasureCode
- )?.label
- }
- </span>
- )}
</VStack>
</Td>
</Tr>
@@ -202,7 +200,7 @@ const LineItems = ({
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
- line.supplierUnitPrice ?? 0
+ line.convertedUnitPrice ?? 0
)}
</span>
)}
@@ -219,7 +217,7 @@ const LineItems = ({
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
- line.supplierShippingCost ?? 0
+ line.convertedShippingCost ?? 0
)}
</span>
)}
@@ -230,11 +228,11 @@ const LineItems = ({
<Td>Extended Price</Td>
<Td className="text-right">
<VStack spacing={0}>
- <span>{formatter.format(lineTotal)}</span>
+ <span>{formatter.format(lineSubtotal)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
- supplierLineTotal
+ customerSubtotal
)}
</span>
)}
@@ -248,11 +246,11 @@ const LineItems = ({
</Td>
<Td className="text-right">
<VStack spacing={0}>
- <span>{formatter.format(line.taxAmount ?? 0)}</span>
+ <span>{formatter.format(lineTaxAmount)}</span>
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
- line.supplierTaxAmount ?? 0
+ customerLineTaxAmount
)}
</span>
)}
@@ -268,7 +266,7 @@ const LineItems = ({
{shouldConvertCurrency && (
<span className="text-muted-foreground text-xs">
{presentationCurrencyFormatter.format(
- supplierTotal
+ customerTotal
)}
</span>
)}
@@ -285,90 +283,105 @@ const LineItems = ({
</VStack>
);
};
-type PurchaseInvoiceSummaryProps = {
+type SalesInvoiceSummaryProps = {
onEditShippingCost: () => void;
};
-const PurchaseInvoiceSummary = ({
+const SalesInvoiceSummary = ({
onEditShippingCost,
-}: PurchaseInvoiceSummaryProps) => {
+}: SalesInvoiceSummaryProps) => {
const { invoiceId } = useParams();
if (!invoiceId) throw new Error("Could not find invoiceId");
const routeData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- purchaseInvoiceLines: PurchaseInvoiceLine[];
- purchaseInvoiceDelivery: PurchaseInvoiceDelivery;
- }>(path.to.purchaseInvoice(invoiceId));
+ salesInvoice: SalesInvoice;
+ salesInvoiceLines: SalesInvoiceLine[];
+ salesInvoiceShipment: SalesInvoiceShipment;
+ }>(path.to.salesInvoice(invoiceId));
const { locale } = useLocale();
const { company } = useUser();
const shouldConvertCurrency =
- routeData?.purchaseInvoice?.currencyCode !== company?.baseCurrencyCode;
+ routeData?.salesInvoice?.currencyCode !== company?.baseCurrencyCode;
const formatter = useCurrencyFormatter({
currency: company?.baseCurrencyCode ?? "USD",
});
const presentationCurrencyFormatter = useCurrencyFormatter({
- currency: routeData?.purchaseInvoice?.currencyCode ?? "USD",
+ currency: routeData?.salesInvoice?.currencyCode ?? "USD",
});
const isEditable = ["Draft", "To Review"].includes(
- routeData?.purchaseInvoice?.status ?? ""
+ routeData?.salesInvoice?.status ?? ""
);
// Calculate totals
const subtotal =
- routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- const lineTotal =
- (line.unitPrice ?? 0) * (line.quantity ?? 0) + (line.shippingCost ?? 0);
- return acc + lineTotal;
+ routeData?.salesInvoiceLines?.reduce((acc, line) => {
+ const lineSubtotal =
+ (line.unitPrice ?? 0) * (line.quantity ?? 0) +
+ (line.shippingCost ?? 0) +
+ (line.addOnCost ?? 0);
+ return acc + lineSubtotal;
}, 0) ?? 0;
- const supplierSubtotal =
- routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- const lineTotal =
- (line.supplierUnitPrice ?? 0) * (line.quantity ?? 0) +
- (line.supplierShippingCost ?? 0);
- return acc + lineTotal;
+ const customerSubtotal =
+ routeData?.salesInvoiceLines?.reduce((acc, line) => {
+ const lineSubtotal =
+ (line.convertedUnitPrice ?? 0) * (line.quantity ?? 0) +
+ (line.convertedShippingCost ?? 0) +
+ (line.convertedAddOnCost ?? 0);
+
+ return acc + lineSubtotal;
}, 0) ?? 0;
const tax =
- routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- return acc + (line.taxAmount ?? 0);
+ routeData?.salesInvoiceLines?.reduce((acc, line) => {
+ const lineTaxAmount =
+ (line.taxPercent ?? 0) *
+ ((line.unitPrice ?? 0) * (line.quantity ?? 0) +
+ (line.shippingCost ?? 0) +
+ (line.addOnCost ?? 0));
+ return acc + lineTaxAmount;
}, 0) ?? 0;
- const supplierTax =
- routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- return acc + (line.supplierTaxAmount ?? 0);
+ const customerTax =
+ routeData?.salesInvoiceLines?.reduce((acc, line) => {
+ const lineTaxAmount =
+ (line.taxPercent ?? 0) *
+ ((line.convertedUnitPrice ?? 0) * (line.quantity ?? 0) +
+ (line.convertedShippingCost ?? 0) +
+ (line.convertedAddOnCost ?? 0));
+ return acc + lineTaxAmount;
}, 0) ?? 0;
const shippingCost =
- (routeData?.purchaseInvoiceDelivery?.supplierShippingCost ?? 0) *
- (routeData?.purchaseInvoice?.exchangeRate ?? 1);
+ (routeData?.salesInvoiceShipment?.shippingCost ?? 0) *
+ (routeData?.salesInvoice?.exchangeRate ?? 1);
- const supplierShippingCost =
- routeData?.purchaseInvoiceDelivery?.supplierShippingCost ?? 0;
+ const customerShippingCost =
+ (routeData?.salesInvoiceShipment?.shippingCost ?? 0) *
+ (routeData?.salesInvoice?.exchangeRate ?? 1);
const total = subtotal + tax + shippingCost;
- const supplierTotal = supplierSubtotal + supplierTax + supplierShippingCost;
+ const customerTotal = customerSubtotal + customerTax + customerShippingCost;
return (
<Card>
<CardHeader>
<HStack className="justify-between items-center">
<div className="flex flex-col gap-1">
- <CardTitle>{routeData?.purchaseInvoice.invoiceId}</CardTitle>
- <CardDescription>Purchase Invoice</CardDescription>
+ <CardTitle>{routeData?.salesInvoice.invoiceId}</CardTitle>
+ <CardDescription>Sales Invoice</CardDescription>
</div>
<div className="flex flex-col gap-1 items-end">
- <SupplierAvatar
- supplierId={routeData?.purchaseInvoice.supplierId ?? null}
+ <CustomerAvatar
+ customerId={routeData?.salesInvoice.customerId ?? null}
/>
- {routeData?.purchaseInvoice?.dateDue && (
+ {routeData?.salesInvoice?.dateDue && (
<span className="text-muted-foreground text-sm">
- Due {formatDate(routeData?.purchaseInvoice.dateDue)}
+ Due {formatDate(routeData?.salesInvoice.dateDue)}
</span>
)}
</div>
@@ -380,7 +393,7 @@ const PurchaseInvoiceSummary = ({
presentationCurrencyFormatter={presentationCurrencyFormatter}
formatter={formatter}
locale={locale}
- purchaseInvoiceLines={routeData?.purchaseInvoiceLines ?? []}
+ salesInvoiceLines={routeData?.salesInvoiceLines ?? []}
shouldConvertCurrency={shouldConvertCurrency}
/>
@@ -391,7 +404,7 @@ const PurchaseInvoiceSummary = ({
<span>{formatter.format(subtotal)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
- {presentationCurrencyFormatter.format(supplierSubtotal)}
+ {presentationCurrencyFormatter.format(customerSubtotal)}
</span>
)}
</VStack>
@@ -403,7 +416,7 @@ const PurchaseInvoiceSummary = ({
<span>{formatter.format(tax)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
- {presentationCurrencyFormatter.format(supplierTax)}
+ {presentationCurrencyFormatter.format(customerTax)}
</span>
)}
</VStack>
@@ -430,7 +443,7 @@ const PurchaseInvoiceSummary = ({
{shouldConvertCurrency && (
<span className="text-sm">
{presentationCurrencyFormatter.format(
- supplierShippingCost
+ customerShippingCost
)}
</span>
)}
@@ -454,7 +467,7 @@ const PurchaseInvoiceSummary = ({
<span>{formatter.format(total)}</span>
{shouldConvertCurrency && (
<span className="text-sm">
- {presentationCurrencyFormatter.format(supplierTotal)}
+ {presentationCurrencyFormatter.format(customerTotal)}
</span>
)}
</VStack>
@@ -465,4 +478,4 @@ const PurchaseInvoiceSummary = ({
);
};
-export default PurchaseInvoiceSummary;
+export default SalesInvoiceSummary;
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index ddce323600..772506edc1 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -848,7 +848,7 @@ export async function updatePurchaseOrderExchangeRate(
exchangeRateUpdatedAt: new Date().toISOString(),
};
- return client.from("salesOrder").update(update).eq("id", update.id);
+ return client.from("purchaseOrder").update(update).eq("id", update.id);
}
export async function updatePurchaseOrderFavorite(
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
index 6a4a7663b3..d42db2bd61 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
@@ -34,8 +34,8 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import {
- LuGripVertical,
LuEllipsisVertical,
+ LuGripVertical,
LuRadioTower,
LuShoppingCart,
LuUpload,
@@ -53,7 +53,7 @@ type OpportunityDocumentsProps = {
attachments: FileObject[];
opportunity: Opportunity;
id: string;
- type: "Sales Order" | "Request for Quote" | "Quote";
+ type: "Sales Order" | "Request for Quote" | "Quote" | "Sales Invoice";
};
const OpportunityDocuments = ({
@@ -265,7 +265,7 @@ const DraggableCell = ({
type OpportunityDocumentFormProps = {
opportunityId: string;
id: string;
- type: "Sales Order" | "Request for Quote" | "Quote";
+ type: "Sales Order" | "Request for Quote" | "Quote" | "Sales Invoice";
};
export const useOpportunityDocuments = ({
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index 08b0e51e35..d3683a23c1 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -45,7 +45,7 @@ const useOpportunityLineDocuments = ({
}: {
id: string;
lineId: string;
- type: "Request for Quote" | "Sales Order" | "Quote";
+ type: "Request for Quote" | "Sales Order" | "Quote" | "Sales Invoice";
}) => {
const permissions = usePermissions();
const revalidator = useRevalidator();
@@ -86,21 +86,29 @@ const useOpportunityLineDocuments = ({
async (lineId: string) => {
if (!lineId || !carbon) return;
- const [salesRfqLineResult, quoteLineResult, salesOrderLineResult] =
- await Promise.all([
- carbon
- .from("salesRfqLine")
- .update({ modelUploadId: null })
- .eq("id", lineId),
- carbon
- .from("quoteLine")
- .update({ modelUploadId: null })
- .eq("id", lineId),
- carbon
- .from("salesOrderLine")
- .update({ modelUploadId: null })
- .eq("id", lineId),
- ]);
+ const [
+ salesRfqLineResult,
+ quoteLineResult,
+ salesOrderLineResult,
+ salesInvoiceLineResult,
+ ] = await Promise.all([
+ carbon
+ .from("salesRfqLine")
+ .update({ modelUploadId: null })
+ .eq("id", lineId),
+ carbon
+ .from("quoteLine")
+ .update({ modelUploadId: null })
+ .eq("id", lineId),
+ carbon
+ .from("salesOrderLine")
+ .update({ modelUploadId: null })
+ .eq("id", lineId),
+ carbon
+ .from("salesInvoiceLine")
+ .update({ modelUploadId: null })
+ .eq("id", lineId),
+ ]);
if (salesRfqLineResult.error) {
toast.error("Error removing model from RFQ line");
@@ -116,6 +124,12 @@ const useOpportunityLineDocuments = ({
toast.error("Error removing model from sales order line");
return;
}
+
+ if (salesInvoiceLineResult.error) {
+ toast.error("Error removing model from sales invoice line");
+ return;
+ }
+
toast.success("Model removed from line");
revalidator.revalidate();
},
@@ -256,7 +270,7 @@ type OpportunityLineDocumentsProps = {
files: FileObject[];
id: string;
lineId: string;
- type: "Request for Quote" | "Sales Order" | "Quote";
+ type: "Request for Quote" | "Sales Order" | "Quote" | "Sales Invoice";
modelUpload?: ModelUpload;
};
@@ -473,7 +487,7 @@ export default OpportunityLineDocuments;
type OpportunityLineDocumentFormProps = {
id: string;
lineId: string;
- type: "Request for Quote" | "Sales Order" | "Quote";
+ type: "Request for Quote" | "Sales Order" | "Quote" | "Sales Invoice";
};
const OpportunityLineDocumentForm = ({
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
index f786162331..5cb6b6414d 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineNotes.tsx
@@ -31,7 +31,7 @@ const OpportunityLineNotes = ({
externalNotes: initialExternalNotes,
}: {
id: string | null;
- table: "salesRfqLine" | "quoteLine" | "salesOrderLine";
+ table: "salesRfqLine" | "quoteLine" | "salesOrderLine" | "salesInvoiceLine";
title: string;
subTitle: string;
internalNotes?: JSONContent;
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
index 250271fdfc..a5186afa0e 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityNotes.tsx
@@ -30,7 +30,7 @@ const OpportunityNotes = ({
externalNotes: initialExternalNotes,
}: {
id: string | null;
- table: "salesRfq" | "quote" | "salesOrder";
+ table: "salesRfq" | "quote" | "salesOrder" | "salesInvoice";
title: string;
internalNotes?: JSONContent;
externalNotes?: JSONContent;
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
index 7acd386e90..11a39b18ff 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx
@@ -25,7 +25,7 @@ import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
- view: "parts",
+ view: "invoicing",
role: "employee",
});
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
index 3adfd32c00..6b8312d5a5 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
@@ -3,8 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import { getCurrencyByCode } from "~/modules/accounting";
-import { updatePurchaseOrderExchangeRate } from "~/modules/purchasing";
-import { path } from "~/utils/path";
+import { updatePurchaseInvoiceExchangeRate } from "~/modules/invoicing";
+import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -23,7 +23,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (currency.error || !currency.data.exchangeRate)
throw new Error("Could not find currency");
- const update = await updatePurchaseOrderExchangeRate(client, {
+ const update = await updatePurchaseInvoiceExchangeRate(client, {
id: invoiceId,
exchangeRate: currency.data.exchangeRate,
});
@@ -33,7 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- path.to.purchaseInvoiceDetails(invoiceId),
+ requestReferrer(request) ?? path.to.purchaseInvoiceDetails(invoiceId),
await flash(request, success("Successfully updated exchange rate"))
);
}
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
index 1cfed9021c..4e4960cb49 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
export const config = { runtime: "nodejs" };
@@ -24,7 +24,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (setPendingState.error) {
throw redirect(
- path.to.purchaseInvoices,
+ requestReferrer(request) ?? path.to.purchaseInvoice(invoiceId),
await flash(
request,
error(setPendingState.error, "Failed to post purchase invoice")
@@ -97,5 +97,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.eq("id", invoiceId);
}
- throw redirect(path.to.purchaseInvoices);
+ throw redirect(
+ requestReferrer(request) ?? path.to.purchaseInvoice(invoiceId)
+ );
}
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
index e7d0a01986..d253c110ef 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
@@ -29,7 +29,7 @@ export const handle: Handle = {
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
- view: "parts",
+ view: "invoicing",
});
const { invoiceId } = params;
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 4ab2cfbcf8..770eeec3ba 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost, error } from "@carbon/auth";
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
@@ -8,11 +8,11 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { useUrlParams, useUser } from "~/hooks";
import {
+ createPurchaseInvoiceFromPurchaseOrder,
PurchaseInvoiceForm,
purchaseInvoiceValidator,
upsertPurchaseInvoice,
} from "~/modules/invoicing";
-import { createPurchaseInvoiceFromPurchaseOrder } from "~/modules/invoicing/invoicing.server";
import { getNextSequence } from "~/modules/settings";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
@@ -40,6 +40,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
case "Purchase Order":
if (!sourceDocumentId) throw new Error("Missing sourceDocumentId");
result = await createPurchaseInvoiceFromPurchaseOrder(
+ getCarbonServiceRole(),
sourceDocumentId,
companyId,
userId
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
index 7acd386e90..67da594e0b 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx
@@ -10,33 +10,33 @@ import { defer, redirect } from "@vercel/remix";
import { Suspense } from "react";
import { Fragment } from "react/jsx-runtime";
import {
- PurchaseInvoiceLineForm,
- getPurchaseInvoiceLine,
- purchaseInvoiceLineValidator,
- upsertPurchaseInvoiceLine,
+ getSalesInvoiceLine,
+ salesInvoiceLineValidator,
+ upsertSalesInvoiceLine,
} from "~/modules/invoicing";
-import { getSupplierInteractionLineDocuments } from "~/modules/purchasing";
+import SalesInvoiceLineForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm";
+import { getOpportunityLineDocuments } from "~/modules/sales";
import {
- SupplierInteractionLineDocuments,
- SupplierInteractionLineNotes,
-} from "~/modules/purchasing/ui/SupplierInteraction";
+ OpportunityLineDocuments,
+ OpportunityLineNotes,
+} from "~/modules/sales/ui/Opportunity";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
- view: "parts",
+ view: "invoicing",
role: "employee",
});
const { lineId } = params;
if (!lineId) throw notFound("lineId not found");
- const purchaseInvoiceLine = await getPurchaseInvoiceLine(client, lineId);
+ const salesInvoiceLine = await getSalesInvoiceLine(client, lineId);
return defer({
- purchaseInvoiceLine: purchaseInvoiceLine?.data ?? null,
- files: getSupplierInteractionLineDocuments(client, companyId, lineId),
+ salesInvoiceLine: salesInvoiceLine?.data ?? null,
+ files: getOpportunityLineDocuments(client, companyId, lineId),
});
}
@@ -51,7 +51,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!lineId) throw new Error("Could not find lineId");
const formData = await request.formData();
- const validation = await validator(purchaseInvoiceLineValidator).validate(
+ const validation = await validator(salesInvoiceLineValidator).validate(
formData
);
@@ -77,72 +77,67 @@ export async function action({ request, params }: ActionFunctionArgs) {
// data.assetId = undefined;
// }
- const updatePurchaseInvoiceLine = await upsertPurchaseInvoiceLine(client, {
+ const updateSalesInvoiceLine = await upsertSalesInvoiceLine(client, {
id: lineId,
...data,
updatedBy: userId,
customFields: setCustomFields(formData),
});
- if (updatePurchaseInvoiceLine.error) {
+ if (updateSalesInvoiceLine.error) {
throw redirect(
- path.to.purchaseInvoiceLine(invoiceId, lineId),
+ path.to.salesInvoiceLine(invoiceId, lineId),
await flash(
request,
error(
- updatePurchaseInvoiceLine.error,
- "Failed to update purchase invoice line"
+ updateSalesInvoiceLine.error,
+ "Failed to update sales invoice line"
)
)
);
}
- throw redirect(path.to.purchaseInvoiceLine(invoiceId, lineId));
+ throw redirect(path.to.salesInvoiceLine(invoiceId, lineId));
}
-export default function EditPurchaseInvoiceLineRoute() {
+export default function EditSalesInvoiceLineRoute() {
const { invoiceId, lineId } = useParams();
if (!invoiceId) throw notFound("invoiceId not found");
if (!lineId) throw notFound("lineId not found");
- const { purchaseInvoiceLine, files } = useLoaderData<typeof loader>();
+ const { salesInvoiceLine, files } = useLoaderData<typeof loader>();
const initialValues = {
- id: purchaseInvoiceLine?.id ?? undefined,
- invoiceId: purchaseInvoiceLine?.invoiceId ?? "",
- invoiceLineType: (purchaseInvoiceLine?.invoiceLineType ?? "Part") as "Part",
- itemId: purchaseInvoiceLine?.itemId ?? "",
- itemReadableId: purchaseInvoiceLine?.itemReadableId ?? "",
- accountNumber: purchaseInvoiceLine?.accountNumber ?? "",
- assetId: purchaseInvoiceLine?.assetId ?? "",
- description: purchaseInvoiceLine?.description ?? "",
- quantity: purchaseInvoiceLine?.quantity ?? 1,
- supplierUnitPrice: purchaseInvoiceLine?.supplierUnitPrice ?? 0,
- supplierShippingCost: purchaseInvoiceLine?.supplierShippingCost ?? 0,
- supplierTaxAmount: purchaseInvoiceLine?.supplierTaxAmount ?? 0,
- exchangeRate: purchaseInvoiceLine?.exchangeRate ?? 1,
- purchaseUnitOfMeasureCode:
- purchaseInvoiceLine?.purchaseUnitOfMeasureCode ?? "",
- inventoryUnitOfMeasureCode:
- purchaseInvoiceLine?.inventoryUnitOfMeasureCode ?? "",
- conversionFactor: purchaseInvoiceLine?.conversionFactor ?? 1,
- shelfId: purchaseInvoiceLine?.shelfId ?? "",
- taxPercent: purchaseInvoiceLine?.taxPercent ?? 0,
- ...getCustomFields(purchaseInvoiceLine?.customFields),
+ id: salesInvoiceLine?.id ?? undefined,
+ invoiceId: salesInvoiceLine?.invoiceId ?? "",
+ invoiceLineType: (salesInvoiceLine?.invoiceLineType ?? "Part") as "Part",
+ itemId: salesInvoiceLine?.itemId ?? "",
+ itemReadableId: salesInvoiceLine?.itemReadableId ?? "",
+ accountNumber: salesInvoiceLine?.accountNumber ?? "",
+ assetId: salesInvoiceLine?.assetId ?? "",
+ description: salesInvoiceLine?.description ?? "",
+ quantity: salesInvoiceLine?.quantity ?? 1,
+ unitPrice: salesInvoiceLine?.unitPrice ?? 0,
+ shippingCost: salesInvoiceLine?.shippingCost ?? 0,
+ taxPercent: salesInvoiceLine?.taxPercent ?? 0,
+ exchangeRate: salesInvoiceLine?.exchangeRate ?? 1,
+ unitOfMeasureCode: salesInvoiceLine?.unitOfMeasureCode ?? "",
+ shelfId: salesInvoiceLine?.shelfId ?? "",
+ ...getCustomFields(salesInvoiceLine?.customFields),
};
return (
- <Fragment key={purchaseInvoiceLine?.id}>
- <PurchaseInvoiceLineForm
+ <Fragment key={salesInvoiceLine?.id}>
+ <SalesInvoiceLineForm
key={initialValues.id}
initialValues={initialValues}
/>
- <SupplierInteractionLineNotes
- id={purchaseInvoiceLine?.id ?? ""}
- table="purchaseInvoiceLine"
+ <OpportunityLineNotes
+ id={salesInvoiceLine?.id ?? ""}
+ table="salesInvoiceLine"
title="Notes"
- subTitle={purchaseInvoiceLine?.itemReadableId ?? ""}
- internalNotes={purchaseInvoiceLine?.internalNotes as JSONContent}
+ subTitle={salesInvoiceLine?.itemReadableId ?? ""}
+ internalNotes={salesInvoiceLine?.internalNotes as JSONContent}
/>
<Suspense
@@ -154,11 +149,11 @@ export default function EditPurchaseInvoiceLineRoute() {
>
<Await resolve={files}>
{(resolvedFiles) => (
- <SupplierInteractionLineDocuments
+ <OpportunityLineDocuments
files={resolvedFiles ?? []}
id={invoiceId}
lineId={lineId}
- type="Purchase Invoice"
+ type="Sales Invoice"
/>
)}
</Await>
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx
index c60533a9a0..f7a757c0e9 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { deletePurchaseInvoice } from "~/modules/invoicing";
+import { deleteSalesInvoice } from "~/modules/invoicing";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -15,17 +15,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { invoiceId } = params;
if (!invoiceId) throw notFound("invoiceId not found");
- const remove = await deletePurchaseInvoice(client, invoiceId);
+ const remove = await deleteSalesInvoice(client, invoiceId);
if (remove.error) {
throw redirect(
- path.to.purchaseInvoices,
+ path.to.salesInvoices,
await flash(
request,
- error(remove.error, "Failed to delete purchase invoice")
+ error(remove.error, "Failed to delete sales invoice")
)
);
}
- throw redirect(path.to.purchaseInvoices);
+ throw redirect(path.to.salesInvoices);
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx
index 48b7df0b01..51b7914ee2 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx
@@ -12,23 +12,23 @@ import { Suspense, useRef } from "react";
import { Fragment } from "react/jsx-runtime";
import { useRouteData, useUser } from "~/hooks";
import type {
- PurchaseInvoice,
- PurchaseInvoiceDelivery,
- PurchaseInvoiceLine,
+ SalesInvoice,
+ SalesInvoiceLine,
+ SalesInvoiceShipment,
} from "~/modules/invoicing";
import {
- getPurchaseInvoice,
- PurchaseInvoiceSummary,
- purchaseInvoiceValidator,
- upsertPurchaseInvoice,
+ getSalesInvoice,
+ salesInvoiceValidator,
+ upsertSalesInvoice,
} from "~/modules/invoicing";
-import { PurchaseInvoiceDeliveryForm } from "~/modules/invoicing/ui/PurchaseInvoice";
-import type { PurchaseInvoiceDeliveryFormRef } from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm";
-import type { SupplierInteraction } from "~/modules/purchasing";
+import type { SalesInvoiceShipmentFormRef } from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm";
+import SalesInvoiceShipmentForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm";
+import SalesInvoiceSummary from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary";
+import type { Opportunity } from "~/modules/sales";
import {
- SupplierInteractionDocuments,
- SupplierInteractionNotes,
-} from "~/modules/purchasing/ui/SupplierInteraction";
+ OpportunityDocuments,
+ OpportunityNotes,
+} from "~/modules/sales/ui/Opportunity";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -40,14 +40,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
- const invoice = await getPurchaseInvoice(client, invoiceId);
+ const invoice = await getSalesInvoice(client, invoiceId);
if (invoice.error) {
throw redirect(
- path.to.purchaseInvoices,
- await flash(
- request,
- error(invoice.error, "Failed to load purchase invoice")
- )
+ path.to.salesInvoices,
+ await flash(request, error(invoice.error, "Failed to load sales invoice"))
);
}
@@ -66,9 +63,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!id) throw new Error("Could not find invoiceId");
const formData = await request.formData();
- const validation = await validator(purchaseInvoiceValidator).validate(
- formData
- );
+ const validation = await validator(salesInvoiceValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
@@ -77,87 +72,86 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { invoiceId, ...data } = validation.data;
if (!invoiceId) throw new Error("Could not find invoiceId");
- const updatePurchaseInvoice = await upsertPurchaseInvoice(client, {
+ const updateSalesInvoice = await upsertSalesInvoice(client, {
id,
invoiceId,
...data,
updatedBy: userId,
customFields: setCustomFields(formData),
});
- if (updatePurchaseInvoice.error) {
+ if (updateSalesInvoice.error) {
throw redirect(
- path.to.purchaseInvoice(id),
+ path.to.salesInvoice(id),
await flash(
request,
- error(updatePurchaseInvoice.error, "Failed to update purchase invoice")
+ error(updateSalesInvoice.error, "Failed to update sales invoice")
)
);
}
throw redirect(
- path.to.purchaseInvoice(id),
- await flash(request, success("Updated purchase invoice"))
+ path.to.salesInvoice(id),
+ await flash(request, success("Updated sales invoice"))
);
}
-export default function PurchaseInvoiceBasicRoute() {
+export default function SalesInvoiceBasicRoute() {
const { internalNotes } = useLoaderData<typeof loader>();
const { invoiceId } = useParams();
if (!invoiceId) throw new Error("invoiceId not found");
const invoiceData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- purchaseInvoiceLines: PurchaseInvoiceLine[];
- purchaseInvoiceDelivery: PurchaseInvoiceDelivery;
- interaction: SupplierInteraction;
+ salesInvoice: SalesInvoice;
+ salesInvoiceLines: SalesInvoiceLine[];
+ salesInvoiceShipment: SalesInvoiceShipment;
+ opportunity: Opportunity;
files: Promise<FileObject[]>;
- }>(path.to.purchaseInvoice(invoiceId));
+ }>(path.to.salesInvoice(invoiceId));
- if (!invoiceData?.purchaseInvoice)
- throw new Error("purchaseInvoice not found");
- const { purchaseInvoice, purchaseInvoiceDelivery } = invoiceData;
+ if (!invoiceData?.salesInvoice) throw new Error("salesInvoice not found");
+ const { salesInvoice, salesInvoiceShipment } = invoiceData;
if (!invoiceData) throw new Error("Could not find invoice data");
- const deliveryFormRef = useRef<PurchaseInvoiceDeliveryFormRef>(null);
+ const shipmentFormRef = useRef<SalesInvoiceShipmentFormRef>(null);
const handleEditShippingCost = () => {
- deliveryFormRef.current?.focusShippingCost();
+ shipmentFormRef.current?.focusShippingCost();
};
const initialValues = {
- id: purchaseInvoice.id ?? "",
- invoiceId: purchaseInvoice.invoiceId ?? "",
- supplierId: purchaseInvoice.supplierId ?? "",
- supplierReference: purchaseInvoice.supplierReference ?? "",
- invoiceSupplierId: purchaseInvoice.invoiceSupplierId ?? "",
- paymentTermId: purchaseInvoice.paymentTermId ?? "",
- currencyCode: purchaseInvoice.currencyCode ?? "",
- dateIssued: purchaseInvoice.dateIssued ?? "",
- dateDue: purchaseInvoice.dateDue ?? "",
- status: purchaseInvoice.status ?? ("Draft" as "Draft"),
- ...getCustomFields(purchaseInvoice.customFields),
+ id: salesInvoice.id ?? "",
+ invoiceId: salesInvoice.invoiceId ?? "",
+ customerId: salesInvoice.customerId ?? "",
+ customerReference: salesInvoice.customerReference ?? "",
+ invoiceCustomerId: salesInvoice.invoiceCustomerId ?? "",
+ paymentTermId: salesInvoice.paymentTermId ?? "",
+ currencyCode: salesInvoice.currencyCode ?? "",
+ dateIssued: salesInvoice.dateIssued ?? "",
+ dateDue: salesInvoice.dateDue ?? "",
+ status: salesInvoice.status ?? ("Draft" as "Draft"),
+ ...getCustomFields(salesInvoice.customFields),
};
- const deliveryInitialValues = {
- id: purchaseInvoiceDelivery.id,
- locationId: purchaseInvoiceDelivery.locationId ?? "",
- supplierShippingCost: purchaseInvoiceDelivery.supplierShippingCost ?? 0,
- shippingMethodId: purchaseInvoiceDelivery.shippingMethodId ?? "",
- shippingTermId: purchaseInvoiceDelivery.shippingTermId ?? "",
- ...getCustomFields(purchaseInvoiceDelivery.customFields),
+ const shipmentInitialValues = {
+ id: salesInvoiceShipment.id,
+ locationId: salesInvoiceShipment.locationId ?? "",
+ shippingCost: salesInvoiceShipment.shippingCost ?? 0,
+ shippingMethodId: salesInvoiceShipment.shippingMethodId ?? "",
+ shippingTermId: salesInvoiceShipment.shippingTermId ?? "",
+ ...getCustomFields(salesInvoiceShipment.customFields),
};
const { company } = useUser();
return (
<Fragment key={invoiceId}>
- <PurchaseInvoiceSummary onEditShippingCost={handleEditShippingCost} />
- <SupplierInteractionNotes
+ <SalesInvoiceSummary onEditShippingCost={handleEditShippingCost} />
+ <OpportunityNotes
key={`notes-${initialValues.id}`}
id={invoiceId}
title="Notes"
- table="purchaseInvoice"
+ table="salesInvoice"
internalNotes={internalNotes}
/>
<Suspense
@@ -170,19 +164,19 @@ export default function PurchaseInvoiceBasicRoute() {
>
<Await resolve={invoiceData.files}>
{(resolvedFiles) => (
- <SupplierInteractionDocuments
- interactionId={invoiceData.interaction.id}
+ <OpportunityDocuments
+ opportunity={invoiceData.opportunity}
attachments={resolvedFiles}
id={invoiceId}
- type="Purchase Invoice"
+ type="Sales Invoice"
/>
)}
</Await>
</Suspense>
- <PurchaseInvoiceDeliveryForm
- key={`delivery-${invoiceId}`}
- ref={deliveryFormRef}
- initialValues={deliveryInitialValues}
+ <SalesInvoiceShipmentForm
+ key={`shipment-${invoiceId}`}
+ ref={shipmentFormRef}
+ initialValues={shipmentInitialValues}
currencyCode={initialValues.currencyCode || company.baseCurrencyCode}
defaultCollapsed={true}
/>
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
index 3adfd32c00..29186af642 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
@@ -3,8 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import { getCurrencyByCode } from "~/modules/accounting";
-import { updatePurchaseOrderExchangeRate } from "~/modules/purchasing";
-import { path } from "~/utils/path";
+import { updateSalesInvoiceExchangeRate } from "~/modules/invoicing";
+import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
@@ -23,7 +23,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (currency.error || !currency.data.exchangeRate)
throw new Error("Could not find currency");
- const update = await updatePurchaseOrderExchangeRate(client, {
+ const update = await updateSalesInvoiceExchangeRate(client, {
id: invoiceId,
exchangeRate: currency.data.exchangeRate,
});
@@ -33,7 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- path.to.purchaseInvoiceDetails(invoiceId),
+ requestReferrer(request) ?? path.to.salesInvoiceDetails(invoiceId),
await flash(request, success("Successfully updated exchange rate"))
);
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx
index d24b4bbed0..787832b41e 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.new.tsx
@@ -7,12 +7,12 @@ import { useParams } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { useUser } from "~/hooks";
-import type { PurchaseInvoice } from "~/modules/invoicing";
+import type { SalesInvoice } from "~/modules/invoicing";
import {
- PurchaseInvoiceLineForm,
- purchaseInvoiceLineValidator,
- upsertPurchaseInvoiceLine,
+ salesInvoiceLineValidator,
+ upsertSalesInvoiceLine,
} from "~/modules/invoicing";
+import SalesInvoiceLineForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm";
import type { MethodItemType } from "~/modules/shared";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -27,7 +27,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!invoiceId) throw new Error("Could not find invoiceId");
const formData = await request.formData();
- const validation = await validator(purchaseInvoiceLineValidator).validate(
+ const validation = await validator(salesInvoiceLineValidator).validate(
formData
);
@@ -37,52 +37,52 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const createPurchaseInvoiceLine = await upsertPurchaseInvoiceLine(client, {
+ const createSalesInvoiceLine = await upsertSalesInvoiceLine(client, {
...data,
companyId,
createdBy: userId,
customFields: setCustomFields(formData),
});
- if (createPurchaseInvoiceLine.error) {
+ if (createSalesInvoiceLine.error) {
throw redirect(
- path.to.purchaseInvoiceDetails(invoiceId),
+ path.to.salesInvoiceDetails(invoiceId),
await flash(
request,
error(
- createPurchaseInvoiceLine.error,
- "Failed to create purchase invoice line."
+ createSalesInvoiceLine.error,
+ "Failed to create sales invoice line."
)
)
);
}
- throw redirect(path.to.purchaseInvoiceDetails(invoiceId));
+ throw redirect(path.to.salesInvoiceDetails(invoiceId));
}
-export default function NewPurchaseInvoiceLineRoute() {
+export default function NewSalesInvoiceLineRoute() {
const { defaults } = useUser();
const { invoiceId } = useParams();
- if (!invoiceId) throw new Error("Could not find purchase invoice id");
- const purchaseInvoiceData = useRouteData<{
- purchaseInvoice: PurchaseInvoice;
- }>(path.to.purchaseInvoice(invoiceId));
+ if (!invoiceId) throw new Error("Could not find sales invoice id");
+ const salesInvoiceData = useRouteData<{
+ salesInvoice: SalesInvoice;
+ }>(path.to.salesInvoice(invoiceId));
- if (!invoiceId) throw new Error("Could not find purchase invoice id");
+ if (!invoiceId) throw new Error("Could not find sales invoice id");
const initialValues = {
invoiceId: invoiceId,
invoiceLineType: "Item" as MethodItemType,
- purchaseQuantity: 1,
+ quantity: 1,
+ unitOfMeasureCode: "EA",
locationId:
- purchaseInvoiceData?.purchaseInvoice?.locationId ??
- defaults.locationId ??
- "",
- supplierUnitPrice: 0,
- supplierShippingCost: 0,
- supplierTaxAmount: 0,
- exchangeRate: purchaseInvoiceData?.purchaseInvoice?.exchangeRate ?? 1,
+ salesInvoiceData?.salesInvoice?.locationId ?? defaults.locationId ?? "",
+ unitPrice: 0,
+ shippingCost: 0,
+ addOnCost: 0,
+ taxPercent: 0,
+ exchangeRate: salesInvoiceData?.salesInvoice?.exchangeRate ?? 1,
};
- return <PurchaseInvoiceLineForm initialValues={initialValues} />;
+ return <SalesInvoiceLineForm initialValues={initialValues} />;
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index 1cfed9021c..7a04267cac 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { path } from "~/utils/path";
+import { path, requestReferrer } from "~/utils/path";
export const config = { runtime: "nodejs" };
@@ -16,7 +16,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!invoiceId) throw new Error("invoiceId not found");
const setPendingState = await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
status: "Pending",
})
@@ -24,18 +24,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (setPendingState.error) {
throw redirect(
- path.to.purchaseInvoices,
+ requestReferrer(request) ?? path.to.salesInvoices,
await flash(
request,
- error(setPendingState.error, "Failed to post purchase invoice")
+ error(setPendingState.error, "Failed to post sales invoice")
)
);
}
try {
const serviceRole = await getCarbonServiceRole();
- const postPurchaseInvoice = await serviceRole.functions.invoke(
- "post-purchase-invoice",
+ const postSalesInvoice = await serviceRole.functions.invoke(
+ "post-sales-invoice",
{
body: {
invoiceId: invoiceId,
@@ -45,25 +45,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
);
- if (postPurchaseInvoice.error) {
+ if (postSalesInvoice.error) {
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
status: "Draft",
})
.eq("id", invoiceId);
throw redirect(
- path.to.purchaseInvoices,
+ path.to.salesInvoices,
await flash(
request,
- error(postPurchaseInvoice.error, "Failed to post purchase invoice")
+ error(postSalesInvoice.error, "Failed to post sales invoice")
)
);
}
const priceUpdate = await serviceRole.functions.invoke(
- "update-purchased-prices",
+ "update-sales-prices",
{
body: {
invoiceId: invoiceId,
@@ -74,14 +74,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (priceUpdate.error) {
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
status: "Draft",
})
.eq("id", invoiceId);
throw redirect(
- path.to.purchaseInvoices,
+ path.to.salesInvoices,
await flash(
request,
error(priceUpdate.error, "Failed to update prices")
@@ -90,12 +90,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
} catch (error) {
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
status: "Draft",
})
.eq("id", invoiceId);
}
- throw redirect(path.to.purchaseInvoices);
+ throw redirect(requestReferrer(request) ?? path.to.salesInvoice(invoiceId));
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delivery.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.shipment.tsx
similarity index 57%
rename from apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delivery.tsx
rename to apps/erp/app/routes/x+/sales-invoice+/$invoiceId.shipment.tsx
index d64fb71fd2..cc5ceaa18c 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delivery.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.shipment.tsx
@@ -5,8 +5,8 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import {
- purchaseInvoiceDeliveryValidator,
- upsertPurchaseInvoiceDelivery,
+ salesInvoiceShipmentValidator,
+ upsertSalesInvoiceShipment,
} from "~/modules/invoicing";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -21,7 +21,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!invoiceId) throw new Error("Could not find invoiceId");
const formData = await request.formData();
- const validation = await validator(purchaseInvoiceDeliveryValidator).validate(
+ const validation = await validator(salesInvoiceShipmentValidator).validate(
formData
);
@@ -29,31 +29,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- // Note: Need to add upsertPurchaseInvoiceDelivery to invoicing.service.ts
- const updatePurchaseInvoiceDelivery = await upsertPurchaseInvoiceDelivery(
- client,
- {
- ...validation.data,
- id: invoiceId,
- updatedBy: userId,
- customFields: setCustomFields(formData),
- }
- );
- if (updatePurchaseInvoiceDelivery.error) {
+ const updateSalesInvoiceShipment = await upsertSalesInvoiceShipment(client, {
+ ...validation.data,
+ id: invoiceId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateSalesInvoiceShipment.error) {
throw redirect(
- path.to.purchaseInvoice(invoiceId),
+ path.to.salesInvoice(invoiceId),
await flash(
request,
error(
- updatePurchaseInvoiceDelivery.error,
- "Failed to update purchase invoice delivery"
+ updateSalesInvoiceShipment.error,
+ "Failed to update sales invoice shipping"
)
)
);
}
throw redirect(
- path.to.purchaseInvoice(invoiceId),
- await flash(request, success("Updated purchase invoice delivery"))
+ path.to.salesInvoice(invoiceId),
+ await flash(request, success("Updated sales invoice shipping"))
);
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
index e7d0a01986..92554805e5 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
@@ -7,69 +7,72 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { defer, redirect } from "@vercel/remix";
import { PanelProvider, ResizablePanels } from "~/components/Layout";
import {
- PurchaseInvoiceHeader,
- getPurchaseInvoice,
- getPurchaseInvoiceDelivery,
- getPurchaseInvoiceLines,
+ getSalesInvoice,
+ getSalesInvoiceLines,
+ getSalesInvoiceShipment,
} from "~/modules/invoicing";
-import PurchaseInvoiceExplorer from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer";
-import PurchaseInvoiceProperties from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties";
+import SalesInvoiceExplorer from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer";
+import SalesInvoiceHeader from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader";
+import SalesInvoiceProperties from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties";
+
import {
- getSupplier,
- getSupplierInteraction,
- getSupplierInteractionDocuments,
-} from "~/modules/purchasing/purchasing.service";
+ getCustomer,
+ getOpportunity,
+ getOpportunityDocuments,
+} from "~/modules/sales/sales.service";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
- breadcrumb: "Purchase Invoices",
- to: path.to.purchaseInvoices,
+ breadcrumb: "Sales Invoices",
+ to: path.to.salesInvoices,
};
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
- view: "parts",
+ view: "invoicing",
});
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
- const [purchaseInvoice, purchaseInvoiceLines, purchaseInvoiceDelivery] =
+ const [salesInvoice, salesInvoiceLines, salesInvoiceShipment] =
await Promise.all([
- getPurchaseInvoice(client, invoiceId),
- getPurchaseInvoiceLines(client, invoiceId),
- getPurchaseInvoiceDelivery(client, invoiceId),
+ getSalesInvoice(client, invoiceId),
+ getSalesInvoiceLines(client, invoiceId),
+ getSalesInvoiceShipment(client, invoiceId),
]);
- if (purchaseInvoice.error) {
+ if (salesInvoice.error) {
throw redirect(
- path.to.purchaseInvoices,
+ path.to.salesInvoices,
await flash(
request,
- error(purchaseInvoice.error, "Failed to load purchase invoice")
+ error(salesInvoice.error, "Failed to load sales invoice")
)
);
}
- const [supplier, interaction] = await Promise.all([
- purchaseInvoice.data?.supplierId
- ? getSupplier(client, purchaseInvoice.data.supplierId)
+ const [customer, opportunity] = await Promise.all([
+ salesInvoice.data?.customerId
+ ? getCustomer(client, salesInvoice.data.customerId)
+ : null,
+ salesInvoice.data?.opportunityId
+ ? getOpportunity(client, salesInvoice.data.opportunityId)
: null,
- getSupplierInteraction(client, purchaseInvoice.data.supplierInteractionId!),
]);
return defer({
- purchaseInvoice: purchaseInvoice.data,
- purchaseInvoiceLines: purchaseInvoiceLines.data ?? [],
- purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,
- files: getSupplierInteractionDocuments(
+ salesInvoice: salesInvoice.data,
+ salesInvoiceLines: salesInvoiceLines.data ?? [],
+ salesInvoiceShipment: salesInvoiceShipment.data,
+ files: getOpportunityDocuments(
client,
companyId,
- purchaseInvoice.data.supplierInteractionId!
+ salesInvoice.data?.opportunityId!
),
- interaction: interaction.data,
- supplier: supplier?.data ?? null,
+ opportunity: opportunity?.data ?? null,
+ customer: customer?.data ?? null,
});
}
@@ -77,7 +80,7 @@ export async function action({ request }: ActionFunctionArgs) {
throw redirect(request.headers.get("Referer") ?? request.url);
}
-export default function PurchaseInvoiceRoute() {
+export default function SalesInvoiceRoute() {
const params = useParams();
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
@@ -85,11 +88,11 @@ export default function PurchaseInvoiceRoute() {
return (
<PanelProvider>
<div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
- <PurchaseInvoiceHeader />
+ <SalesInvoiceHeader />
<div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
<div className="flex flex-grow overflow-hidden">
<ResizablePanels
- explorer={<PurchaseInvoiceExplorer />}
+ explorer={<SalesInvoiceExplorer />}
content={
<div className="h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
<VStack spacing={2} className="p-2">
@@ -97,7 +100,7 @@ export default function PurchaseInvoiceRoute() {
</VStack>
</div>
}
- properties={<PurchaseInvoiceProperties />}
+ properties={<SalesInvoiceProperties />}
/>
</div>
</div>
diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
index 4ab2cfbcf8..55518fabc7 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost, error } from "@carbon/auth";
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
@@ -8,20 +8,20 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { useUrlParams, useUser } from "~/hooks";
import {
- PurchaseInvoiceForm,
- purchaseInvoiceValidator,
- upsertPurchaseInvoice,
+ createSalesInvoiceFromSalesOrder,
+ salesInvoiceValidator,
+ upsertSalesInvoice,
} from "~/modules/invoicing";
-import { createPurchaseInvoiceFromPurchaseOrder } from "~/modules/invoicing/invoicing.server";
+import SalesInvoiceForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm";
import { getNextSequence } from "~/modules/settings";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
export const handle: Handle = {
- breadcrumb: "Purchasing",
- to: path.to.purchasing,
- module: "purchasing",
+ breadcrumb: "Sales",
+ to: path.to.sales,
+ module: "sales",
};
export async function loader({ request }: LoaderFunctionArgs) {
@@ -37,9 +37,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
let result: FunctionsResponse<{ id: string }>;
switch (sourceDocument) {
- case "Purchase Order":
+ case "Sales Order":
if (!sourceDocumentId) throw new Error("Missing sourceDocumentId");
- result = await createPurchaseInvoiceFromPurchaseOrder(
+ result = await createSalesInvoiceFromSalesOrder(
+ getCarbonServiceRole(),
sourceDocumentId,
companyId,
userId
@@ -47,15 +48,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (result.error || !result?.data) {
throw redirect(
- request.headers.get("Referer") ?? path.to.purchaseOrders,
+ request.headers.get("Referer") ?? path.to.salesOrders,
await flash(
request,
- error(result.error, "Failed to create purchase invoice")
+ error(result.error, "Failed to create sales invoice")
)
);
}
- throw redirect(path.to.purchaseInvoice(result.data?.id!));
+ throw redirect(path.to.salesInvoice(result.data?.id!));
default:
return null;
@@ -69,22 +70,16 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(purchaseInvoiceValidator).validate(
- formData
- );
+ const validation = await validator(salesInvoiceValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
}
- const nextSequence = await getNextSequence(
- client,
- "purchaseInvoice",
- companyId
- );
+ const nextSequence = await getNextSequence(client, "salesInvoice", companyId);
if (nextSequence.error) {
throw redirect(
- path.to.newPurchaseInvoice,
+ path.to.newSalesInvoice,
await flash(
request,
error(nextSequence.error, "Failed to get next sequence")
@@ -94,7 +89,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const createPurchaseInvoice = await upsertPurchaseInvoice(client, {
+ const createSalesInvoice = await upsertSalesInvoice(client, {
...data,
invoiceId: nextSequence.data,
companyId,
@@ -102,37 +97,38 @@ export async function action({ request }: ActionFunctionArgs) {
customFields: setCustomFields(formData),
});
- if (createPurchaseInvoice.error || !createPurchaseInvoice.data?.[0]) {
+ if (createSalesInvoice.error || !createSalesInvoice.data?.[0]) {
+ console.error(createSalesInvoice.error);
throw redirect(
- path.to.purchaseInvoices,
+ path.to.salesInvoices,
await flash(
request,
- error(createPurchaseInvoice.error, "Failed to insert purchase invoice")
+ error(createSalesInvoice.error, "Failed to insert sales invoice")
)
);
}
- const invoice = createPurchaseInvoice.data?.[0];
+ const invoice = createSalesInvoice.data?.[0];
- throw redirect(path.to.purchaseInvoice(invoice?.id!));
+ throw redirect(path.to.salesInvoice(invoice?.id!));
}
-export default function PurchaseInvoiceNewRoute() {
+export default function SalesInvoiceNewRoute() {
const [params] = useUrlParams();
- const supplierId = params.get("supplierId");
+ const customerId = params.get("customerId");
const { defaults } = useUser();
const initialValues = {
id: undefined,
invoiceId: undefined,
- supplierId: supplierId ?? "",
+ customerId: customerId ?? "",
locationId: defaults?.locationId ?? "",
dateIssued: today(getLocalTimeZone()).toString(),
};
return (
<div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
- <PurchaseInvoiceForm initialValues={initialValues} />
+ <SalesInvoiceForm initialValues={initialValues} />
</div>
);
}
diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
index c431dc9537..0e75f13813 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
@@ -21,17 +21,17 @@ export async function action({ request }: ActionFunctionArgs) {
}
switch (field) {
- case "invoiceSupplierId":
+ case "invoiceCustomerId":
let currencyCode: string | undefined;
if (value && ids.length === 1) {
- const supplier = await client
- ?.from("supplier")
+ const customer = await client
+ ?.from("customer")
.select("currencyCode")
.eq("id", value)
.single();
- if (supplier.data?.currencyCode) {
- currencyCode = supplier.data.currencyCode;
+ if (customer.data?.currencyCode) {
+ currencyCode = customer.data.currencyCode;
const currency = await getCurrencyByCode(
client,
companyId,
@@ -40,11 +40,11 @@ export async function action({ request }: ActionFunctionArgs) {
// TODO: update delivery and payment terms
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
- invoiceSupplierId: value ?? undefined,
- invoiceSupplierContactId: null,
- invoiceSupplierLocationId: null,
+ invoiceCustomerId: value ?? undefined,
+ invoiceCustomerContactId: null,
+ invoiceCustomerLocationId: null,
currencyCode: currencyCode ?? undefined,
exchangeRate: currency.data?.exchangeRate ?? 1,
updatedBy: userId,
@@ -57,9 +57,9 @@ export async function action({ request }: ActionFunctionArgs) {
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
- supplierId: value ?? undefined,
+ customerId: value ?? undefined,
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
@@ -75,7 +75,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (paymentTerms.data) {
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
dateIssued: value,
dateDue: parseDate(value as string)
@@ -89,7 +89,7 @@ export async function action({ request }: ActionFunctionArgs) {
} else {
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
[field]: value ? value : null,
updatedBy: userId,
@@ -111,7 +111,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (currency.data) {
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
currencyCode: value as string,
exchangeRate: currency.data.exchangeRate ?? 1,
@@ -123,18 +123,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
// don't break -- just let it catch the next case
- case "supplierId":
- case "invoiceSupplierContactId":
- case "invoiceSupplierLocationId":
+ case "customerId":
+ case "invoiceCustomerContactId":
+ case "invoiceCustomerLocationId":
case "locationId":
- case "supplierReference":
+ case "customerReference":
case "paymentTermId":
case "exchangeRate":
case "dateDue":
case "datePaid":
return json(
await client
- .from("purchaseInvoice")
+ .from("salesInvoice")
.update({
[field]: value ? value : null,
updatedBy: userId,
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 77f85370b2..8e4c1ca417 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -281,6 +281,7 @@ export const path = {
bulkUpdatePurchaseInvoice: `${x}/purchase-invoice/update`,
bulkUpdateQuote: `${x}/quote/update`,
bulkUpdateReceiptLine: `${x}/receipt/lines/update`,
+ bulkUpdateSalesInvoice: `${x}/sales-invoice/update`,
bulkUpdateSalesOrder: `${x}/sales-order/update`,
bulkUpdateSalesRfq: `${x}/sales-rfq/update`,
bulkUpdateShipmentLine: `${x}/shipment/lines/update`,
@@ -804,6 +805,8 @@ export const path = {
generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/new`),
newReceipt: `${x}/receipt/new`,
newSalesInvoice: `${x}/sales-invoice/new`,
+ newSalesInvoiceLine: (id: string) =>
+ generatePath(`${x}/sales-invoice/${id}/new`),
newSalesOrder: `${x}/sales-order/new`,
newSalesOrderLine: (id: string) =>
generatePath(`${x}/sales-order/${id}/new`),
@@ -1021,8 +1024,12 @@ export const path = {
salesInvoice: (id: string) => generatePath(`${x}/sales-invoice/${id}`),
salesInvoiceDetails: (id: string) =>
generatePath(`${x}/sales-invoice/${id}/details`),
+ salesInvoiceExchangeRate: (id: string) =>
+ generatePath(`${x}/sales-invoice/${id}/exchange-rate`),
salesInvoiceLine: (id: string, lineId: string) =>
generatePath(`${x}/sales-invoice/${id}/${lineId}/details`),
+ salesInvoiceShipment: (id: string) =>
+ generatePath(`${x}/sales-invoice/${id}/shipment`),
salesInvoices: `${x}/sales/invoices`,
salesOrder: (id: string) => generatePath(`${x}/sales-order/${id}`),
salesOrderShipment: (id: string) =>
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 435a9e6afe..ae5ee6a685 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -26040,6 +26040,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLines.invoiceLineType",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLines.description",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLines.itemId",
},
@@ -26103,6 +26106,15 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLines.modelUploadId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLines.opportunityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLines.salesOrderId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLines.salesOrderLineId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLines.customFields",
},
@@ -48960,6 +48972,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.invoiceLineType",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.description",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.itemId",
},
@@ -49023,6 +49038,15 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.modelUploadId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.opportunityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderLineId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.customFields",
},
@@ -49109,6 +49133,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.invoiceLineType",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.description",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.itemId",
},
@@ -49172,6 +49199,15 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.modelUploadId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.opportunityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderLineId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.customFields",
},
@@ -49212,6 +49248,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.invoiceLineType",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.description",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.itemId",
},
@@ -49275,6 +49314,15 @@ export default {
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.modelUploadId",
},
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.opportunityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceLine.salesOrderLineId",
+ },
{
$ref: "#/parameters/rowFilter.salesInvoiceLine.customFields",
},
@@ -66505,6 +66553,10 @@ export default {
format: 'public."salesInvoiceLineType"',
type: "string",
},
+ description: {
+ format: "text",
+ type: "string",
+ },
itemId: {
description:
"Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
@@ -66595,6 +66647,24 @@ export default {
format: "text",
type: "string",
},
+ opportunityId: {
+ description:
+ "Note:\nThis is a Foreign Key to `opportunity.id`.<fk table='opportunity' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ salesOrderId: {
+ description:
+ "Note:\nThis is a Foreign Key to `salesOrder.id`.<fk table='salesOrder' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ salesOrderLineId: {
+ description:
+ "Note:\nThis is a Foreign Key to `salesOrderLine.id`.<fk table='salesOrderLine' column='id'/>",
+ format: "text",
+ type: "string",
+ },
customFields: {
format: "jsonb",
},
@@ -77643,6 +77713,10 @@ export default {
format: 'public."salesInvoiceLineType"',
type: "string",
},
+ description: {
+ format: "text",
+ type: "string",
+ },
itemId: {
description:
"Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
@@ -77740,6 +77814,24 @@ export default {
format: "text",
type: "string",
},
+ opportunityId: {
+ description:
+ "Note:\nThis is a Foreign Key to `opportunity.id`.<fk table='opportunity' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ salesOrderId: {
+ description:
+ "Note:\nThis is a Foreign Key to `salesOrder.id`.<fk table='salesOrder' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ salesOrderLineId: {
+ description:
+ "Note:\nThis is a Foreign Key to `salesOrderLine.id`.<fk table='salesOrderLine' column='id'/>",
+ format: "text",
+ type: "string",
+ },
customFields: {
format: "jsonb",
},
@@ -91523,6 +91615,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoiceLines.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoiceLines.itemId": {
name: "itemId",
required: false,
@@ -91649,6 +91747,24 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoiceLines.opportunityId": {
+ name: "opportunityId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLines.salesOrderId": {
+ name: "salesOrderId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLines.salesOrderLineId": {
+ name: "salesOrderLineId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoiceLines.customFields": {
name: "customFields",
required: false,
@@ -104135,6 +104251,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoiceLine.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoiceLine.itemId": {
name: "itemId",
required: false,
@@ -104261,6 +104383,24 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesInvoiceLine.opportunityId": {
+ name: "opportunityId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLine.salesOrderId": {
+ name: "salesOrderId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.salesInvoiceLine.salesOrderLineId": {
+ name: "salesOrderLineId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.salesInvoiceLine.customFields": {
name: "customFields",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index cf072f2216..fff9fc082b 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -23628,6 +23628,7 @@ export type Database = {
createdAt: string;
createdBy: string;
customFields: Json;
+ description: string | null;
exchangeRate: number;
externalNotes: Json;
id: string;
@@ -23638,7 +23639,10 @@ export type Database = {
itemReadableId: string | null;
locationId: string | null;
modelUploadId: string | null;
+ opportunityId: string | null;
quantity: number;
+ salesOrderId: string | null;
+ salesOrderLineId: string | null;
setupPrice: number;
shelfId: string | null;
shippingCost: number;
@@ -23660,6 +23664,7 @@ export type Database = {
createdAt?: string;
createdBy: string;
customFields?: Json;
+ description?: string | null;
exchangeRate?: number;
externalNotes?: Json;
id?: string;
@@ -23670,7 +23675,10 @@ export type Database = {
itemReadableId?: string | null;
locationId?: string | null;
modelUploadId?: string | null;
+ opportunityId?: string | null;
quantity?: number;
+ salesOrderId?: string | null;
+ salesOrderLineId?: string | null;
setupPrice?: number;
shelfId?: string | null;
shippingCost?: number;
@@ -23692,6 +23700,7 @@ export type Database = {
createdAt?: string;
createdBy?: string;
customFields?: Json;
+ description?: string | null;
exchangeRate?: number;
externalNotes?: Json;
id?: string;
@@ -23702,7 +23711,10 @@ export type Database = {
itemReadableId?: string | null;
locationId?: string | null;
modelUploadId?: string | null;
+ opportunityId?: string | null;
quantity?: number;
+ salesOrderId?: string | null;
+ salesOrderLineId?: string | null;
setupPrice?: number;
shelfId?: string | null;
shippingCost?: number;
@@ -23853,6 +23865,48 @@ export type Database = {
referencedRelation: "tools";
referencedColumns: ["modelId"];
},
+ {
+ foreignKeyName: "salesInvoiceLine_opportunityId_fkey";
+ columns: ["opportunityId"];
+ isOneToOne: false;
+ referencedRelation: "opportunity";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLine";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLines";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "salesInvoiceLine_shelfId_fkey";
columns: ["shelfId"];
@@ -38859,6 +38913,7 @@ export type Database = {
createdBy: string | null;
customerPartId: string | null;
customFields: Json | null;
+ description: string | null;
exchangeRate: number | null;
externalNotes: Json | null;
id: string | null;
@@ -38873,7 +38928,10 @@ export type Database = {
itemReadableId: string | null;
locationId: string | null;
modelUploadId: string | null;
+ opportunityId: string | null;
quantity: number | null;
+ salesOrderId: string | null;
+ salesOrderLineId: string | null;
setupPrice: number | null;
shelfId: string | null;
shippingCost: number | null;
@@ -39026,6 +39084,48 @@ export type Database = {
referencedRelation: "tools";
referencedColumns: ["modelId"];
},
+ {
+ foreignKeyName: "salesInvoiceLine_opportunityId_fkey";
+ columns: ["opportunityId"];
+ isOneToOne: false;
+ referencedRelation: "opportunity";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLine";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLines";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "salesInvoiceLine_shelfId_fkey";
columns: ["shelfId"];
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 3ff9986165..dc9cb9d140 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -137,3 +137,25 @@ entrypoint = "./functions/sync/index.ts"
# Specifies static files to be bundled with the function. Supports glob patterns.
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/sync/*.html" ]
+
+[functions.post-sales-invoice]
+enabled = true
+verify_jwt = true
+import_map = "./functions/post-sales-invoice/deno.json"
+# Uncomment to specify a custom file path to the entrypoint.
+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
+entrypoint = "./functions/post-sales-invoice/index.ts"
+# Specifies static files to be bundled with the function. Supports glob patterns.
+# For example, if you want to serve static HTML pages in your function:
+# static_files = [ "./functions/post-sales-invoice/*.html" ]
+
+[functions.update-sales-prices]
+enabled = true
+verify_jwt = true
+import_map = "./functions/update-sales-prices/deno.json"
+# Uncomment to specify a custom file path to the entrypoint.
+# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
+entrypoint = "./functions/update-sales-prices/index.ts"
+# Specifies static files to be bundled with the function. Supports glob patterns.
+# For example, if you want to serve static HTML pages in your function:
+# static_files = [ "./functions/update-sales-prices/*.html" ]
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index c114836073..00dc1d1b79 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -51,6 +51,12 @@ const payloadValidator = z.discriminatedUnion("type", [
digitalQuoteAcceptedBy: z.string().optional(),
digitalQuoteAcceptedByEmail: z.string().optional(),
}),
+ z.object({
+ type: z.literal("salesOrderToSalesInvoice"),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("supplierQuoteToPurchaseOrder"),
id: z.string(),
@@ -484,6 +490,9 @@ serve(async (req: Request) => {
convertedId = insertedSalesOrderId;
break;
}
+ case "salesOrderToSalesInvoice": {
+ throw new Error("Not implemented");
+ }
case "salesRfqToQuote": {
const [salesRfq, salesRfqLines] = await Promise.all([
client.from("salesRfq").select("*").eq("id", id).single(),
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index cf072f2216..fff9fc082b 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -23628,6 +23628,7 @@ export type Database = {
createdAt: string;
createdBy: string;
customFields: Json;
+ description: string | null;
exchangeRate: number;
externalNotes: Json;
id: string;
@@ -23638,7 +23639,10 @@ export type Database = {
itemReadableId: string | null;
locationId: string | null;
modelUploadId: string | null;
+ opportunityId: string | null;
quantity: number;
+ salesOrderId: string | null;
+ salesOrderLineId: string | null;
setupPrice: number;
shelfId: string | null;
shippingCost: number;
@@ -23660,6 +23664,7 @@ export type Database = {
createdAt?: string;
createdBy: string;
customFields?: Json;
+ description?: string | null;
exchangeRate?: number;
externalNotes?: Json;
id?: string;
@@ -23670,7 +23675,10 @@ export type Database = {
itemReadableId?: string | null;
locationId?: string | null;
modelUploadId?: string | null;
+ opportunityId?: string | null;
quantity?: number;
+ salesOrderId?: string | null;
+ salesOrderLineId?: string | null;
setupPrice?: number;
shelfId?: string | null;
shippingCost?: number;
@@ -23692,6 +23700,7 @@ export type Database = {
createdAt?: string;
createdBy?: string;
customFields?: Json;
+ description?: string | null;
exchangeRate?: number;
externalNotes?: Json;
id?: string;
@@ -23702,7 +23711,10 @@ export type Database = {
itemReadableId?: string | null;
locationId?: string | null;
modelUploadId?: string | null;
+ opportunityId?: string | null;
quantity?: number;
+ salesOrderId?: string | null;
+ salesOrderLineId?: string | null;
setupPrice?: number;
shelfId?: string | null;
shippingCost?: number;
@@ -23853,6 +23865,48 @@ export type Database = {
referencedRelation: "tools";
referencedColumns: ["modelId"];
},
+ {
+ foreignKeyName: "salesInvoiceLine_opportunityId_fkey";
+ columns: ["opportunityId"];
+ isOneToOne: false;
+ referencedRelation: "opportunity";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLine";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLines";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "salesInvoiceLine_shelfId_fkey";
columns: ["shelfId"];
@@ -38859,6 +38913,7 @@ export type Database = {
createdBy: string | null;
customerPartId: string | null;
customFields: Json | null;
+ description: string | null;
exchangeRate: number | null;
externalNotes: Json | null;
id: string | null;
@@ -38873,7 +38928,10 @@ export type Database = {
itemReadableId: string | null;
locationId: string | null;
modelUploadId: string | null;
+ opportunityId: string | null;
quantity: number | null;
+ salesOrderId: string | null;
+ salesOrderLineId: string | null;
setupPrice: number | null;
shelfId: string | null;
shippingCost: number | null;
@@ -39026,6 +39084,48 @@ export type Database = {
referencedRelation: "tools";
referencedColumns: ["modelId"];
},
+ {
+ foreignKeyName: "salesInvoiceLine_opportunityId_fkey";
+ columns: ["opportunityId"];
+ isOneToOne: false;
+ referencedRelation: "opportunity";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrder";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLocations";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderId_fkey";
+ columns: ["salesOrderId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrders";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLine";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "salesInvoiceLine_salesOrderLineId_fkey";
+ columns: ["salesOrderLineId"];
+ isOneToOne: false;
+ referencedRelation: "salesOrderLines";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "salesInvoiceLine_shelfId_fkey";
columns: ["shelfId"];
diff --git a/packages/database/supabase/functions/post-sales-invoice/.npmrc b/packages/database/supabase/functions/post-sales-invoice/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/post-sales-invoice/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/post-sales-invoice/deno.json b/packages/database/supabase/functions/post-sales-invoice/deno.json
new file mode 100644
index 0000000000..f6ca8454c5
--- /dev/null
+++ b/packages/database/supabase/functions/post-sales-invoice/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
new file mode 100644
index 0000000000..77180dad0e
--- /dev/null
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -0,0 +1,1168 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import z from "npm:zod@^3.24.1";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+import type { Database } from "../lib/types.ts";
+import { credit, debit, journalReference } from "../lib/utils.ts";
+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { getNextSequence } from "../shared/get-next-sequence.ts";
+import {
+ getInventoryPostingGroup,
+ getSalesPostingGroup,
+} from "../shared/get-posting-group.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.object({
+ invoiceId: z.string(),
+ userId: z.string(),
+ companyId: z.string(),
+});
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ const payload = await req.json();
+ const today = format(new Date(), "yyyy-MM-dd");
+
+ try {
+ const { invoiceId, userId, companyId } = payloadValidator.parse(payload);
+
+ console.log({
+ function: "post-sales-invoice",
+ invoiceId,
+ userId,
+ });
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ companyId
+ );
+
+ const [salesInvoice, salesInvoiceLines, salesInvoiceShipment] =
+ await Promise.all([
+ client.from("salesInvoice").select("*").eq("id", invoiceId).single(),
+ client.from("salesInvoiceLine").select("*").eq("invoiceId", invoiceId),
+ client
+ .from("salesInvoiceShipment")
+ .select("customerShippingCost")
+ .eq("id", invoiceId)
+ .single(),
+ ]);
+
+ if (salesInvoice.error) throw new Error("Failed to fetch salesInvoice");
+ if (salesInvoiceLines.error)
+ throw new Error("Failed to fetch shipment lines");
+ if (salesInvoiceShipment.error)
+ throw new Error("Failed to fetch sales invoice shipment");
+
+ const shippingCost =
+ (salesInvoiceShipment.data?.shippingCost ?? 0) *
+ (salesInvoice.data?.exchangeRate ?? 1);
+
+ const totalLinesCost = salesInvoiceLines.data.reduce((acc, invoiceLine) => {
+ const lineCost =
+ (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
+ (invoiceLine.shippingCost ?? 0) +
+ (invoiceLine.addOnCost ?? 0);
+ return acc + lineCost;
+ }, 0);
+
+ const itemIds = salesInvoiceLines.data.reduce<string[]>(
+ (acc, invoiceLine) => {
+ if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {
+ acc.push(invoiceLine.itemId);
+ }
+ return acc;
+ },
+ []
+ );
+
+ const [items, itemCosts, salesOrderLines, customer] = await Promise.all([
+ client
+ .from("item")
+ .select("id, itemTrackingType, readableId")
+ .in("id", itemIds)
+ .eq("companyId", companyId),
+ client
+ .from("itemCost")
+ .select("itemId, itemPostingGroupId")
+ .in("itemId", itemIds),
+ client
+ .from("salesOrderLine")
+ .select("*")
+ .in(
+ "id",
+ salesInvoiceLines.data.reduce<string[]>((acc, invoiceLine) => {
+ if (
+ invoiceLine.salesOrderLineId &&
+ !acc.includes(invoiceLine.salesOrderLineId)
+ ) {
+ acc.push(invoiceLine.salesOrderLineId);
+ }
+ return acc;
+ }, [])
+ ),
+ client
+ .from("customer")
+ .select("*")
+ .eq("id", salesInvoice.data.customerId ?? "")
+ .eq("companyId", companyId)
+ .single(),
+ ]);
+ if (items.error) throw new Error("Failed to fetch items");
+ if (itemCosts.error) throw new Error("Failed to fetch item costs");
+ if (salesOrderLines.error)
+ throw new Error("Failed to fetch sales order lines");
+ if (customer.error) throw new Error("Failed to fetch customer");
+
+ const salesOrders = await client
+ .from("salesOrder")
+ .select("*")
+ .in(
+ "salesOrderId",
+ salesOrderLines.data.reduce<string[]>((acc, salesOrderLine) => {
+ if (
+ salesOrderLine.salesOrderId &&
+ !acc.includes(salesOrderLine.salesOrderId)
+ ) {
+ acc.push(salesOrderLine.salesOrderId);
+ }
+ return acc;
+ }, [])
+ )
+ .eq("companyId", companyId);
+
+ if (salesOrders.error) throw new Error("Failed to fetch sales orders");
+
+ const costLedgerInserts: Database["public"]["Tables"]["costLedger"]["Insert"][] =
+ [];
+
+ const journalLineInserts: Omit<
+ Database["public"]["Tables"]["journalLine"]["Insert"],
+ "journalId"
+ >[] = [];
+
+ const shipmentLineInserts: Omit<
+ Database["public"]["Tables"]["shipmentLine"]["Insert"],
+ "shipmentId"
+ >[] = [];
+
+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =
+ [];
+
+ const salesInvoiceLinesBySalesOrderLine = salesInvoiceLines.data.reduce<
+ Record<string, Database["public"]["Tables"]["salesInvoiceLine"]["Row"]>
+ >((acc, invoiceLine) => {
+ if (invoiceLine.salesOrderLineId) {
+ acc[invoiceLine.salesOrderLineId] = invoiceLine;
+ }
+ return acc;
+ }, {});
+
+ const salesOrderLineUpdates = salesOrderLines.data.reduce<
+ Record<string, Database["public"]["Tables"]["salesOrderLine"]["Update"]>
+ >((acc, salesOrderLine) => {
+ const invoiceLine = salesInvoiceLinesBySalesOrderLine[salesOrderLine.id];
+ if (
+ invoiceLine &&
+ invoiceLine.quantity &&
+ salesOrderLine.saleQuantity &&
+ salesOrderLine.saleQuantity > 0
+ ) {
+ const newQuantityInvoiced =
+ (salesOrderLine.quantityInvoiced ?? 0) + invoiceLine.quantity;
+
+ const invoicedComplete =
+ salesOrderLine.invoicedComplete ||
+ invoiceLine.quantity >=
+ (salesOrderLine.quantityToInvoice ?? salesOrderLine.saleQuantity);
+
+ return {
+ ...acc,
+ [salesOrderLine.id]: {
+ quantityInvoiced: newQuantityInvoiced,
+ invoicedComplete,
+ salesOrderId: salesOrderLine.salesOrderId,
+ },
+ };
+ }
+
+ return acc;
+ }, {});
+
+ const journalLines = await client
+ .from("journalLine")
+ .select("*")
+ .in(
+ "documentLineReference",
+ salesOrderLines.data.reduce<string[]>((acc, salesOrderLine) => {
+ if (
+ (salesOrderLine.quantitySent ?? 0) >
+ (salesOrderLine.quantityInvoiced ?? 0)
+ ) {
+ acc.push(journalReference.to.shipment(salesOrderLine.id));
+ }
+ return acc;
+ }, [])
+ )
+ .eq("companyId", companyId);
+ if (journalLines.error) {
+ throw new Error("Failed to fetch journal entries to reverse");
+ }
+
+ const journalLinesBySalesOrderLine = journalLines.data.reduce<
+ Record<string, Database["public"]["Tables"]["journalLine"]["Row"][]>
+ >((acc, journalEntry) => {
+ const [type, salesOrderLineId] = (
+ journalEntry.documentLineReference ?? ""
+ ).split(":");
+ if (type === "shipment") {
+ if (acc[salesOrderLineId] && Array.isArray(acc[salesOrderLineId])) {
+ acc[salesOrderLineId].push(journalEntry);
+ } else {
+ acc[salesOrderLineId] = [journalEntry];
+ }
+ }
+ return acc;
+ }, {});
+
+ // save the posting groups in memory to avoid unnecessary queries
+ const inventoryPostingGroups: Record<
+ string,
+ Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
+ > = {};
+
+ for await (const invoiceLine of salesInvoiceLines.data) {
+ const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;
+
+ const totalLineCost =
+ (invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
+ (invoiceLine.shippingCost ?? 0) +
+ (invoiceLine.addOnCost ?? 0)) *
+ (1 + (invoiceLine.taxRate ?? 0));
+
+ const lineCostPercentageOfTotalCost =
+ totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;
+ const lineWeightedShippingCost =
+ shippingCost * lineCostPercentageOfTotalCost;
+ const totalLineCostWithWeightedShipping =
+ totalLineCost + lineWeightedShippingCost;
+
+ const invoiceLineUnitCostInInventoryUnit =
+ totalLineCostWithWeightedShipping / invoiceLine.quantity;
+
+ // declaring shared variables between part and service cases
+ // outside of the switch case to avoid redeclaring them
+ let postingGroupInventory:
+ | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
+ | null = null;
+
+ let itemPostingGroupId: string | null = null;
+
+ // sales posting group
+ const salesPostingGroups: Record<
+ string,
+ Database["public"]["Tables"]["postingGroupSales"]["Row"] | null
+ > = {};
+
+ let postingGroupSales:
+ | Database["public"]["Tables"]["postingGroupSales"]["Row"]
+ | null = null;
+
+ const locationId = invoiceLine.locationId ?? null;
+ const customerTypeId: string | null =
+ customer.data.customerTypeId ?? null;
+
+ let journalLineReference: string;
+
+ switch (invoiceLine.invoiceLineType) {
+ case "Part":
+ case "Service":
+ case "Consumable":
+ case "Fixture":
+ case "Material":
+ case "Tool":
+ {
+ const itemTrackingType =
+ items.data.find((item) => item.id === invoiceLine.itemId)
+ ?.itemTrackingType ?? "Inventory";
+
+ itemPostingGroupId =
+ itemCosts.data.find((item) => item.itemId === invoiceLine.itemId)
+ ?.itemPostingGroupId ?? null;
+
+ // inventory posting group
+ if (
+ `${itemPostingGroupId}-${locationId}` in inventoryPostingGroups
+ ) {
+ postingGroupInventory =
+ inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`];
+ } else {
+ const inventoryPostingGroup = await getInventoryPostingGroup(
+ client,
+ companyId,
+ {
+ itemPostingGroupId,
+ locationId,
+ }
+ );
+
+ if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
+ throw new Error("Error getting inventory posting group");
+ }
+
+ postingGroupInventory = inventoryPostingGroup.data ?? null;
+ inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`] =
+ postingGroupInventory;
+ }
+
+ if (!postingGroupInventory) {
+ throw new Error("No inventory posting group found");
+ }
+
+ if (
+ `${itemPostingGroupId}-${customerTypeId}` in salesPostingGroups
+ ) {
+ postingGroupSales =
+ salesPostingGroups[`${itemPostingGroupId}-${customerTypeId}`];
+ } else {
+ const salesPostingGroup = await getSalesPostingGroup(
+ client,
+ companyId,
+ {
+ itemPostingGroupId,
+ customerTypeId,
+ }
+ );
+
+ if (salesPostingGroup.error || !salesPostingGroup.data) {
+ throw new Error("Error getting sales posting group");
+ }
+
+ postingGroupSales = salesPostingGroup.data ?? null;
+ salesPostingGroups[`${itemPostingGroupId}-${customerTypeId}`] =
+ postingGroupSales;
+ }
+
+ if (!postingGroupSales) {
+ throw new Error("No sales posting group found");
+ }
+
+ // if the sales order line is null, we receive the part, do the normal entries and do not use accrual/reversing
+ if (invoiceLine.salesOrderLineId === null) {
+ // create the shipment line
+ shipmentLineInserts.push({
+ itemId: invoiceLine.itemId!,
+ lineId: invoiceLine.id,
+ orderQuantity: invoiceLineQuantityInInventoryUnit,
+ outstandingQuantity: invoiceLineQuantityInInventoryUnit,
+ shippedQuantity: invoiceLineQuantityInInventoryUnit,
+ locationId: invoiceLine.locationId,
+ shelfId: invoiceLine.shelfId,
+ unitOfMeasure: invoiceLine.unitOfMeasureCode ?? "EA",
+ unitPrice: invoiceLine.unitPrice ?? 0,
+ createdBy: invoiceLine.createdBy,
+ companyId,
+ });
+
+ if (itemTrackingType === "Inventory") {
+ // create the part ledger line
+ itemLedgerInserts.push({
+ postingDate: today,
+ itemId: invoiceLine.itemId!,
+ itemReadableId: invoiceLine.itemReadableId!,
+ quantity: invoiceLineQuantityInInventoryUnit,
+ locationId: invoiceLine.locationId,
+ shelfId: invoiceLine.shelfId,
+ entryType: "Positive Adjmt.",
+ documentType: "Sales Receipt",
+ documentId: salesInvoice.data?.id ?? undefined,
+ externalDocumentId:
+ salesInvoice.data?.customerReference ?? undefined,
+ createdBy: userId,
+ companyId,
+ });
+ }
+
+ // create the cost ledger line
+ costLedgerInserts.push({
+ itemLedgerType: "Sales",
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: "Sales Invoice",
+ documentId: salesInvoice.data?.id ?? undefined,
+ externalDocumentId:
+ salesInvoice.data?.customerReference ?? undefined,
+ itemId: invoiceLine.itemId,
+ quantity: invoiceLineQuantityInInventoryUnit,
+ nominalCost:
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
+ cost: totalLineCostWithWeightedShipping,
+ customerId: salesInvoice.data?.customerId,
+ companyId,
+ });
+
+ // create the normal GL entries for a part
+
+ journalLineReference = nanoid();
+
+ if (itemTrackingType === "Inventory") {
+ // debit the inventory account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.inventoryAccount,
+ description: "Inventory Account",
+ amount: debit("asset", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ journalLineReference,
+ companyId,
+ });
+
+ // creidt the direct cost applied account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.directCostAppliedAccount,
+ description: "Direct Cost Applied",
+ amount: credit("expense", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ journalLineReference,
+ companyId,
+ });
+ } else {
+ // debit the overhead account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.overheadAccount,
+ description: "Overhead Account",
+ amount: debit("asset", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ journalLineReference,
+ companyId,
+ });
+
+ // creidt the overhead cost applied account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.overheadCostAppliedAccount,
+ description: "Overhead Cost Applied",
+ amount: credit("expense", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ journalLineReference,
+ companyId,
+ });
+ }
+
+ journalLineReference = nanoid();
+
+ // debit the sales account
+ journalLineInserts.push({
+ accountNumber: postingGroupSales.salesAccount,
+ description: "Sales Account",
+ amount: debit("expense", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // credit the accounts payable account
+ journalLineInserts.push({
+ accountNumber: postingGroupSales.payablesAccount,
+ description: "Accounts Payable",
+ amount: credit("liability", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ } // if the line is associated with a sales order line, we do accrual/reversing
+ else {
+ // create the cost entry
+ costLedgerInserts.push({
+ itemLedgerType: "Sales",
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: "Sales Invoice",
+ documentId: salesInvoice.data?.id ?? undefined,
+ externalDocumentId:
+ salesInvoice.data?.customerReference ?? undefined,
+ itemId: invoiceLine.itemId,
+ quantity: invoiceLineQuantityInInventoryUnit,
+ nominalCost:
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
+ cost: totalLineCostWithWeightedShipping,
+ customerId: salesInvoice.data?.customerId,
+ companyId,
+ });
+
+ // determine the journal lines that should be reversed
+ const existingJournalLines = invoiceLine.salesOrderLineId
+ ? journalLinesBySalesOrderLine[invoiceLine.salesOrderLineId] ??
+ []
+ : [];
+
+ let previousJournalId: number | null = null;
+ let previousAccrual: boolean | null = null;
+ let currentGroup = 0;
+
+ const existingJournalLineGroups = existingJournalLines.reduce<
+ Database["public"]["Tables"]["journalLine"]["Row"][][]
+ >((acc, entry) => {
+ const { journalId, accrual } = entry;
+
+ if (
+ journalId === previousJournalId &&
+ accrual === previousAccrual
+ ) {
+ acc[currentGroup - 1].push(entry);
+ } else {
+ acc.push([entry]);
+ currentGroup++;
+ }
+
+ previousJournalId = journalId;
+ previousAccrual = accrual;
+ return acc;
+ }, []);
+
+ const salesOrderLine = salesOrderLines.data.find(
+ (line) => line.id === invoiceLine.salesOrderLineId
+ );
+
+ const isOutsideProcessing = !!salesOrderLine?.jobOperationId;
+
+ const quantitySent =
+ (salesOrderLine?.quantitySent ?? 0) *
+ (salesOrderLine?.conversionFactor ?? 1);
+
+ const quantityInvoiced =
+ (salesOrderLine?.quantityInvoiced ?? 0) *
+ (salesOrderLine?.conversionFactor ?? 1);
+
+ const quantityToReverse = Math.max(
+ 0,
+ Math.min(
+ invoiceLineQuantityInInventoryUnit,
+ quantitySent - quantityInvoiced
+ )
+ );
+
+ const quantityAlreadyReversed =
+ quantitySent > quantityInvoiced ? quantityInvoiced : 0;
+
+ if (quantityToReverse > 0) {
+ let quantityCounted = 0;
+ let quantityReversed = 0;
+
+ existingJournalLineGroups.forEach((entry) => {
+ if (entry[0].quantity) {
+ const unitCostForEntry =
+ (entry[0].amount ?? 0) / entry[0].quantity;
+
+ // we don't want to reverse an entry twice, so we need to keep track of what's been previously reversed
+
+ // akin to supply
+ const quantityAvailableToReverseForEntry =
+ quantityAlreadyReversed > quantityCounted
+ ? entry[0].quantity +
+ quantityCounted -
+ quantityAlreadyReversed
+ : entry[0].quantity;
+
+ // akin to demand
+ const quantityRequiredToReverse =
+ quantityToReverse - quantityReversed;
+
+ // we can't reverse more than what's available or what's required
+ const quantityToReverseForEntry = Math.max(
+ 0,
+ Math.min(
+ quantityAvailableToReverseForEntry,
+ quantityRequiredToReverse
+ )
+ );
+
+ if (quantityToReverseForEntry > 0) {
+ journalLineReference = nanoid();
+
+ // create the reversal entries
+ journalLineInserts.push({
+ accountNumber: entry[0].accountNumber!,
+ description: entry[0].description,
+ amount:
+ entry[0].description === "Interim Inventory Accrual"
+ ? credit(
+ "asset",
+ quantityToReverseForEntry * unitCostForEntry
+ )
+ : debit(
+ "liability",
+ quantityToReverseForEntry * unitCostForEntry
+ ),
+ quantity: quantityToReverseForEntry,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId:
+ salesInvoice?.data.customerReference,
+ documentLineReference: invoiceLine.salesOrderLineId
+ ? journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId
+ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+
+ journalLineInserts.push({
+ accountNumber: entry[1].accountNumber!,
+ description: entry[1].description,
+ amount:
+ entry[1].description === "Interim Inventory Accrual"
+ ? credit(
+ "asset",
+ quantityToReverseForEntry * unitCostForEntry
+ )
+ : debit(
+ "liability",
+ quantityToReverseForEntry * unitCostForEntry
+ ),
+ quantity: quantityToReverseForEntry,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId:
+ salesInvoice?.data.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ }
+
+ quantityCounted += entry[0].quantity;
+ quantityReversed += quantityToReverseForEntry;
+ }
+ });
+
+ // create the normal GL entries for a part
+
+ journalLineReference = nanoid();
+
+ if (itemTrackingType !== "Non-Inventory") {
+ // debit the inventory account
+ journalLineInserts.push({
+ accountNumber: isOutsideProcessing
+ ? postingGroupInventory.workInProgressAccount
+ : postingGroupInventory.inventoryAccount,
+ description: isOutsideProcessing
+ ? "WIP Account"
+ : "Inventory Account",
+ amount: debit(
+ "asset",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // creidt the direct cost applied account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.directCostAppliedAccount,
+ description: "Direct Cost Applied",
+ amount: credit(
+ "expense",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ } else {
+ // debit the overhead account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.overheadAccount,
+ description: "Overhead Account",
+ amount: debit(
+ "asset",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // creidt the overhead cost applied account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.overheadCostAppliedAccount,
+ description: "Overhead Cost Applied",
+ amount: credit(
+ "expense",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ }
+
+ journalLineReference = nanoid();
+
+ // debit the sales account
+ journalLineInserts.push({
+ accountNumber: postingGroupSales.salesAccount,
+ description: "Sales Account",
+ amount: debit(
+ "expense",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // credit the accounts payable account
+ journalLineInserts.push({
+ accountNumber: postingGroupSales.payablesAccount,
+ description: "Accounts Payable",
+ amount: credit(
+ "liability",
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ }
+
+ if (invoiceLineQuantityInInventoryUnit > quantityToReverse) {
+ // create the accrual entries for invoiced not received
+ const quantityToAccrue =
+ invoiceLineQuantityInInventoryUnit - quantityToReverse;
+
+ journalLineReference = nanoid();
+
+ // debit the inventory invoiced not received account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInvoicedNotReceivedAccount,
+ description: "Inventory Invoiced Not Received",
+ accrual: true,
+ amount: debit(
+ "asset",
+ quantityToAccrue * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: invoiceLine.salesOrderLineId
+ ? journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId
+ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+
+ // credit the inventory interim accrual account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInterimAccrualAccount,
+ accrual: true,
+ description: "Interim Inventory Accrual",
+ amount: credit(
+ "asset",
+ quantityToAccrue * invoiceLineUnitCostInInventoryUnit
+ ),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: invoiceLine.salesOrderLineId
+ ? journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId
+ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+ }
+ }
+ }
+
+ break;
+ case "Fixed Asset":
+ // TODO: fixed assets
+ break;
+ case "Comment":
+ break;
+ case "G/L Account": {
+ const [account, accountDefaults] = await Promise.all([
+ client
+ .from("accounts")
+ .select("name, number, directPosting")
+ .eq("number", invoiceLine.accountNumber ?? "")
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("accountDefault")
+ .select(
+ "overheadCostAppliedAccount, payablesAccount, salesAccount"
+ )
+ .eq("companyId", companyId)
+ .single(),
+ ]);
+ if (account.error || !account.data)
+ throw new Error("Failed to fetch account");
+ if (!account.data.directPosting)
+ throw new Error("Account is not a direct posting account");
+
+ if (accountDefaults.error || !accountDefaults.data)
+ throw new Error("Failed to fetch account defaults");
+
+ journalLineReference = nanoid();
+
+ // debit the G/L account
+ journalLineInserts.push({
+ accountNumber: account.data.number!,
+ description: account.data.name!,
+ // we limit the account to assets and expenses in the UI, so we don't need to check here
+ amount: debit("asset", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // credit the direct cost applied account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.overheadCostAppliedAccount!,
+ description: "Overhead Cost Applied",
+ amount: credit("expense", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ journalLineReference = nanoid();
+
+ // debit the sales account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.salesAccount!,
+ description: "Sales Account",
+ amount: debit("expense", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+
+ // credit the accounts payable account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.payablesAccount!,
+ description: "Accounts Payable",
+ amount: credit("liability", totalLineCostWithWeightedShipping),
+ quantity: invoiceLineQuantityInInventoryUnit,
+ documentType: "Invoice",
+ documentId: salesInvoice.data?.id,
+ externalDocumentId: salesInvoice.data?.customerReference,
+ documentLineReference: journalReference.to.salesInvoice(
+ invoiceLine.salesOrderLineId!
+ ),
+ journalLineReference,
+ companyId,
+ });
+ break;
+ }
+ default:
+ throw new Error("Unsupported invoice line type");
+ }
+ }
+
+ const accountingPeriodId = await getCurrentAccountingPeriod(
+ client,
+ companyId,
+ db
+ );
+
+ await db.transaction().execute(async (trx) => {
+ if (shipmentLineInserts.length > 0) {
+ const shipmentLinesGroupedByLocationId = shipmentLineInserts.reduce<
+ Record<string, typeof shipmentLineInserts>
+ >((acc, line) => {
+ if (line.locationId) {
+ if (line.locationId in acc) {
+ acc[line.locationId].push(line);
+ } else {
+ acc[line.locationId] = [line];
+ }
+ }
+
+ return acc;
+ }, {});
+
+ for await (const [locationId, shipmentLines] of Object.entries(
+ shipmentLinesGroupedByLocationId
+ )) {
+ const readableReceiptId = await getNextSequence(
+ trx,
+ "shipment",
+ companyId
+ );
+ const shipment = await trx
+ .insertInto("shipment")
+ .values({
+ shipmentId: readableReceiptId,
+ locationId,
+ sourceDocument: "Sales Invoice",
+ sourceDocumentId: salesInvoice.data.id,
+ sourceDocumentReadableId: salesInvoice.data.invoiceId,
+ externalDocumentId: salesInvoice.data.customerReference,
+ customerId: salesInvoice.data.customerId,
+ status: "Posted",
+ postingDate: today,
+ postedBy: userId,
+ invoiced: true,
+ companyId,
+ createdBy: salesInvoice.data.createdBy,
+ })
+ .returning(["id"])
+ .execute();
+
+ const shipmentId = shipment[0].id;
+ if (!shipmentId) throw new Error("Failed to insert shipment");
+
+ await trx
+ .insertInto("shipmentLine")
+ .values(
+ shipmentLines.map((r) => ({
+ ...r,
+ shipmentId: shipmentId,
+ }))
+ )
+ .returning(["id"])
+ .execute();
+ }
+ }
+
+ for await (const [salesOrderLineId, update] of Object.entries(
+ salesOrderLineUpdates
+ )) {
+ await trx
+ .updateTable("salesOrderLine")
+ .set(update)
+ .where("id", "=", salesOrderLineId)
+ .execute();
+ }
+
+ const salesOrdersUpdated = Object.values(salesOrderLineUpdates).reduce<
+ string[]
+ >((acc, update) => {
+ if (update.salesOrderId && !acc.includes(update.salesOrderId)) {
+ acc.push(update.salesOrderId);
+ }
+ return acc;
+ }, []);
+
+ for await (const salesOrderId of salesOrdersUpdated) {
+ const salesOrderLines = await trx
+ .selectFrom("salesOrderLine")
+ .select([
+ "id",
+ "salesOrderLineType",
+ "invoicedComplete",
+ "receivedComplete",
+ ])
+ .where("salesOrderId", "=", salesOrderId)
+ .execute();
+
+ const areAllLinesInvoiced = salesOrderLines.every(
+ (line) =>
+ line.salesOrderLineType === "Comment" || line.invoicedComplete
+ );
+
+ const areAllLinesReceived = salesOrderLines.every(
+ (line) =>
+ line.salesOrderLineType === "Comment" || line.receivedComplete
+ );
+
+ let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
+ "To Receive and Invoice";
+
+ if (areAllLinesInvoiced && areAllLinesReceived) {
+ status = "Completed";
+ } else if (areAllLinesInvoiced) {
+ status = "To Receive";
+ } else if (areAllLinesReceived) {
+ status = "To Invoice";
+ }
+
+ await trx
+ .updateTable("salesOrder")
+ .set({
+ status,
+ })
+ .where("id", "=", salesOrderId)
+ .execute();
+ }
+
+ const journal = await trx
+ .insertInto("journal")
+ .values({
+ accountingPeriodId,
+ description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,
+ postingDate: today,
+ companyId,
+ })
+ .returning(["id"])
+ .execute();
+
+ const journalId = journal[0].id;
+ if (!journalId) throw new Error("Failed to insert journal");
+
+ await trx
+ .insertInto("journalLine")
+ .values(
+ journalLineInserts.map((journalLine) => ({
+ ...journalLine,
+ journalId,
+ }))
+ )
+ .returning(["id"])
+ .execute();
+
+ if (itemLedgerInserts.length > 0) {
+ await trx
+ .insertInto("itemLedger")
+ .values(itemLedgerInserts)
+ .returning(["id"])
+ .execute();
+ }
+
+ if (costLedgerInserts.length > 0) {
+ await trx
+ .insertInto("costLedger")
+ .values(costLedgerInserts)
+ .returning(["id"])
+ .execute();
+ }
+
+ await trx
+ .updateTable("salesInvoice")
+ .set({
+ datePaid: today, // TODO: remove this once we have payments working
+ postingDate: today,
+ status: "Submitted",
+ })
+ .where("id", "=", invoiceId)
+ .execute();
+ });
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ if ("invoiceId" in payload) {
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key") ?? "",
+ payload.companyId
+ );
+ await client
+ .from("salesInvoice")
+ .update({ status: "Draft" })
+ .eq("id", payload.invoiceId);
+ }
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/functions/update-sales-prices/.npmrc b/packages/database/supabase/functions/update-sales-prices/.npmrc
new file mode 100644
index 0000000000..48c6388638
--- /dev/null
+++ b/packages/database/supabase/functions/update-sales-prices/.npmrc
@@ -0,0 +1,3 @@
+# Configuration for private npm package dependencies
+# For more information on using private registries with Edge Functions, see:
+# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
diff --git a/packages/database/supabase/functions/update-sales-prices/deno.json b/packages/database/supabase/functions/update-sales-prices/deno.json
new file mode 100644
index 0000000000..f6ca8454c5
--- /dev/null
+++ b/packages/database/supabase/functions/update-sales-prices/deno.json
@@ -0,0 +1,3 @@
+{
+ "imports": {}
+}
diff --git a/packages/database/supabase/functions/update-sales-prices/index.ts b/packages/database/supabase/functions/update-sales-prices/index.ts
new file mode 100644
index 0000000000..89a5c1b63f
--- /dev/null
+++ b/packages/database/supabase/functions/update-sales-prices/index.ts
@@ -0,0 +1,60 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+// const pool = getConnectionPool(1);
+// const db = getDatabaseClient<DB>(pool);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ const { invoiceId, companyId } = await req.json();
+
+ console.log({
+ function: "update-sales-prices",
+ invoiceId,
+ companyId,
+ });
+
+ try {
+ if (!invoiceId) throw new Error("Payload is missing invoiceId");
+
+ const client = await getSupabaseServiceRole(
+ req.headers.get("Authorization"),
+ req.headers.get("carbon-key"),
+ companyId
+ );
+
+ const [salesInvoice, salesInvoiceLines] = await Promise.all([
+ client.from("salesInvoice").select("*").eq("id", invoiceId).single(),
+ client.from("salesInvoiceLine").select("*").eq("invoiceId", invoiceId),
+ ]);
+
+ if (salesInvoice.error) throw new Error("Failed to fetch salesInvoice");
+ if (salesInvoiceLines.error)
+ throw new Error("Failed to fetch receipt lines");
+
+ // const itemIds = salesInvoiceLines.data
+ // .filter((line) => Boolean(line.itemId))
+ // .map((line) => line.itemId);
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ } catch (err) {
+ console.error(err);
+
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
index 07c1b856db..9d5aacab31 100644
--- a/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
+++ b/packages/database/supabase/migrations/20250507143421_sales-invoice.sql
@@ -90,6 +90,7 @@ CREATE TABLE "salesInvoiceLine" (
"id" TEXT NOT NULL DEFAULT xid(),
"invoiceId" TEXT NOT NULL,
"invoiceLineType" "salesInvoiceLineType" NOT NULL,
+ "description" TEXT,
"itemId" TEXT,
"itemReadableId" TEXT,
"accountNumber" TEXT,
@@ -111,6 +112,9 @@ CREATE TABLE "salesInvoiceLine" (
"externalNotes" JSON NOT NULL DEFAULT '{}',
"internalNotes" JSON NOT NULL DEFAULT '{}',
"modelUploadId" TEXT,
+ "opportunityId" TEXT,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
"customFields" JSONB NOT NULL DEFAULT '{}',
"companyId" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
@@ -125,6 +129,9 @@ CREATE TABLE "salesInvoiceLine" (
CONSTRAINT "salesInvoiceLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoiceLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoiceLine_modelUploadId_fkey" FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesInvoiceLine_opportunityId_fkey" FOREIGN KEY ("opportunityId") REFERENCES "opportunity"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesInvoiceLine_salesOrderId_fkey" FOREIGN KEY ("salesOrderId") REFERENCES "salesOrder"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesInvoiceLine_salesOrderLineId_fkey" FOREIGN KEY ("salesOrderLineId") REFERENCES "salesOrderLine"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoiceLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesInvoiceLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,
CONSTRAINT "salesInvoiceLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE