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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add payment terms and shipping to sales orders and quotes
Brad Barbin8bb798d95e33
diff --git a/apps/carbon/app/components/Form/PaymentTerm.tsx b/apps/carbon/app/components/Form/PaymentTerm.tsxnew file mode 100644index 0000000000..8820ac48df--- /dev/null+++ b/apps/carbon/app/components/Form/PaymentTerm.tsx@@ -0,0 +1,81 @@+import { useDisclosure, useMount } from "@carbon/react";+import { useFetcher } from "@remix-run/react";+import { useMemo, useRef, useState } from "react";+import { usePermissions } from "~/hooks";+import type { getPaymentTermsList } from "~/modules/accounting";+import { PaymentTermForm } from "~/modules/accounting";+import { path } from "~/utils/path";+import type { ComboboxProps } from "./Combobox";+import Combobox from "./Combobox";+import CreatableCombobox from "./CreatableCombobox";++type PaymentTermSelectProps = Omit<ComboboxProps, "options">;++const PaymentTerm = (props: PaymentTermSelectProps) => {+ const options = usePaymentTerm();+ const permissions = usePermissions();++ const newPaymentTermModal = useDisclosure();+ const [created, setCreated] = useState<string>("");+ const triggerRef = useRef<HTMLButtonElement>(null);++ return permissions.can("create", "accounting") ? (+ <>+ <CreatableCombobox+ ref={triggerRef}+ options={options}+ {...props}+ label={props?.label ?? "Payment Term"}+ onCreateOption={(option) => {+ newPaymentTermModal.onOpen();+ setCreated(option);+ }}+ />+ {newPaymentTermModal.isOpen && (+ <PaymentTermForm+ type="modal"+ onClose={() => {+ setCreated("");+ newPaymentTermModal.onClose();+ triggerRef.current?.click();+ }}+ initialValues={{+ name: created,+ calculationMethod: "Net" as const,+ daysDue: 0,+ discountPercentage: 0,+ daysDiscount: 0,+ }}+ />+ )}+ </>+ ) : (+ <Combobox+ options={options}+ {...props}+ label={props?.label ?? "Payment Term"}+ />+ );+};++PaymentTerm.displayName = "PaymentTerm";++export default PaymentTerm;++export const usePaymentTerm = () => {+ const paymentTermFetcher =+ useFetcher<Awaited<ReturnType<typeof getPaymentTermsList>>>();++ useMount(() => {+ paymentTermFetcher.load(path.to.api.paymentTerms);+ });++ const options = useMemo(() => {+ return (paymentTermFetcher.data?.data ?? []).map((c) => ({+ value: c.id,+ label: c.name,+ }));+ }, [paymentTermFetcher.data?.data]);++ return options;+};diff --git a/apps/carbon/app/components/Form/ShippingMethod.tsx b/apps/carbon/app/components/Form/ShippingMethod.tsxnew file mode 100644index 0000000000..5cfb1f6185--- /dev/null+++ b/apps/carbon/app/components/Form/ShippingMethod.tsx@@ -0,0 +1,78 @@+import { useDisclosure, useMount } from "@carbon/react";+import { useFetcher } from "@remix-run/react";+import { useMemo, useRef, useState } from "react";+import { usePermissions } from "~/hooks";+import type { getShippingMethodsList } from "~/modules/inventory";+import { ShippingMethodForm } from "~/modules/inventory";+import { path } from "~/utils/path";+import type { ComboboxProps } from "./Combobox";+import Combobox from "./Combobox";+import CreatableCombobox from "./CreatableCombobox";++type ShippingMethodSelectProps = Omit<ComboboxProps, "options">;++const ShippingMethod = (props: ShippingMethodSelectProps) => {+ const options = useShippingMethod();+ const permissions = usePermissions();++ const newShippingMethodModal = useDisclosure();+ const [created, setCreated] = useState<string>("");+ const triggerRef = useRef<HTMLButtonElement>(null);++ return permissions.can("create", "inventory") ? (+ <>+ <CreatableCombobox+ ref={triggerRef}+ options={options}+ {...props}+ label={props?.label ?? "Shipping Method"}+ onCreateOption={(option) => {+ newShippingMethodModal.onOpen();+ setCreated(option);+ }}+ />+ {newShippingMethodModal.isOpen && (+ <ShippingMethodForm+ type="modal"+ onClose={() => {+ setCreated("");+ newShippingMethodModal.onClose();+ triggerRef.current?.click();+ }}+ initialValues={{+ name: created,+ carrier: "" as "FedEx",+ }}+ />+ )}+ </>+ ) : (+ <Combobox+ options={options}+ {...props}+ label={props?.label ?? "Shipping Method"}+ />+ );+};++ShippingMethod.displayName = "ShippingMethod";++export default ShippingMethod;++export const useShippingMethod = () => {+ const shippingMethodFetcher =+ useFetcher<Awaited<ReturnType<typeof getShippingMethodsList>>>();++ useMount(() => {+ shippingMethodFetcher.load(path.to.api.shippingMethods);+ });++ const options = useMemo(() => {+ return (shippingMethodFetcher.data?.data ?? []).map((c) => ({+ value: c.id,+ label: c.name,+ }));+ }, [shippingMethodFetcher.data?.data]);++ return options;+};diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.tsindex 65a85612a9..3ee1ece84e 100644--- a/apps/carbon/app/components/Form/index.ts+++ b/apps/carbon/app/components/Form/index.ts@@ -33,6 +33,7 @@ import Number from "./Number";import NumberControlled from "./NumberControlled";import Part from "./Part";import Password from "./Password";+import PaymentTerm from "./PaymentTerm";import PhoneInput from "./PhoneInput";import Process from "./Process";import Processes from "./Processes";@@ -43,6 +44,7 @@ import SelectControlled from "./SelectControlled";import Sequence from "./Sequence";import Service from "./Service";import Shift from "./Shift";+import ShippingMethod from "./ShippingMethod";import StandardFactor from "./StandardFactor";import Submit from "./Submit";import Supplier from "./Supplier";@@ -99,6 +101,7 @@ export {NumberControlled,Part,Password,+ PaymentTerm,PhoneInput,Process,Processes,@@ -109,6 +112,7 @@ export {Sequence,Service,Shift,+ ShippingMethod,StandardFactor,Submit,Supplier,diff --git a/apps/carbon/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx b/apps/carbon/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsxindex fdaec49073..d6542522c9 100644--- a/apps/carbon/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx+++ b/apps/carbon/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx@@ -1,17 +1,19 @@import {- Button,- Drawer,- DrawerBody,- DrawerContent,- DrawerFooter,- DrawerHeader,- DrawerTitle,HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,VStack,+ toast,} from "@carbon/react";import { ValidatedForm } from "@carbon/remix-validated-form";-import { useNavigate } from "@remix-run/react";-import { useState } from "react";+import { useFetcher } from "@remix-run/react";+import type { PostgrestResponse } from "@supabase/supabase-js";+import { useEffect, useState } from "react";import type { z } from "zod";import {CustomFormFields,@@ -31,96 +33,117 @@ import { path } from "~/utils/path";type PaymentTermFormProps = {initialValues: z.infer<typeof paymentTermValidator>;+ type?: "modal" | "drawer";+ open?: boolean;+ onClose?: (data?: { id: string; name: string }) => void;};-const PaymentTermForm = ({ initialValues }: PaymentTermFormProps) => {+const PaymentTermForm = ({+ initialValues,+ open = true,+ type = "drawer",+ onClose,+}: PaymentTermFormProps) => {const permissions = usePermissions();- const navigate = useNavigate();- const onClose = () => navigate(-1);+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();+ const [selectedCalculationMethod, setSelectedCalculationMethod] =+ useState<PaymentTermCalculationMethod>(initialValues.calculationMethod);++ useEffect(() => {+ if (type !== "modal") return;++ if (fetcher.state === "loading" && fetcher.data?.data) {+ onClose?.();+ toast.success(`Created payment term`);+ } else if (fetcher.state === "idle" && fetcher.data?.error) {+ toast.error(+ `Failed to create payment term: ${fetcher.data.error.message}`+ );+ }+ }, [fetcher.data, fetcher.state, onClose, type]);const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "accounting"): !permissions.can("create", "accounting");- const [selectedCalculationMethod, setSelectedCalculationMethod] = useState(- initialValues.calculationMethod- );-const calculationMethodOptions = paymentTermsCalculationMethod.map((v) => ({label: v,value: v,}));return (- <Drawer- open- onOpenChange={(open) => {- if (!open) onClose();- }}- >- <DrawerContent>- <ValidatedForm- validator={paymentTermValidator}- method="post"- action={- isEditing- ? path.to.paymentTerm(initialValues.id!)- : path.to.newPaymentTerm- }- defaultValues={initialValues}- className="flex flex-col h-full"- >- <DrawerHeader>- <DrawerTitle>{isEditing ? "Edit" : "New"} Payment Term</DrawerTitle>- </DrawerHeader>- <DrawerBody>- <Hidden name="id" />- <VStack spacing={4}>- <Input name="name" label="Name" />- <Select- name="calculationMethod"- label="After"- options={calculationMethodOptions}- onChange={(value) => {- setSelectedCalculationMethod(- value?.value as PaymentTermCalculationMethod- );- }}- />- <Number- name="daysDue"- label={`Due Days after ${selectedCalculationMethod}`}- minValue={0}- helperText="The amount of days after the calculation method that the payment is due"- />- <Number- name="daysDiscount"- label={`Discount Days after ${selectedCalculationMethod}`}- minValue={0}- helperText="The amount of days after the calculation method that the cash discount is available"- />- <Number- name="discountPercentage"- label="Discount Percent"- minValue={0}- maxValue={100}- helperText="The percentage of the cash discount. Use 0 for no discount."- />- <CustomFormFields table="paymentTerm" />- </VStack>- </DrawerBody>- <DrawerFooter>- <HStack>- <Submit isDisabled={isDisabled}>Save</Submit>- <Button variant="solid" onClick={onClose}>- Cancel- </Button>- </HStack>- </DrawerFooter>- </ValidatedForm>- </DrawerContent>- </Drawer>+ <ModalDrawerProvider type={type}>+ <ModalDrawer+ open={open}+ onOpenChange={(open) => {+ if (!open) onClose?.();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ validator={paymentTermValidator}+ method="post"+ action={+ isEditing+ ? path.to.paymentTerm(initialValues.id!)+ : path.to.newPaymentTerm+ }+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing ? "Edit" : "New"} Payment Term+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <Hidden name="type" value={type} />+ <VStack spacing={4}>+ <Input name="name" label="Name" />+ <Select+ name="calculationMethod"+ label="After"+ options={calculationMethodOptions}+ onChange={(value) => {+ setSelectedCalculationMethod(+ value?.value as PaymentTermCalculationMethod+ );+ }}+ />+ <Number+ name="daysDue"+ label={`Due Days after ${selectedCalculationMethod}`}+ minValue={0}+ helperText="The amount of days after the calculation method that the payment is due"+ />+ <Number+ name="daysDiscount"+ label={`Discount Days after ${selectedCalculationMethod}`}+ minValue={0}+ helperText="The amount of days after the calculation method that the cash discount is available"+ />+ <Number+ name="discountPercentage"+ label="Discount Percent"+ minValue={0}+ maxValue={100}+ helperText="The percentage of the cash discount. Use 0 for no discount."+ />+ <CustomFormFields table="paymentTerm" />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>);};diff --git a/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodForm.tsx b/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodForm.tsxindex 767fa4cef8..36c5112b6b 100644--- a/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodForm.tsx+++ b/apps/carbon/app/modules/inventory/ui/ShippingMethods/ShippingMethodForm.tsx@@ -1,17 +1,19 @@import {- Button,- Drawer,- DrawerBody,- DrawerContent,- DrawerFooter,- DrawerHeader,- DrawerTitle,HStack,+ ModalDrawer,+ ModalDrawerBody,+ ModalDrawerContent,+ ModalDrawerFooter,+ ModalDrawerHeader,+ ModalDrawerProvider,+ ModalDrawerTitle,VStack,+ toast,} from "@carbon/react";-import { ValidatedForm } from "@carbon/remix-validated-form";-import { useNavigate } from "@remix-run/react";+import { useFetcher } from "@remix-run/react";+import type { PostgrestResponse } from "@supabase/supabase-js";+import { useEffect } from "react";import type { z } from "zod";import {Account,@@ -30,12 +32,32 @@ import { path } from "~/utils/path";type ShippingMethodFormProps = {initialValues: z.infer<typeof shippingMethodValidator>;+ type?: "modal" | "drawer";+ open?: boolean;+ onClose?: (data?: { id: string; name: string }) => void;};-const ShippingMethodForm = ({ initialValues }: ShippingMethodFormProps) => {+const ShippingMethodForm = ({+ initialValues,+ open = true,+ type = "drawer",+ onClose,+}: ShippingMethodFormProps) => {const permissions = usePermissions();- const navigate = useNavigate();- const onClose = () => navigate(-1);+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();++ useEffect(() => {+ if (type !== "modal") return;++ if (fetcher.state === "loading" && fetcher.data?.data) {+ onClose?.();+ toast.success(`Created shipping method`);+ } else if (fetcher.state === "idle" && fetcher.data?.error) {+ toast.error(+ `Failed to create shipping method: ${fetcher.data.error.message}`+ );+ }+ }, [fetcher.data, fetcher.state, onClose, type]);const isEditing = initialValues.id !== undefined;const isDisabled = isEditing@@ -48,62 +70,63 @@ const ShippingMethodForm = ({ initialValues }: ShippingMethodFormProps) => {}));return (- <Drawer- open- onOpenChange={(open) => {- if (!open) onClose();- }}- >- <DrawerContent>- <ValidatedForm- validator={shippingMethodValidator}- method="post"- action={- isEditing- ? path.to.shippingMethod(initialValues.id!)- : path.to.newShippingMethod- }- defaultValues={initialValues}- className="flex flex-col h-full"- >- <DrawerHeader>- <DrawerTitle>- {isEditing ? "Edit" : "New"} Shipping Method- </DrawerTitle>- </DrawerHeader>- <DrawerBody>- <Hidden name="id" />- <VStack spacing={4}>- <Input name="name" label="Name" />- <Select- name="carrier"- label="Carrier"- options={shippingCarrierOptions}- />- <Account- classes={["Expense"]}- name="carrierAccountId"- label="Carrier Account"- />- <Input- name="trackingUrl"- label="Tracking URL"- prefix="https://"- />- <CustomFormFields table="shippingMethod" />- </VStack>- </DrawerBody>- <DrawerFooter>- <HStack>- <Submit isDisabled={isDisabled}>Save</Submit>- <Button size="md" variant="solid" onClick={onClose}>- Cancel- </Button>- </HStack>- </DrawerFooter>- </ValidatedForm>- </DrawerContent>- </Drawer>+ <ModalDrawerProvider type={type}>+ <ModalDrawer+ open={open}+ onOpenChange={(open) => {+ if (!open) onClose?.();+ }}+ >+ <ModalDrawerContent>+ <ValidatedForm+ validator={shippingMethodValidator}+ method="post"+ action={+ isEditing+ ? path.to.shippingMethod(initialValues.id!)+ : path.to.newShippingMethod+ }+ defaultValues={initialValues}+ fetcher={fetcher}+ className="flex flex-col h-full"+ >+ <ModalDrawerHeader>+ <ModalDrawerTitle>+ {isEditing ? "Edit" : "New"} Shipping Method+ </ModalDrawerTitle>+ </ModalDrawerHeader>+ <ModalDrawerBody>+ <Hidden name="id" />+ <Hidden name="type" value={type} />+ <VStack spacing={4}>+ <Input name="name" label="Name" />+ <Select+ name="carrier"+ label="Carrier"+ options={shippingCarrierOptions}+ />+ <Account+ classes={["Expense"]}+ name="carrierAccountId"+ label="Carrier Account"+ />+ <Input+ name="trackingUrl"+ label="Tracking URL"+ prefix="https://"+ />+ <CustomFormFields table="shippingMethod" />+ </VStack>+ </ModalDrawerBody>+ <ModalDrawerFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ </HStack>+ </ModalDrawerFooter>+ </ValidatedForm>+ </ModalDrawerContent>+ </ModalDrawer>+ </ModalDrawerProvider>);};diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsxindex ef32d71a90..e1f37c0411 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm.tsx@@ -23,24 +23,20 @@ import {SupplierContact,SupplierLocation,} from "~/components/Form";+import PaymentTerm from "~/components/Form/PaymentTerm";import { usePermissions } from "~/hooks";import {purchaseInvoiceStatusType,purchaseInvoiceValidator,} from "~/modules/invoicing";-import type { ListItem } from "~/types";type PurchaseInvoiceFormValues = z.infer<typeof purchaseInvoiceValidator>;type PurchaseInvoiceFormProps = {initialValues: PurchaseInvoiceFormValues;- paymentTerms: ListItem[];};-const PurchaseInvoiceForm = ({- initialValues,- paymentTerms,-}: PurchaseInvoiceFormProps) => {+const PurchaseInvoiceForm = ({ initialValues }: PurchaseInvoiceFormProps) => {const permissions = usePermissions();const [supplier, setSupplier] = useState<string | undefined>(initialValues.supplierId@@ -53,11 +49,6 @@ const PurchaseInvoiceForm = ({value: status,}));- const paymentTermOptions = paymentTerms.map((paymentTerm) => ({- label: paymentTerm.name,- value: paymentTerm.id,- }));-return (<ValidatedFormmethod="post"@@ -126,11 +117,7 @@ const PurchaseInvoiceForm = ({<DatePicker name="dateIssued" label="Date Issued" />{isEditing && (<>- <Select- name="paymentTermId"- label="Payment Terms"- options={paymentTermOptions}- />+ <PaymentTerm name="paymentTermId" label="Payment Terms" /><Currency name="currencyCode" label="Currency" /></>)}diff --git a/apps/carbon/app/modules/purchasing/purchasing.models.ts b/apps/carbon/app/modules/purchasing/purchasing.models.tsindex 842cdf2916..28ca5d13de 100644--- a/apps/carbon/app/modules/purchasing/purchasing.models.ts+++ b/apps/carbon/app/modules/purchasing/purchasing.models.ts@@ -50,7 +50,7 @@ export const purchaseOrderDeliveryValidator = zid: z.string(),locationId: zfd.text(z.string().optional()),shippingMethodId: zfd.text(z.string().optional()),- shippingTermId: zfd.text(z.string().optional()),+ // shippingTermId: zfd.text(z.string().optional()),trackingNumber: z.string(),deliveryDate: zfd.text(z.string().optional()),receiptRequestedDate: zfd.text(z.string().optional()),@@ -210,7 +210,7 @@ export const supplierShippingValidator = z.object({shippingSupplierId: zfd.text(z.string().optional()),shippingSupplierLocationId: zfd.text(z.string().optional()),shippingSupplierContactId: zfd.text(z.string().optional()),- shippingTermId: zfd.text(z.string().optional()),+ // shippingTermId: zfd.text(z.string().optional()),shippingMethodId: zfd.text(z.string().optional()),});diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsxindex 63603dd106..f589967d4b 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx@@ -17,24 +17,21 @@ import {Hidden,Input,Location,- Select,+ ShippingMethod,Submit,} from "~/components/Form";import { usePermissions } from "~/hooks";import { purchaseOrderDeliveryValidator } from "~/modules/purchasing";-import type { ListItem } from "~/types";type PurchaseOrderDeliveryFormProps = {initialValues: z.infer<typeof purchaseOrderDeliveryValidator>;- shippingMethods: ListItem[];- shippingTerms: ListItem[];+ // shippingTerms: ListItem[];};const PurchaseOrderDeliveryForm = ({initialValues,- shippingMethods,- shippingTerms,-}: PurchaseOrderDeliveryFormProps) => {+}: // shippingTerms,+PurchaseOrderDeliveryFormProps) => {const permissions = usePermissions();const [dropShip, setDropShip] = useState<boolean>(initialValues.dropShipment ?? false@@ -43,15 +40,10 @@ const PurchaseOrderDeliveryForm = ({initialValues.customerId);- const shippingMethodOptions = shippingMethods.map((method) => ({- label: method.name,- value: method.id,- }));-- const shippingTermOptions = shippingTerms.map((term) => ({- label: term.name,- value: term.id,- }));+ // const shippingTermOptions = shippingTerms.map((term) => ({+ // label: term.name,+ // value: term.id,+ // }));const isSupplier = permissions.is("supplier");@@ -74,17 +66,13 @@ const PurchaseOrderDeliveryForm = ({isReadOnly={isSupplier}isClearable/>- <Select- name="shippingMethodId"- label="Shipping Method"- options={shippingMethodOptions}- />- <Select+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />+ {/* <Selectname="shippingTermId"label="Shipping Terms"isReadOnly={isSupplier}options={shippingTermOptions}- />+ /> */}<DatePicker name="receiptRequestedDate" label="Requested Date" /><DatePicker name="receiptPromisedDate" label="Promised Date" />diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderPaymentForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderPaymentForm.tsxindex c27a83a846..11a15eeae8 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderPaymentForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderPaymentForm.tsx@@ -13,7 +13,7 @@ import {Currency,CustomFormFields,Hidden,- Select,+ PaymentTerm,Submit,Supplier,SupplierContact,@@ -21,16 +21,13 @@ import {} from "~/components/Form";import { usePermissions } from "~/hooks";import { purchaseOrderPaymentValidator } from "~/modules/purchasing";-import type { ListItem } from "~/types";type PurchaseOrderPaymentFormProps = {initialValues: z.infer<typeof purchaseOrderPaymentValidator>;- paymentTerms: ListItem[];};const PurchaseOrderPaymentForm = ({initialValues,- paymentTerms,}: PurchaseOrderPaymentFormProps) => {const permissions = usePermissions();@@ -38,11 +35,6 @@ const PurchaseOrderPaymentForm = ({initialValues.invoiceSupplierId);- const paymentTermOptions = paymentTerms.map((term) => ({- label: term.name,- value: term.id,- }));-return (<ValidatedFormmethod="post"@@ -72,11 +64,7 @@ const PurchaseOrderPaymentForm = ({supplier={supplier}/>- <Select- name="paymentTermId"- label="Payment Terms"- options={paymentTermOptions}- />+ <PaymentTerm name="paymentTermId" label="Payment Terms" /><Currency name="currencyCode" label="Currency" /><Boolean name="paymentComplete" label="Payment Complete" />diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsxindex 60055a3425..d7fa85ed43 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx@@ -187,11 +187,11 @@ const PurchaseOrdersTable = memo(header: "Shipping Method",cell: (item) => item.getValue(),},- {- accessorKey: "shippingTermName",- header: "Shipping Term",- cell: (item) => <Enumerable value={item.getValue<string>()} />,- },+ // {+ // accessorKey: "shippingTermName",+ // header: "Shipping Term",+ // cell: (item) => <Enumerable value={item.getValue<string>()} />,+ // },{accessorKey: "paymentTermName",header: "Payment Method",@@ -310,7 +310,7 @@ const PurchaseOrdersTable = memo(defaultColumnVisibility={{receiptPromisedDate: false,shippingMethodName: false,- shippingTermName: false,+ // shippingTermName: false,paymentTermName: false,dropShipment: false,createdBy: false,diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsxindex 8e0f1bf0f5..2b34694bd2 100644--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx@@ -21,7 +21,6 @@ import {import { Enumerable } from "~/components/Enumerable";import { usePermissions, useRouteData } from "~/hooks";import type { SupplierDetail, SupplierStatus } from "~/modules/purchasing";-import type { ListItem } from "~/types";import { path } from "~/utils/path";const SupplierHeader = () => {@@ -35,7 +34,6 @@ const SupplierHeader = () => {const sharedSupplierData = useRouteData<{supplierStatuses: SupplierStatus[];- paymentTerms: ListItem[];}>(path.to.supplierRoot);const supplierStatus = sharedSupplierData?.supplierStatuses?.find(diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierPaymentForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierPaymentForm.tsxindex 61f9345c14..2855373326 100644--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierPaymentForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierPaymentForm.tsx@@ -13,16 +13,14 @@ import {Currency,CustomFormFields,Hidden,- Select,Submit,Supplier,SupplierContact,SupplierLocation,} from "~/components/Form";-import { usePermissions, useRouteData } from "~/hooks";+import PaymentTerm from "~/components/Form/PaymentTerm";+import { usePermissions } from "~/hooks";import { supplierPaymentValidator } from "~/modules/purchasing";-import type { ListItem } from "~/types";-import { path } from "~/utils/path";type SupplierPaymentFormProps = {initialValues: z.infer<typeof supplierPaymentValidator>;@@ -34,16 +32,6 @@ const SupplierPaymentForm = ({ initialValues }: SupplierPaymentFormProps) => {initialValues.invoiceSupplierId);- const routeData = useRouteData<{- paymentTerms: ListItem[];- }>(path.to.supplierRoot);-- const paymentTermOptions =- routeData?.paymentTerms?.map((term) => ({- value: term.id,- label: term.name,- })) ?? [];-const isDisabled = !permissions.can("update", "purchasing");return (@@ -75,11 +63,7 @@ const SupplierPaymentForm = ({ initialValues }: SupplierPaymentFormProps) => {supplier={supplier}/>- <Select- name="paymentTermId"- label="Payment Term"- options={paymentTermOptions}- />+ <PaymentTerm name="paymentTermId" label="Payment Term" /><Currency name="currencyCode" label="Currency" /><CustomFormFields table="supplierPayment" /></div>diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierShippingForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierShippingForm.tsxindex 52277b4912..5527f73cc6 100644--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierShippingForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierShippingForm.tsx@@ -12,16 +12,14 @@ import type { z } from "zod";import {CustomFormFields,Hidden,- Select,+ ShippingMethod,Submit,Supplier,SupplierContact,SupplierLocation,} from "~/components/Form";-import { usePermissions, useRouteData } from "~/hooks";+import { usePermissions } from "~/hooks";import { supplierShippingValidator } from "~/modules/purchasing";-import type { ListItem } from "~/types";-import { path } from "~/utils/path";type SupplierShippingFormProps = {initialValues: z.infer<typeof supplierShippingValidator>;@@ -33,22 +31,11 @@ const SupplierShippingForm = ({ initialValues }: SupplierShippingFormProps) => {initialValues.shippingSupplierId);- const routeData = useRouteData<{- shippingMethods: ListItem[];- shippingTerms: ListItem[];- }>(path.to.supplierRoot);-- const shippingMethodOptions =- routeData?.shippingMethods?.map((method) => ({- value: method.id,- label: method.name,- })) ?? [];-- const shippingTermOptions =- routeData?.shippingTerms?.map((term) => ({- value: term.id,- label: term.name,- })) ?? [];+ // const shippingTermOptions =+ // routeData?.shippingTerms?.map((term) => ({+ // value: term.id,+ // label: term.name,+ // })) ?? [];const isDisabled = !permissions.can("update", "purchasing");@@ -81,16 +68,12 @@ const SupplierShippingForm = ({ initialValues }: SupplierShippingFormProps) => {supplier={supplier}/>- <Select- name="shippingMethodId"- label="Shipping Method"- options={shippingMethodOptions}- />- <Select+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />+ {/* <Selectname="shippingTermId"label="Shipping Term"options={shippingTermOptions}- />+ /> */}<CustomFormFields table="supplierShipping" /></div></CardContent>diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex 7dd30e3a8c..e55314a420 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -56,7 +56,7 @@ export const customerShippingValidator = z.object({shippingCustomerId: zfd.text(z.string().optional()),shippingCustomerLocationId: zfd.text(z.string().optional()),shippingCustomerContactId: zfd.text(z.string().optional()),- shippingTermId: zfd.text(z.string().optional()),+ // shippingTermId: zfd.text(z.string().optional()),shippingMethodId: zfd.text(z.string().optional()),});@@ -451,6 +451,22 @@ export const quoteFinalizeValidator = z});+export const quotePaymentValidator = z.object({+ id: z.string(),+ invoiceCustomerId: zfd.text(z.string().optional()),+ invoiceCustomerLocationId: zfd.text(z.string().optional()),+ invoiceCustomerContactId: zfd.text(z.string().optional()),+ paymentTermId: zfd.text(z.string().optional()),+ currencyCode: z.enum(currencyCodes).optional(),+});++export const quoteShipmentValidator = z.object({+ id: z.string(),+ locationId: zfd.text(z.string().optional()),+ shippingMethodId: zfd.text(z.string().optional()),+ receiptRequestedDate: zfd.text(z.string().optional()),+});+export const salesOrderLineType = ["Part","Service",@@ -490,7 +506,7 @@ export const salesOrderShipmentValidator = zid: z.string(),locationId: zfd.text(z.string().optional()),shippingMethodId: zfd.text(z.string().optional()),- shippingTermId: zfd.text(z.string().optional()),+ // shippingTermId: zfd.text(z.string().optional()),trackingNumber: z.string(),deliveryDate: zfd.text(z.string().optional()),receiptRequestedDate: zfd.text(z.string().optional()),@@ -513,18 +529,6 @@ export const salesOrderShipmentValidator = zmessage: "Drop shipment requires supplier and location",path: ["dropShipment"], // path of error}- )- .refine(- (data) => {- if (data.locationId) {- return !data.dropShipment;- }- return true;- },- {- message: "Location is not required for drop shipment",- path: ["locationId"], // path of error- });export const salesOrderLineValidator = z@@ -615,3 +619,11 @@ export const salesRfqLineValidator = z.object({order: zfd.numeric(z.number().min(0)),modelUploadId: zfd.text(z.string().optional()),});++const selectedLineSchema = z.object({+ unitPrice: z.number().nonnegative(),+ addOn: z.number().nonnegative(),+ leadTime: z.number().nonnegative().int(),+});++export const selectedLinesValidator = z.record(z.string(), selectedLineSchema);diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex a6f0fea5db..1cf3bcf590 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -28,6 +28,7 @@ import type {salesRfqLineValidator,salesRFQStatusType,salesRfqValidator,+ selectedLinesValidator,} from "./sales.models";export async function closeSalesOrder(@@ -65,30 +66,19 @@ export async function convertSalesRfqToQuote(export async function convertQuoteToOrder(client: SupabaseClient<Database>,- quoteId: string,- userId: string-) {- const quoteUpdate = await client- .from("quote")- .update({- status: "Ordered",- updatedAt: today(getLocalTimeZone()).toString(),- updatedBy: userId,- })- .eq("id", quoteId);-- if (quoteUpdate.error) {- return quoteUpdate;+ payload: {+ id: string;+ selectedLines: z.infer<typeof selectedLinesValidator>;+ companyId: string;+ userId: string;}-- return client- .from("quoteLine")- .update({- status: "Complete",- updatedAt: today(getLocalTimeZone()).toString(),- updatedBy: userId,- })- .eq("quoteId", quoteId);+) {+ return client.functions.invoke<{ convertedId: string }>("convert", {+ body: {+ type: "quoteToSalesOrder",+ ...payload,+ },+ });}export async function deleteCustomerContact(@@ -720,6 +710,20 @@ export async function getQuoteOperations(return client.from("quoteOperation").select("*").eq("quoteId", quoteId);}+export async function getQuotePayment(+ client: SupabaseClient<Database>,+ quoteId: string+) {+ return client.from("quotePayment").select("*").eq("id", quoteId).single();+}++export async function getQuoteShipment(+ client: SupabaseClient<Database>,+ quoteId: string+) {+ return client.from("quoteShipment").select("*").eq("id", quoteId).single();+}+export async function getSalesOrder(client: SupabaseClient<Database>,salesOrderId: string@@ -759,6 +763,17 @@ export async function getSalesOrders(return query;}+export async function getSalesOrderPayment(+ client: SupabaseClient<Database>,+ salesOrderId: string+) {+ return client+ .from("salesOrderPayment")+ .select("*")+ .eq("id", salesOrderId)+ .single();+}+export async function getSalesOrderShipment(client: SupabaseClient<Database>,salesOrderId: string@@ -1419,6 +1434,26 @@ export async function upsertQuote(})) {if ("createdBy" in quote) {+ const [customerPayment, customerShipping, employee] = await Promise.all([+ getCustomerPayment(client, quote.customerId),+ getCustomerShipping(client, quote.customerId),+ getEmployeeJob(client, quote.createdBy, quote.companyId),+ ]);++ if (customerPayment.error) return customerPayment;+ if (customerShipping.error) return customerShipping;++ const {+ currencyCode,+ paymentTermId,+ invoiceCustomerId,+ invoiceCustomerContactId,+ invoiceCustomerLocationId,+ } = customerPayment.data;++ const { shippingMethodId, shippingTermId } = customerShipping.data;++ const locationId = employee?.data?.locationId ?? null;const insert = await client.from("quote").insert([quote])@@ -1426,12 +1461,49 @@ export async function upsertQuote(if (insert.error) {return insert;}- const opportunity = await client- .from("opportunity")- .insert([{ quoteId: insert.data[0].id, companyId: quote.companyId }]);++ const quoteId = insert.data?.[0]?.id;+ if (!quoteId) return insert;++ const [shipment, payment, opportunity] = await Promise.all([+ client.from("quoteShipment").insert([+ {+ id: quoteId,+ locationId: locationId,+ shippingMethodId: shippingMethodId,+ shippingTermId: shippingTermId,+ companyId: quote.companyId,+ },+ ]),+ client.from("quotePayment").insert([+ {+ id: quoteId,+ currencyCode: currencyCode ?? "USD",+ invoiceCustomerId: invoiceCustomerId,+ invoiceCustomerContactId: invoiceCustomerContactId,+ invoiceCustomerLocationId: invoiceCustomerLocationId,+ paymentTermId: paymentTermId,+ companyId: quote.companyId,+ },+ ]),+ client+ .from("opportunity")+ .insert([{ quoteId, companyId: quote.companyId }]),+ ]);++ if (shipment.error) {+ await deleteQuote(client, quoteId);+ return payment;+ }+ if (payment.error) {+ await deleteQuote(client, quoteId);+ return payment;+ }if (opportunity.error) {+ await deleteQuote(client, quoteId);return opportunity;}+return insert;} else {return client@@ -1733,7 +1805,7 @@ export async function upsertSalesOrder(const salesOrderId = order.data[0].id;- const [shipment, payment] = await Promise.all([+ const [shipment, payment, opportunity] = await Promise.all([client.from("salesOrderShipment").insert([{id: salesOrderId,@@ -1754,6 +1826,9 @@ export async function upsertSalesOrder(companyId: salesOrder.companyId,},]),+ client+ .from("opportunity")+ .insert([{ salesOrderId, companyId: salesOrder.companyId }]),]);if (shipment.error) {@@ -1764,6 +1839,10 @@ export async function upsertSalesOrder(await deleteSalesOrder(client, salesOrderId);return payment;}+ if (opportunity.error) {+ await deleteSalesOrder(client, salesOrderId);+ return opportunity;+ }return order;}diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.tsindex 5d526b6739..9eb65843db 100644--- a/apps/carbon/app/modules/sales/types.ts+++ b/apps/carbon/app/modules/sales/types.ts@@ -14,7 +14,9 @@ import type {getQuoteMaterials,getQuoteMethodTrees,getQuoteOperation,+ getQuotePayment,getQuotes,+ getQuoteShipment,getSalesOrderExternalDocuments,getSalesOrderLines,getSalesOrders,@@ -112,6 +114,14 @@ export type QuotationPrice = NonNullable<export type QuotationStatusType = Database["public"]["Enums"]["quoteStatus"];+export type QuotationPayment = NonNullable<+ Awaited<ReturnType<typeof getQuotePayment>>["data"]+>;++export type QuotationShipment = NonNullable<+ Awaited<ReturnType<typeof getQuoteShipment>>["data"]+>;+export type SalesOrder = NonNullable<Awaited<ReturnType<typeof getSalesOrders>>["data"]>[number];diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsxindex 7669d54e0f..5d55902d6a 100644--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader.tsx@@ -21,7 +21,6 @@ import {import { Enumerable } from "~/components/Enumerable";import { usePermissions, useRouteData } from "~/hooks";import type { CustomerDetail, CustomerStatus } from "~/modules/sales";-import type { ListItem } from "~/types";import { path } from "~/utils/path";const CustomerHeader = () => {@@ -35,7 +34,6 @@ const CustomerHeader = () => {const sharedCustomerData = useRouteData<{customerStatuses: CustomerStatus[];- paymentTerms: ListItem[];}>(path.to.customerRoot);const customerStatus = sharedCustomerData?.customerStatuses?.find(diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerPaymentForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerPaymentForm.tsxindex ed1b79bd64..094d15d4d8 100644--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerPaymentForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerPaymentForm.tsx@@ -16,13 +16,11 @@ import {CustomerContact,CustomerLocation,Hidden,- Select,Submit,} from "~/components/Form";-import { usePermissions, useRouteData } from "~/hooks";+import PaymentTerm from "~/components/Form/PaymentTerm";+import { usePermissions } from "~/hooks";import { customerPaymentValidator } from "~/modules/sales";-import type { ListItem } from "~/types";-import { path } from "~/utils/path";type CustomerPaymentFormProps = {initialValues: z.infer<typeof customerPaymentValidator>;@@ -34,16 +32,6 @@ const CustomerPaymentForm = ({ initialValues }: CustomerPaymentFormProps) => {initialValues.invoiceCustomerId);- const routeData = useRouteData<{- paymentTerms: ListItem[];- }>(path.to.customerRoot);-- const paymentTermOptions =- routeData?.paymentTerms?.map((term) => ({- value: term.id,- label: term.name,- })) ?? [];-const isDisabled = !permissions.can("update", "sales");return (@@ -75,11 +63,7 @@ const CustomerPaymentForm = ({ initialValues }: CustomerPaymentFormProps) => {customer={customer}/>- <Select- name="paymentTermId"- label="Payment Term"- options={paymentTermOptions}- />+ <PaymentTerm name="paymentTermId" label="Payment Term" /><Currency name="currencyCode" label="Currency" /><CustomFormFields table="customerPayment" /></div>diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerShippingForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerShippingForm.tsxindex 064acdab6b..be8f75876f 100644--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerShippingForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerShippingForm.tsx@@ -15,13 +15,11 @@ import {CustomerLocation,CustomFormFields,Hidden,- Select,+ ShippingMethod,Submit,} from "~/components/Form";-import { usePermissions, useRouteData } from "~/hooks";+import { usePermissions } from "~/hooks";import { customerShippingValidator } from "~/modules/sales";-import type { ListItem } from "~/types";-import { path } from "~/utils/path";type CustomerShippingFormProps = {initialValues: z.infer<typeof customerShippingValidator>;@@ -33,22 +31,11 @@ const CustomerShippingForm = ({ initialValues }: CustomerShippingFormProps) => {initialValues.shippingCustomerId);- const routeData = useRouteData<{- shippingMethods: ListItem[];- shippingTerms: ListItem[];- }>(path.to.customerRoot);-- const shippingMethodOptions =- routeData?.shippingMethods?.map((method) => ({- value: method.id,- label: method.name,- })) ?? [];-- const shippingTermOptions =- routeData?.shippingTerms?.map((term) => ({- value: term.id,- label: term.name,- })) ?? [];+ // const shippingTermOptions =+ // routeData?.shippingTerms?.map((term) => ({+ // value: term.id,+ // label: term.name,+ // })) ?? [];const isDisabled = !permissions.can("update", "sales");@@ -81,16 +68,12 @@ const CustomerShippingForm = ({ initialValues }: CustomerShippingFormProps) => {customer={customer}/>- <Select- name="shippingMethodId"- label="Shipping Method"- options={shippingMethodOptions}- />- <Select+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />+ {/* <Selectname="shippingTermId"label="Shipping Term"options={shippingTermOptions}- />+ /> */}<CustomFormFields table="customerShipping" /></div></CardContent>diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuotePaymentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuotePaymentForm.tsxnew file mode 100644index 0000000000..7790e7d3c1--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuotePaymentForm.tsx@@ -0,0 +1,81 @@+import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+ HStack,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useState } from "react";+import type { z } from "zod";+import {+ Currency,+ Customer,+ CustomerContact,+ CustomerLocation,+ Hidden,+ PaymentTerm,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import { quotePaymentValidator } from "~/modules/sales";+import { path } from "~/utils/path";++type QuotePaymentFormProps = {+ initialValues: z.infer<typeof quotePaymentValidator>;+};++const QuotePaymentForm = ({ initialValues }: QuotePaymentFormProps) => {+ const permissions = usePermissions();+ const [customer, setCustomer] = useState<string | undefined>(+ initialValues.invoiceCustomerId+ );++ const isDisabled = !permissions.can("update", "sales");++ return (+ <Card isCollapsible defaultCollapsed>+ <ValidatedForm+ method="post"+ action={path.to.quotePayment(initialValues.id)}+ validator={quotePaymentValidator}+ defaultValues={initialValues}+ >+ <CardHeader>+ <CardTitle>Payment</CardTitle>+ </CardHeader>+ <CardContent>+ <Hidden name="id" />+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">+ <Customer+ name="invoiceCustomerId"+ label="Invoice Customer"+ onChange={(value) => setCustomer(value?.value as string)}+ />+ <CustomerLocation+ name="invoiceCustomerLocationId"+ label="Invoice Location"+ customer={customer}+ />+ <CustomerContact+ name="invoiceCustomerContactId"+ label="Invoice Contact"+ customer={customer}+ />++ <PaymentTerm name="paymentTermId" label="Payment Term" />+ <Currency name="currencyCode" label="Currency" />+ </div>+ </CardContent>+ <CardFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ </HStack>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+};++export default QuotePaymentForm;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsxnew file mode 100644index 0000000000..f1d5e6fc4c--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx@@ -0,0 +1,78 @@+import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import type { z } from "zod";+import {+ DatePicker,+ Hidden,+ Location,+ ShippingMethod,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import { quoteShipmentValidator } from "~/modules/sales";+import { path } from "~/utils/path";++type QuoteShipmentFormProps = {+ initialValues: z.infer<typeof quoteShipmentValidator>;+ // shippingTerms: ListItem[];+};++const QuoteShipmentForm = ({+ initialValues,+}: // shippingTerms,+QuoteShipmentFormProps) => {+ const permissions = usePermissions();++ // const shippingTermOptions = shippingTerms.map((term) => ({+ // label: term.name,+ // value: term.id,+ // }));++ const isCustomer = permissions.is("customer");++ return (+ <Card isCollapsible defaultCollapsed>+ <ValidatedForm+ action={path.to.quoteShipment(initialValues.id)}+ method="post"+ validator={quoteShipmentValidator}+ defaultValues={initialValues}+ >+ <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">+ <Location+ name="locationId"+ label="Shipment Location"+ isReadOnly={isCustomer}+ isClearable+ />+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />+ {/* <Select+ name="shippingTermId"+ label="Shipping Terms"+ isReadOnly={isCustomer}+ options={shippingTermOptions}+ /> */}++ <DatePicker name="receiptRequestedDate" label="Requested Date" />+ </div>+ </CardContent>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "sales")}>Save</Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+};++export default QuoteShipmentForm;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/index.ts b/apps/carbon/app/modules/sales/ui/Quotes/index.tsindex a5202d0fb4..3cb4604324 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/index.ts+++ b/apps/carbon/app/modules/sales/ui/Quotes/index.ts@@ -13,6 +13,8 @@ import QuoteLineForm from "./QuoteLineForm";import QuoteLineNotes from "./QuoteLineNotes";import QuoteLinePricing from "./QuoteLinePricing";import QuoteMaterialForm from "./QuoteMaterialForm";+import QuotePaymentForm from "./QuotePaymentForm";+import QuoteShipmentForm from "./QuoteShipmentForm";import QuotesTable from "./QuotesTable";import { useLineCosts } from "./useLineCosts";@@ -32,6 +34,8 @@ export {QuoteLineNotes,QuoteLinePricing,QuoteMaterialForm,+ QuotePaymentForm,+ QuoteShipmentForm,QuotesTable,useLineCosts,};diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderPaymentForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderPaymentForm.tsxnew file mode 100644index 0000000000..3f3c4735a3--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderPaymentForm.tsx@@ -0,0 +1,83 @@+import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+ HStack,+} from "@carbon/react";+import { ValidatedForm } from "@carbon/remix-validated-form";+import { useState } from "react";+import type { z } from "zod";+import {+ Currency,+ Customer,+ CustomerContact,+ CustomerLocation,+ Hidden,+ PaymentTerm,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import { salesOrderPaymentValidator } from "~/modules/sales";+import { path } from "~/utils/path";++type SalesOrderPaymentFormProps = {+ initialValues: z.infer<typeof salesOrderPaymentValidator>;+};++const SalesOrderPaymentForm = ({+ initialValues,+}: SalesOrderPaymentFormProps) => {+ const permissions = usePermissions();+ const [customer, setCustomer] = useState<string | undefined>(+ initialValues.invoiceCustomerId+ );++ const isDisabled = !permissions.can("update", "sales");++ return (+ <Card isCollapsible defaultCollapsed>+ <ValidatedForm+ method="post"+ action={path.to.salesOrderPayment(initialValues.id)}+ validator={salesOrderPaymentValidator}+ defaultValues={initialValues}+ >+ <CardHeader>+ <CardTitle>Payment</CardTitle>+ </CardHeader>+ <CardContent>+ <Hidden name="id" />+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-x-8 gap-y-4 w-full">+ <Customer+ name="invoiceCustomerId"+ label="Invoice Customer"+ onChange={(value) => setCustomer(value?.value as string)}+ />+ <CustomerLocation+ name="invoiceCustomerLocationId"+ label="Invoice Location"+ customer={customer}+ />+ <CustomerContact+ name="invoiceCustomerContactId"+ label="Invoice Contact"+ customer={customer}+ />++ <PaymentTerm name="paymentTermId" label="Payment Term" />+ <Currency name="currencyCode" label="Currency" />+ </div>+ </CardContent>+ <CardFooter>+ <HStack>+ <Submit isDisabled={isDisabled}>Save</Submit>+ </HStack>+ </CardFooter>+ </ValidatedForm>+ </Card>+ );+};++export default SalesOrderPaymentForm;diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsxindex 52d5b1e090..4601f405e8 100644--- a/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx@@ -17,25 +17,22 @@ import {Hidden,Input,Location,- Select,+ ShippingMethod,Submit,} from "~/components/Form";import { usePermissions } from "~/hooks";import { salesOrderShipmentValidator } from "~/modules/sales";-import type { ListItem } from "~/types";import { path } from "~/utils/path";type SalesOrderShipmentFormProps = {initialValues: z.infer<typeof salesOrderShipmentValidator>;- shippingMethods: ListItem[];- shippingTerms: ListItem[];+ // shippingTerms: ListItem[];};const SalesOrderShipmentForm = ({initialValues,- shippingMethods,- shippingTerms,-}: SalesOrderShipmentFormProps) => {+}: // shippingTerms,+SalesOrderShipmentFormProps) => {const permissions = usePermissions();const [dropShip, setDropShip] = useState<boolean>(initialValues.dropShipment ?? false@@ -44,20 +41,15 @@ const SalesOrderShipmentForm = ({initialValues.customerId);- const shippingMethodOptions = shippingMethods.map((method) => ({- label: method.name,- value: method.id,- }));-- const shippingTermOptions = shippingTerms.map((term) => ({- label: term.name,- value: term.id,- }));+ // const shippingTermOptions = shippingTerms.map((term) => ({+ // label: term.name,+ // value: term.id,+ // }));const isCustomer = permissions.is("customer");return (- <Card>+ <Card isCollapsible defaultCollapsed><ValidatedFormaction={path.to.salesOrderShipment(initialValues.id)}method="post"@@ -76,17 +68,13 @@ const SalesOrderShipmentForm = ({isReadOnly={isCustomer}isClearable/>- <Select- name="shippingMethodId"- label="Shipping Method"- options={shippingMethodOptions}- />- <Select+ <ShippingMethod name="shippingMethodId" label="Shipping Method" />+ {/* <Selectname="shippingTermId"label="Shipping Terms"isReadOnly={isCustomer}options={shippingTermOptions}- />+ /> */}<DatePicker name="receiptRequestedDate" label="Requested Date" /><DatePicker name="receiptPromisedDate" label="Promised Date" />diff --git a/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts b/apps/carbon/app/modules/sales/ui/SalesOrder/index.tsindex 5e6dbb9a89..de4495c299 100644--- a/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts+++ b/apps/carbon/app/modules/sales/ui/SalesOrder/index.ts@@ -7,7 +7,7 @@ import SalesOrderForm from "./SalesOrderForm";import SalesOrderHeader from "./SalesOrderHeader";import SalesOrderLineForm from "./SalesOrderLineForm";import SalesOrderLines from "./SalesOrderLines";-//import SalesOrderPaymentForm from "./SalesOrderPaymentForm";+import SalesOrderPaymentForm from "./SalesOrderPaymentForm";import SalesStatus from "./SalesStatus";import { useSalesOrderTotals } from "./useSalesOrderTotals";@@ -21,8 +21,8 @@ export {SalesOrderHeader,SalesOrderLineForm,SalesOrderLines,+ SalesOrderPaymentForm,SalesOrderShipmentForm,- //SalesOrderPaymentForm,SalesStatus,useSalesOrderTotals,};diff --git a/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx b/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsxindex aceab2cf79..53a5cdf357 100644--- a/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx+++ b/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx@@ -181,11 +181,11 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {header: "Shipping Method",cell: (item) => item.getValue(),},- {- accessorKey: "shippingTermName",- header: "Shipping Term",- cell: (item) => <Enumerable value={item.getValue<string>()} />,- },+ // {+ // accessorKey: "shippingTermName",+ // header: "Shipping Term",+ // cell: (item) => <Enumerable value={item.getValue<string>()} />,+ // },{accessorKey: "paymentTermName",header: "Payment Method",diff --git a/apps/carbon/app/routes/api+/accounting.payment-terms.ts b/apps/carbon/app/routes/api+/accounting.payment-terms.tsnew file mode 100644index 0000000000..c0c93cf4e2--- /dev/null+++ b/apps/carbon/app/routes/api+/accounting.payment-terms.ts@@ -0,0 +1,10 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { getPaymentTermsList } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth/auth.server";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ return json(await getPaymentTermsList(client, companyId));+}diff --git a/apps/carbon/app/routes/api+/inventory.shipping-methods.ts b/apps/carbon/app/routes/api+/inventory.shipping-methods.tsnew file mode 100644index 0000000000..50edc26813--- /dev/null+++ b/apps/carbon/app/routes/api+/inventory.shipping-methods.ts@@ -0,0 +1,10 @@+import type { LoaderFunctionArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { getShippingMethodsList } from "~/modules/inventory";+import { requirePermissions } from "~/services/auth/auth.server";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ return json(await getShippingMethodsList(client, companyId));+}diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsxindex 4e7cbf55d0..d8a0220b8d 100644--- a/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx@@ -29,6 +29,8 @@ export async function action({ request }: ActionFunctionArgs) {});const formData = await request.formData();+ const modal = formData.get("type") === "modal";+const validation = await validator(paymentTermValidator).validate(formData);if (validation.error) {@@ -53,21 +55,12 @@ export async function action({ request }: ActionFunctionArgs) {);}- const paymentTermId = insertPaymentTerm.data?.id;- if (!paymentTermId) {- return json(- {},- await flash(- request,- error(insertPaymentTerm, "Failed to insert payment term")- )- );- }-- throw redirect(- `${path.to.paymentTerms}?${getParams(request)}`,- await flash(request, success("Payment term created"))- );+ return modal+ ? json(insertPaymentTerm, { status: 201 })+ : redirect(+ `${path.to.paymentTerms}?${getParams(request)}`,+ await flash(request, success("Payment term created"))+ );}export default function NewPaymentTermsRoute() {diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.shipping.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.shipping.tsxindex c0634634b4..5300c87668 100644--- a/apps/carbon/app/routes/x+/customer+/$customerId.shipping.tsx+++ b/apps/carbon/app/routes/x+/customer+/$customerId.shipping.tsx@@ -88,7 +88,7 @@ export default function CustomerShippingRoute() {shippingCustomerLocationId:customerShipping?.shippingCustomerLocationId ?? "",shippingMethodId: customerShipping?.shippingMethodId ?? "",- shippingTermId: customerShipping?.shippingTermId ?? "",+ // shippingTermId: customerShipping?.shippingTermId ?? "",};return (diff --git a/apps/carbon/app/routes/x+/customer+/_layout.tsx b/apps/carbon/app/routes/x+/customer+/_layout.tsxindex 0deeb2ba57..c9051a7042 100644--- a/apps/carbon/app/routes/x+/customer+/_layout.tsx+++ b/apps/carbon/app/routes/x+/customer+/_layout.tsx@@ -2,11 +2,6 @@ import { VStack } from "@carbon/react";import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";import { json } from "@remix-run/node";import { Outlet } from "@remix-run/react";-import { getPaymentTermsList } from "~/modules/accounting";-import {- getShippingMethodsList,- getShippingTermsList,-} from "~/modules/inventory";import { getCustomerStatuses, getCustomerTypes } from "~/modules/sales";import { requirePermissions } from "~/services/auth/auth.server";import type { Handle } from "~/utils/handle";@@ -30,23 +25,18 @@ export async function loader({ request }: LoaderFunctionArgs) {const [customerTypes,customerStatuses,- paymentTerms,- shippingMethods,- shippingTerms,+ // shippingTerms,] = await Promise.all([getCustomerTypes(client, companyId),getCustomerStatuses(client, companyId),- getPaymentTermsList(client, companyId),- getShippingMethodsList(client, companyId),- getShippingTermsList(client, companyId),++ // getShippingTermsList(client, companyId),]);return json({customerStatuses: customerStatuses.data ?? [],customerTypes: customerTypes.data ?? [],- paymentTerms: paymentTerms.data ?? [],- shippingMethods: shippingMethods.data ?? [],- shippingTerms: shippingTerms.data ?? [],+ // shippingTerms: shippingTerms.data ?? [],});}diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsxindex 521674782f..05f8ca35a8 100644--- a/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx@@ -29,6 +29,8 @@ export async function action({ request }: ActionFunctionArgs) {});const formData = await request.formData();+ const modal = formData.get("type") === "modal";+const validation = await validator(shippingMethodValidator).validate(formData);@@ -55,21 +57,12 @@ export async function action({ request }: ActionFunctionArgs) {);}- const shippingMethodId = insertShippingMethod.data?.id;- if (!shippingMethodId) {- return json(- {},- await flash(- request,- error(insertShippingMethod, "Failed to insert shipping method")- )- );- }-- throw redirect(- `${path.to.shippingMethods}?${getParams(request)}`,- await flash(request, success("Shipping method created"))- );+ return modal+ ? json(insertShippingMethod, { status: 201 })+ : redirect(+ `${path.to.shippingMethods}?${getParams(request)}`,+ await flash(request, success("Shipping method created"))+ );}export default function NewShippingMethodsRoute() {diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsxindex 31c6c24b1b..14bff84e7d 100644--- a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx+++ b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx@@ -11,7 +11,6 @@ import {} from "~/modules/invoicing";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";-import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";@@ -64,9 +63,7 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function PurchaseInvoiceBasicRoute() {const { invoiceId } = useParams();if (!invoiceId) throw new Error("invoiceId not found");- const sharedData = useRouteData<{ paymentTerms: ListItem[] }>(- path.to.purchaseInvoiceRoot- );+const invoiceData = useRouteData<{ purchaseInvoice: PurchaseInvoice }>(path.to.purchaseInvoice(invoiceId));@@ -92,10 +89,6 @@ export default function PurchaseInvoiceBasicRoute() {};return (- <PurchaseInvoiceForm- key={initialValues.id}- initialValues={initialValues}- paymentTerms={sharedData?.paymentTerms ?? []}- />+ <PurchaseInvoiceForm key={initialValues.id} initialValues={initialValues} />);}diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/_layout.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/_layout.tsxindex 68cb59e793..f6f04bd609 100644--- a/apps/carbon/app/routes/x+/purchase-invoice+/_layout.tsx+++ b/apps/carbon/app/routes/x+/purchase-invoice+/_layout.tsx@@ -1,8 +1,6 @@import { VStack } from "@carbon/react";-import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";+import type { MetaFunction } from "@remix-run/node";import { Outlet } from "@remix-run/react";-import { getPaymentTermsList } from "~/modules/accounting";-import { requirePermissions } from "~/services/auth/auth.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -16,19 +14,6 @@ export const handle: Handle = {module: "invoicing",};-export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing",- });- const [paymentTerms] = await Promise.all([- getPaymentTermsList(client, companyId),- ]);-- return {- paymentTerms: paymentTerms.data ?? [],- };-}-export default function PurchaseInvoiceRoute() {return (<VStack spacing={4} className="h-full p-2">diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsxindex e9f18522f6..e2c6adda09 100644--- a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx+++ b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx@@ -2,7 +2,7 @@ import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { redirect } from "@remix-run/node";import type { FunctionsResponse } from "@supabase/functions-js";-import { useRouteData, useUrlParams } from "~/hooks";+import { useUrlParams } from "~/hooks";import type { PurchaseInvoiceStatus } from "~/modules/invoicing";import {PurchaseInvoiceForm,@@ -13,7 +13,6 @@ import { createPurchaseInvoiceFromPurchaseOrder } from "~/modules/invoicing/invoimport { getNextSequence, rollbackNextSequence } from "~/modules/settings";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";-import type { ListItem } from "~/types";import { setCustomFields } from "~/utils/form";import type { Handle } from "~/utils/handle";import { assertIsPost } from "~/utils/http";@@ -123,10 +122,6 @@ export default function PurchaseInvoiceNewRoute() {const [params] = useUrlParams();const supplierId = params.get("supplierId");- const sharedData = useRouteData<{ paymentTerms: ListItem[] }>(- path.to.purchaseInvoiceRoot- );-const initialValues = {id: undefined,invoiceId: undefined,@@ -136,10 +131,7 @@ export default function PurchaseInvoiceNewRoute() {return (<div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">- <PurchaseInvoiceForm- initialValues={initialValues}- paymentTerms={sharedData?.paymentTerms ?? []}- />+ <PurchaseInvoiceForm initialValues={initialValues} /></div>);}diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsxindex 1d32d22f6f..68bc19a7b1 100644--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx@@ -2,10 +2,6 @@ import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";-import {- getShippingMethodsList,- getShippingTermsList,-} from "~/modules/inventory";import {PurchaseOrderDeliveryForm,getPurchaseOrderDelivery,@@ -14,26 +10,23 @@ import {} from "~/modules/purchasing";import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";-import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";import { error, success } from "~/utils/result";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ const { client } = await requirePermissions(request, {view: "purchasing",});const { orderId } = params;if (!orderId) throw new Error("Could not find orderId");- const [purchaseOrderDelivery, shippingMethods, shippingTerms] =- await Promise.all([- getPurchaseOrderDelivery(client, orderId),- getShippingMethodsList(client, companyId),- getShippingTermsList(client, companyId),- ]);+ const [purchaseOrderDelivery] = await Promise.all([+ getPurchaseOrderDelivery(client, orderId),+ // getShippingTermsList(client, companyId),+ ]);if (purchaseOrderDelivery.error) {throw redirect(@@ -48,30 +41,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- if (shippingMethods.error) {- throw redirect(- path.to.purchaseOrders,- await flash(- request,- error(shippingMethods.error, "Failed to load shipping methods")- )- );- }-- if (shippingTerms.error) {- throw redirect(- path.to.purchaseOrders,- await flash(- request,- error(shippingTerms.error, "Failed to load shipping terms")- )- );- }+ // if (shippingTerms.error) {+ // throw redirect(+ // path.to.purchaseOrders,+ // await flash(+ // request,+ // error(shippingTerms.error, "Failed to load shipping terms")+ // )+ // );+ // }return json({purchaseOrderDelivery: purchaseOrderDelivery.data,- shippingMethods: shippingMethods.data ?? [],- shippingTerms: shippingTerms.data ?? [],+ // shippingTerms: shippingTerms.data ?? [],});}@@ -122,8 +104,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function PurchaseOrderDeliveryRoute() {- const { purchaseOrderDelivery, shippingMethods, shippingTerms } =- useLoaderData<typeof loader>();+ const { purchaseOrderDelivery } = useLoaderData<typeof loader>();const initialValues = {id: purchaseOrderDelivery.id,@@ -145,8 +126,7 @@ export default function PurchaseOrderDeliveryRoute() {<PurchaseOrderDeliveryFormkey={initialValues.id}initialValues={initialValues}- shippingMethods={shippingMethods as ListItem[]}- shippingTerms={shippingTerms as ListItem[]}+ // shippingTerms={shippingTerms as ListItem[]}/>);}diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsxindex 527a33fcb0..098771f58e 100644--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx@@ -2,7 +2,6 @@ import { validationError, validator } from "@carbon/remix-validated-form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { useLoaderData } from "@remix-run/react";-import { getPaymentTermsList } from "~/modules/accounting";import {PurchaseOrderPaymentForm,getPurchaseOrderPayment,@@ -17,16 +16,15 @@ import { path } from "~/utils/path";import { error, success } from "~/utils/result";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {+ const { client } = await requirePermissions(request, {view: "purchasing",});const { orderId } = params;if (!orderId) throw new Error("Could not find orderId");- const [purchaseOrderPayment, paymentTerms] = await Promise.all([+ const [purchaseOrderPayment] = await Promise.all([getPurchaseOrderPayment(client, orderId),- getPaymentTermsList(client, companyId),]);if (purchaseOrderPayment.error) {@@ -42,19 +40,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- if (paymentTerms.error) {- throw redirect(- path.to.purchaseOrders,- await flash(- request,- error(paymentTerms.error, "Failed to load payment terms")- )- );- }-return json({purchaseOrderPayment: purchaseOrderPayment.data,- paymentTerms: paymentTerms.data ?? [],});}@@ -102,7 +89,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function PurchaseOrderPaymentRoute() {- const { purchaseOrderPayment, paymentTerms } = useLoaderData<typeof loader>();+ const { purchaseOrderPayment } = useLoaderData<typeof loader>();const initialValues = {id: purchaseOrderPayment.id,@@ -121,7 +108,6 @@ export default function PurchaseOrderPaymentRoute() {<PurchaseOrderPaymentFormkey={initialValues.id}initialValues={initialValues}- paymentTerms={paymentTerms}/>);}diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsxnew file mode 100644index 0000000000..9d8d367706--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.convert.tsx@@ -0,0 +1,66 @@+import { type ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "remix-typedjson";+import { getSupabaseServiceRole } from "~/lib/supabase";+import { convertQuoteToOrder, selectedLinesValidator } from "~/modules/sales";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ create: "sales",+ });++ const { quoteId } = params;+ if (!quoteId) throw new Error("Could not find quoteId");++ const formData = await request.formData();+ const selectedLinesRaw = formData.get("selectedLines");++ if (typeof selectedLinesRaw !== "string") {+ throw redirect(+ path.to.quoteDetails(quoteId),+ await flash(request, error("Invalid selected lines data"))+ );+ }++ const parseResult = selectedLinesValidator.safeParse(+ JSON.parse(selectedLinesRaw)+ );++ if (!parseResult.success) {+ console.error("Validation error:", parseResult.error);+ throw redirect(+ path.to.quoteDetails(quoteId),+ await flash(request, error("Invalid selected lines data"))+ );+ }++ const selectedLines = parseResult.data;++ const serviceRole = getSupabaseServiceRole();+ const convert = await convertQuoteToOrder(serviceRole, {+ id: quoteId,+ companyId,+ userId,+ selectedLines,+ });++ if (convert.error) {+ throw redirect(+ path.to.quoteDetails(quoteId),+ await flash(+ request,+ error(convert.error, "Failed to convert quote to order")+ )+ );+ }++ throw redirect(+ path.to.salesOrder(convert.data?.convertedId!),+ await flash(request, success("Successfully converted quote to order"))+ );+}diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsxindex 8f18b134b6..df31bc164a 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx@@ -19,10 +19,16 @@ import type { FileObject } from "@supabase/storage-js";import { nanoid } from "nanoid";import { usePermissions, useRouteData, useUser } from "~/hooks";import { useSupabase } from "~/lib/supabase";-import type { Quotation } from "~/modules/sales";+import type {+ Quotation,+ QuotationPayment,+ QuotationShipment,+} from "~/modules/sales";import {QuoteDocuments,QuoteForm,+ QuotePaymentForm,+ QuoteShipmentForm,quoteValidator,upsertQuote,} from "~/modules/sales";@@ -79,6 +85,8 @@ export default function QuoteDetailsRoute() {const quoteData = useRouteData<{quote: Quotation;files: (FileObject & { quoteLineId: string | null })[];+ shipment: QuotationShipment;+ payment: QuotationPayment;}>(path.to.quote(quoteId));if (!quoteData) throw new Error("Could not find quote data");@@ -96,10 +104,36 @@ export default function QuoteDetailsRoute() {status: quoteData?.quote?.status ?? "Draft",};+ const shipmentInitialValues = {+ id: quoteData?.shipment.id!,+ locationId: quoteData?.shipment?.locationId ?? "",+ shippingMethodId: quoteData?.shipment?.shippingMethodId ?? "",+ shippingTermId: quoteData?.shipment?.shippingTermId ?? "",+ receiptRequestedDate: quoteData?.shipment?.receiptRequestedDate ?? "",+ };++ const paymentInitialValues = {+ ...quoteData?.payment,+ invoiceCustomerId: quoteData?.payment.invoiceCustomerId ?? "",+ invoiceCustomerLocationId:+ quoteData?.payment.invoiceCustomerLocationId ?? "",+ invoiceCustomerContactId: quoteData?.payment.invoiceCustomerContactId ?? "",+ paymentTermId: quoteData?.payment.paymentTermId ?? "",+ currencyCode: quoteData?.payment.currencyCode as "USD",+ };+return (<><QuoteForm key={initialValues.id} initialValues={initialValues} /><QuoteDocuments id={quoteId} attachments={quoteData?.files ?? []} />+ <QuotePaymentForm+ key={`payment-${initialValues.id}`}+ initialValues={paymentInitialValues}+ />+ <QuoteShipmentForm+ key={`shipment-${initialValues.id}`}+ initialValues={shipmentInitialValues}+ /><QuoteNotes quote={quoteData?.quote} /></>);diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsxindex f5aca233b8..4810d94893 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx@@ -15,6 +15,8 @@ import {getQuoteLinePricesByQuoteId,getQuoteLines,getQuoteMethodTrees,+ getQuotePayment,+ getQuoteShipment,QuoteBreadcrumbs,QuoteExplorer,QuoteHeader,@@ -39,27 +41,59 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { quoteId } = params;if (!quoteId) throw new Error("Could not find quoteId");- const [quote, lines, files, methods, prices] = await Promise.all([+ const [+ quote,+ shipment,+ payment,+ lines,+ files,+ methods,+ prices,+ // shippingTerms,+ ] = await Promise.all([getQuote(client, quoteId),+ getQuoteShipment(client, quoteId),+ getQuotePayment(client, quoteId),getQuoteLines(client, quoteId),getQuoteDocuments(client, companyId, quoteId),getQuoteMethodTrees(client, quoteId),getQuoteLinePricesByQuoteId(client, quoteId),+ // getShippingTermsList(client, companyId),]);if (quote.error) {throw redirect(- path.to.items,+ path.to.quotes,await flash(request, error(quote.error, "Failed to load quote")));}+ if (shipment.error) {+ throw redirect(+ path.to.quotes,+ await flash(+ request,+ error(shipment.error, "Failed to load quote shipment")+ )+ );+ }++ if (payment.error) {+ throw redirect(+ path.to.quotes,+ await flash(request, error(payment.error, "Failed to load quote payment"))+ );+ }+return json({quote: quote.data,lines: lines.data ?? [],methods: methods.data ?? [],files: files.data ?? [],prices: prices.data ?? [],+ shipment: shipment.data,+ payment: payment.data,+ // shippingTerms: shippingTerms.data ?? [],});}diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsxindex 81d14e6a64..ef507da6c0 100644--- a/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.details.tsx@@ -3,21 +3,21 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { useLoaderData, useParams } from "@remix-run/react";import { useRouteData } from "~/hooks";-import {- getShippingMethodsList,- getShippingTermsList,-} from "~/modules/inventory";+import { getPaymentTermsList } from "~/modules/accounting";+import { getShippingMethodsList } from "~/modules/inventory";import type { SalesOrder } from "~/modules/sales";import {+ getSalesOrderPayment,getSalesOrderShipment,SalesOrderForm,+ SalesOrderPaymentForm,SalesOrderShipmentForm,salesOrderValidator,upsertSalesOrder,} from "~/modules/sales";+import { requirePermissions } from "~/services/auth/auth.server";import { flash } from "~/services/session.server";-import type { ListItem } from "~/types";import { getCustomFields, setCustomFields } from "~/utils/form";import { assertIsPost } from "~/utils/http";import { path } from "~/utils/path";@@ -31,16 +31,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { orderId } = params;if (!orderId) throw new Error("Could not find orderId");- const [salesOrderShipment, shippingMethods, shippingTerms] =- await Promise.all([- getSalesOrderShipment(client, orderId),- getShippingMethodsList(client, companyId),- getShippingTermsList(client, companyId),- ]);+ const [+ salesOrderShipment,+ salesOrderPayment,++ // shippingTerms,+ ] = await Promise.all([+ getSalesOrderShipment(client, orderId),+ getSalesOrderPayment(client, orderId),+ getPaymentTermsList(client, companyId),+ getShippingMethodsList(client, companyId),+ // getShippingTermsList(client, companyId),+ ]);if (salesOrderShipment.error) {+ // TODO: insert a salesOrderShipment recordthrow redirect(- path.to.salesOrder(orderId),+ path.to.salesOrders,await flash(request,error(salesOrderShipment.error, "Failed to load sales order shipment")@@ -48,30 +55,31 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- if (shippingMethods.error) {+ if (salesOrderPayment.error) {+ // TODO: insert a salesOrderPayment recordthrow redirect(path.to.salesOrders,await flash(request,- error(shippingMethods.error, "Failed to load shipping methods")+ error(salesOrderPayment.error, "Failed to load sales order payment")));}- if (shippingTerms.error) {- throw redirect(- path.to.salesOrders,- await flash(- request,- error(shippingTerms.error, "Failed to load shipping terms")- )- );- }+ // if (shippingTerms.error) {+ // throw redirect(+ // path.to.salesOrders,+ // await flash(+ // request,+ // error(shippingTerms.error, "Failed to load shipping terms")+ // )+ // );+ // }return json({salesOrderShipment: salesOrderShipment.data,- shippingMethods: shippingMethods.data ?? [],- shippingTerms: shippingTerms.data ?? [],+ salesOrderPayment: salesOrderPayment.data,+ // shippingTerms: shippingTerms.data ?? [],});}@@ -117,9 +125,12 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export default function SalesOrderBasicRoute() {- const { salesOrderShipment, shippingMethods, shippingTerms } =- useLoaderData<typeof loader>();+export default function SalesOrderRoute() {+ const {+ salesOrderShipment,+ salesOrderPayment,+ // shippingTerms,+ } = useLoaderData<typeof loader>();const { orderId } = useParams();if (!orderId) throw new Error("Could not find orderId");const orderData = useRouteData<{ salesOrder: SalesOrder }>(@@ -158,6 +169,17 @@ export default function SalesOrderBasicRoute() {...getCustomFields(salesOrderShipment.customFields),};+ const paymentInitialValues = {+ ...salesOrderPayment,+ invoiceCustomerId: salesOrderPayment.invoiceCustomerId ?? "",+ invoiceCustomerLocationId:+ salesOrderPayment.invoiceCustomerLocationId ?? "",+ invoiceCustomerContactId: salesOrderPayment.invoiceCustomerContactId ?? "",+ paymentTermId: salesOrderPayment.paymentTermId ?? "",+ currencyCode: salesOrderPayment.currencyCode as "USD",+ ...getCustomFields(salesOrderPayment.customFields),+ };+return (<><SalesOrderForm key={initialValues.id} initialValues={initialValues} />@@ -165,8 +187,13 @@ export default function SalesOrderBasicRoute() {<SalesOrderShipmentFormkey={initialValues.id}initialValues={shipmentInitialValues}- shippingMethods={shippingMethods as ListItem[]}- shippingTerms={shippingTerms as ListItem[]}++ // shippingTerms={shippingTerms as ListItem[]}+ />++ <SalesOrderPaymentForm+ key={initialValues.id}+ initialValues={paymentInitialValues}/></>);diff --git a/apps/carbon/app/routes/x+/sales-order+/$orderId.payment.tsx b/apps/carbon/app/routes/x+/sales-order+/$orderId.payment.tsxnew file mode 100644index 0000000000..3a7b0b0ffe--- /dev/null+++ b/apps/carbon/app/routes/x+/sales-order+/$orderId.payment.tsx@@ -0,0 +1,56 @@+import { validationError, validator } from "@carbon/remix-validated-form";+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import {+ salesOrderPaymentValidator,+ upsertSalesOrderPayment,+} from "~/modules/sales";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { setCustomFields } from "~/utils/form";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error, success } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "sales",+ });++ const { orderId } = params;+ if (!orderId) throw new Error("Could not find orderId");++ const formData = await request.formData();+ const validation = await validator(salesOrderPaymentValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateSalesOrderPayment = await upsertSalesOrderPayment(client, {+ ...validation.data,+ id: orderId,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });+ if (updateSalesOrderPayment.error) {+ throw redirect(+ path.to.salesOrderDetails(orderId),+ await flash(+ request,+ error(+ updateSalesOrderPayment.error,+ "Failed to update sales order payment"+ )+ )+ );+ }++ throw redirect(+ path.to.salesOrderDetails(orderId),+ await flash(request, success("Updated sales order payment"))+ );+}diff --git a/apps/carbon/app/routes/x+/supplier+/_layout.tsx b/apps/carbon/app/routes/x+/supplier+/_layout.tsxindex 7c3a92f92a..7fcfa205a0 100644--- a/apps/carbon/app/routes/x+/supplier+/_layout.tsx+++ b/apps/carbon/app/routes/x+/supplier+/_layout.tsx@@ -2,11 +2,7 @@ import { VStack } from "@carbon/react";import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";import { json } from "@remix-run/node";import { Outlet } from "@remix-run/react";-import { getPaymentTermsList } from "~/modules/accounting";-import {- getShippingMethodsList,- getShippingTermsList,-} from "~/modules/inventory";+import { getShippingTermsList } from "~/modules/inventory";import { getSupplierStatuses, getSupplierTypes } from "~/modules/purchasing";import { requirePermissions } from "~/services/auth/auth.server";import type { Handle } from "~/utils/handle";@@ -30,23 +26,17 @@ export async function loader({ request }: LoaderFunctionArgs) {const [supplierTypes,supplierStatuses,- paymentTerms,- shippingMethods,- shippingTerms,+ // shippingTerms,] = await Promise.all([getSupplierTypes(client, companyId),getSupplierStatuses(client, companyId),- getPaymentTermsList(client, companyId),- getShippingMethodsList(client, companyId),getShippingTermsList(client, companyId),]);return json({supplierStatuses: supplierStatuses.data ?? [],supplierTypes: supplierTypes.data ?? [],- paymentTerms: paymentTerms.data ?? [],- shippingMethods: shippingMethods.data ?? [],- shippingTerms: shippingTerms.data ?? [],+ // shippingTerms: shippingTerms.data ?? [],});}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 71aac50ddc..e587e092ef 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -57,6 +57,8 @@ export const path = {workCentersByLocation: (id: string) =>generatePath(`${api}/resources/work-centers?location=${id}`),workCenters: `${api}/resources/work-centers`,+ paymentTerms: `${api}/accounting/payment-terms`,+ shippingMethods: `${api}/inventory/shipping-methods`,},file: {cadModel: (urn: string) => generatePath(`${file}/autodesk/${urn}`),@@ -141,7 +143,7 @@ export const path = {consumableSuppliers: (id: string) =>generatePath(`${x}/consumable/${id}/suppliers`),convertQuoteToOrder: (id: string) =>- generatePath(`${x}/quote/${id}/convert-to-order`),+ generatePath(`${x}/quote/${id}/convert`),currency: (id: string) => generatePath(`${x}/accounting/currencies/${id}`),currencies: `${x}/accounting/currencies`,customer: (id: string) => generatePath(`${x}/customer/${id}`),@@ -565,6 +567,7 @@ export const path = {quoteExternalDocuments: (id: string) =>generatePath(`${x}/quote/${id}/external`),quoteFavorite: `${x}/sales/quotes/favorite`,+ quoteFinalize: (id: string) => generatePath(`${x}/quote/${id}/finalize`),quoteInternalDocuments: (id: string) =>generatePath(`${x}/quote/${id}/internal`),quoteLine: (quoteId: string, id: string) =>@@ -592,6 +595,9 @@ export const path = {),quoteLineMethod: (quoteId: string, quoteLineId: string, methodId: string) =>generatePath(`${x}/quote/${quoteId}/${quoteLineId}/method/${methodId}`),+ quoteLineRecalculatePrice: (quoteId: string, lineId: string) =>+ generatePath(`${x}/quote/${quoteId}/${lineId}/recalculate-price`),+quoteMaterial: (quoteId: string, lineId: string, id: string) =>generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/${id}`),quoteMaterialsOrder: `${x}/quote/methods/material/order`,@@ -600,9 +606,8 @@ export const path = {quoteOperation: (quoteId: string, lineId: string, id: string) =>generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/${id}`),quoteOperationsOrder: `${x}/quote/methods/operation/order`,- quoteLineRecalculatePrice: (quoteId: string, lineId: string) =>- generatePath(`${x}/quote/${quoteId}/${lineId}/recalculate-price`),- quoteFinalize: (id: string) => generatePath(`${x}/quote/${id}/finalize`),+ quotePayment: (id: string) => generatePath(`${x}/quote/${id}/payment`),+ quoteShipment: (id: string) => generatePath(`${x}/quote/${id}/shipment`),quoteStatus: (id: string) => generatePath(`${x}/quote/${id}/status`),quotes: `${x}/sales/quotes`,receipt: (id: string) => generatePath(`${x}/receipt/${id}`),diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex a5aff5a8db..1d8adb35d1 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -8721,6 +8721,9 @@ export default {{$ref: "#/parameters/rowFilter.salesOrderLine.modelUploadId",},+ {+ $ref: "#/parameters/rowFilter.salesOrderLine.promisedDate",+ },{$ref: "#/parameters/select",},@@ -8867,6 +8870,9 @@ export default {{$ref: "#/parameters/rowFilter.salesOrderLine.modelUploadId",},+ {+ $ref: "#/parameters/rowFilter.salesOrderLine.promisedDate",+ },{$ref: "#/parameters/preferReturn",},@@ -8967,6 +8973,9 @@ export default {{$ref: "#/parameters/rowFilter.salesOrderLine.modelUploadId",},+ {+ $ref: "#/parameters/rowFilter.salesOrderLine.promisedDate",+ },{$ref: "#/parameters/body.salesOrderLine",},@@ -12810,6 +12819,186 @@ export default {tags: ["accountCategories"],},},+ "/quotePayment": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quotePayment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerLocationId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerContactId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.paymentTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.currencyCode",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.customFields",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/quotePayment",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["quotePayment"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.quotePayment",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["quotePayment"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quotePayment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerLocationId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerContactId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.paymentTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.currencyCode",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.customFields",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["quotePayment"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quotePayment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerLocationId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.invoiceCustomerContactId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.paymentTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.currencyCode",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedAt",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quotePayment.customFields",+ },+ {+ $ref: "#/parameters/body.quotePayment",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["quotePayment"],+ },+ },"/accountCategory": {get: {parameters: [@@ -16413,6 +16602,168 @@ export default {tags: ["user"],},},+ "/quoteShipment": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quoteShipment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingMethodId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.receiptRequestedDate",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedAt",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/order",+ },+ {+ $ref: "#/parameters/range",+ },+ {+ $ref: "#/parameters/rangeUnit",+ },+ {+ $ref: "#/parameters/offset",+ },+ {+ $ref: "#/parameters/limit",+ },+ {+ $ref: "#/parameters/preferCount",+ },+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/quoteShipment",+ },+ type: "array",+ },+ },+ "206": {+ description: "Partial Content",+ },+ },+ tags: ["quoteShipment"],+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.quoteShipment",+ },+ {+ $ref: "#/parameters/select",+ },+ {+ $ref: "#/parameters/preferPost",+ },+ ],+ responses: {+ "201": {+ description: "Created",+ },+ },+ tags: ["quoteShipment"],+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quoteShipment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingMethodId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.receiptRequestedDate",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedAt",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["quoteShipment"],+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.quoteShipment.id",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.locationId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingMethodId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.shippingTermId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.receiptRequestedDate",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.companyId",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedBy",+ },+ {+ $ref: "#/parameters/rowFilter.quoteShipment.updatedAt",+ },+ {+ $ref: "#/parameters/body.quoteShipment",+ },+ {+ $ref: "#/parameters/preferReturn",+ },+ ],+ responses: {+ "204": {+ description: "No Content",+ },+ },+ tags: ["quoteShipment"],+ },+ },"/modelUpload": {get: {parameters: [@@ -23628,6 +23979,12 @@ export default {{$ref: "#/parameters/rowFilter.salesOrder.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.salesOrder.addOnCost",+ },+ {+ $ref: "#/parameters/rowFilter.salesOrder.locationId",+ },{$ref: "#/parameters/select",},@@ -23747,6 +24104,12 @@ export default {{$ref: "#/parameters/rowFilter.salesOrder.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.salesOrder.addOnCost",+ },+ {+ $ref: "#/parameters/rowFilter.salesOrder.locationId",+ },{$ref: "#/parameters/preferReturn",},@@ -23820,6 +24183,12 @@ export default {{$ref: "#/parameters/rowFilter.salesOrder.updatedBy",},+ {+ $ref: "#/parameters/rowFilter.salesOrder.addOnCost",+ },+ {+ $ref: "#/parameters/rowFilter.salesOrder.locationId",+ },{$ref: "#/parameters/body.salesOrder",},@@ -36029,6 +36398,10 @@ export default {format: "text",type: "string",},+ promisedDate: {+ format: "date",+ type: "string",+ },},type: "object",},@@ -37786,6 +38159,63 @@ export default {},type: "object",},+ quotePayment: {+ required: ["id", "currencyCode", "companyId"],+ properties: {+ id: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ invoiceCustomerId: {+ description:+ "Note:\nThis is a Foreign Key to `customer.id`.<fk table='customer' column='id'/>",+ format: "text",+ type: "string",+ },+ invoiceCustomerLocationId: {+ description:+ "Note:\nThis is a Foreign Key to `customerLocation.id`.<fk table='customerLocation' column='id'/>",+ format: "text",+ type: "string",+ },+ invoiceCustomerContactId: {+ description:+ "Note:\nThis is a Foreign Key to `customerContact.id`.<fk table='customerContact' column='id'/>",+ format: "text",+ type: "string",+ },+ paymentTermId: {+ description:+ "Note:\nThis is a Foreign Key to `paymentTerm.id`.<fk table='paymentTerm' column='id'/>",+ format: "text",+ type: "string",+ },+ currencyCode: {+ default: "USD",+ format: "text",+ type: "string",+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ updatedBy: {+ format: "text",+ type: "string",+ },+ customFields: {+ format: "jsonb",+ },+ },+ type: "object",+ },accountCategory: {required: ["id",@@ -39457,6 +39887,55 @@ export default {},type: "object",},+ quoteShipment: {+ required: ["id", "companyId"],+ properties: {+ id: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string",+ },+ locationId: {+ description:+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",+ format: "text",+ type: "string",+ },+ shippingMethodId: {+ description:+ "Note:\nThis is a Foreign Key to `shippingMethod.id`.<fk table='shippingMethod' column='id'/>",+ format: "text",+ type: "string",+ },+ shippingTermId: {+ description:+ "Note:\nThis is a Foreign Key to `shippingTerm.id`.<fk table='shippingTerm' column='id'/>",+ format: "text",+ type: "string",+ },+ receiptRequestedDate: {+ format: "date",+ type: "string",+ },+ companyId: {+ description:+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string",+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string",+ },+ },+ type: "object",+ },modelUpload: {required: ["id", "modelPath", "companyId", "createdBy"],properties: {@@ -42756,6 +43235,16 @@ export default {format: "text",type: "string",},+ addOnCost: {+ format: "numeric",+ type: "number",+ },+ locationId: {+ description:+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",+ format: "text",+ type: "string",+ },},type: "object",},@@ -50940,6 +51429,13 @@ export default {in: "query",type: "string",},+ "rowFilter.salesOrderLine.promisedDate": {+ name: "promisedDate",+ required: false,+ format: "date",+ in: "query",+ type: "string",+ },"body.salesOrderTransaction": {name: "salesOrderTransaction",description: "salesOrderTransaction",@@ -53321,6 +53817,85 @@ export default {in: "query",type: "string",},+ "body.quotePayment": {+ name: "quotePayment",+ description: "quotePayment",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/quotePayment",+ },+ },+ "rowFilter.quotePayment.id": {+ name: "id",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.invoiceCustomerId": {+ name: "invoiceCustomerId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.invoiceCustomerLocationId": {+ name: "invoiceCustomerLocationId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.invoiceCustomerContactId": {+ name: "invoiceCustomerContactId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.paymentTermId": {+ name: "paymentTermId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.currencyCode": {+ name: "currencyCode",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.companyId": {+ name: "companyId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.updatedAt": {+ name: "updatedAt",+ required: false,+ format: "timestamp with time zone",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.updatedBy": {+ name: "updatedBy",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quotePayment.customFields": {+ name: "customFields",+ required: false,+ format: "jsonb",+ in: "query",+ type: "string",+ },"body.accountCategory": {name: "accountCategory",description: "accountCategory",@@ -55431,6 +56006,71 @@ export default {in: "query",type: "string",},+ "body.quoteShipment": {+ name: "quoteShipment",+ description: "quoteShipment",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/quoteShipment",+ },+ },+ "rowFilter.quoteShipment.id": {+ name: "id",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.locationId": {+ name: "locationId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.shippingMethodId": {+ name: "shippingMethodId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.shippingTermId": {+ name: "shippingTermId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.receiptRequestedDate": {+ name: "receiptRequestedDate",+ required: false,+ format: "date",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.companyId": {+ name: "companyId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.updatedBy": {+ name: "updatedBy",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },+ "rowFilter.quoteShipment.updatedAt": {+ name: "updatedAt",+ required: false,+ format: "timestamp with time zone",+ in: "query",+ type: "string",+ },"body.modelUpload": {name: "modelUpload",description: "modelUpload",@@ -59760,6 +60400,20 @@ export default {in: "query",type: "string",},+ "rowFilter.salesOrder.addOnCost": {+ name: "addOnCost",+ required: false,+ format: "numeric",+ in: "query",+ type: "string",+ },+ "rowFilter.salesOrder.locationId": {+ name: "locationId",+ required: false,+ format: "text",+ in: "query",+ type: "string",+ },"body.userAttributeValue": {name: "userAttributeValue",description: "userAttributeValue",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 0173281ae1..f1007716e6 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -13960,6 +13960,304 @@ export type Database = {},]}+ quotePayment: {+ Row: {+ companyId: string+ currencyCode: string+ customFields: Json | null+ id: string+ invoiceCustomerContactId: string | null+ invoiceCustomerId: string | null+ invoiceCustomerLocationId: string | null+ paymentTermId: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ currencyCode?: string+ customFields?: Json | null+ id: string+ invoiceCustomerContactId?: string | null+ invoiceCustomerId?: string | null+ invoiceCustomerLocationId?: string | null+ paymentTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ currencyCode?: string+ customFields?: Json | null+ id?: string+ invoiceCustomerContactId?: string | null+ invoiceCustomerId?: string | null+ invoiceCustomerLocationId?: string | null+ paymentTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quotePayment_currencyCode_fkey"+ columns: ["currencyCode", "companyId"]+ isOneToOne: false+ referencedRelation: "currency"+ referencedColumns: ["code", "companyId"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerContactId_fkey"+ columns: ["invoiceCustomerContactId"]+ isOneToOne: false+ referencedRelation: "customerContact"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerLocationId_fkey"+ columns: ["invoiceCustomerLocationId"]+ isOneToOne: false+ referencedRelation: "customerLocation"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_paymentTermId_fkey"+ columns: ["paymentTermId"]+ isOneToOne: false+ referencedRelation: "paymentTerm"+ referencedColumns: ["id"]+ },+ ]+ }+ quoteShipment: {+ Row: {+ companyId: string+ id: string+ locationId: string | null+ receiptRequestedDate: string | null+ shippingMethodId: string | null+ shippingTermId: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ id: string+ locationId?: string | null+ receiptRequestedDate?: string | null+ shippingMethodId?: string | null+ shippingTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ id?: string+ locationId?: string | null+ receiptRequestedDate?: string | null+ shippingMethodId?: string | null+ shippingTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "itemQuantities"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "purchaseOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "salesOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_shippingMethodId_fkey"+ columns: ["shippingMethodId"]+ isOneToOne: false+ referencedRelation: "shippingMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_shippingTermId_fkey"+ columns: ["shippingTermId"]+ isOneToOne: false+ referencedRelation: "shippingTerm"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }receipt: {Row: {assignee: string | null@@ -14425,6 +14723,7 @@ export type Database = {}salesOrder: {Row: {+ addOnCost: number | nullassignee: string | nullclosedAt: string | nullclosedBy: string | null@@ -14438,6 +14737,7 @@ export type Database = {customerReference: string | nullcustomFields: Json | nullid: string+ locationId: string | nullnotes: string | nullorderDate: stringrevisionId: number@@ -14447,6 +14747,7 @@ export type Database = {updatedBy: string | null}Insert: {+ addOnCost?: number | nullassignee?: string | nullclosedAt?: string | nullclosedBy?: string | null@@ -14460,6 +14761,7 @@ export type Database = {customerReference?: string | nullcustomFields?: Json | nullid?: string+ locationId?: string | nullnotes?: string | nullorderDate?: stringrevisionId?: number@@ -14469,6 +14771,7 @@ export type Database = {updatedBy?: string | null}Update: {+ addOnCost?: number | nullassignee?: string | nullclosedAt?: string | nullclosedBy?: string | null@@ -14482,6 +14785,7 @@ export type Database = {customerReference?: string | nullcustomFields?: Json | nullid?: string+ locationId?: string | nullnotes?: string | nullorderDate?: stringrevisionId?: number@@ -14666,6 +14970,34 @@ export type Database = {referencedRelation: "customerLocation"referencedColumns: ["id"]},+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "itemQuantities"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "purchaseOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "salesOrders"+ referencedColumns: ["locationId"]+ },{foreignKeyName: "salesOrder_updatedBy_fkey"columns: ["updatedBy"]@@ -14783,6 +15115,7 @@ export type Database = {itemReadableId: string | nulllocationId: string | nullmodelUploadId: string | null+ promisedDate: string | nullquantityInvoiced: number | nullquantitySent: number | nullquantityToInvoice: number | null@@ -14814,6 +15147,7 @@ export type Database = {itemReadableId?: string | nulllocationId?: string | nullmodelUploadId?: string | null+ promisedDate?: string | nullquantityInvoiced?: number | nullquantitySent?: number | nullquantityToInvoice?: number | null@@ -14845,6 +15179,7 @@ export type Database = {itemReadableId?: string | nulllocationId?: string | nullmodelUploadId?: string | null+ promisedDate?: string | nullquantityInvoiced?: number | nullquantitySent?: number | nullquantityToInvoice?: number | nulldiff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex f993fcecc2..3c3e6eadee 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -3,6 +3,7 @@ import { z } from "https://deno.land/x/[email protected]/mod.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { format } from "https://deno.land/[email protected]/datetime/format.ts";import { corsHeaders } from "../lib/headers.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";import { Database } from "../lib/types.ts";@@ -11,12 +12,30 @@ import { getNextSequence } from "../shared/get-next-sequence.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);-const payloadValidator = z.object({- type: z.enum(["salesRfqToQuote"]),- id: z.string(),- companyId: z.string(),- userId: z.string(),-});+const payloadValidator = z+ .object({+ type: z.enum(["salesRfqToQuote", "quoteToSalesOrder"]),+ id: z.string(),+ companyId: z.string(),+ userId: z.string(),+ selectedLines: z+ .record(+ z.string(),+ z.object({+ quantity: z.number(),+ unitPrice: z.number(),+ addOn: z.number(),+ leadTime: z.number(),+ })+ )+ .optional(),+ })+ .refine((data) => {+ if (data.type === "quoteToSalesOrder") {+ return !!data.selectedLines && Object.keys(data.selectedLines).length > 0;+ }+ return true;+ });serve(async (req: Request) => {if (req.method === "OPTIONS") {@@ -25,7 +44,8 @@ serve(async (req: Request) => {const payload = await req.json();let convertedId = "";try {- const { type, id, companyId, userId } = payloadValidator.parse(payload);+ const { type, id, companyId, userId, selectedLines } =+ payloadValidator.parse(payload);console.log({function: "convert",@@ -38,6 +58,187 @@ serve(async (req: Request) => {const client = getSupabaseServiceRole(req.headers.get("Authorization"));switch (type) {+ case "quoteToSalesOrder": {+ const [quote, quoteLines, quotePayment, quoteShipping] =+ await Promise.all([+ client.from("quote").select("*").eq("id", id).single(),+ client.from("quoteLine").select("*").eq("quoteId", id),+ client.from("quotePayment").select("*").eq("quoteId", id).single(),+ client.from("quoteShipment").select("*").eq("quoteId", id).single(),+ ]);++ if (quote.error) throw new Error(`Quote with id ${id} not found`);+ if (quoteLines.error)+ throw new Error(`Quote Lines with id ${id} not found`);+ if (quotePayment.error)+ throw new Error(`Quote Payment with id ${id} not found`);+ if (quoteShipping.error)+ throw new Error(`Quote Shipping with id ${id} not found`);++ let insertedSalesOrderId = "";+ await db.transaction().execute(async (trx) => {+ const today = format(new Date(), "yyyy-MM-dd");+ const salesOrderId = await getNextSequence(+ trx,+ "salesOrder",+ companyId+ );++ const salesOrder = await trx+ .insertInto("salesOrder")+ .values([+ {+ salesOrderId,+ revisionId: 0,+ orderDate: today,+ customerId: quote.data.customerId,+ customerContactId: quote.data.customerContactId,+ customerLocationId: quote.data.customerLocationId,+ customerReference: quote.data.customerReference,+ locationId: quote.data.locationId,+ status: "Draft",+ createdBy: userId,+ companyId: companyId,+ },+ ])+ .returning(["id"])+ .executeTakeFirstOrThrow();++ if (!salesOrder.id) {+ throw new Error("sales order is not created");+ }+ insertedSalesOrderId = salesOrder.id;++ // Copy quotePayment data to salesOrderPayment+ await trx+ .insertInto("salesOrderPayment")+ .values({+ ...quotePayment.data,+ id: insertedSalesOrderId,+ })+ .execute();++ // Copy quoteShipment data to salesOrderShipment+ await trx+ .insertInto("salesOrderShipment")+ .values({+ ...quoteShipping.data,+ id: insertedSalesOrderId,+ })+ .execute();++ const salesOrderLineInserts: Database["public"]["Tables"]["salesOrderLine"]["Insert"][] =+ quoteLines.data+ .filter(+ (line) => line.id && selectedLines && line.id in selectedLines+ )+ .map((line) => {+ const quantity = selectedLines![line.id!].quantity;+ return {+ salesOrderId: insertedSalesOrderId,+ salesOrderLineType: line.itemType as "Part",+ status: "Ordered",+ itemId: line.itemId,+ itemReadableId: line.itemReadableId,+ saleQuantity: selectedLines![line.id!].unitPrice,+ quantityToSend: quantity,+ quantityToInvoice: quantity,+ unitOfMeasureCode: line.unitOfMeasureCode,+ locationId: quote.data.locationId,+ unitPrice: selectedLines![line.id!].unitPrice,+ addOnCost: selectedLines![line.id!].addOn,+ promisedDate: format(+ new Date(+ Date.now() ++ selectedLines![line.id!].leadTime * 24 * 60 * 60 * 1000+ ),+ "yyyy-MM-dd"+ ),+ createdBy: userId,+ companyId,+ };+ });++ await trx+ .insertInto("salesOrderLines")+ .values(salesOrderLineInserts)+ .execute();++ await trx+ .updateTable("item")+ .set({ active: true })+ .where(+ "id",+ "in",+ salesOrderLineInserts.map((insert) => insert.itemId)+ )+ .execute();++ const newQuoteStatus: "Ordered" | "Partial" =+ quoteLines.data.length === salesOrderLineInserts.length+ ? "Ordered"+ : "Partial";+ await trx+ .updateTable("quote")+ .set({ status: newQuoteStatus })+ .where("id", "=", quote.data.id)+ .execute();++ await trx+ .updateTable("opportunity")+ .set({+ salesOrderId: insertedSalesOrderId,+ })+ .where("quoteId", "=", quote.data.id)+ .execute();++ const customerPartToItemInserts = quoteLines.data+ .map((line) => ({+ companyId,+ customerId: quote.data?.customerId!,+ customerPartId: line.customerPartId!,+ customerPartRevision: line.customerPartRevision ?? "",+ itemId: line.itemId!,+ }))+ .filter((line) => !!line.itemId && !!line.customerPartId);+ if (customerPartToItemInserts.length > 0) {+ await trx+ .insertInto("customerPartToItem")+ .values(customerPartToItemInserts)+ .onConflict((oc) =>+ oc.columns(["customerId", "itemId"]).doUpdateSet((eb) => ({+ customerPartId: eb.ref("excluded.customerPartId"),+ customerPartRevision: eb.ref("excluded.customerPartRevision"),+ }))+ )+ .execute();+ }++ const updatedItemModels = quoteLines.data+ .filter((line) => !!line.modelUploadId && !!line.itemId)+ .map((line) => ({+ id: line.itemId!,+ modelUploadId: line.modelUploadId!,+ }));++ if (updatedItemModels.length > 0) {+ for await (const update of updatedItemModels) {+ await trx+ .updateTable("item")+ .set(update)+ .where("id", "=", update.id)+ .execute();+ }+ }+ });++ if (!insertedSalesOrderId) {+ throw new Error("Failed to insert sales order");+ }++ convertedId = insertedSalesOrderId;+ break;+ }case "salesRfqToQuote": {const [salesRfq, salesRfqLines] = await Promise.all([client.from("salesRfq").select("*").eq("id", id).single(),@@ -55,6 +256,39 @@ serve(async (req: Request) => {throw new Error(`Sales RFQ Lines with id ${id} not found`);}+ const [customerPayment, customerShipping, employee] = await Promise.all(+ [+ client+ .from("customerPayment")+ .select("*")+ .eq("customerId", salesRfq.data.customerId)+ .single(),+ client+ .from("customerShipping")+ .select("*")+ .eq("customerId", salesRfq.data.customerId)+ .single(),+ client+ .from("employeeJob")+ .select("*")+ .eq("employeeId", userId)+ .eq("companyId", companyId),+ ]+ );++ if (customerPayment.error) throw customerPayment.error;+ if (customerShipping.error) throw customerShipping.error;++ const {+ currencyCode,+ paymentTermId,+ invoiceCustomerId,+ invoiceCustomerContactId,+ invoiceCustomerLocationId,+ } = customerPayment.data;++ const { shippingMethodId, shippingTermId } = customerShipping.data;+const validLines = salesRfqLines.data?.filter((line) =>line.itemId &&@@ -99,6 +333,32 @@ serve(async (req: Request) => {throw new Error("Failed to insert quote");}+ // Insert quotePayment+ await trx+ .insertInto("quotePayment")+ .values({+ id: quote.id,+ currencyCode: currencyCode ?? "USD",+ invoiceCustomerId: invoiceCustomerId,+ invoiceCustomerContactId: invoiceCustomerContactId,+ invoiceCustomerLocationId: invoiceCustomerLocationId,+ paymentTermId: paymentTermId,+ companyId,+ })+ .execute();++ // Insert quoteShipment+ await trx+ .insertInto("quoteShipment")+ .values({+ id: quote.id,+ locationId: salesRfq.data?.locationId,+ shippingMethodId: shippingMethodId,+ shippingTermId: shippingTermId,+ companyId,+ })+ .execute();+const quoteLineInserts: Database["public"]["Tables"]["quoteLine"]["Insert"][] =validLines.map((line) => ({quoteId: quote.id!,diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 0173281ae1..f1007716e6 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -13960,6 +13960,304 @@ export type Database = {},]}+ quotePayment: {+ Row: {+ companyId: string+ currencyCode: string+ customFields: Json | null+ id: string+ invoiceCustomerContactId: string | null+ invoiceCustomerId: string | null+ invoiceCustomerLocationId: string | null+ paymentTermId: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ currencyCode?: string+ customFields?: Json | null+ id: string+ invoiceCustomerContactId?: string | null+ invoiceCustomerId?: string | null+ invoiceCustomerLocationId?: string | null+ paymentTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ currencyCode?: string+ customFields?: Json | null+ id?: string+ invoiceCustomerContactId?: string | null+ invoiceCustomerId?: string | null+ invoiceCustomerLocationId?: string | null+ paymentTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quotePayment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quotePayment_currencyCode_fkey"+ columns: ["currencyCode", "companyId"]+ isOneToOne: false+ referencedRelation: "currency"+ referencedColumns: ["code", "companyId"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quotePayment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerContactId_fkey"+ columns: ["invoiceCustomerContactId"]+ isOneToOne: false+ referencedRelation: "customerContact"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerId_fkey"+ columns: ["invoiceCustomerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_invoiceCustomerLocationId_fkey"+ columns: ["invoiceCustomerLocationId"]+ isOneToOne: false+ referencedRelation: "customerLocation"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quotePayment_paymentTermId_fkey"+ columns: ["paymentTermId"]+ isOneToOne: false+ referencedRelation: "paymentTerm"+ referencedColumns: ["id"]+ },+ ]+ }+ quoteShipment: {+ Row: {+ companyId: string+ id: string+ locationId: string | null+ receiptRequestedDate: string | null+ shippingMethodId: string | null+ shippingTermId: string | null+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ id: string+ locationId?: string | null+ receiptRequestedDate?: string | null+ shippingMethodId?: string | null+ shippingTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ id?: string+ locationId?: string | null+ receiptRequestedDate?: string | null+ shippingMethodId?: string | null+ shippingTermId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quoteShipment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quote"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quoteCustomerDetails"+ referencedColumns: ["quoteId"]+ },+ {+ foreignKeyName: "quoteShipment_id_fkey"+ columns: ["id"]+ isOneToOne: true+ referencedRelation: "quotes"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "itemQuantities"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "purchaseOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "salesOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "quoteShipment_shippingMethodId_fkey"+ columns: ["shippingMethodId"]+ isOneToOne: false+ referencedRelation: "shippingMethod"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_shippingTermId_fkey"+ columns: ["shippingTermId"]+ isOneToOne: false+ referencedRelation: "shippingTerm"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "quoteShipment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }receipt: {Row: {assignee: string | null@@ -14425,6 +14723,7 @@ export type Database = {}salesOrder: {Row: {+ addOnCost: number | nullassignee: string | nullclosedAt: string | nullclosedBy: string | null@@ -14438,6 +14737,7 @@ export type Database = {customerReference: string | nullcustomFields: Json | nullid: string+ locationId: string | nullnotes: string | nullorderDate: stringrevisionId: number@@ -14447,6 +14747,7 @@ export type Database = {updatedBy: string | null}Insert: {+ addOnCost?: number | nullassignee?: string | nullclosedAt?: string | nullclosedBy?: string | null@@ -14460,6 +14761,7 @@ export type Database = {customerReference?: string | nullcustomFields?: Json | nullid?: string+ locationId?: string | nullnotes?: string | nullorderDate?: stringrevisionId?: number@@ -14469,6 +14771,7 @@ export type Database = {updatedBy?: string | null}Update: {+ addOnCost?: number | nullassignee?: string | nullclosedAt?: string | nullclosedBy?: string | null@@ -14482,6 +14785,7 @@ export type Database = {customerReference?: string | nullcustomFields?: Json | nullid?: string+ locationId?: string | nullnotes?: string | nullorderDate?: stringrevisionId?: number@@ -14666,6 +14970,34 @@ export type Database = {referencedRelation: "customerLocation"referencedColumns: ["id"]},+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "itemQuantities"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "purchaseOrders"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "salesOrder_locationId_fkey"+ columns: ["locationId"]+ isOneToOne: false+ referencedRelation: "salesOrders"+ referencedColumns: ["locationId"]+ },{foreignKeyName: "salesOrder_updatedBy_fkey"columns: ["updatedBy"]@@ -14783,6 +15115,7 @@ export type Database = {itemReadableId: string | nulllocationId: string | nullmodelUploadId: string | null+ promisedDate: string | nullquantityInvoiced: number | nullquantitySent: number | nullquantityToInvoice: number | null@@ -14814,6 +15147,7 @@ export type Database = {itemReadableId?: string | nulllocationId?: string | nullmodelUploadId?: string | null+ promisedDate?: string | nullquantityInvoiced?: number | nullquantitySent?: number | nullquantityToInvoice?: number | null@@ -14845,6 +15179,7 @@ export type Database = {itemReadableId?: string | nulllocationId?: string | nullmodelUploadId?: string | null+ promisedDate?: string | nullquantityInvoiced?: number | nullquantitySent?: number | nullquantityToInvoice?: number | nulldiff --git a/packages/database/supabase/migrations/20240831131003_sales-order-conversion.sql b/packages/database/supabase/migrations/20240831131003_sales-order-conversion.sqlnew file mode 100644index 0000000000..225e0f998f--- /dev/null+++ b/packages/database/supabase/migrations/20240831131003_sales-order-conversion.sql@@ -0,0 +1,118 @@+CREATE TABLE "quotePayment" (+ "id" TEXT NOT NULL,+ "invoiceCustomerId" TEXT,+ "invoiceCustomerLocationId" TEXT,+ "invoiceCustomerContactId" TEXT,+ "paymentTermId" TEXT,+ "currencyCode" TEXT NOT NULL DEFAULT 'USD',+ "companyId" TEXT NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "updatedBy" TEXT,+ "customFields" JSONB,++ CONSTRAINT "quotePayment_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quotePayment_id_fkey" FOREIGN KEY ("id") REFERENCES "quote" ("id") ON DELETE CASCADE,+ CONSTRAINT "quotePayment_invoiceCustomerId_fkey" FOREIGN KEY ("invoiceCustomerId") REFERENCES "customer" ("id") ON DELETE CASCADE,+ CONSTRAINT "quotePayment_invoiceCustomerLocationId_fkey" FOREIGN KEY ("invoiceCustomerLocationId") REFERENCES "customerLocation" ("id") ON DELETE CASCADE,+ CONSTRAINT "quotePayment_invoiceCustomerContactId_fkey" FOREIGN KEY ("invoiceCustomerContactId") REFERENCES "customerContact" ("id") ON DELETE CASCADE,+ CONSTRAINT "quotePayment_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,+ CONSTRAINT "quotePayment_currencyCode_fkey" FOREIGN KEY ("currencyCode", "companyId") REFERENCES "currency" ("code", "companyId") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quotePayment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE ON UPDATE CASCADE+);+++-- QuotePayment RLS+ALTER TABLE "quotePayment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with sales_view can view quote payments" ON "quotePayment"+ FOR SELECT+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_view', "companyId")+ );++CREATE POLICY "Employees with sales_create can create quote payments" ON "quotePayment"+ FOR INSERT+ WITH CHECK (+ has_role('employee', "companyId") AND+ has_company_permission('sales_create', "companyId")+ );++CREATE POLICY "Employees with sales_update can update quote payments" ON "quotePayment"+ FOR UPDATE+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_update', "companyId")+ );++CREATE POLICY "Employees with sales_delete can delete quote payments" ON "quotePayment"+ FOR DELETE+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_delete', "companyId")+ );++CREATE TABLE "quoteShipment" (+ "id" TEXT NOT NULL,+ "locationId" TEXT,+ "shippingMethodId" TEXT,+ "shippingTermId" TEXT,+ "receiptRequestedDate" DATE,+ "companyId" TEXT NOT NULL,+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "quoteShipment_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "quoteShipment_id_fkey" FOREIGN KEY ("id") REFERENCES "quote" ("id") ON DELETE CASCADE,+ CONSTRAINT "quoteShipment_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE CASCADE,+ CONSTRAINT "quoteShipment_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,+ CONSTRAINT "quoteShipment_shippingTermId_fkey" FOREIGN KEY ("shippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE CASCADE,+ CONSTRAINT "quoteShipment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "quoteShipment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT+);+-- QuoteShipment RLS+ALTER TABLE "quoteShipment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with sales_view can view quote shipments" ON "quoteShipment"+ FOR SELECT+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_view', "companyId")+ );++CREATE POLICY "Employees with sales_create can create quote shipments" ON "quoteShipment"+ FOR INSERT+ WITH CHECK (+ has_role('employee', "companyId") AND+ has_company_permission('sales_create', "companyId")+ );++CREATE POLICY "Employees with sales_update can update quote shipments" ON "quoteShipment"+ FOR UPDATE+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_update', "companyId")+ );++CREATE POLICY "Employees with sales_delete can delete quote shipments" ON "quoteShipment"+ FOR DELETE+ USING (+ has_role('employee', "companyId") AND+ has_company_permission('sales_delete', "companyId")+ );++++-- Add locationId to salesOrder table and remove quoteId+ALTER TABLE "salesOrder"+ ADD COLUMN "addOnCost" NUMERIC(10,4),+ ADD COLUMN "locationId" TEXT;++ALTER TABLE "salesOrderLine"+ ADD COLUMN "promisedDate" DATE;++-- Add foreign key constraint for locationId+ALTER TABLE "salesOrder"+ ADD CONSTRAINT "salesOrder_locationId_fkey"+ FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL;+diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsxindex c3ce2d893f..a517d71806 100644--- a/packages/react/src/Card.tsx+++ b/packages/react/src/Card.tsx@@ -1,18 +1,59 @@import type { HTMLAttributes } from "react";-import { forwardRef } from "react";+import { createContext, forwardRef, useContext, useState } from "react";+import { LuChevronDown, LuChevronUp } from "react-icons/lu";import { cn } from "./utils/cn";-const Card = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn(- "flex flex-col rounded-lg border border-border bg-gradient-to-bl from-card to-background text-card-foreground shadow-sm w-full",- className- )}- {...props}- />- )+interface CardProps extends HTMLAttributes<HTMLDivElement> {+ isCollapsible?: boolean;+ defaultCollapsed?: boolean;+}++const CardContext = createContext<+ { isCollapsed: boolean; toggle: () => void } | undefined+>(undefined);++const Card = forwardRef<HTMLDivElement, CardProps>(+ (+ {+ className,+ isCollapsible = false,+ defaultCollapsed = false,+ children,+ ...props+ },+ ref+ ) => {+ const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);+ const toggle = () => setIsCollapsed(!isCollapsed);++ return (+ <CardContext.Provider value={{ isCollapsed, toggle }}>+ <div+ ref={ref}+ className={cn(+ "relative flex flex-col rounded-lg border border-border bg-gradient-to-bl from-card to-background text-card-foreground shadow-sm w-full",+ className+ )}+ {...props}+ >+ {isCollapsible && (+ <button+ type="button"+ onClick={toggle}+ className="absolute right-3 top-4 p-2 text-muted-foreground hover:text-foreground"+ >+ {isCollapsed ? (+ <LuChevronDown className="w-6 h-6" />+ ) : (+ <LuChevronUp className="w-6 h-6" />+ )}+ </button>+ )}+ {children}+ </div>+ </CardContext.Provider>+ );+ });Card.displayName = "Card";@@ -79,13 +120,27 @@ const CardAttributeValue = forwardRef<CardAttributeValue.displayName = "CardAttributeValue";const CardHeader = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn("flex flex-col space-y-1.5 p-6", className)}- {...props}- />- )+ ({ className, ...props }, ref) => {+ const context = useContext(CardContext);+ const handleClick = () => {+ if (context?.isCollapsed) {+ context.toggle();+ }+ };++ return (+ <div+ ref={ref}+ className={cn(+ "flex flex-col space-y-1.5 p-6",+ context?.isCollapsed && "cursor-pointer",+ className+ )}+ onClick={handleClick}+ {...props}+ />+ );+ });CardHeader.displayName = "CardHeader";@@ -117,24 +172,36 @@ const CardDescription = forwardRef<CardDescription.displayName = "CardDescription";const CardContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn("flex flex-col flex-1 p-6 pt-0", className)}- {...props}- />- )+ ({ className, ...props }, ref) => {+ const context = useContext(CardContext);+ if (context?.isCollapsed) {+ return null;+ }+ return (+ <div+ ref={ref}+ className={cn("flex flex-col flex-1 p-6 pt-0", className)}+ {...props}+ />+ );+ });CardContent.displayName = "CardContent";const CardFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(- ({ className, ...props }, ref) => (- <div- ref={ref}- className={cn("flex items-center p-6 pt-0", className)}- {...props}- />- )+ ({ className, ...props }, ref) => {+ const context = useContext(CardContext);+ if (context?.isCollapsed) {+ return null;+ }+ return (+ <div+ ref={ref}+ className={cn("flex items-center p-6 pt-0", className)}+ {...props}+ />+ );+ });CardFooter.displayName = "CardFooter";@@ -143,8 +210,8 @@ export {CardAction,CardAttribute,CardAttributeLabel,- CardAttributeValue,CardAttributes,+ CardAttributeValue,CardContent,CardDescription,CardFooter,diff --git a/packages/react/src/Command.tsx b/packages/react/src/Command.tsxindex 4fc5235a60..19a4508205 100644--- a/packages/react/src/Command.tsx+++ b/packages/react/src/Command.tsx@@ -179,7 +179,7 @@ const CommandShortcut = ({CommandShortcut.displayName = "CommandShortcut";const commandTriggerVariants = cva(- "text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",+ "text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 overflow-hidden",{variants: {size: {