Skip to content

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

feat: add sales and purchasing terms to settings/pdfs

Brad Barbin009eefd4d021
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 0bc50ef8dc..e034035362 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -233,6 +233,17 @@ export async function getPurchaseOrderSuppliers(
.order("name");
}
+export async function getPurchasingTerms(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("terms")
+ .select("purchasingTerms")
+ .eq("id", companyId)
+ .single();
+}
+
export async function getSupplier(
client: SupabaseClient<Database>,
supplierId: string
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 07bcf2bb3f..1228ac937d 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -798,6 +798,13 @@ export async function getSalesOrderPayment(
.single();
}
+export async function getSalesTerms(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client.from("terms").select("salesTerms").eq("id", companyId).single();
+}
+
export async function getSalesOrderShipment(
client: SupabaseClient<Database>,
salesOrderId: string
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index a16e571054..341281d9b2 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -391,3 +391,11 @@ export async function updateSequence(
.eq("companyId", companyId)
.eq("table", table);
}
+
+// Add this function to the file
+export async function getTerms(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client.from("terms").select("*").eq("id", companyId).single();
+}
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
index dfb72fb675..48d5984621 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,4 +1,4 @@
-import { LuFactory, LuSheet, LuWorkflow } from "react-icons/lu";
+import { LuFactory, LuFileText, LuSheet, LuWorkflow } from "react-icons/lu";
import { MdOutlineDashboardCustomize } from "react-icons/md";
import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
@@ -14,6 +14,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
role: "employee",
icon: <LuFactory />,
},
+ {
+ name: "Terms",
+ to: path.to.terms,
+ role: "employee",
+ icon: <LuFileText />,
+ },
],
},
{
diff --git a/apps/carbon/app/modules/shared/ui/MethodBadge.tsx b/apps/carbon/app/modules/shared/ui/MethodBadge.tsx
index e2c0fcb147..84d2ff2966 100644
--- a/apps/carbon/app/modules/shared/ui/MethodBadge.tsx
+++ b/apps/carbon/app/modules/shared/ui/MethodBadge.tsx
@@ -1,6 +1,8 @@
-import { Badge, HStack, cn } from "@carbon/react";
+import { Badge, HStack } from "@carbon/react";
+import { getColor } from "@carbon/utils";
import { Link } from "@remix-run/react";
import { LuExternalLink } from "react-icons/lu";
+import { useMode } from "~/hooks/useMode";
import type { MethodType } from "../types";
import { MethodIcon } from "./MethodIcon";
@@ -12,10 +14,12 @@ type MethodBadgeProps = {
};
export function MethodBadge({ type, text, to, className }: MethodBadgeProps) {
+ const mode = useMode();
+ const style = getBadgeColor(type, mode);
return (
<HStack className="group" spacing={1}>
- <Badge className={cn(getBadgeColor(type), className)}>
- <MethodIcon type={type} className="w-3 h-3 mr-1 text-white" />
+ <Badge style={style}>
+ <MethodIcon type={type} className="w-3 h-3 mr-1 " />
{text}
</Badge>
<Link
@@ -29,10 +33,10 @@ export function MethodBadge({ type, text, to, className }: MethodBadgeProps) {
);
}
-function getBadgeColor(type: MethodType) {
+function getBadgeColor(type: MethodType, mode: "light" | "dark") {
return type === "Buy"
- ? "bg-blue-500 hover:bg-blue-600 text-white"
+ ? getColor("blue", mode)
: type === "Make"
- ? "bg-green-500 hover:bg-green-600 text-white"
- : "bg-orange-500 hover:bg-orange-600 text-white";
+ ? getColor("green", mode)
+ : getColor("orange", mode);
}
diff --git a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
index f6bd7823a7..a37ffde677 100644
--- a/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
@@ -1,4 +1,5 @@
import { PurchaseOrderPDF } from "@carbon/documents";
+import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
import { type LoaderFunctionArgs } from "@remix-run/node";
import logger from "~/lib/logger";
@@ -6,6 +7,7 @@ import {
getPurchaseOrder,
getPurchaseOrderLines,
getPurchaseOrderLocations,
+ getPurchasingTerms,
} from "~/modules/purchasing";
import { getCompany } from "~/modules/settings";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -18,13 +20,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
- const [company, purchaseOrder, purchaseOrderLines, purchaseOrderLocations] =
- await Promise.all([
- getCompany(client, companyId),
- getPurchaseOrder(client, orderId),
- getPurchaseOrderLines(client, orderId),
- getPurchaseOrderLocations(client, orderId),
- ]);
+ const [
+ company,
+ purchaseOrder,
+ purchaseOrderLines,
+ purchaseOrderLocations,
+ terms,
+ ] = await Promise.all([
+ getCompany(client, companyId),
+ getPurchaseOrder(client, orderId),
+ getPurchaseOrderLines(client, orderId),
+ getPurchaseOrderLocations(client, orderId),
+ getPurchasingTerms(client, companyId),
+ ]);
if (company.error) {
logger.error(company.error);
@@ -42,11 +50,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
logger.error(purchaseOrderLocations.error);
}
+ if (terms.error) {
+ logger.error(terms.error);
+ }
+
if (
company.error ||
purchaseOrder.error ||
purchaseOrderLines.error ||
- purchaseOrderLocations.error
+ purchaseOrderLocations.error ||
+ terms.error
) {
throw new Error("Failed to load purchase order");
}
@@ -57,6 +70,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
purchaseOrder={purchaseOrder.data}
purchaseOrderLines={purchaseOrderLines.data ?? []}
purchaseOrderLocations={purchaseOrderLocations.data}
+ terms={(terms?.data?.purchasingTerms ?? {}) as JSONContent}
/>
);
diff --git a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
index 68299407e7..847120e8c2 100644
--- a/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -1,4 +1,5 @@
import { QuotePDF } from "@carbon/documents";
+import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
import { type LoaderFunctionArgs } from "@remix-run/node";
import logger from "~/lib/logger";
@@ -11,6 +12,7 @@ import {
getQuoteLines,
getQuotePayment,
getQuoteShipment,
+ getSalesTerms,
} from "~/modules/sales";
import { getCompany } from "~/modules/settings";
import { getBase64ImageFromSupabase } from "~/modules/shared";
@@ -33,6 +35,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
quotePayment,
quoteShipment,
paymentTerms,
+ terms,
shippingMethods,
] = await Promise.all([
getCompany(client, companyId),
@@ -43,6 +46,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getQuotePayment(client, id),
getQuoteShipment(client, id),
getPaymentTermsList(client, companyId),
+ getSalesTerms(client, companyId),
getShippingMethodsList(client, companyId),
]);
@@ -112,6 +116,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
shipment={quoteShipment?.data}
paymentTerms={paymentTerms.data ?? []}
shippingMethods={shippingMethods.data ?? []}
+ terms={(terms?.data?.salesTerms ?? {}) as JSONContent}
thumbnails={thumbnails}
/>
);
diff --git a/apps/carbon/app/routes/file+/sales-order+/$id[.]pdf.tsx b/apps/carbon/app/routes/file+/sales-order+/$id[.]pdf.tsx
index 85eb7b4da5..dd7006af5a 100644
--- a/apps/carbon/app/routes/file+/sales-order+/$id[.]pdf.tsx
+++ b/apps/carbon/app/routes/file+/sales-order+/$id[.]pdf.tsx
@@ -1,4 +1,5 @@
import { SalesOrderPDF } from "@carbon/documents";
+import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
import { type LoaderFunctionArgs } from "@remix-run/node";
import logger from "~/lib/logger";
@@ -6,6 +7,7 @@ import {
getSalesOrder,
getSalesOrderCustomerDetails,
getSalesOrderLines,
+ getSalesTerms,
} from "~/modules/sales";
import { getCompany } from "~/modules/settings";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -18,12 +20,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find id");
- const [company, salesOrder, salesOrderLines, salesOrderLocations] =
+ const [company, salesOrder, salesOrderLines, salesOrderLocations, terms] =
await Promise.all([
getCompany(client, companyId),
getSalesOrder(client, id),
getSalesOrderLines(client, id),
getSalesOrderCustomerDetails(client, id),
+ getSalesTerms(client, companyId),
]);
if (company.error) {
@@ -42,11 +45,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
logger.error(salesOrderLocations.error);
}
+ if (terms.error) {
+ logger.error(terms.error);
+ }
+
if (
company.error ||
salesOrder.error ||
salesOrderLines.error ||
- salesOrderLocations.error
+ salesOrderLocations.error ||
+ terms.error
) {
throw new Error("Failed to load sales order");
}
@@ -62,6 +70,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
salesOrder={salesOrder.data}
salesOrderLines={salesOrderLines.data ?? []}
salesOrderLocations={salesOrderLocations.data}
+ terms={(terms?.data?.salesTerms ?? {}) as JSONContent}
title="Sales Order"
/>
);
diff --git a/apps/carbon/app/routes/x+/settings+/terms.tsx b/apps/carbon/app/routes/x+/settings+/terms.tsx
new file mode 100644
index 0000000000..8a6115393c
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/terms.tsx
@@ -0,0 +1,181 @@
+import type { JSONContent } from "@carbon/react";
+import {
+ Badge,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Editor,
+ generateHTML,
+ HStack,
+ useThrottle,
+ VStack,
+} from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect, useLoaderData } from "@remix-run/react";
+import { useState } from "react";
+import { LuCheckCircle } from "react-icons/lu";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { getTerms } from "~/modules/settings";
+
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Terms",
+ to: path.to.terms,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const terms = await getTerms(client, companyId);
+ if (terms.error) {
+ throw redirect(
+ path.to.settings,
+ await flash(request, error(terms.error, "Failed to load terms"))
+ );
+ }
+
+ return json({
+ terms: terms.data,
+ });
+}
+
+export default function Terms() {
+ const { terms } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+ const { supabase } = useSupabase();
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+
+ const [purchasingTermsStatus, setPurchasingTermsStatus] = useState<
+ "saved" | "draft"
+ >("saved");
+ const [salesTermsStatus, setSalesTermsStatus] = useState<"saved" | "draft">(
+ "saved"
+ );
+
+ const handleUpdatePurchasingTerms = (content: JSONContent) => {
+ setPurchasingTermsStatus("draft");
+ onUpdatePurchasingTerms(content);
+ };
+ const onUpdatePurchasingTerms = useThrottle(async (content: JSONContent) => {
+ if (!supabase) return;
+ const { error } = await supabase
+ .from("terms")
+ .update({
+ purchasingTerms: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", companyId);
+ if (!error) setPurchasingTermsStatus("saved");
+ }, 2500);
+
+ const handleUpdateSalesTerms = (content: JSONContent) => {
+ setSalesTermsStatus("draft");
+ onUpdateSalesTerms(content);
+ };
+ const onUpdateSalesTerms = useThrottle(async (content: JSONContent) => {
+ setSalesTermsStatus("draft");
+ await supabase
+ ?.from("terms")
+ .update({
+ salesTerms: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", companyId);
+ setSalesTermsStatus("saved");
+ }, 2500);
+
+ const onUploadImage = async (file: File) => {
+ // Implement image upload logic here
+ // This is a placeholder function
+ console.log("Image upload not implemented", file);
+ return "";
+ };
+
+ return (
+ <VStack spacing={4} className="p-4 h-full">
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Purchasing Terms</CardTitle>
+ <CardDescription>
+ Define the terms and conditions for purchase orders
+ </CardDescription>
+ </CardHeader>
+ <CardAction className="py-6">
+ {purchasingTermsStatus === "draft" ? (
+ <Badge variant="secondary">Draft</Badge>
+ ) : (
+ <LuCheckCircle className="w-4 h-4 text-green-500" />
+ )}
+ </CardAction>
+ </HStack>
+ <CardContent>
+ {permissions.can("update", "settings") ? (
+ <Editor
+ initialValue={(terms.purchasingTerms ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={handleUpdatePurchasingTerms}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(terms.purchasingTerms as JSONContent),
+ }}
+ />
+ )}
+ </CardContent>
+ </Card>
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Sales Terms</CardTitle>
+ <CardDescription>
+ Define the terms and conditions for quotes and sales orders
+ </CardDescription>
+ </CardHeader>
+ <CardAction className="py-6">
+ {salesTermsStatus === "draft" ? (
+ <Badge variant="secondary">Draft</Badge>
+ ) : (
+ <LuCheckCircle className="w-4 h-4 text-green-500" />
+ )}
+ </CardAction>
+ </HStack>
+ <CardContent>
+ {permissions.can("update", "settings") ? (
+ <Editor
+ initialValue={(terms.salesTerms ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={handleUpdateSalesTerms}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(terms.salesTerms as JSONContent),
+ }}
+ />
+ )}
+ </CardContent>
+ </Card>
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 32b342cde2..92f8ede392 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -709,6 +709,7 @@ export const path = {
supplierTypes: `${x}/purchasing/supplier-types`,
tableSequence: (id: string) =>
generatePath(`${x}/settings/sequences/${id}`),
+ terms: `${x}/settings/terms`,
theme: `${x}/account/theme`,
timecards: `${x}/timecards`,
tool: (id: string) => generatePath(`${x}/tool/${id}`),
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index f6458c9eea..03800390a8 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -16356,6 +16356,141 @@ export default {
tags: ["supplierStatus"],
},
},
+ "/terms": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.terms.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.purchasingTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.salesTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedBy",
+ },
+ {
+ $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/terms",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["terms"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.terms",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["terms"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.terms.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.purchasingTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.salesTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedBy",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["terms"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.terms.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.purchasingTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.salesTerms",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.terms.updatedBy",
+ },
+ {
+ $ref: "#/parameters/body.terms",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["terms"],
+ },
+ },
"/employeeShift": {
get: {
parameters: [
@@ -40416,6 +40551,34 @@ export default {
},
type: "object",
},
+ terms: {
+ required: ["id"],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ purchasingTerms: {
+ format: "json",
+ },
+ salesTerms: {
+ format: "json",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
employeeShift: {
required: ["id", "employeeId", "shiftId"],
properties: {
@@ -56761,6 +56924,50 @@ export default {
in: "query",
type: "string",
},
+ "body.terms": {
+ name: "terms",
+ description: "terms",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/terms",
+ },
+ },
+ "rowFilter.terms.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.terms.purchasingTerms": {
+ name: "purchasingTerms",
+ required: false,
+ format: "json",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.terms.salesTerms": {
+ name: "salesTerms",
+ required: false,
+ format: "json",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.terms.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.terms.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.employeeShift": {
name: "employeeShift",
description: "employeeShift",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index f416025f52..3fc96f4992 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -19243,6 +19243,94 @@ export type Database = {
},
]
}
+ terms: {
+ Row: {
+ id: string
+ purchasingTerms: Json | null
+ salesTerms: Json | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ id?: string
+ purchasingTerms?: Json | null
+ salesTerms?: Json | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ id?: string
+ purchasingTerms?: Json | null
+ salesTerms?: Json | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tool: {
Row: {
approved: boolean
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index f416025f52..3fc96f4992 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -19243,6 +19243,94 @@ export type Database = {
},
]
}
+ terms: {
+ Row: {
+ id: string
+ purchasingTerms: Json | null
+ salesTerms: Json | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ id?: string
+ purchasingTerms?: Json | null
+ salesTerms?: Json | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ id?: string
+ purchasingTerms?: Json | null
+ salesTerms?: Json | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "terms_id_fkey"
+ columns: ["id"]
+ isOneToOne: true
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "terms_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
tool: {
Row: {
approved: boolean
diff --git a/packages/database/supabase/migrations/20240908100622_terms.sql b/packages/database/supabase/migrations/20240908100622_terms.sql
new file mode 100644
index 0000000000..54398a2891
--- /dev/null
+++ b/packages/database/supabase/migrations/20240908100622_terms.sql
@@ -0,0 +1,52 @@
+CREATE TABLE "terms" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchasingTerms" JSON DEFAULT '{}',
+ "salesTerms" JSON DEFAULT '{}',
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "terms_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "terms_id_fkey" FOREIGN KEY ("id") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "terms_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE SET NULL
+);
+
+-- Create a function to insert a row into the terms table
+CREATE OR REPLACE FUNCTION insert_terms_for_new_company()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO "terms" ("id")
+ VALUES (NEW.id);
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Create a trigger that calls the function after an insert into the company table
+CREATE TRIGGER create_terms_after_company_insert
+AFTER INSERT ON "company"
+FOR EACH ROW
+EXECUTE FUNCTION insert_terms_for_new_company();
+
+-- Insert terms for all existing companies
+INSERT INTO "terms" ("id")
+SELECT "id" FROM "company"
+WHERE "id" NOT IN (SELECT "id" FROM "terms");
+
+ALTER TABLE "terms" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view or sales_view or settings_view can view terms" ON "terms"
+ FOR SELECT
+ USING (
+ has_role('employee', "id") AND (
+ has_company_permission('purchasing_view', "id") OR
+ has_company_permission('sales_view', "id") OR
+ has_company_permission('settings_view', "id")
+ )
+ );
+
+CREATE POLICY "Employees with settings_update can update terms" ON "terms"
+ FOR UPDATE
+ USING (
+ has_role('employee', "id") AND
+ has_company_permission('settings_update', "id")
+ );
+
diff --git a/packages/documents/src/pdf/PurchaseOrderPDF.tsx b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
index 333c0b22e6..b32d5d7f1c 100644
--- a/packages/documents/src/pdf/PurchaseOrderPDF.tsx
+++ b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
@@ -2,6 +2,7 @@ import type { Database } from "@carbon/database";
import { Text, View } from "@react-pdf/renderer";
import { createTw } from "react-pdf-tailwind";
+import type { JSONContent } from "@carbon/react";
import type { PDF } from "../types";
import {
getLineDescription,
@@ -10,12 +11,13 @@ import {
getTotal,
} from "../utils/purchase-order";
import { formatAddress } from "../utils/shared";
-import { Header, Summary, Template } from "./components";
+import { Header, Note, Summary, Template } from "./components";
interface PurchaseOrderPDFProps extends PDF {
purchaseOrder: Database["public"]["Views"]["purchaseOrders"]["Row"];
purchaseOrderLines: Database["public"]["Views"]["purchaseOrderLines"]["Row"][];
purchaseOrderLocations: Database["public"]["Views"]["purchaseOrderLocations"]["Row"];
+ terms: JSONContent;
}
// TODO: format currency based on settings
@@ -46,6 +48,7 @@ const PurchaseOrderPDF = ({
purchaseOrder,
purchaseOrderLines,
purchaseOrderLocations,
+ terms,
title = "Purchase Order",
}: PurchaseOrderPDFProps) => {
const {
@@ -223,6 +226,9 @@ const PurchaseOrderPDF = ({
</View>
)}
</View>
+ <View style={tw("flex flex-col gap-4 w-full")}>
+ <Note title="Terms" content={terms} />
+ </View>
</Template>
);
};
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index 9ddb85c3fb..fdd098ab87 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -18,6 +18,7 @@ interface QuotePDFProps extends PDF {
shipment?: Database["public"]["Tables"]["quoteShipment"]["Row"] | null;
paymentTerms: { id: string; name: string }[];
shippingMethods: { id: string; name: string }[];
+ terms: JSONContent;
thumbnails: Record<string, string | null>;
}
@@ -53,6 +54,7 @@ const QuotePDF = ({
paymentTerms,
shipment,
shippingMethods,
+ terms,
thumbnails,
title = "Quote",
}: QuotePDFProps) => {
@@ -272,7 +274,13 @@ const QuotePDF = ({
})}
</View>
</View>
- <Note note={(quote.externalNotes ?? {}) as JSONContent} />
+ <View style={tw("flex flex-col gap-4 w-full")}>
+ <Note
+ title="Notes"
+ content={(quote.externalNotes ?? {}) as JSONContent}
+ />
+ <Note title="Terms" content={terms} />
+ </View>
</Template>
);
};
diff --git a/packages/documents/src/pdf/SalesOrderPDF.tsx b/packages/documents/src/pdf/SalesOrderPDF.tsx
index b2dc483cdb..7af1d3a7fb 100644
--- a/packages/documents/src/pdf/SalesOrderPDF.tsx
+++ b/packages/documents/src/pdf/SalesOrderPDF.tsx
@@ -2,6 +2,7 @@ import type { Database } from "@carbon/database";
import { Text, View } from "@react-pdf/renderer";
import { createTw } from "react-pdf-tailwind";
+import type { JSONContent } from "@carbon/react";
import type { PDF } from "../types";
import {
getLineDescription,
@@ -10,12 +11,13 @@ import {
getTotal,
} from "../utils/sales-order";
import { formatAddress } from "../utils/shared";
-import { Header, Summary, Template } from "./components";
+import { Header, Note, Summary, Template } from "./components";
interface SalesOrderPDFProps extends PDF {
salesOrder: Database["public"]["Views"]["salesOrders"]["Row"];
salesOrderLines: Database["public"]["Views"]["salesOrderLines"]["Row"][];
salesOrderLocations: Database["public"]["Views"]["salesOrderLocations"]["Row"];
+ terms: JSONContent;
}
// TODO: format currency based on settings
@@ -46,6 +48,7 @@ const SalesOrderPDF = ({
salesOrder,
salesOrderLines,
salesOrderLocations,
+ terms,
title = "Sales Order",
}: SalesOrderPDFProps) => {
const {
@@ -218,6 +221,9 @@ const SalesOrderPDF = ({
</View>
)}
</View>
+ <View style={tw("flex flex-col gap-4 w-full")}>
+ <Note title="Terms" content={terms} />
+ </View>
</Template>
);
};
diff --git a/packages/documents/src/pdf/components/Note.tsx b/packages/documents/src/pdf/components/Note.tsx
index 3b40283074..85744657d6 100644
--- a/packages/documents/src/pdf/components/Note.tsx
+++ b/packages/documents/src/pdf/components/Note.tsx
@@ -3,15 +3,18 @@ import { StyleSheet, Text, View } from "@react-pdf/renderer";
const convertTiptapJSON = (
node: JSONContent,
- index?: number,
- parentNodeType?: string
+ args?: {
+ index?: number;
+ parentNodeType?: string;
+ title?: string;
+ }
) => {
switch (node.type) {
case "doc":
return (
<View style={{ fontSize: 11 }}>
<View style={styles.thead}>
- <Text>Notes</Text>
+ <Text>{args?.title ?? "Notes"}</Text>
</View>
{node.content.map((child, index) => convertTiptapJSON(child))}
</View>
@@ -42,7 +45,10 @@ const convertTiptapJSON = (
return (
<View key="bulletList" style={{ marginLeft: 20 }}>
{node.content.map((child, index) =>
- convertTiptapJSON(child, index, "bulletList")
+ convertTiptapJSON(child, {
+ index,
+ parentNodeType: "bulletList",
+ })
)}
</View>
);
@@ -51,16 +57,20 @@ const convertTiptapJSON = (
return (
<View key="orderedList" style={{ marginLeft: 20 }}>
{node.content.map((child, index) =>
- convertTiptapJSON(child, index, "orderedList")
+ convertTiptapJSON(child, {
+ index,
+ parentNodeType: "orderedList",
+ })
)}
</View>
);
case "listItem":
- const indicator = parentNodeType == "orderedList" ? `${index + 1}.` : "•";
+ const indicator =
+ args.parentNodeType == "orderedList" ? `${args.index + 1}.` : "•";
return (
<View
- key={`listItem-${index}`}
+ key={`listItem-${args.index}`}
style={{ flexDirection: "row", marginBottom: 5 }}
>
<Text style={{ marginRight: 5 }}> {indicator} </Text>
@@ -73,14 +83,16 @@ const convertTiptapJSON = (
case "taskList":
return (
<View key="taskList" style={{ marginLeft: 20 }}>
- {node.content.map((child, index) => convertTiptapJSON(child, index))}
+ {node.content.map((child, index) =>
+ convertTiptapJSON(child, { index })
+ )}
</View>
);
case "taskItem":
return (
<View
- key={`taskItem-${index}`}
+ key={`taskItem-${args.index}`}
style={{ flexDirection: "row", marginBottom: 5 }}
>
<Text style={{ marginRight: 5 }}>•</Text>
@@ -101,9 +113,9 @@ const convertTiptapJSON = (
}
};
-const Note = ({ note }: { note: JSONContent }) => {
- if (!note || !("content" in note)) return null;
- return <View>{convertTiptapJSON(note)}</View>;
+const Note = ({ title, content }: { title: string; content: JSONContent }) => {
+ if (!content || !("content" in content)) return null;
+ return <View>{convertTiptapJSON(content, { title })}</View>;
};
export default Note;