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: add shipping cost to the top level summary, accounting, and order totals

Brad Barbinec7587b1a508
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index e50d318665..483f95bdef 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -43,6 +43,15 @@ export const purchaseInvoiceValidator = z.object({
exchangeRateUpdatedAt: zfd.text(z.string().optional()),
});
+export const purchaseInvoiceDeliveryValidator = z.object({
+ id: z.string(),
+ locationId: zfd.text(z.string().optional()),
+ shippingMethodId: zfd.text(z.string().optional()),
+ shippingTermId: zfd.text(z.string().optional()),
+ supplierShippingCost: zfd.numeric(z.number().optional().default(0)),
+ customFields: z.any().optional(),
+});
+
export const purchaseInvoiceLineValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index e4260022d9..8cd00e66c8 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -4,6 +4,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import {
getSupplierPayment,
+ getSupplierShipping,
insertSupplierInteraction,
} from "~/modules/purchasing";
import type { GenericQueryFilters } from "~/utils/query";
@@ -12,6 +13,7 @@ import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
import { getEmployeeJob } from "../people/people.service";
import type {
+ purchaseInvoiceDeliveryValidator,
purchaseInvoiceLineValidator,
purchaseInvoiceValidator,
} from "./invoicing.models";
@@ -74,6 +76,17 @@ export async function getPurchaseInvoices(
return query;
}
+export async function getPurchaseInvoiceDelivery(
+ client: SupabaseClient<Database>,
+ purchaseInvoiceId: string
+) {
+ return client
+ .from("purchaseInvoiceDelivery")
+ .select("*")
+ .eq("id", purchaseInvoiceId)
+ .single();
+}
+
export async function getPurchaseInvoiceLines(
client: SupabaseClient<Database>,
purchaseInvoiceId: string
@@ -123,18 +136,25 @@ export async function upsertPurchaseInvoice(
.select("id, invoiceId");
}
- const [supplierInteraction, supplierPayment, purchaser] = await Promise.all([
- insertSupplierInteraction(client, purchaseInvoice.companyId),
- getSupplierPayment(client, purchaseInvoice.supplierId),
- getEmployeeJob(
- client,
- purchaseInvoice.createdBy,
- purchaseInvoice.companyId
- ),
- ]);
+ const [supplierInteraction, supplierPayment, supplierShipping, purchaser] =
+ await Promise.all([
+ insertSupplierInteraction(client, purchaseInvoice.companyId),
+ getSupplierPayment(client, purchaseInvoice.supplierId),
+ getSupplierShipping(client, purchaseInvoice.supplierId),
+ getEmployeeJob(
+ client,
+ purchaseInvoice.createdBy,
+ purchaseInvoice.companyId
+ ),
+ ]);
if (supplierInteraction.error) return supplierInteraction;
if (supplierPayment.error) return supplierPayment;
+ if (supplierShipping.error) return supplierShipping;
+
+ const { paymentTermId, invoiceSupplierId } = supplierPayment.data;
+
+ const { shippingMethodId, shippingTermId } = supplierShipping.data;
if (purchaseInvoice.currencyCode) {
const currency = await getCurrencyByCode(
@@ -154,26 +174,70 @@ export async function upsertPurchaseInvoice(
const locationId =
purchaseInvoice.locationId ?? purchaser?.data?.locationId ?? null;
- const { paymentTermId } = supplierPayment.data;
-
const invoice = await client
.from("purchaseInvoice")
.insert([
{
...purchaseInvoice,
- invoiceSupplierId:
- purchaseInvoice.invoiceSupplierId ?? purchaseInvoice.supplierId ?? "",
- supplierInteractionId: supplierInteraction.data.id,
+ invoiceSupplierId: invoiceSupplierId ?? purchaseInvoice.supplierId,
+ supplierInteractionId: supplierInteraction.data?.id,
currencyCode: purchaseInvoice.currencyCode ?? "USD",
paymentTermId: purchaseInvoice.paymentTermId ?? paymentTermId,
- locationId,
},
])
.select("id, invoiceId");
+ if (invoice.error) return invoice;
+
+ const invoiceId = invoice.data[0].id;
+
+ const delivery = await client.from("purchaseInvoiceDelivery").insert([
+ {
+ id: invoiceId,
+ locationId: locationId,
+ shippingMethodId: shippingMethodId,
+ shippingTermId: shippingTermId,
+ companyId: purchaseInvoice.companyId,
+ },
+ ]);
+
+ if (delivery.error) {
+ await client.from("purchaseInvoice").delete().eq("id", invoiceId);
+ return delivery;
+ }
+
return invoice;
}
+export async function upsertPurchaseInvoiceDelivery(
+ client: SupabaseClient<Database>,
+ purchaseInvoiceDelivery:
+ | (z.infer<typeof purchaseInvoiceDeliveryValidator> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (z.infer<typeof purchaseInvoiceDeliveryValidator> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in purchaseInvoiceDelivery) {
+ return client
+ .from("purchaseInvoiceDelivery")
+ .update(sanitize(purchaseInvoiceDelivery))
+ .eq("id", purchaseInvoiceDelivery.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("purchaseInvoiceDelivery")
+ .insert([purchaseInvoiceDelivery])
+ .select("id")
+ .single();
+}
+
export async function upsertPurchaseInvoiceLine(
client: SupabaseClient<Database>,
purchaseInvoiceLine:
diff --git a/apps/erp/app/modules/invoicing/types.ts b/apps/erp/app/modules/invoicing/types.ts
index f36add4bd1..9a2864cf73 100644
--- a/apps/erp/app/modules/invoicing/types.ts
+++ b/apps/erp/app/modules/invoicing/types.ts
@@ -3,6 +3,7 @@ import type {
purchaseInvoiceStatusType,
} from "./invoicing.models";
import type {
+ getPurchaseInvoiceDelivery,
getPurchaseInvoiceLines,
getPurchaseInvoices,
} from "./invoicing.service";
@@ -11,6 +12,10 @@ export type PurchaseInvoice = NonNullable<
Awaited<ReturnType<typeof getPurchaseInvoices>>["data"]
>[number];
+export type PurchaseInvoiceDelivery = NonNullable<
+ Awaited<ReturnType<typeof getPurchaseInvoiceDelivery>>["data"]
+>;
+
export type PurchaseInvoiceLine = NonNullable<
Awaited<ReturnType<typeof getPurchaseInvoiceLines>>["data"]
>[number];
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx
new file mode 100644
index 0000000000..8114db25a1
--- /dev/null
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx
@@ -0,0 +1,126 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
+import { forwardRef, useImperativeHandle, useRef, useState } from "react";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Hidden,
+ Location,
+ Number,
+ ShippingMethod,
+ 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 { path } from "~/utils/path";
+
+type PurchaseInvoiceDeliveryFormProps = {
+ initialValues: z.infer<typeof purchaseInvoiceDeliveryValidator>;
+ currencyCode: string;
+ defaultCollapsed?: boolean;
+};
+
+export type PurchaseInvoiceDeliveryFormRef = {
+ focusShippingCost: () => void;
+};
+
+const PurchaseInvoiceDeliveryForm = forwardRef<
+ PurchaseInvoiceDeliveryFormRef,
+ PurchaseInvoiceDeliveryFormProps
+>(({ initialValues, currencyCode, defaultCollapsed = true }, ref) => {
+ const { invoiceId } = useParams();
+ if (!invoiceId) {
+ throw new Error("invoiceId not found");
+ }
+
+ const routeData = useRouteData<{
+ purchaseInvoice: PurchaseInvoice;
+ }>(path.to.purchaseInvoice(invoiceId));
+
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.purchaseInvoice?.status ?? ""
+ );
+
+ const permissions = usePermissions();
+ const fetcher = useFetcher<typeof action>();
+ const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
+
+ const shippingCostRef = useRef<HTMLInputElement>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
+
+ useImperativeHandle(ref, () => ({
+ focusShippingCost: () => {
+ setIsCollapsed(false);
+ setTimeout(() => {
+ cardRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ shippingCostRef.current?.focus();
+ }, 100);
+ },
+ }));
+
+ const isSupplier = permissions.is("supplier");
+
+ return (
+ <Card
+ ref={cardRef}
+ isCollapsible
+ defaultCollapsed={defaultCollapsed}
+ isCollapsed={isCollapsed}
+ onCollapsedChange={setIsCollapsed}
+ >
+ <ValidatedForm
+ method="post"
+ action={path.to.purchaseInvoiceDelivery(invoiceId)}
+ validator={purchaseInvoiceDeliveryValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ >
+ <CardHeader>
+ <CardTitle>Shipping</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <Hidden name="id" />
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">
+ <Number
+ name="supplierShippingCost"
+ label="Shipping Cost"
+ formatOptions={{
+ style: "currency",
+ currency: currencyCode,
+ }}
+ ref={shippingCostRef}
+ />
+ <Location
+ name="locationId"
+ label="Delivery Location"
+ isReadOnly={isSupplier}
+ isClearable
+ />
+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />
+ <CustomFormFields table="purchaseInvoiceDelivery" />
+ </div>
+ </CardContent>
+ <CardFooter>
+ <Submit
+ isDisabled={!permissions.can("update", "invoicing") || !isEditable}
+ >
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+});
+
+PurchaseInvoiceDeliveryForm.displayName = "PurchaseInvoiceDeliveryForm";
+
+export default PurchaseInvoiceDeliveryForm;
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx
index 0ca244a563..01a9462468 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx
@@ -21,7 +21,6 @@ import {
Hidden,
Input,
Location,
- Number,
Submit,
Supplier,
SupplierContact,
@@ -209,14 +208,7 @@ const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {
<DatePicker name="dateDue" label="Due Date" />
<DatePicker name="dateIssued" label="Date Issued" />
- <Number
- name="supplierShippingCost"
- label="Shipping Cost"
- formatOptions={{
- style: "currency",
- currency: invoiceSupplier?.currencyCode,
- }}
- />
+
<PaymentTerm
name="paymentTermId"
label="Payment Terms"
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
index b226d14c6e..80ffa0453d 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceSummary.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardDescription,
@@ -6,7 +7,6 @@ import {
CardTitle,
Heading,
HStack,
- IconButton,
Table,
Tbody,
Td,
@@ -18,7 +18,7 @@ import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
import { useState } from "react";
-import { LuChevronDown, LuExternalLink, LuImage } from "react-icons/lu";
+import { LuChevronDown, LuImage } from "react-icons/lu";
import { SupplierAvatar } from "~/components";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import {
@@ -28,7 +28,11 @@ import {
useUser,
} from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
-import type { PurchaseInvoice, PurchaseInvoiceLine } from "../../types";
+import type {
+ PurchaseInvoice,
+ PurchaseInvoiceDelivery,
+ PurchaseInvoiceLine,
+} from "../../types";
const LineItems = ({
currencyCode,
@@ -100,21 +104,23 @@ const LineItems = ({
onClick={() => toggleOpen(line.id!)}
>
<div className="flex items-center gap-x-4 justify-between flex-grow min-w-0">
- <HStack spacing={0} className="min-w-0 flex-shrink ">
+ <HStack spacing={2} className="min-w-0 flex-shrink">
<Heading className="truncate">
{line.itemReadableId}
</Heading>
- <Link
- to={path.to.purchaseInvoiceLine(invoiceId, line.id!)}
+ <Button
+ asChild
+ variant="link"
+ size="sm"
className="text-muted-foreground flex-shrink-0"
>
- <IconButton
- aria-label="View Line Item"
- icon={<LuExternalLink />}
- variant="ghost"
- />
- </Link>
+ <Link
+ to={path.to.purchaseInvoiceLine(invoiceId, line.id!)}
+ >
+ Edit
+ </Link>
+ </Button>
</HStack>
<HStack spacing={4} className="flex-shrink-0 ml-4">
<VStack spacing={0}>
@@ -279,14 +285,20 @@ const LineItems = ({
</VStack>
);
};
+type PurchaseInvoiceSummaryProps = {
+ onEditShippingCost: () => void;
+};
-const PurchaseInvoiceSummary = () => {
+const PurchaseInvoiceSummary = ({
+ onEditShippingCost,
+}: PurchaseInvoiceSummaryProps) => {
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));
const { locale } = useLocale();
@@ -300,19 +312,24 @@ const PurchaseInvoiceSummary = () => {
routeData?.purchaseInvoice?.currencyCode ?? "USD"
);
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.purchaseInvoice?.status ?? ""
+ );
+
// Calculate totals
const subtotal =
routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- const lineTotal = (line.unitPrice ?? 0) * (line.quantity ?? 0);
- const shippingCost = line.shippingCost ?? 0;
- return acc + lineTotal + shippingCost;
+ const lineTotal =
+ (line.unitPrice ?? 0) * (line.quantity ?? 0) + (line.shippingCost ?? 0);
+ return acc + lineTotal;
}, 0) ?? 0;
const supplierSubtotal =
routeData?.purchaseInvoiceLines?.reduce((acc, line) => {
- const lineTotal = (line.supplierUnitPrice ?? 0) * (line.quantity ?? 0);
- const shippingCost = line.supplierShippingCost ?? 0;
- return acc + lineTotal + shippingCost;
+ const lineTotal =
+ (line.supplierUnitPrice ?? 0) * (line.quantity ?? 0) +
+ (line.supplierShippingCost ?? 0);
+ return acc + lineTotal;
}, 0) ?? 0;
const tax =
@@ -325,8 +342,15 @@ const PurchaseInvoiceSummary = () => {
return acc + (line.supplierTaxAmount ?? 0);
}, 0) ?? 0;
- const total = subtotal + tax;
- const supplierTotal = supplierSubtotal + supplierTax;
+ const shippingCost =
+ (routeData?.purchaseInvoiceDelivery?.supplierShippingCost ?? 0) *
+ (routeData?.purchaseInvoice?.exchangeRate ?? 1);
+
+ const supplierShippingCost =
+ routeData?.purchaseInvoiceDelivery?.supplierShippingCost ?? 0;
+
+ const total = subtotal + tax + shippingCost;
+ const supplierTotal = supplierSubtotal + supplierTax + supplierShippingCost;
return (
<Card>
@@ -370,6 +394,7 @@ const PurchaseInvoiceSummary = () => {
)}
</VStack>
</HStack>
+
<HStack className="justify-between text-base text-muted-foreground w-full">
<span>Tax:</span>
<VStack spacing={0} className="items-end">
@@ -382,6 +407,45 @@ const PurchaseInvoiceSummary = () => {
</VStack>
</HStack>
+ <HStack className="justify-between text-base text-muted-foreground w-full">
+ {shippingCost > 0 ? (
+ <>
+ <VStack spacing={0}>
+ <span>Shipping:</span>
+ {isEditable && (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Edit Shipping
+ </Button>
+ )}
+ </VStack>
+ <VStack spacing={0} className="items-end">
+ <span>{formatter.format(shippingCost)}</span>
+ {shouldConvertCurrency && (
+ <span className="text-sm">
+ {presentationCurrencyFormatter.format(
+ supplierShippingCost
+ )}
+ </span>
+ )}
+ </VStack>
+ </>
+ ) : isEditable ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Add Shipping
+ </Button>
+ ) : null}
+ </HStack>
+
<HStack className="justify-between text-xl font-bold w-full">
<span>Total:</span>
<VStack spacing={0} className="items-end">
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/index.ts b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/index.ts
index 5c48e90e2a..8f67948af0 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/index.ts
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/index.ts
@@ -1,3 +1,4 @@
+import PurchaseInvoiceDeliveryForm from "./PurchaseInvoiceDeliveryForm";
import PurchaseInvoiceForm from "./PurchaseInvoiceForm";
import PurchaseInvoiceHeader from "./PurchaseInvoiceHeader";
import PurchaseInvoiceLineForm from "./PurchaseInvoiceLineForm";
@@ -5,6 +6,7 @@ import PurchaseInvoicesTable from "./PurchaseInvoicesTable";
import PurchaseInvoiceSummary from "./PurchaseInvoiceSummary";
import PurchaseInvoicingStatus from "./PurchaseInvoicingStatus";
export {
+ PurchaseInvoiceDeliveryForm,
PurchaseInvoiceForm,
PurchaseInvoiceHeader,
PurchaseInvoiceLineForm,
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 79f429a955..0f34e7470b 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -300,6 +300,23 @@ export async function getItemCost(
.single();
}
+export async function getItemCostHistory(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ const dateOneYearAgo = today(getLocalTimeZone())
+ .subtract({ years: 1 })
+ .toString();
+
+ return client
+ .from("costLedger")
+ .select("quantity, cost, postingDate")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .gte("postingDate", dateOneYearAgo);
+}
+
export async function getItemCustomerPart(
client: SupabaseClient<Database>,
id: string,
@@ -910,7 +927,10 @@ export async function getServices(
}
if (args.type) {
- query = query.eq("serviceType", args.type);
+ query = query.eq(
+ "serviceType",
+ args.type as NonNullable<"Internal" | "External">
+ );
}
if (args.group) {
diff --git a/apps/erp/app/modules/items/types.ts b/apps/erp/app/modules/items/types.ts
index fc29446161..dc9021b14c 100644
--- a/apps/erp/app/modules/items/types.ts
+++ b/apps/erp/app/modules/items/types.ts
@@ -5,6 +5,7 @@ import type {
getConsumable,
getConsumables,
getItemCost,
+ getItemCostHistory,
getItemCustomerParts,
getItemFiles,
getItemPostingGroups,
@@ -64,6 +65,10 @@ export type ItemCost = NonNullable<
Awaited<ReturnType<typeof getItemCost>>
>["data"];
+export type ItemCostHistory = NonNullable<
+ Awaited<ReturnType<typeof getItemCostHistory>>
+>["data"];
+
export type ItemCostingMethod =
Database["public"]["Enums"]["itemCostingMethod"];
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
index 152c956c4f..fb9739d512 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
@@ -7,7 +7,7 @@ import {
CardTitle,
} from "@carbon/react";
import { useFetcher, useParams } from "@remix-run/react";
-import { useState } from "react";
+import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import type { z } from "zod";
import {
Boolean,
@@ -22,7 +22,8 @@ import {
ShippingMethod,
Submit,
} from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { PurchaseOrder } from "~/modules/purchasing";
import { purchaseOrderDeliveryValidator } from "~/modules/purchasing";
import type { action } from "~/routes/x+/purchase-order+/$orderId.delivery";
import { path } from "~/utils/path";
@@ -30,18 +31,30 @@ import { path } from "~/utils/path";
type PurchaseOrderDeliveryFormProps = {
initialValues: z.infer<typeof purchaseOrderDeliveryValidator>;
currencyCode: string;
+ defaultCollapsed?: boolean;
};
-const PurchaseOrderDeliveryForm = ({
- initialValues,
- currencyCode,
-}: // shippingTerms,
-PurchaseOrderDeliveryFormProps) => {
+export type PurchaseOrderDeliveryFormRef = {
+ focusShippingCost: () => void;
+};
+
+const PurchaseOrderDeliveryForm = forwardRef<
+ PurchaseOrderDeliveryFormRef,
+ PurchaseOrderDeliveryFormProps
+>(({ initialValues, currencyCode, defaultCollapsed = true }, ref) => {
const { orderId } = useParams();
if (!orderId) {
throw new Error("orderId not found");
}
+ const routeData = useRouteData<{
+ purchaseOrder: PurchaseOrder;
+ }>(path.to.purchaseOrder(orderId));
+
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ );
+
const permissions = usePermissions();
const fetcher = useFetcher<typeof action>();
const [dropShip, setDropShip] = useState<boolean>(
@@ -50,11 +63,31 @@ PurchaseOrderDeliveryFormProps) => {
const [customer, setCustomer] = useState<string | undefined>(
initialValues.customerId
);
+ const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
+
+ const shippingCostRef = useRef<HTMLInputElement>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
+
+ useImperativeHandle(ref, () => ({
+ focusShippingCost: () => {
+ setIsCollapsed(false);
+ setTimeout(() => {
+ cardRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ shippingCostRef.current?.focus();
+ }, 100);
+ },
+ }));
const isSupplier = permissions.is("supplier");
return (
- <Card isCollapsible defaultCollapsed>
+ <Card
+ ref={cardRef}
+ isCollapsible
+ defaultCollapsed={defaultCollapsed}
+ isCollapsed={isCollapsed}
+ onCollapsedChange={setIsCollapsed}
+ >
<ValidatedForm
method="post"
action={path.to.purchaseOrderDelivery(orderId)}
@@ -63,7 +96,7 @@ PurchaseOrderDeliveryFormProps) => {
fetcher={fetcher}
>
<CardHeader>
- <CardTitle>Delivery</CardTitle>
+ <CardTitle>Shipping</CardTitle>
</CardHeader>
<CardContent>
<Hidden name="id" />
@@ -75,6 +108,7 @@ PurchaseOrderDeliveryFormProps) => {
style: "currency",
currency: currencyCode,
}}
+ ref={shippingCostRef}
/>
<Location
name="locationId"
@@ -83,19 +117,12 @@ PurchaseOrderDeliveryFormProps) => {
isClearable
/>
<ShippingMethod name="shippingMethodId" label="Shipping Method" />
- {/* <Select
- name="shippingTermId"
- label="Shipping Terms"
- isReadOnly={isSupplier}
- options={shippingTermOptions}
- /> */}
<DatePicker name="receiptRequestedDate" label="Requested Date" />
<DatePicker name="receiptPromisedDate" label="Promised Date" />
<DatePicker name="deliveryDate" label="Delivery Date" />
<Input name="trackingNumber" label="Tracking Number" />
- {/* <TextArea name="notes" label="Shipping Notes" /> */}
<Boolean
name="dropShipment"
label="Drop Shipment"
@@ -119,13 +146,17 @@ PurchaseOrderDeliveryFormProps) => {
</div>
</CardContent>
<CardFooter>
- <Submit isDisabled={!permissions.can("update", "purchasing")}>
+ <Submit
+ isDisabled={!permissions.can("update", "purchasing") || !isEditable}
+ >
Save
</Submit>
</CardFooter>
</ValidatedForm>
</Card>
);
-};
+});
+
+PurchaseOrderDeliveryForm.displayName = "PurchaseOrderDeliveryForm";
export default PurchaseOrderDeliveryForm;
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
index 84e1cd0d83..0594537b0f 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSummary.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardDescription,
@@ -6,7 +7,6 @@ import {
CardTitle,
Heading,
HStack,
- IconButton,
Table,
Tbody,
Td,
@@ -18,7 +18,7 @@ import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
import { useState } from "react";
-import { LuChevronDown, LuExternalLink, LuImage } from "react-icons/lu";
+import { LuChevronDown, LuImage } from "react-icons/lu";
import { SupplierAvatar } from "~/components";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import {
@@ -105,21 +105,21 @@ const LineItems = ({
onClick={() => toggleOpen(line.id!)}
>
<div className="flex items-center gap-x-4 justify-between flex-grow min-w-0">
- <HStack spacing={0} className="min-w-0 flex-shrink ">
+ <HStack spacing={2} className="min-w-0 flex-shrink ">
<Heading className="truncate">
{line.itemReadableId}
</Heading>
- <Link
- to={path.to.purchaseOrderLine(orderId, line.id!)}
+ <Button
+ asChild
+ variant="link"
+ size="sm"
className="text-muted-foreground flex-shrink-0"
>
- <IconButton
- aria-label="View Line Item"
- icon={<LuExternalLink />}
- variant="ghost"
- />
- </Link>
+ <Link to={path.to.purchaseOrderLine(orderId, line.id!)}>
+ Edit
+ </Link>
+ </Button>
</HStack>
<HStack spacing={4} className="flex-shrink-0 ml-4">
<VStack spacing={0}>
@@ -286,7 +286,13 @@ const LineItems = ({
);
};
-const PurchaseOrderSummary = () => {
+type PurchaseOrderSummaryProps = {
+ onEditShippingCost: () => void;
+};
+
+const PurchaseOrderSummary = ({
+ onEditShippingCost,
+}: PurchaseOrderSummaryProps) => {
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
@@ -298,6 +304,10 @@ const PurchaseOrderSummary = () => {
supplier: Supplier;
}>(path.to.purchaseOrder(orderId));
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ );
+
const { locale } = useLocale();
const formatter = useCurrencyFormatter();
const presentationCurrencyFormatter = useCurrencyFormatter(
@@ -310,27 +320,18 @@ const PurchaseOrderSummary = () => {
// Calculate totals
const subtotal =
routeData?.lines?.reduce((acc, line) => {
- const lineTotal = (line.unitPrice ?? 0) * (line.purchaseQuantity ?? 0);
+ const lineTotal =
+ (line.unitPrice ?? 0) * (line.purchaseQuantity ?? 0) +
+ (line.shippingCost ?? 0);
return acc + lineTotal;
}, 0) ?? 0;
- const supplierShippingCost =
- (routeData?.lines?.reduce((acc, line) => {
- return acc + (line.supplierShippingCost ?? 0);
- }, 0) ?? 0) + (routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0);
-
- const shippingCost =
- (routeData?.lines?.reduce((acc, line) => {
- return acc + (line.shippingCost ?? 0);
- }, 0) ?? 0) +
- (routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0) *
- (routeData?.purchaseOrder?.exchangeRate ?? 1);
-
const supplierSubtotal =
routeData?.lines?.reduce((acc, line) => {
const lineTotal =
- (line.supplierUnitPrice ?? 0) * (line.purchaseQuantity ?? 0);
+ (line.supplierUnitPrice ?? 0) * (line.purchaseQuantity ?? 0) +
+ (line.supplierShippingCost ?? 0);
return acc + lineTotal;
}, 0) ?? 0;
@@ -345,6 +346,13 @@ const PurchaseOrderSummary = () => {
return acc + (line.supplierTaxAmount ?? 0);
}, 0) ?? 0;
+ const shippingCost =
+ (routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0) *
+ (routeData?.purchaseOrder?.exchangeRate ?? 1);
+
+ const supplierShippingCost =
+ routeData?.purchaseOrderDelivery?.supplierShippingCost ?? 0;
+
const total = subtotal + tax + shippingCost;
const supplierTotal = supplierSubtotal + supplierTax + supplierShippingCost;
@@ -403,15 +411,42 @@ const PurchaseOrderSummary = () => {
</HStack>
<HStack className="justify-between text-base text-muted-foreground w-full">
- <span>Shipping:</span>
- <VStack spacing={0} className="items-end">
- <span>{formatter.format(shippingCost)}</span>
- {shouldConvertCurrency && (
- <span className="text-sm">
- {presentationCurrencyFormatter.format(supplierShippingCost)}
- </span>
- )}
- </VStack>
+ {shippingCost > 0 ? (
+ <>
+ <VStack spacing={0}>
+ <span>Shipping:</span>
+ {isEditable && (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Edit Shipping
+ </Button>
+ )}
+ </VStack>
+ <VStack spacing={0} className="items-end">
+ <span>{formatter.format(shippingCost)}</span>
+ {shouldConvertCurrency && (
+ <span className="text-sm">
+ {presentationCurrencyFormatter.format(
+ supplierShippingCost
+ )}
+ </span>
+ )}
+ </VStack>
+ </>
+ ) : isEditable ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Add Shipping
+ </Button>
+ ) : null}
</HStack>
<HStack className="justify-between text-xl font-bold w-full">
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
index 5c9f6a0e43..9ad0202501 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteSummary.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardDescription,
@@ -6,7 +7,6 @@ import {
CardTitle,
HStack,
Heading,
- IconButton,
Table,
Tbody,
Td,
@@ -20,7 +20,7 @@ import { useLocale } from "@react-aria/i18n";
import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
import { useMemo, useState } from "react";
-import { LuChevronDown, LuExternalLink, LuImage } from "react-icons/lu";
+import { LuChevronDown, LuImage } from "react-icons/lu";
import { SupplierAvatar } from "~/components";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useCurrencyFormatter, useRouteData, useUser } from "~/hooks";
@@ -118,20 +118,20 @@ const LineItems = ({
onClick={() => toggleOpen(line.id!)}
>
<div className="flex items-center gap-x-4 justify-between flex-grow">
- <HStack spacing={0} className="min-w-0 flex-shrink">
+ <HStack spacing={2} className="min-w-0 flex-shrink">
<Heading className="truncate">
{line.itemReadableId}
</Heading>
- <Link
- to={path.to.supplierQuoteLine(id, line.id!)}
- className="text-muted-foreground"
+ <Button
+ asChild
+ variant="link"
+ size="sm"
+ className="text-muted-foreground flex-shrink-0"
>
- <IconButton
- aria-label="View Line Item"
- icon={<LuExternalLink />}
- variant="ghost"
- />
- </Link>
+ <Link to={path.to.supplierQuoteLine(id, line.id!)}>
+ Edit
+ </Link>
+ </Button>
</HStack>
<HStack spacing={4}>
<motion.div
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
index 5e3ee99602..a7818d7192 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
@@ -7,6 +7,7 @@ import {
CardTitle,
} from "@carbon/react";
import { useFetcher, useParams } from "@remix-run/react";
+import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import type { z } from "zod";
import {
DatePicker,
@@ -23,20 +24,33 @@ import type { Quotation } from "../../types";
type QuoteShipmentFormProps = {
initialValues: z.infer<typeof quoteShipmentValidator>;
- // shippingTerms: ListItem[];
+ defaultCollapsed?: boolean;
};
-const QuoteShipmentForm = ({
- initialValues,
-}: // shippingTerms,
-QuoteShipmentFormProps) => {
+export type QuoteShipmentFormRef = {
+ focusShippingCost: () => void;
+};
+
+const QuoteShipmentForm = forwardRef<
+ QuoteShipmentFormRef,
+ QuoteShipmentFormProps
+>(({ initialValues, defaultCollapsed = true }, ref) => {
const permissions = usePermissions();
const fetcher = useFetcher<{}>();
+ const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
+
+ const shippingCostRef = useRef<HTMLInputElement>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
- // const shippingTermOptions = shippingTerms.map((term) => ({
- // label: term.name,
- // value: term.id,
- // }));
+ useImperativeHandle(ref, () => ({
+ focusShippingCost: () => {
+ setIsCollapsed(false);
+ setTimeout(() => {
+ cardRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ shippingCostRef.current?.focus();
+ }, 100);
+ },
+ }));
const isCustomer = permissions.is("customer");
@@ -53,7 +67,13 @@ QuoteShipmentFormProps) => {
const { company } = useUser();
return (
- <Card isCollapsible defaultCollapsed>
+ <Card
+ ref={cardRef}
+ isCollapsible
+ defaultCollapsed={defaultCollapsed}
+ isCollapsed={isCollapsed}
+ onCollapsedChange={setIsCollapsed}
+ >
<ValidatedForm
action={path.to.quoteShipment(initialValues.id)}
method="post"
@@ -74,6 +94,7 @@ QuoteShipmentFormProps) => {
style: "currency",
currency: company?.baseCurrencyCode,
}}
+ ref={shippingCostRef}
/>
<Location
name="locationId"
@@ -82,12 +103,6 @@ QuoteShipmentFormProps) => {
isClearable
/>
<ShippingMethod name="shippingMethodId" label="Shipping Method" />
- {/* <Select
- name="shippingTermId"
- label="Shipping Terms"
- isReadOnly={isCustomer}
- options={shippingTermOptions}
- /> */}
<DatePicker name="receiptRequestedDate" label="Requested Date" />
</div>
@@ -102,6 +117,8 @@ QuoteShipmentFormProps) => {
</ValidatedForm>
</Card>
);
-};
+});
+
+QuoteShipmentForm.displayName = "QuoteShipmentForm";
export default QuoteShipmentForm;
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
index 36baa17229..898a876b1d 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardDescription,
@@ -6,7 +7,6 @@ import {
CardTitle,
HStack,
Heading,
- IconButton,
RadioGroup,
RadioGroupItem,
Table,
@@ -24,7 +24,7 @@ import { motion } from "framer-motion";
import MotionNumber from "motion-number";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
-import { LuChevronDown, LuExternalLink, LuImage } from "react-icons/lu";
+import { LuChevronDown, LuImage } from "react-icons/lu";
import { CustomerAvatar } from "~/components";
import { usePercentFormatter, useRouteData, useUser } from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
@@ -154,20 +154,20 @@ const LineItems = ({
onClick={() => toggleOpen(line.id!)}
>
<div className="flex items-center gap-x-4 justify-between flex-grow">
- <HStack spacing={0} className="min-w-0 flex-shrink">
+ <HStack spacing={2} className="min-w-0 flex-shrink">
<Heading className="truncate">
{line.itemReadableId}
</Heading>
- <Link
- to={path.to.quoteLine(quoteId, line.id!)}
- className="text-muted-foreground"
+ <Button
+ asChild
+ variant="link"
+ size="sm"
+ className="text-muted-foreground flex-shrink-0"
>
- <IconButton
- aria-label="View Line Item"
- icon={<LuExternalLink />}
- variant="ghost"
- />
- </Link>
+ <Link to={path.to.quoteLine(quoteId, line.id!)}>
+ Edit
+ </Link>
+ </Button>
</HStack>
<HStack spacing={4}>
{/* <span className="font-medium text-xl">
@@ -532,7 +532,11 @@ const LinePricingOptions = ({
);
};
-const QuoteSummary = () => {
+const QuoteSummary = ({
+ onEditShippingCost,
+}: {
+ onEditShippingCost: () => void;
+}) => {
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quote id");
const routeData = useRouteData<{
@@ -543,6 +547,10 @@ const QuoteSummary = () => {
salesOrderLines: SalesOrderLine[];
}>(path.to.quote(quoteId));
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.quote?.status ?? ""
+ );
+
const { locale } = useLocale();
const formatter = useMemo(
() =>
@@ -699,19 +707,40 @@ const QuoteSummary = () => {
locales={locale}
/>
</HStack>
- {convertedShippingCost > 0 && (
- <HStack className="justify-between text-base text-muted-foreground w-full">
- <span>Shipping:</span>
- <MotionNumber
- value={convertedShippingCost}
- format={{
- style: "currency",
- currency: routeData?.quote.currencyCode ?? "USD",
- }}
- locales={locale}
- />
- </HStack>
- )}
+ <HStack className="justify-between text-base text-muted-foreground w-full">
+ {convertedShippingCost > 0 ? (
+ <>
+ <VStack spacing={0}>
+ <span>Shipping:</span>
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Edit Shipping
+ </Button>
+ </VStack>
+ <MotionNumber
+ value={convertedShippingCost}
+ format={{
+ style: "currency",
+ currency: routeData?.quote.currencyCode ?? "USD",
+ }}
+ locales={locale}
+ />
+ </>
+ ) : isEditable ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Add Shipping
+ </Button>
+ ) : null}
+ </HStack>
<HStack className="justify-between text-xl font-bold w-full">
<span>Total:</span>
<MotionNumber
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
index e21cd58879..c0b1684037 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
@@ -7,7 +7,7 @@ import {
CardTitle,
} from "@carbon/react";
import { useFetcher, useParams } from "@remix-run/react";
-import { useState } from "react";
+import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import type { z } from "zod";
import {
Boolean,
@@ -30,13 +30,17 @@ import type { SalesOrder } from "../../types";
type SalesOrderShipmentFormProps = {
initialValues: z.infer<typeof salesOrderShipmentValidator>;
- // shippingTerms: ListItem[];
+ defaultCollapsed?: boolean;
};
-const SalesOrderShipmentForm = ({
- initialValues,
-}: // shippingTerms,
-SalesOrderShipmentFormProps) => {
+export type SalesOrderShipmentFormRef = {
+ focusShippingCost: () => void;
+};
+
+const SalesOrderShipmentForm = forwardRef<
+ SalesOrderShipmentFormRef,
+ SalesOrderShipmentFormProps
+>(({ initialValues, defaultCollapsed = true }, ref) => {
const permissions = usePermissions();
const fetcher = useFetcher<typeof action>();
const [dropShip, setDropShip] = useState<boolean>(
@@ -45,6 +49,20 @@ SalesOrderShipmentFormProps) => {
const [customer, setCustomer] = useState<string | undefined>(
initialValues.customerId
);
+ const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
+
+ const shippingCostRef = useRef<HTMLInputElement>(null);
+ const cardRef = useRef<HTMLDivElement>(null);
+
+ useImperativeHandle(ref, () => ({
+ focusShippingCost: () => {
+ setIsCollapsed(false);
+ setTimeout(() => {
+ cardRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ shippingCostRef.current?.focus();
+ }, 100);
+ },
+ }));
const { orderId } = useParams();
if (!orderId) throw new Error("orderId not found");
@@ -57,7 +75,13 @@ SalesOrderShipmentFormProps) => {
const isCustomer = permissions.is("customer");
return (
- <Card isCollapsible defaultCollapsed>
+ <Card
+ ref={cardRef}
+ isCollapsible
+ defaultCollapsed={defaultCollapsed}
+ isCollapsed={isCollapsed}
+ onCollapsedChange={setIsCollapsed}
+ >
<ValidatedForm
action={path.to.salesOrderShipment(initialValues.id)}
method="post"
@@ -80,6 +104,7 @@ SalesOrderShipmentFormProps) => {
routeData?.salesOrder?.currencyCode ??
company?.baseCurrencyCode,
}}
+ ref={shippingCostRef}
/>
<Location
name="locationId"
@@ -88,19 +113,12 @@ SalesOrderShipmentFormProps) => {
isClearable
/>
<ShippingMethod name="shippingMethodId" label="Shipping Method" />
- {/* <Select
- name="shippingTermId"
- label="Shipping Terms"
- isReadOnly={isCustomer}
- options={shippingTermOptions}
- /> */}
<DatePicker name="receiptRequestedDate" label="Requested Date" />
<DatePicker name="receiptPromisedDate" label="Promised Date" />
<DatePicker name="shipmentDate" label="Shipment Date" />
<Input name="trackingNumber" label="Tracking Number" />
- {/* <TextArea name="notes" label="Shipping Notes" /> */}
<Boolean
name="dropShipment"
label="Drop Shipment"
@@ -129,6 +147,8 @@ SalesOrderShipmentFormProps) => {
</ValidatedForm>
</Card>
);
-};
+});
+
+SalesOrderShipmentForm.displayName = "SalesOrderShipmentForm";
export default SalesOrderShipmentForm;
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index b518830fe8..8288fed85c 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardDescription,
@@ -6,7 +7,6 @@ import {
CardTitle,
Heading,
HStack,
- IconButton,
Table,
Tbody,
Td,
@@ -19,7 +19,7 @@ import { Link, useParams } from "@remix-run/react";
import { motion } from "framer-motion";
import MotionNumber from "motion-number";
import { useMemo, useState } from "react";
-import { LuChevronDown, LuExternalLink, LuImage } from "react-icons/lu";
+import { LuChevronDown, LuImage } from "react-icons/lu";
import { CustomerAvatar } from "~/components";
import { usePercentFormatter, useRouteData } from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
@@ -79,21 +79,20 @@ const LineItems = ({
onClick={() => toggleOpen(line.id!)}
>
<div className="flex items-center gap-x-4 justify-between flex-grow min-w-0">
- <HStack spacing={0} className="min-w-0 flex-shrink ">
+ <HStack spacing={2} className="min-w-0 flex-shrink">
<Heading className="truncate">
{line.itemReadableId}
</Heading>
-
- <Link
- to={path.to.salesOrderLine(orderId, line.id!)}
+ <Button
+ asChild
+ variant="link"
+ size="sm"
className="text-muted-foreground flex-shrink-0"
>
- <IconButton
- aria-label="View Line Item"
- icon={<LuExternalLink />}
- variant="ghost"
- />
- </Link>
+ <Link to={path.to.salesOrderLine(orderId, line.id!)}>
+ Edit
+ </Link>
+ </Button>
</HStack>
<HStack spacing={4} className="flex-shrink-0 ml-4">
<MotionNumber
@@ -255,8 +254,11 @@ const LineItems = ({
</VStack>
);
};
-
-const SalesOrderSummary = () => {
+const SalesOrderSummary = ({
+ onEditShippingCost,
+}: {
+ onEditShippingCost: () => void;
+}) => {
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
@@ -276,6 +278,10 @@ const SalesOrderSummary = () => {
[locale, routeData?.salesOrder?.currencyCode]
);
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.salesOrder?.status ?? ""
+ );
+
// Calculate totals
const subtotal =
routeData?.lines?.reduce((acc, line) => {
@@ -295,10 +301,10 @@ const SalesOrderSummary = () => {
return acc + (lineTotal + addOns) * (line.taxPercent ?? 0);
}, 0) ?? 0;
- const shippingCost =
- (routeData?.salesOrder?.shippingCost ?? 0) *
- (routeData?.salesOrder?.exchangeRate ?? 1);
- const total = subtotal + tax + shippingCost;
+ const convertedShippingCost =
+ (routeData?.salesOrder?.exchangeRate ?? 1) *
+ (routeData?.salesOrder?.shippingCost ?? 0);
+ const total = subtotal + tax + convertedShippingCost;
return (
<Card>
@@ -351,19 +357,40 @@ const SalesOrderSummary = () => {
locales={locale}
/>
</HStack>
- {shippingCost > 0 && (
- <HStack className="justify-between text-base text-muted-foreground w-full">
- <span>Shipping:</span>
- <MotionNumber
- value={shippingCost}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD",
- }}
- locales={locale}
- />
- </HStack>
- )}
+ <HStack className="justify-between text-base text-muted-foreground w-full">
+ {convertedShippingCost > 0 ? (
+ <>
+ <VStack spacing={0}>
+ <span>Shipping:</span>
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Edit Shipping
+ </Button>
+ </VStack>
+ <MotionNumber
+ value={convertedShippingCost}
+ format={{
+ style: "currency",
+ currency: routeData?.salesOrder.currencyCode ?? "USD",
+ }}
+ locales={locale}
+ />
+ </>
+ ) : isEditable ? (
+ <Button
+ variant="link"
+ size="sm"
+ className="text-muted-foreground"
+ onClick={onEditShippingCost}
+ >
+ Add Shipping
+ </Button>
+ ) : null}
+ </HStack>
<HStack className="justify-between text-xl font-bold w-full">
<span>Total:</span>
<MotionNumber
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delivery.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delivery.tsx
new file mode 100644
index 0000000000..d64fb71fd2
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delivery.tsx
@@ -0,0 +1,59 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { redirect } from "@vercel/remix";
+import {
+ purchaseInvoiceDeliveryValidator,
+ upsertPurchaseInvoiceDelivery,
+} from "~/modules/invoicing";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "invoicing",
+ });
+
+ const { invoiceId } = params;
+ if (!invoiceId) throw new Error("Could not find invoiceId");
+
+ const formData = await request.formData();
+ const validation = await validator(purchaseInvoiceDeliveryValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ 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) {
+ throw redirect(
+ path.to.purchaseInvoice(invoiceId),
+ await flash(
+ request,
+ error(
+ updatePurchaseInvoiceDelivery.error,
+ "Failed to update purchase invoice delivery"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.purchaseInvoice(invoiceId),
+ await flash(request, success("Updated purchase invoice delivery"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx
index 4d6b349dba..816d7f9028 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx
@@ -8,16 +8,22 @@ import { Await, useLoaderData, useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { Suspense } from "react";
+import { Suspense, useRef } from "react";
import { Fragment } from "react/jsx-runtime";
import { useRouteData } from "~/hooks";
-import type { PurchaseInvoice, PurchaseInvoiceLine } from "~/modules/invoicing";
+import type {
+ PurchaseInvoice,
+ PurchaseInvoiceDelivery,
+ PurchaseInvoiceLine,
+} from "~/modules/invoicing";
import {
getPurchaseInvoice,
PurchaseInvoiceSummary,
purchaseInvoiceValidator,
upsertPurchaseInvoice,
} 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 {
SupplierInteractionDocuments,
@@ -26,10 +32,6 @@ import {
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
-type LoaderData = {
- internalNotes: JSONContent;
-};
-
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client } = await requirePermissions(request, {
view: "invoicing",
@@ -49,7 +51,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- return json<LoaderData>({
+ return json({
internalNotes: (invoice.data?.internalNotes ?? {}) as JSONContent,
});
}
@@ -106,16 +108,23 @@ export default function PurchaseInvoiceBasicRoute() {
const invoiceData = useRouteData<{
purchaseInvoice: PurchaseInvoice;
purchaseInvoiceLines: PurchaseInvoiceLine[];
+ purchaseInvoiceDelivery: PurchaseInvoiceDelivery;
interaction: SupplierInteraction;
files: Promise<FileObject[]>;
}>(path.to.purchaseInvoice(invoiceId));
if (!invoiceData?.purchaseInvoice)
throw new Error("purchaseInvoice not found");
- const { purchaseInvoice } = invoiceData;
+ const { purchaseInvoice, purchaseInvoiceDelivery } = invoiceData;
if (!invoiceData) throw new Error("Could not find invoice data");
+ const deliveryFormRef = useRef<PurchaseInvoiceDeliveryFormRef>(null);
+
+ const handleEditShippingCost = () => {
+ deliveryFormRef.current?.focusShippingCost();
+ };
+
const initialValues = {
id: purchaseInvoice.id ?? "",
invoiceId: purchaseInvoice.invoiceId ?? "",
@@ -130,9 +139,18 @@ export default function PurchaseInvoiceBasicRoute() {
...getCustomFields(purchaseInvoice.customFields),
};
+ const deliveryInitialValues = {
+ id: purchaseInvoiceDelivery.id,
+ locationId: purchaseInvoiceDelivery.locationId ?? "",
+ supplierShippingCost: purchaseInvoiceDelivery.supplierShippingCost ?? 0,
+ shippingMethodId: purchaseInvoiceDelivery.shippingMethodId ?? "",
+ shippingTermId: purchaseInvoiceDelivery.shippingTermId ?? "",
+ ...getCustomFields(purchaseInvoiceDelivery.customFields),
+ };
+
return (
<Fragment key={invoiceId}>
- <PurchaseInvoiceSummary />
+ <PurchaseInvoiceSummary onEditShippingCost={handleEditShippingCost} />
<SupplierInteractionNotes
key={`notes-${initialValues.id}`}
id={invoiceId}
@@ -159,6 +177,13 @@ export default function PurchaseInvoiceBasicRoute() {
)}
</Await>
</Suspense>
+ <PurchaseInvoiceDeliveryForm
+ key={`delivery-${invoiceId}`}
+ ref={deliveryFormRef}
+ initialValues={deliveryInitialValues}
+ currencyCode={initialValues.currencyCode}
+ defaultCollapsed={true}
+ />
</Fragment>
);
}
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
index ba60a88566..995f6a6c3a 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
@@ -9,6 +9,7 @@ import { PanelProvider, ResizablePanels } from "~/components/Layout";
import {
PurchaseInvoiceHeader,
getPurchaseInvoice,
+ getPurchaseInvoiceDelivery,
getPurchaseInvoiceLines,
} from "~/modules/invoicing";
import PurchaseInvoiceExplorer from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer";
@@ -34,10 +35,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
- const [purchaseInvoice, purchaseInvoiceLines] = await Promise.all([
- getPurchaseInvoice(client, invoiceId),
- getPurchaseInvoiceLines(client, invoiceId),
- ]);
+ const [purchaseInvoice, purchaseInvoiceLines, purchaseInvoiceDelivery] =
+ await Promise.all([
+ getPurchaseInvoice(client, invoiceId),
+ getPurchaseInvoiceLines(client, invoiceId),
+ getPurchaseInvoiceDelivery(client, invoiceId),
+ ]);
if (purchaseInvoice.error) {
throw redirect(
@@ -59,6 +62,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
purchaseInvoice: purchaseInvoice.data,
purchaseInvoiceLines: purchaseInvoiceLines.data ?? [],
+ purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,
files: getSupplierInteractionDocuments(
client,
companyId,
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
index 878d1fbeec..18c66cf4be 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx
@@ -8,7 +8,7 @@ import { Await, useLoaderData, useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { Suspense } from "react";
+import { Suspense, useRef } from "react";
import { useRouteData } from "~/hooks";
import type {
PurchaseOrder,
@@ -26,6 +26,7 @@ import {
PurchaseOrderPaymentForm,
PurchaseOrderSummary,
} from "~/modules/purchasing/ui/PurchaseOrder";
+import type { PurchaseOrderDeliveryFormRef } from "~/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm";
import {
SupplierInteractionDocuments,
SupplierInteractionNotes,
@@ -122,6 +123,12 @@ export default function PurchaseOrderBasicRoute() {
}>(path.to.purchaseOrder(orderId));
if (!orderData) throw new Error("Could not find order data");
+ const deliveryFormRef = useRef<PurchaseOrderDeliveryFormRef>(null);
+
+ const handleEditShippingCost = () => {
+ deliveryFormRef.current?.focusShippingCost();
+ };
+
const initialValues = {
id: orderData?.purchaseOrder?.id ?? "",
purchaseOrderId: orderData?.purchaseOrder?.purchaseOrderId ?? "",
@@ -172,7 +179,7 @@ export default function PurchaseOrderBasicRoute() {
return (
<>
- <PurchaseOrderSummary />
+ <PurchaseOrderSummary onEditShippingCost={handleEditShippingCost} />
<SupplierInteractionNotes
key={`notes-${initialValues.id}`}
id={orderData.purchaseOrder.id}
@@ -202,8 +209,10 @@ export default function PurchaseOrderBasicRoute() {
</Suspense>
<PurchaseOrderDeliveryForm
key={`delivery-${orderId}`}
+ ref={deliveryFormRef}
initialValues={deliveryInitialValues}
currencyCode={initialValues.currencyCode}
+ defaultCollapsed={true}
/>
<PurchaseOrderPaymentForm
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
index e439920bb6..261fc10f04 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
@@ -8,7 +8,7 @@ import { Await, useLoaderData, useParams } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { Suspense } from "react";
+import { Suspense, useRef } from "react";
import { useRouteData } from "~/hooks";
import type {
Opportunity,
@@ -27,6 +27,7 @@ import {
QuoteShipmentForm,
QuoteSummary,
} from "~/modules/sales/ui/Quotes";
+import type { QuoteShipmentFormRef } from "~/modules/sales/ui/Quotes/QuoteShipmentForm";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -110,6 +111,13 @@ export default function QuoteDetailsRoute() {
}>(path.to.quote(quoteId));
if (!quoteData) throw new Error("Could not find quote data");
+
+ const shipmentFormRef = useRef<QuoteShipmentFormRef>(null);
+
+ const handleEditShippingCost = () => {
+ shipmentFormRef.current?.focusShippingCost();
+ };
+
const initialValues = {
id: quoteData?.quote?.id ?? "",
customerId: quoteData?.quote?.customerId ?? "",
@@ -152,7 +160,7 @@ export default function QuoteDetailsRoute() {
key={`state-${initialValues.id}`}
opportunity={quoteData?.opportunity!}
/>
- <QuoteSummary key={quoteId} />
+ <QuoteSummary key={quoteId} onEditShippingCost={handleEditShippingCost} />
<OpportunityNotes
key={`notes-${initialValues.id}`}
id={quoteData.quote.id}
@@ -186,6 +194,7 @@ export default function QuoteDetailsRoute() {
/>
<QuoteShipmentForm
key={`shipment-${initialValues.id}`}
+ ref={shipmentFormRef}
initialValues={shipmentInitialValues}
/>
</>
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
index 7d34b7fe29..170c3b5b06 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
@@ -9,7 +9,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { JSONContent } from "@tiptap/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { Suspense } from "react";
+import { Suspense, useRef } from "react";
import { useRouteData } from "~/hooks";
import type { Opportunity, SalesOrder, SalesOrderLine } from "~/modules/sales";
import {
@@ -29,6 +29,7 @@ import {
SalesOrderShipmentForm,
SalesOrderSummary,
} from "~/modules/sales/ui/SalesOrder";
+import type { SalesOrderShipmentFormRef } from "~/modules/sales/ui/SalesOrder/SalesOrderShipmentForm";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
@@ -139,6 +140,12 @@ export default function SalesOrderDetailsRoute() {
if (!orderData) throw new Error("Could not find order data");
+ const shipmentFormRef = useRef<SalesOrderShipmentFormRef>(null);
+
+ const handleEditShippingCost = () => {
+ shipmentFormRef.current?.focusShippingCost();
+ };
+
const shipmentInitialValues = {
id: shipment.id,
locationId: shipment?.locationId ?? "",
@@ -172,7 +179,7 @@ export default function SalesOrderDetailsRoute() {
key={`state-${orderId}`}
opportunity={orderData?.opportunity!}
/>
- <SalesOrderSummary />
+ <SalesOrderSummary onEditShippingCost={handleEditShippingCost} />
<OpportunityNotes
key={`notes-${orderId}`}
id={orderData.salesOrder.id}
@@ -203,6 +210,7 @@ export default function SalesOrderDetailsRoute() {
<SalesOrderShipmentForm
key={`shipment-${orderId}`}
+ ref={shipmentFormRef}
initialValues={shipmentInitialValues}
/>
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 58737c0efa..c8ea6bfbd4 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -650,6 +650,8 @@ export const path = {
profile: `${x}/account/profile`,
purchaseInvoice: (id: string) =>
generatePath(`${x}/purchase-invoice/${id}`),
+ purchaseInvoiceDelivery: (id: string) =>
+ generatePath(`${x}/purchase-invoice/${id}/delivery`),
purchaseInvoiceDetails: (id: string) =>
generatePath(`${x}/purchase-invoice/${id}/details`),
purchaseInvoiceExchangeRate: (id: string) =>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5cfc28ce4f..4c916e0f7f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13550,6 +13550,120 @@ export type Database = {
},
]
}
+ purchaseInvoiceDelivery: {
+ Row: {
+ companyId: string
+ customFields: Json | null
+ id: string
+ locationId: string | null
+ shippingMethodId: string | null
+ shippingTermId: string | null
+ supplierShippingCost: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ customFields?: Json | null
+ id: string
+ locationId?: string | null
+ shippingMethodId?: string | null
+ shippingTermId?: string | null
+ supplierShippingCost?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ customFields?: Json | null
+ id?: string
+ locationId?: string | null
+ shippingMethodId?: string | null
+ shippingTermId?: string | null
+ supplierShippingCost?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "purchaseInvoice"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "purchaseInvoices"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_shippingMethodId_fkey"
+ columns: ["shippingMethodId"]
+ isOneToOne: false
+ referencedRelation: "shippingMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_shippingTermId_fkey"
+ columns: ["shippingTermId"]
+ isOneToOne: false
+ referencedRelation: "shippingTerm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
purchaseInvoiceLine: {
Row: {
accountNumber: string | null
@@ -30301,7 +30415,6 @@ export type Database = {
itemType: Database["public"]["Enums"]["itemType"] | null
jobs: Json[] | null
locationId: string | null
- locationName: string | null
orderDate: string | null
orderTotal: number | null
paymentTermId: string | null
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 68188e8386..213ed0ebc2 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -196,6 +196,20 @@ serve(async (req: Request) => {
throw new Error("Purchase invoice not created");
purchaseInvoiceId = purchaseInvoice.id;
+ await trx
+ .insertInto("purchaseInvoiceDelivery")
+ .values({
+ id: purchaseInvoiceId,
+ locationId: purchaseOrderDelivery.data.locationId,
+ supplierShippingCost:
+ purchaseOrderDelivery.data.supplierShippingCost ?? 0,
+ shippingMethodId: purchaseOrderDelivery.data.shippingMethodId,
+ shippingTermId: purchaseOrderDelivery.data.shippingTermId,
+ companyId,
+ updatedBy: userId,
+ })
+ .execute();
+
const purchaseInvoiceLines = uninvoicedLines?.reduce<
Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][]
>((acc, line) => {
diff --git a/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts b/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
index 294bef6c0d..95bbdeb11d 100644
--- a/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
+++ b/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
@@ -99,6 +99,10 @@ serve(async (req: Request) => {
const outstandingQuantity =
d.purchaseQuantity - (previouslyReceivedQuantitiesByLine[d.id!] ?? 0);
+ const shippingAndTaxUnitCost =
+ ((d.taxAmount ?? 0) + (d.shippingCost ?? 0)) /
+ (d.purchaseQuantity * (d.conversionFactor ?? 1));
+
acc.push({
lineId: d.id,
companyId: companyId,
@@ -108,7 +112,8 @@ serve(async (req: Request) => {
outstandingQuantity: outstandingQuantity * (d.conversionFactor ?? 1),
receivedQuantity: outstandingQuantity * (d.conversionFactor ?? 1),
conversionFactor: d.conversionFactor ?? 1,
- unitPrice: d.unitPrice / (d.conversionFactor ?? 1),
+ unitPrice:
+ d.unitPrice / (d.conversionFactor ?? 1) + shippingAndTaxUnitCost,
unitOfMeasure: d.inventoryUnitOfMeasureCode ?? "EA",
locationId: d.locationId,
shelfId: d.shelfId,
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5cfc28ce4f..4c916e0f7f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -13550,6 +13550,120 @@ export type Database = {
},
]
}
+ purchaseInvoiceDelivery: {
+ Row: {
+ companyId: string
+ customFields: Json | null
+ id: string
+ locationId: string | null
+ shippingMethodId: string | null
+ shippingTermId: string | null
+ supplierShippingCost: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ customFields?: Json | null
+ id: string
+ locationId?: string | null
+ shippingMethodId?: string | null
+ shippingTermId?: string | null
+ supplierShippingCost?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ customFields?: Json | null
+ id?: string
+ locationId?: string | null
+ shippingMethodId?: string | null
+ shippingTermId?: string | null
+ supplierShippingCost?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "purchaseInvoice"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "purchaseInvoices"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrders"
+ referencedColumns: ["locationId"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_shippingMethodId_fkey"
+ columns: ["shippingMethodId"]
+ isOneToOne: false
+ referencedRelation: "shippingMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_shippingTermId_fkey"
+ columns: ["shippingTermId"]
+ isOneToOne: false
+ referencedRelation: "shippingTerm"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "purchaseInvoiceDelivery_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
purchaseInvoiceLine: {
Row: {
accountNumber: string | null
@@ -30301,7 +30415,6 @@ export type Database = {
itemType: Database["public"]["Enums"]["itemType"] | null
jobs: Json[] | null
locationId: string | null
- locationName: string | null
orderDate: string | null
orderTotal: number | null
paymentTermId: string | null
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 8ed23541b0..0996888989 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -46,15 +46,41 @@ serve(async (req: Request) => {
companyId
);
- const [purchaseInvoice, purchaseInvoiceLines] = await Promise.all([
- client.from("purchaseInvoice").select("*").eq("id", invoiceId).single(),
- client.from("purchaseInvoiceLine").select("*").eq("invoiceId", invoiceId),
- ]);
+ const [purchaseInvoice, purchaseInvoiceLines, purchaseInvoiceDelivery] =
+ await Promise.all([
+ client.from("purchaseInvoice").select("*").eq("id", invoiceId).single(),
+ client
+ .from("purchaseInvoiceLine")
+ .select("*")
+ .eq("invoiceId", invoiceId),
+ client
+ .from("purchaseInvoiceDelivery")
+ .select("supplierShippingCost")
+ .eq("id", invoiceId)
+ .single(),
+ ]);
if (purchaseInvoice.error)
throw new Error("Failed to fetch purchaseInvoice");
if (purchaseInvoiceLines.error)
throw new Error("Failed to fetch receipt lines");
+ if (purchaseInvoiceDelivery.error)
+ throw new Error("Failed to fetch purchase invoice delivery");
+
+ const shippingCost =
+ (purchaseInvoiceDelivery.data?.supplierShippingCost ?? 0) *
+ (purchaseInvoice.data?.exchangeRate ?? 1);
+
+ const totalLinesCost = purchaseInvoiceLines.data.reduce(
+ (acc, invoiceLine) => {
+ const lineCost =
+ (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
+ (invoiceLine.shippingCost ?? 0) +
+ (invoiceLine.taxAmount ?? 0);
+ return acc + lineCost;
+ },
+ 0
+ );
const itemIds = purchaseInvoiceLines.data.reduce<string[]>(
(acc, invoiceLine) => {
@@ -238,8 +264,21 @@ serve(async (req: Request) => {
const invoiceLineQuantityInInventoryUnit =
invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1);
- const invoiceLineUnitPriceInInventoryUnit =
- (invoiceLine.unitPrice ?? 0) / (invoiceLine.conversionFactor ?? 1);
+ const totalLineCost =
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
+ (invoiceLine.shippingCost ?? 0) +
+ (invoiceLine.taxAmount ?? 0);
+
+ const lineCostPercentageOfTotalCost =
+ totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;
+ const lineWeightedShippingCost =
+ shippingCost * lineCostPercentageOfTotalCost;
+ const totalLineCostWithWeightedShipping =
+ totalLineCost + lineWeightedShippingCost;
+
+ const invoiceLineUnitCostInInventoryUnit =
+ totalLineCostWithWeightedShipping /
+ (invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1));
// declaring shared variables between part and service cases
// outside of the switch case to avoid redeclaring them
@@ -385,9 +424,8 @@ serve(async (req: Request) => {
itemId: invoiceLine.itemId,
itemReadableId: invoiceLine.itemReadableId,
quantity: invoiceLineQuantityInInventoryUnit,
- cost: invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
- costPostedToGL:
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
+ cost: totalLineCostWithWeightedShipping,
+ costPostedToGL: totalLineCostWithWeightedShipping,
companyId,
});
@@ -400,10 +438,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupInventory.inventoryAccount,
description: "Inventory Account",
- amount: debit(
- "asset",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -416,10 +451,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupInventory.directCostAppliedAccount,
description: "Direct Cost Applied",
- amount: credit(
- "expense",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: credit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -432,10 +464,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupInventory.overheadAccount,
description: "Overhead Account",
- amount: debit(
- "asset",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -448,10 +477,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupInventory.overheadCostAppliedAccount,
description: "Overhead Cost Applied",
- amount: credit(
- "expense",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: credit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -467,10 +493,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupPurchasing.purchaseAccount,
description: "Purchase Account",
- amount: debit(
- "expense",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: debit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -486,10 +509,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: postingGroupPurchasing.payablesAccount,
description: "Accounts Payable",
- amount: credit(
- "liability",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: credit("liability", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -514,9 +534,8 @@ serve(async (req: Request) => {
itemId: invoiceLine.itemId,
itemReadableId: invoiceLine.itemReadableId,
quantity: invoiceLineQuantityInInventoryUnit,
- cost: invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
- costPostedToGL:
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
+ cost: totalLineCostWithWeightedShipping,
+ costPostedToGL: totalLineCostWithWeightedShipping,
companyId,
});
@@ -680,7 +699,7 @@ serve(async (req: Request) => {
description: "Inventory Account",
amount: debit(
"asset",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -699,7 +718,7 @@ serve(async (req: Request) => {
description: "Direct Cost Applied",
amount: credit(
"expense",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -718,7 +737,7 @@ serve(async (req: Request) => {
description: "Overhead Account",
amount: debit(
"asset",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -738,7 +757,7 @@ serve(async (req: Request) => {
description: "Overhead Cost Applied",
amount: credit(
"expense",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -760,7 +779,7 @@ serve(async (req: Request) => {
description: "Purchase Account",
amount: debit(
"expense",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -779,7 +798,7 @@ serve(async (req: Request) => {
description: "Accounts Payable",
amount: credit(
"liability",
- quantityToReverse * invoiceLineUnitPriceInInventoryUnit
+ quantityToReverse * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToReverse,
documentType: "Invoice",
@@ -808,7 +827,7 @@ serve(async (req: Request) => {
accrual: true,
amount: debit(
"asset",
- quantityToAccrue * invoiceLineUnitPriceInInventoryUnit
+ quantityToAccrue * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToAccrue,
documentType: "Invoice",
@@ -831,7 +850,7 @@ serve(async (req: Request) => {
description: "Interim Inventory Accrual",
amount: credit(
"asset",
- quantityToAccrue * invoiceLineUnitPriceInInventoryUnit
+ quantityToAccrue * invoiceLineUnitCostInInventoryUnit
),
quantity: quantityToAccrue,
documentType: "Invoice",
@@ -885,10 +904,7 @@ serve(async (req: Request) => {
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",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -904,10 +920,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: accountDefaults.data.overheadCostAppliedAccount!,
description: "Overhead Cost Applied",
- amount: credit(
- "expense",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: credit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -925,10 +938,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: accountDefaults.data.purchaseAccount!,
description: "Purchase Account",
- amount: debit(
- "expense",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: debit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
@@ -944,10 +954,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber: accountDefaults.data.payablesAccount!,
description: "Accounts Payable",
- amount: credit(
- "liability",
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
- ),
+ amount: credit("liability", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 52dc95c87b..0f4a9f6095 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -86,21 +86,39 @@ serve(async (req: Request) => {
if (!receipt.data.sourceDocumentId)
throw new Error("Receipt has no sourceDocumentId");
- const [purchaseOrder, purchaseOrderLines] = await Promise.all([
- client
- .from("purchaseOrder")
- .select("*")
- .eq("id", receipt.data.sourceDocumentId)
- .single(),
- client
- .from("purchaseOrderLine")
- .select("*")
- .eq("purchaseOrderId", receipt.data.sourceDocumentId),
- ]);
+ const [purchaseOrder, purchaseOrderLines, purchaseOrderDelivery] =
+ await Promise.all([
+ client
+ .from("purchaseOrder")
+ .select("*")
+ .eq("id", receipt.data.sourceDocumentId)
+ .single(),
+ client
+ .from("purchaseOrderLine")
+ .select("*")
+ .eq("purchaseOrderId", receipt.data.sourceDocumentId),
+ client
+ .from("purchaseOrderDelivery")
+ .select("supplierShippingCost")
+ .eq("id", receipt.data.sourceDocumentId)
+ .single(),
+ ]);
if (purchaseOrder.error)
throw new Error("Failed to fetch purchase order");
if (purchaseOrderLines.error)
throw new Error("Failed to fetch purchase order lines");
+ if (purchaseOrderDelivery.error)
+ throw new Error("Failed to fetch purchase order delivery");
+
+ const shippingCost =
+ (purchaseOrderDelivery.data?.supplierShippingCost ?? 0) *
+ (purchaseOrder.data?.exchangeRate ?? 1);
+
+ const totalLinesCost = receiptLines.data.reduce((acc, receiptLine) => {
+ const lineCost =
+ (receiptLine.receivedQuantity ?? 0) * (receiptLine.unitPrice ?? 0);
+ return acc + lineCost;
+ }, 0);
const supplier = await client
.from("supplier")
@@ -418,6 +436,7 @@ serve(async (req: Request) => {
journalLineReference,
companyId,
});
+
journalLineInserts.push({
accountNumber: entry[1].accountNumber!,
description: entry[1].description,
@@ -563,6 +582,13 @@ serve(async (req: Request) => {
(receiptLine.receivedQuantity - quantityToReverse) *
receiptLine.unitPrice;
+ // Add proportional shipping cost to the expected value based on line value percentage
+ const lineValuePercentage =
+ totalLinesCost === 0 ? 0 : expectedValue / totalLinesCost;
+ const lineWeightedShippingCost = shippingCost * lineValuePercentage;
+ const expectedValueWithShipping =
+ expectedValue + lineWeightedShippingCost;
+
const journalLineReference = nanoid();
journalLineInserts.push({
@@ -570,7 +596,7 @@ serve(async (req: Request) => {
postingGroupInventory.inventoryInterimAccrualAccount,
description: "Interim Inventory Accrual",
accrual: true,
- amount: debit("asset", expectedValue),
+ amount: debit("asset", expectedValueWithShipping),
quantity: quantityToAccrue,
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
@@ -586,7 +612,7 @@ serve(async (req: Request) => {
postingGroupInventory.inventoryReceivedNotInvoicedAccount,
description: "Inventory Received Not Invoiced",
accrual: true,
- amount: credit("liability", expectedValue),
+ amount: credit("liability", expectedValueWithShipping),
quantity: quantityToAccrue,
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
diff --git a/packages/database/supabase/migrations/20250116182231_shipping-cost-on-purchase-order.sql b/packages/database/supabase/migrations/20250116182231_shipping-cost-on-purchase-order.sql
index c8054b583a..2fdae3ea16 100644
--- a/packages/database/supabase/migrations/20250116182231_shipping-cost-on-purchase-order.sql
+++ b/packages/database/supabase/migrations/20250116182231_shipping-cost-on-purchase-order.sql
@@ -2,14 +2,101 @@ ALTER TABLE "purchaseOrderDelivery"
ADD COLUMN "supplierShippingCost" NUMERIC NOT NULL DEFAULT 0;
+
+INSERT INTO "customFieldTable" ("table", "name", "module")
+VALUES ('purchaseInvoiceDelivery', 'Purchase Invoice Delivery', 'Purchase Orders');
+
+CREATE TABLE "purchaseInvoiceDelivery" (
+ "id" TEXT NOT NULL,
+ "locationId" TEXT,
+ "shippingMethodId" TEXT,
+ "shippingTermId" TEXT,
+ "supplierShippingCost" NUMERIC NOT NULL DEFAULT 0,
+ "companyId" TEXT NOT NULL,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+
+ CONSTRAINT "purchaseInvoiceDelivery_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseInvoiceDelivery_id_fkey" FOREIGN KEY ("id") REFERENCES "purchaseInvoice" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseInvoiceDelivery_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseInvoiceDelivery_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseInvoiceDelivery_shippingTermId_fkey" FOREIGN KEY ("shippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseInvoiceDelivery_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT
+);
+
+
+CREATE POLICY "Employees with invoicing_view can view purchase invoice deliveries" ON "purchaseInvoiceDelivery"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('invoicing_view', "companyId")
+ );
+
+
+CREATE POLICY "Employees with invoicing_create can insert purchase invoice deliveries" ON "purchaseInvoiceDelivery"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('invoicing_create', "companyId")
+);
+
+CREATE POLICY "Employees with invoicing_update can update purchase invoice deliveries" ON "purchaseInvoiceDelivery"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('invoicing_update', "companyId")
+ );
+
+CREATE POLICY "Employees with invoicing_delete can delete purchase invoice deliveries" ON "purchaseInvoiceDelivery"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('invoicing_delete', "companyId")
+ );
+
+
+-- Backfill purchaseInvoiceDelivery table for existing purchase invoices
+WITH supplier_shipping AS (
+ SELECT
+ ss."supplierId",
+ ss."shippingMethodId",
+ ss."shippingTermId"
+ FROM "supplierShipping" ss
+),
+purchase_invoices AS (
+ SELECT
+ pi."id",
+ pi."supplierId",
+ pi."companyId",
+ pi."locationId"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pi.id = pid.id
+ WHERE pid.id IS NULL
+)
+INSERT INTO "purchaseInvoiceDelivery" (
+ "id",
+ "locationId",
+ "shippingMethodId",
+ "shippingTermId",
+ "companyId"
+)
+SELECT
+ pi."id",
+ pi."locationId",
+ ss."shippingMethodId",
+ ss."shippingTermId",
+ pi."companyId"
+FROM purchase_invoices pi
+LEFT JOIN supplier_shipping ss ON pi."supplierId" = ss."supplierId";
+
DROP VIEW IF EXISTS "purchaseOrders";
CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS
SELECT
p.*,
pl."thumbnailPath",
pl."itemType",
- pl."orderTotal",
- pd."supplierShippingCost",
+ pl."orderTotal" + pd."supplierShippingCost" * p."exchangeRate" AS "orderTotal",
pd."shippingMethodId",
pd."shippingTermId",
pd."receiptRequestedDate",
@@ -17,8 +104,8 @@ CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS
pd."deliveryDate",
pd."dropShipment",
pp."paymentTermId",
- l."id" AS "locationId",
- l."name" AS "locationName"
+ pd."locationId",
+ pd."supplierShippingCost"
FROM "purchaseOrder" p
LEFT JOIN (
SELECT
@@ -37,5 +124,108 @@ CREATE OR REPLACE VIEW "purchaseOrders" WITH(SECURITY_INVOKER=true) AS
) pl ON pl."purchaseOrderId" = p."id"
LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"
LEFT JOIN "shippingTerm" st ON st."id" = pd."shippingTermId"
- LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id"
- LEFT JOIN "location" l ON l."id" = pd."locationId";
\ No newline at end of file
+ LEFT JOIN "purchaseOrderPayment" pp ON pp."id" = p."id";
+
+
+DROP VIEW IF EXISTS "purchaseInvoices";
+CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ pi."id",
+ pi."invoiceId",
+ pi."supplierId",
+ pi."invoiceSupplierId",
+ pi."supplierInteractionId",
+ pi."supplierReference",
+ pi."invoiceSupplierContactId",
+ pi."invoiceSupplierLocationId",
+ pi."locationId",
+ pi."postingDate",
+ pi."dateIssued",
+ pi."dateDue",
+ pi."datePaid",
+ pi."paymentTermId",
+ pi."currencyCode",
+ pi."exchangeRate",
+ pi."exchangeRateUpdatedAt",
+ pi."subtotal",
+ pi."totalDiscount",
+ pi."totalAmount",
+ pi."totalTax",
+ pi."balance",
+ pi."assignee",
+ pi."createdBy",
+ pi."createdAt",
+ pi."updatedBy",
+ pi."updatedAt",
+ pi."internalNotes",
+ pi."customFields",
+ pi."companyId",
+ pl."thumbnailPath",
+ pl."itemType",
+ pl."orderTotal" + COALESCE(pid."supplierShippingCost", 0) * pi."exchangeRate" AS "orderTotal",
+ CASE
+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Submitted' THEN 'Overdue'
+ ELSE pi."status"
+ END AS status,
+ pt."name" AS "paymentTermName"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN (
+ SELECT
+ pol."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(COALESCE(pol."quantity", 0)*(COALESCE(pol."unitPrice", 0)) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)) AS "orderTotal",
+ MIN(i."type") AS "itemType"
+ FROM "purchaseInvoiceLine" pol
+ LEFT JOIN "item" i
+ ON i."id" = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY pol."invoiceId"
+ ) pl ON pl."invoiceId" = pi."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id";
+
+
+DROP VIEW IF EXISTS "salesOrders";
+CREATE OR REPLACE VIEW "salesOrders" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.*,
+ sl."thumbnailPath",
+ sl."itemType",
+ sl."orderTotal" + COALESCE(ss."shippingCost", 0) AS "orderTotal",
+ sl."jobs",
+ st."name" AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost"
+ FROM "salesOrder" s
+ LEFT JOIN (
+ SELECT
+ sol."salesOrderId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM((1+COALESCE(sol."taxPercent", 0))*(COALESCE(sol."saleQuantity", 0)*(COALESCE(sol."unitPrice", 0)) + COALESCE(sol."shippingCost", 0) + COALESCE(sol."addOnCost", 0))) AS "orderTotal",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object('id', j.id, 'jobId', j."jobId", 'status', j."status")
+ ELSE NULL
+ END
+ ) FILTER (WHERE j.id IS NOT NULL) AS "jobs"
+ FROM "salesOrderLine" sol
+ LEFT JOIN "item" i
+ ON i."id" = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "job" j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol."id"
+ GROUP BY sol."salesOrderId"
+ ) sl ON sl."salesOrderId" = s."id"
+ LEFT JOIN "salesOrderShipment" ss ON ss."id" = s."id"
+ LEFT JOIN "shippingTerm" st ON st."id" = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp."id" = s."id";
\ No newline at end of file
diff --git a/packages/documents/src/pdf/PurchaseOrderPDF.tsx b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
index 300524f972..1e85d9f241 100644
--- a/packages/documents/src/pdf/PurchaseOrderPDF.tsx
+++ b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
@@ -187,7 +187,7 @@ const PurchaseOrderPDF = ({
>
<Text style={tw("w-[35%]")}>Description</Text>
<Text style={tw("w-[15%] text-right")}>Qty</Text>
- <Text style={tw("w-[15%] text-right")}>UnitPrice</Text>
+ <Text style={tw("w-[15%] text-right")}>Unit Price</Text>
<Text style={tw("w-[15%] text-right")}>Shipping</Text>
<Text style={tw("w-[20%] text-right")}>Total</Text>
</View>
@@ -267,7 +267,7 @@ const PurchaseOrderPDF = ({
>
<Text>Total</Text>
<Text style={tw("font-bold text-black")}>
- {formatter.format(getTotal(purchaseOrderLines))}
+ {formatter.format(getTotal(purchaseOrderLines) + shippingCost)}
</Text>
</View>
</View>
diff --git a/packages/form/src/components/Number.tsx b/packages/form/src/components/Number.tsx
index a1f14482f9..07b9e97b75 100644
--- a/packages/form/src/components/Number.tsx
+++ b/packages/form/src/components/Number.tsx
@@ -59,7 +59,7 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
})}
>
<NumberInputGroup className="relative">
- <NumberInput isReadOnly={isReadOnly} />
+ <NumberInput isReadOnly={isReadOnly} ref={ref} />
{!isReadOnly && (
<NumberInputStepper>
<NumberIncrementStepper>
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index b89abd2f3e..76dbea7dfc 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -28,7 +28,7 @@ export const buttonVariants = cva(
"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-button-danger",
ghost:
"bg-transparent hover:bg-primary/10 text-accent-foreground hover:text-accent-foreground/90",
- link: "text-foreground hover:text-foreground underline-offset-4 hover:underline",
+ link: "text-foreground hover:text-foreground underline-offset-4 hover:underline px-0 py-0",
},
size: {
sm: "h-6 rounded-sm text-xs",
@@ -81,6 +81,21 @@ export const buttonVariants = cva(
isIcon: false,
class: "px-6",
},
+ {
+ variant: "link",
+ size: "sm",
+ class: "px-0 py-0",
+ },
+ {
+ variant: "link",
+ size: "md",
+ class: "px-0 py-0",
+ },
+ {
+ variant: "link",
+ size: "lg",
+ class: "px-0 py-0",
+ },
],
defaultVariants: {
variant: "primary",
diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsx
index 4cc7384a90..9531ec8cbc 100644
--- a/packages/react/src/Card.tsx
+++ b/packages/react/src/Card.tsx
@@ -6,6 +6,8 @@ import { cn } from "./utils/cn";
interface CardProps extends HTMLAttributes<HTMLDivElement> {
isCollapsible?: boolean;
defaultCollapsed?: boolean;
+ isCollapsed?: boolean;
+ onCollapsedChange?: (isCollapsed: boolean) => void;
}
const CardContext = createContext<
@@ -18,13 +20,25 @@ const Card = forwardRef<HTMLDivElement, CardProps>(
className,
isCollapsible = false,
defaultCollapsed = false,
+ isCollapsed: controlledIsCollapsed,
+ onCollapsedChange,
children,
...props
},
ref
) => {
- const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
- const toggle = () => setIsCollapsed(!isCollapsed);
+ const [uncontrolledIsCollapsed, setUncontrolledIsCollapsed] =
+ useState(defaultCollapsed);
+
+ const isCollapsed = controlledIsCollapsed ?? uncontrolledIsCollapsed;
+
+ const toggle = () => {
+ if (onCollapsedChange) {
+ onCollapsedChange(!isCollapsed);
+ } else {
+ setUncontrolledIsCollapsed(!isCollapsed);
+ }
+ };
return (
<CardContext.Provider value={{ isCollapsed, toggle }}>
diff --git a/packages/react/src/ModelViewer.tsx b/packages/react/src/ModelViewer.tsx
index b484ccdea9..f202dac0c7 100644
--- a/packages/react/src/ModelViewer.tsx
+++ b/packages/react/src/ModelViewer.tsx
@@ -61,18 +61,18 @@ export function ModelViewer({
45.0
),
backgroundColor: isDarkMode
- ? new OV.RGBAColor(20, 22, 25, 0)
+ ? new OV.RGBAColor(21, 22, 25, 0)
: new OV.RGBAColor(255, 255, 255, 0),
defaultColor: new OV.RGBColor(0, 125, 125),
onModelLoaded: (model) => {
if (viewerRef.current) {
const viewer3D = viewerRef.current.GetViewer();
- updateColor(
- color ??
- getComputedStyle(document.documentElement)
- .getPropertyValue("--card")
- .trim()
- );
+ // updateColor(
+ // color ??
+ // getComputedStyle(document.documentElement)
+ // .getPropertyValue("--card")
+ // .trim()
+ // );
viewer3D.Resize(
parentDiv.current?.clientWidth,
@@ -196,26 +196,26 @@ export function ModelViewer({
viewer.LoadModelFromUrlList([url]);
}
- function updateColor(color: string) {
- if (!viewerRef.current) return;
+ // function updateColor(color: string) {
+ // if (!viewerRef.current) return;
- const viewer3D = viewerRef.current.GetViewer();
- viewer3D.mainModel.EnumerateMeshes((mesh) => {
- if (Array.isArray(mesh.material)) {
- mesh.material.forEach((material) => {
- if (material) {
- (material as THREE.MeshStandardMaterial).color.set(color);
- }
- });
- }
- });
- }
+ // const viewer3D = viewerRef.current.GetViewer();
+ // viewer3D.mainModel.EnumerateMeshes((mesh) => {
+ // if (Array.isArray(mesh.material)) {
+ // mesh.material.forEach((material) => {
+ // if (material) {
+ // (material as THREE.MeshStandardMaterial).color.set(color);
+ // }
+ // });
+ // }
+ // });
+ // }
- useEffect(() => {
- if (color) {
- updateColor(color);
- }
- }, [color]);
+ // useEffect(() => {
+ // if (color) {
+ // updateColor(color);
+ // }
+ // }, [color]);
useEffect(() => {
if (!file || !viewerRef.current) return;
@@ -239,13 +239,13 @@ export function ModelViewer({
: new OV.RGBAColor(255, 255, 255, 255)
);
- if (!color) {
- updateColor(
- getComputedStyle(document.documentElement)
- .getPropertyValue("--card")
- .trim()
- );
- }
+ // if (!color) {
+ // updateColor(
+ // getComputedStyle(document.documentElement)
+ // .getPropertyValue("--card")
+ // .trim()
+ // );
+ // }
}
}, [isDarkMode, color]);
diff --git a/packages/react/src/Number.tsx b/packages/react/src/Number.tsx
index b295938367..8fe05af8f6 100644
--- a/packages/react/src/Number.tsx
+++ b/packages/react/src/Number.tsx
@@ -1,6 +1,7 @@
import * as ReactAria from "react-aria-components";
import { Input, type InputProps } from "./Input";
+import { forwardRef } from "react";
import { cn } from "./utils/cn";
export type NumberFieldProps = ReactAria.NumberFieldProps;
@@ -30,31 +31,42 @@ const NumberInputStepper = ({
);
};
-const NumberInput = ({ className, ...props }: InputProps) => {
- return (
- <Input
- ref={(input) => {
- if (input) {
- const handleFocus = () => input.select();
+const NumberInput = forwardRef<HTMLInputElement, InputProps>(
+ ({ className, ...props }, ref) => {
+ const handleFocus = (input: HTMLInputElement) => {
+ input.select();
+ };
+
+ const internalRef = (input: HTMLInputElement | null) => {
+ if (input && !input.hasAttribute("data-focus-listener")) {
+ input.addEventListener("focus", () => handleFocus(input));
+ input.setAttribute("data-focus-listener", "true");
- // Check if the event listener is already added
- if (!input.hasAttribute("data-focus-listener")) {
- input.addEventListener("focus", handleFocus);
- input.setAttribute("data-focus-listener", "true");
+ return () => {
+ input.removeEventListener("focus", () => handleFocus(input));
+ input.removeAttribute("data-focus-listener");
+ };
+ }
+ };
- // Remove the event listener when the component unmounts
- return () => {
- input.removeEventListener("focus", handleFocus);
- input.removeAttribute("data-focus-listener");
- };
+ return (
+ <Input
+ ref={(input) => {
+ if (typeof ref === "function") {
+ ref(input);
+ } else if (ref) {
+ ref.current = input;
}
- }
- }}
- className={cn("pr-6", className)}
- {...props}
- />
- );
-};
+ internalRef(input);
+ }}
+ className={cn("pr-6", className)}
+ {...props}
+ />
+ );
+ }
+);
+
+NumberInput.displayName = "NumberInput";
const NumberIncrementStepper = ({
className,
diff --git a/packages/react/src/Popover.tsx b/packages/react/src/Popover.tsx
index cda2abaadb..7fbef0e5f7 100644
--- a/packages/react/src/Popover.tsx
+++ b/packages/react/src/Popover.tsx
@@ -20,7 +20,7 @@ const PopoverContent = forwardRef<
align={align}
sideOffset={sideOffset}
className={cn(
- "z-50 w-72 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ "z-50 rounded-md border border-border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
diff --git a/packages/react/src/Tabs.tsx b/packages/react/src/Tabs.tsx
index 215b36693f..8bb6a6f82e 100644
--- a/packages/react/src/Tabs.tsx
+++ b/packages/react/src/Tabs.tsx
@@ -15,7 +15,7 @@ const TabsList = forwardRef<
<TabsPrimitive.List
ref={ref}
className={cn(
- "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
+ "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground shadow-[inset_0_1px_2px_rgba(0,0,0,0.15)]",
className
)}
{...props}