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: refactor jobs, integrations, and add onboarding emails

Brad Barbinbdb7b47c9741
diff --git a/.github/workflows/trigger.yml b/.github/workflows/trigger.yml
index f9b6b70ba3..771ce24ec6 100644
--- a/.github/workflows/trigger.yml
+++ b/.github/workflows/trigger.yml
@@ -5,7 +5,7 @@ on:
branches:
- main
paths:
- - "apps/erp/app/trigger/**"
+ - "packages/jobs/**"
workflow_dispatch:
jobs:
@@ -30,5 +30,5 @@ jobs:
env:
TRIGGER_ACCESS_TOKEN: ${{ secrets.TRIGGER_ACCESS_TOKEN }}
run: |
- cd apps/erp
+ cd packages/jobs
npx [email protected] deploy
diff --git a/.gitignore b/.gitignore
index 3508b41990..db6bbe7891 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,13 +3,14 @@ node_modules
.turbo
*.log
.next
+.vercel
+.trigger
dist
dist-ssr
*.local
.cache
server/dist
public/dist
-.turbo
vite.config.ts.timestamp*
# local env files
diff --git a/README.md b/README.md
index bf71211cef..33884b9779 100644
--- a/README.md
+++ b/README.md
@@ -10,14 +10,15 @@ Features:
- [x] ERP
- [x] MES
+- [ ] QMS
- [x] Custom Fields
- [x] Nested BoM
- [x] Traceability
+- [x] MRP
- [x] Configurator
- [x] MCP Client/Server
- [x] API
- [x] Webhooks
-- [x] Purchase Planning
- [ ] Accounting
Technical highlights:
@@ -45,6 +46,7 @@ Technical highlights:
- [Resend](https://resend.com) – email
- [Novu](https://novu.co) – notifications
- [Vercel](https://vercel.com) – hosting
+- [Stripe](https://stripe.com) - billing
## Codebase
@@ -59,7 +61,7 @@ The monorepo follows the Turborepo convention of grouping packages into one of t
| ------------ | --------------- | ------------------------ |
| `erp` | ERP Application | `npm run dev` |
| `mes` | MES | `npm run dev:mes` |
-| `univeristy` | University | `npm run dev:university` |
+| `university` | University | `npm run dev:university` |
| `starter` | Starter | `npm run dev:starter` |
### `/packages`
@@ -69,11 +71,14 @@ The monorepo follows the Turborepo convention of grouping packages into one of t
| `eslint-config-carbon` | Shared, extendable eslint configuration for apps and packages |
| `@carbon/database` | Database schema, migrations and types |
| `@carbon/documents` | Transactional PDFs and email templates |
+| `@carbon/integrations` | Integration definitions and configurations |
| `@carbon/jest` | Jest preset configuration shared across apps and packages |
+| `@carbon/jobs` | Background jobs and workers |
| `@carbon/logger` | Shared logger used across apps |
| `@carbon/react` | Shared web-based UI components |
| `@carbon/kv` | Redis cache client |
-| `@carbon/lib` | Third-party client libraries (slack, resend, stripe) |
+| `@carbon/lib` | Third-party client libraries (slack, resend) |
+| `@carbon/stripe` | Stripe integration |
| `@carbon/tsconfig` | Shared, extendable tsconfig configuration used across apps and packages |
| `@carbon/utils` | Shared utility functions used across apps and packages |
@@ -231,8 +236,8 @@ $ npm run test -w @carbon/react
To run Stripe locally, run:
```
-$ npm run -w erp register:stripe
-$ npm run -w erp dev:stripe
+$ npm run -w stripe register:stripe
+$ npm run -w stripe dev:stripe
```
### Restoring a Production Database Locally
diff --git a/apps/erp/app/components/Configurator/utils.ts b/apps/erp/app/components/Configurator/utils.ts
index da1ea2b914..cb94fda8c5 100644
--- a/apps/erp/app/components/Configurator/utils.ts
+++ b/apps/erp/app/components/Configurator/utils.ts
@@ -113,6 +113,8 @@ export function getDefaultValue(
return listOptions ? listOptions[0] : "";
case "enum":
return listOptions ? listOptions[0] : "";
+ default:
+ return "";
}
}
diff --git a/apps/erp/app/components/Form/AccountCategory.tsx b/apps/erp/app/components/Form/AccountCategory.tsx
index df8319d124..b737c8e27c 100644
--- a/apps/erp/app/components/Form/AccountCategory.tsx
+++ b/apps/erp/app/components/Form/AccountCategory.tsx
@@ -37,7 +37,7 @@ const AccountCategory = (props: AccountCategorySelectProps) => {
const onChange = (
selection: {
value: string;
- label: string;
+ label: string | React.ReactNode;
} | null
) => {
const category =
diff --git a/apps/erp/app/components/Form/AccountSubcategory.tsx b/apps/erp/app/components/Form/AccountSubcategory.tsx
index 1c40ec93f2..63a76ba19f 100644
--- a/apps/erp/app/components/Form/AccountSubcategory.tsx
+++ b/apps/erp/app/components/Form/AccountSubcategory.tsx
@@ -39,7 +39,12 @@ const AccountSubcategory = (props: AccountSubcategorySelectProps) => {
[accountSubcategoriesFetcher.data]
);
- const onChange = (newValue: { label: string; value: string } | null) => {
+ const onChange = (
+ newValue: {
+ label: string | React.ReactNode;
+ value: string;
+ } | null
+ ) => {
const subCategory =
accountSubcategoriesFetcher.data?.data?.find(
(subCategory) => subCategory.id === newValue?.value
diff --git a/apps/erp/app/components/Form/Currency.tsx b/apps/erp/app/components/Form/Currency.tsx
index 71b62b97c1..1cc2894e1f 100644
--- a/apps/erp/app/components/Form/Currency.tsx
+++ b/apps/erp/app/components/Form/Currency.tsx
@@ -12,7 +12,7 @@ type CurrencySelectProps = Omit<ComboboxProps, "options" | "inline"> & {
const CurrencyPreview = (
value: string,
- options: { value: string; label: string }[]
+ options: { value: string; label: string | React.ReactNode }[]
) => {
const currency = options.find((o) => o.value === value);
if (!currency) return null;
diff --git a/apps/erp/app/components/Form/Employee.tsx b/apps/erp/app/components/Form/Employee.tsx
index e96e3d6c0f..82a05ed795 100644
--- a/apps/erp/app/components/Form/Employee.tsx
+++ b/apps/erp/app/components/Form/Employee.tsx
@@ -15,7 +15,7 @@ type EmployeeSelectProps = Omit<
const EmployeePreview = (
value: string,
- options: { value: string; label: string | JSX.Element }[]
+ options: { value: string; label: string | React.ReactNode }[]
) => {
return <EmployeeAvatar employeeId={value} />;
};
diff --git a/apps/erp/app/components/Form/PaymentTerm.tsx b/apps/erp/app/components/Form/PaymentTerm.tsx
index da7c73fc05..cd658c12ab 100644
--- a/apps/erp/app/components/Form/PaymentTerm.tsx
+++ b/apps/erp/app/components/Form/PaymentTerm.tsx
@@ -14,7 +14,7 @@ type PaymentTermSelectProps = Omit<ComboboxProps, "options" | "inline"> & {
const PaymentTermPreview = (
value: string,
- options: { value: string; label: string }[]
+ options: { value: string; label: string | React.ReactNode }[]
) => {
const paymentTerm = options.find((o) => o.value === value);
if (!paymentTerm) return null;
diff --git a/apps/erp/app/components/Form/Shape.tsx b/apps/erp/app/components/Form/Shape.tsx
index 9f67ec22b8..9bcd259453 100644
--- a/apps/erp/app/components/Form/Shape.tsx
+++ b/apps/erp/app/components/Form/Shape.tsx
@@ -6,8 +6,8 @@ import { useMemo, useRef, useState } from "react";
import { usePermissions } from "~/hooks";
import type { getMaterialFormsList } from "~/modules/items";
import { MaterialShapeForm } from "~/modules/items/ui/MaterialForms";
-import { Enumerable } from "../Enumerable";
import { path } from "~/utils/path";
+import { Enumerable } from "../Enumerable";
type ShapeSelectProps = Omit<ComboboxProps, "options" | "inline"> & {
inline?: boolean;
@@ -15,7 +15,7 @@ type ShapeSelectProps = Omit<ComboboxProps, "options" | "inline"> & {
const ShapePreview = (
value: string,
- options: { value: string; label: string | JSX.Element }[]
+ options: { value: string; label: string | React.ReactNode }[]
) => {
const shape = options.find((o) => o.value === value);
// @ts-ignore
diff --git a/apps/erp/app/components/Form/Substance.tsx b/apps/erp/app/components/Form/Substance.tsx
index 84c94307f2..abc2ab8f99 100644
--- a/apps/erp/app/components/Form/Substance.tsx
+++ b/apps/erp/app/components/Form/Substance.tsx
@@ -6,8 +6,8 @@ import { useMemo, useRef, useState } from "react";
import { usePermissions } from "~/hooks";
import type { getMaterialSubstancesList } from "~/modules/items";
import { MaterialSubstanceForm } from "~/modules/items/ui/MaterialSubstances";
-import { Enumerable } from "../Enumerable";
import { path } from "~/utils/path";
+import { Enumerable } from "../Enumerable";
type SubstanceSelectProps = Omit<ComboboxProps, "options" | "inline"> & {
inline?: boolean;
@@ -15,7 +15,7 @@ type SubstanceSelectProps = Omit<ComboboxProps, "options" | "inline"> & {
const SubstancePreview = (
value: string,
- options: { value: string; label: string | JSX.Element }[]
+ options: { value: string; label: string | React.ReactNode }[]
) => {
const substance = options.find((o) => o.value === value);
// @ts-ignore
diff --git a/apps/erp/app/components/Gantt/Gantt.tsx b/apps/erp/app/components/Gantt/Gantt.tsx
index 8be41405fc..6025231f8d 100644
--- a/apps/erp/app/components/Gantt/Gantt.tsx
+++ b/apps/erp/app/components/Gantt/Gantt.tsx
@@ -301,7 +301,6 @@ const Gantt = ({
</div>
<div className="flex items-center gap-4">
<Slider
- variant="primary"
className="w-20"
leftIcon={<LuZoomOut />}
rightIcon={<LuZoomIn />}
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 6be9087b67..524f29a978 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -112,7 +112,7 @@ const NavigationIconLink = forwardRef<
className={cn(classes, props.className)}
prefetch="intent"
>
- <link.icon className={cn(...iconClasses)} style={{ color: link.color }} />
+ <link.icon className={cn(...iconClasses)} />
<span
aria-hidden={isOpen || undefined}
diff --git a/apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx b/apps/erp/app/components/OnshapeSync.tsx
similarity index 99%
rename from apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx
rename to apps/erp/app/components/OnshapeSync.tsx
index f0ba8d0666..537c8eb893 100644
--- a/apps/erp/app/integrations/onshape/lib/OnshapeSync.tsx
+++ b/apps/erp/app/components/OnshapeSync.tsx
@@ -1,4 +1,5 @@
import { useCarbon } from "@carbon/auth";
+import { OnshapeLogo } from "@carbon/integrations";
import {
Badge,
Button,
@@ -25,7 +26,6 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { LuChevronRight } from "react-icons/lu";
import { MethodIcon } from "~/components";
import { OnshapeStatus } from "~/components/Icons";
-import { Logo } from "~/integrations/onshape/config";
import { methodType } from "~/modules/shared";
import type { action as onShapeSyncAction } from "~/routes/api+/integrations.onshape.sync";
import { path } from "~/utils/path";
@@ -236,7 +236,7 @@ export const OnshapeSync = ({
<div className="flex flex-col gap-2 w-full">
<div className="flex flex-col gap-2 border bg-muted/30 rounded p-2 w-full">
<div className="flex items-center w-full justify-between">
- <Logo className="h-5 w-auto" />
+ <OnshapeLogo className="h-5 w-auto" />
<IconButton
aria-label="Show sync options"
variant="ghost"
diff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
index 8b6a727d81..df5dfdefca 100644
--- a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
@@ -54,12 +54,14 @@ const ChartOfAccountsTableFilters = () => {
<p className="text-sm text-muted-foreground">Start Date</p>
<DatePicker
value={startDate ? parseDate(startDate) : null}
- onChange={(value) => setParams({ startDate: value.toString() })}
+ onChange={(value) =>
+ setParams({ startDate: value?.toString() })
+ }
/>
<p className="text-sm text-muted-foreground">End Date</p>
<DatePicker
value={endDate ? parseDate(endDate) : null}
- onChange={(value) => setParams({ endDate: value.toString() })}
+ onChange={(value) => setParams({ endDate: value?.toString() })}
/>
</div>
</PopoverContent>
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
index 2d84d8a170..3518b25449 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptPostModal.tsx
@@ -17,14 +17,14 @@ import {
useMount,
} from "@carbon/react";
import { useRouteData } from "@carbon/remix";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { useFetcher, useNavigation, useParams } from "@remix-run/react";
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
+import { useUser } from "~/hooks";
import { path } from "~/utils/path";
-import type { ReceiptLine } from "../../types";
import { getReceiptTracking } from "../../inventory.service";
-import type { TrackedEntityAttributes } from "@carbon/utils";
-import { useUser } from "~/hooks";
+import type { ReceiptLine } from "../../types";
const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
const { receiptId } = useParams();
@@ -95,7 +95,7 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
if (!attributes?.["Batch Number"]) {
errors.push({
itemReadableId: line.itemReadableId,
- receivedQuantity: line.receivedQuantity,
+ receivedQuantity: line.receivedQuantity ?? 0,
receivedQuantityError: "Batch number is required",
});
}
@@ -118,7 +118,7 @@ const ReceiptPostModal = ({ onClose }: { onClose: () => void }) => {
if (quantityWithSerial !== line.receivedQuantity) {
errors.push({
itemReadableId: line.itemReadableId,
- receivedQuantity: line.receivedQuantity,
+ receivedQuantity: line.receivedQuantity ?? 0,
receivedQuantityError: "Serial numbers are missing",
});
}
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
index 7ccdb35306..fa1d99db8f 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentPostModal.tsx
@@ -17,14 +17,14 @@ import {
useMount,
} from "@carbon/react";
import { useRouteData } from "@carbon/remix";
+import type { TrackedEntityAttributes } from "@carbon/utils";
import { useFetcher, useNavigation, useParams } from "@remix-run/react";
import { useEffect, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
-import { getShipmentTracking } from "../..";
-import type { ShipmentLine } from "../..";
-import { path } from "~/utils/path";
-import type { TrackedEntityAttributes } from "@carbon/utils";
import { useUser } from "~/hooks";
+import { path } from "~/utils/path";
+import type { ShipmentLine } from "../..";
+import { getShipmentTracking } from "../..";
const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
const { shipmentId } = useParams();
@@ -91,7 +91,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
if (trackedEntity?.status !== "Available") {
errors.push({
itemReadableId: line.itemReadableId,
- shippedQuantity: line.shippedQuantity,
+ shippedQuantity: line.shippedQuantity ?? 0,
shippedQuantityError: "Tracked entity is not available",
});
}
@@ -114,7 +114,7 @@ const ShipmentPostModal = ({ onClose }: { onClose: () => void }) => {
if (quantityAvailable !== line.shippedQuantity) {
errors.push({
itemReadableId: line.itemReadableId,
- shippedQuantity: line.shippedQuantity,
+ shippedQuantity: line.shippedQuantity ?? 0,
shippedQuantityError: "Serial numbers are missing or unavailable",
});
}
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
index 098e85569d..903d12580c 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx
@@ -8,14 +8,14 @@ import {
VStack,
useMount,
} from "@carbon/react";
-import {
+import type {
TrackedActivityAttributes,
TrackedEntityAttributes,
} from "@carbon/utils";
import * as d3 from "d3";
import { motion } from "framer-motion";
-import { useRef, useState, useEffect } from "react";
-import { LuLink, LuCopy } from "react-icons/lu";
+import { useEffect, useRef, useState } from "react";
+import { LuCopy, LuLink } from "react-icons/lu";
import {
CustomerAvatar,
EmployeeAvatar,
@@ -23,12 +23,12 @@ import {
SupplierAvatar,
} from "~/components";
import { useWorkCenters } from "~/components/Form/WorkCenter";
-import {
+import type {
+ Activity,
GraphData,
- GraphNode,
GraphLink,
+ GraphNode,
TrackedEntity,
- Activity,
} from "~/modules/inventory";
import { path } from "~/utils/path";
import { capitalize, copyToClipboard } from "~/utils/string";
@@ -637,7 +637,7 @@ function JobMakeMethodAttribute({
<Hyperlink
to={
materialId
- ? path.to.jobMakeMethod(jobId, makeMethodId, materialId)
+ ? path.to.jobMakeMethod(jobId, makeMethodId)
: path.to.jobMethod(jobId, makeMethodId)
}
>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index f42d5f21cc..6e84d4548e 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -141,6 +141,7 @@ export default function SalesInvoiceExplorer() {
</VStack>
{newSalesInvoiceLineDisclosure.isOpen && (
<SalesInvoiceLineForm
+ // @ts-ignore
initialValues={salesInvoiceLineInitialValues}
type="modal"
onClose={newSalesInvoiceLineDisclosure.onClose}
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index 1a13fd3a19..7305a93c15 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -33,10 +33,10 @@ import {
} from "react-icons/lu";
import { MethodIcon, MethodItemTypeIcon } from "~/components";
import { OnshapeStatus } from "~/components/Icons";
+import { OnshapeSync } from "~/components/OnshapeSync";
import type { FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useIntegrations } from "~/hooks/useIntegrations";
-import { OnshapeSync } from "~/integrations/onshape/lib/OnshapeSync";
import { type MethodItemType } from "~/modules/shared";
import { useBom } from "~/stores";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
index 7bb09336be..fab257ed80 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
@@ -68,7 +68,7 @@ const ItemManufacturingForm = ({
<Boolean
name="requiresConfiguration"
label=""
- description="Use parameters to generate the Bill of Materials and Bill of Process"
+ description="Configured"
/>
)}
<CustomFormFields table="partReplenishment" />
diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.ts
index 37dde6644f..9e96cd837a 100644
--- a/apps/erp/app/modules/resources/resources.service.ts
+++ b/apps/erp/app/modules/resources/resources.service.ts
@@ -171,19 +171,19 @@ export async function getContractors(
return query;
}
-export async function getEmployeeAbility(
- client: SupabaseClient<Database>,
- abilityId: string,
- employeeAbilityId: string
-) {
- return client
- .from("employeeAbility")
- .select(`*, user(id, fullName, avatarUrl)`)
- .eq("abilityId", abilityId)
- .eq("id", employeeAbilityId)
- .eq("active", true)
- .single();
-}
+// export async function getEmployeeAbility(
+// client: SupabaseClient<Database>,
+// abilityId: string,
+// employeeAbilityId: string
+// ) {
+// return client
+// .from("employeeAbility")
+// .select(`*, user(id, fullName, avatarUrl)`)
+// .eq("abilityId", abilityId)
+// .eq("id", employeeAbilityId)
+// .eq("active", true)
+// .single();
+// }
export async function getEmployeeAbilities(
client: SupabaseClient<Database>,
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 90fa35c024..6e562bbfad 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -12,6 +12,7 @@ import {
toast,
} from "@carbon/react";
import { useFetcher } from "@remix-run/react";
+import type { ReactNode } from "react";
import { useState } from "react";
import { flushSync } from "react-dom";
import type { z } from "zod";
@@ -164,7 +165,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
onChange={(
newValue: {
value: string | undefined;
- label: string | JSX.Element;
+ label: string | ReactNode;
} | null
) => {
if (newValue?.value) {
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
index ef2ebc65a6..a8d042acbe 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
@@ -1,4 +1,5 @@
import { Boolean, Input, Submit, ValidatedForm } from "@carbon/form";
+import { integrations as availableIntegrations } from "@carbon/integrations";
import {
Badge,
Button,
@@ -16,7 +17,6 @@ import {
import { SUPPORT_EMAIL } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { usePermissions, useUser } from "~/hooks";
-import { integrations as availableIntegrations } from "~/integrations";
import { path } from "~/utils/path";
interface IntegrationFormProps {
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
index 2ecf7dcf31..568c03a8bd 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
@@ -1,3 +1,4 @@
+import type { IntegrationConfig } from "@carbon/integrations";
import {
Badge,
Button,
@@ -8,7 +9,6 @@ import {
CardTitle,
} from "@carbon/react";
import { Link, useFetcher, useNavigate } from "@remix-run/react";
-import type { IntegrationConfig } from "~/integrations/types";
import { path } from "~/utils/path";
type IntegrationsListProps = {
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index d110072f51..dec932c1e5 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -60,7 +60,7 @@ export async function getCustomFieldsSchemas(
}
if (args?.module) {
- query.eq("module", args.module);
+ query.eq("module", args.module as any);
}
if (args?.table) {
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 8c355bd5bd..1ad91dc285 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -256,7 +256,7 @@ export async function upsertModelUpload(
id: string;
name: string;
size: number;
- autodeskUrn: string;
+ autodeskUrn?: string | null;
thumbnailPath: string;
}
) {
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 61a6106404..bef09c06b8 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -1,6 +1,11 @@
import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { deleteAuthAccount } from "@carbon/auth/auth.server";
import { flash, requireAuthSession } from "@carbon/auth/session.server";
+import {
+ deactivateCustomer,
+ deactivateEmployee,
+ deactivateSupplier,
+} from "@carbon/auth/users.server";
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
import type { SupabaseClient } from "@supabase/supabase-js";
@@ -532,257 +537,6 @@ async function createUser(
return { data, error };
}
-export async function deactivateCustomer(
- serviceRole: SupabaseClient<Database>,
- userId: string,
- companyId: string
-): Promise<Result> {
- const currentPermissions = await serviceRole
- .from("userPermission")
- .select("*")
- .eq("id", userId)
- .maybeSingle();
-
- if (currentPermissions.error) {
- return error(currentPermissions.error, "Failed to get user permissions");
- }
-
- const permissions = Object.entries(
- (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
- ).reduce<Record<string, string[]>>((acc, [key, value]) => {
- acc[key] = value.filter((id) => id !== companyId);
- return acc;
- }, {});
-
- const [updatePermissions, userToCompanyDelete, customerAccountDelete] =
- await Promise.all([
- serviceRole
- .from("userPermission")
- .update({ permissions })
- .eq("id", userId),
- serviceRole
- .from("userToCompany")
- .delete()
- .eq("userId", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("customerAccount")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("search")
- .delete()
- .eq("uuid", userId)
- .eq("companyId", companyId),
- ]);
-
- if (updatePermissions.error) {
- return error(updatePermissions.error, "Failed to update user permissions");
- }
-
- if (userToCompanyDelete.error) {
- return error(
- userToCompanyDelete.error,
- "Failed to remove user from company"
- );
- }
-
- if (customerAccountDelete.error) {
- return error(
- customerAccountDelete.error,
- "Failed to remove customer account"
- );
- }
-
- return success("Sucessfully deactivated customer");
-}
-
-export async function deactivateEmployee(
- serviceRole: SupabaseClient<Database>,
- userId: string,
- companyId: string
-): Promise<Result> {
- const currentPermissions = await serviceRole
- .from("userPermission")
- .select("*")
- .eq("id", userId)
- .maybeSingle();
-
- if (currentPermissions.error) {
- return error(currentPermissions.error, "Failed to get user permissions");
- }
-
- const permissions = Object.entries(
- (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
- ).reduce<Record<string, string[]>>((acc, [key, value]) => {
- acc[key] = value.filter((id) => id !== companyId);
- return acc;
- }, {});
-
- const [updatePermissions, userToCompanyDelete, employeeDelete] =
- await Promise.all([
- serviceRole
- .from("userPermission")
- .update({ permissions })
- .eq("id", userId),
- serviceRole
- .from("userToCompany")
- .delete()
- .eq("userId", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("employee")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("search")
- .delete()
- .eq("uuid", userId)
- .eq("companyId", companyId),
- serviceRole.from("employeeJob").delete().eq("id", userId),
- ]);
-
- if (updatePermissions.error) {
- return error(updatePermissions.error, "Failed to update user permissions");
- }
-
- if (userToCompanyDelete.error) {
- return error(
- userToCompanyDelete.error,
- "Failed to remove user from company"
- );
- }
-
- if (employeeDelete.error) {
- return error(employeeDelete.error, "Failed to remove employee");
- }
-
- return success("Sucessfully deactivated employee");
-}
-
-export async function deactivateUser(
- serviceRole: SupabaseClient<Database>,
- userId: string,
- companyId: string
-) {
- const userToCompany = await serviceRole
- .from("userToCompany")
- .select("role")
- .eq("userId", userId)
- .eq("companyId", companyId)
- .single();
-
- if (userToCompany.error) {
- // maybe they are invited but not added to the company yet
- const user = await serviceRole
- .from("user")
- .select("*")
- .eq("id", userId)
- .single();
- if (user.error) {
- return error(user.error, "Failed to get user");
- }
-
- const invite = await serviceRole
- .from("invite")
- .select("*")
- .eq("email", user.data?.email)
- .eq("companyId", companyId)
- .single();
- if (invite.error) {
- return error(invite.error, "Failed to get invite");
- }
-
- if (invite.data?.role === "customer") {
- return deactivateCustomer(serviceRole, userId, companyId);
- } else if (invite.data?.role === "employee") {
- return deactivateEmployee(serviceRole, userId, companyId);
- } else if (invite.data?.role === "supplier") {
- return deactivateSupplier(serviceRole, userId, companyId);
- } else {
- throw new Error("Invalid user role");
- }
- }
-
- if (userToCompany.data?.role === "customer") {
- return deactivateCustomer(serviceRole, userId, companyId);
- } else if (userToCompany.data?.role === "employee") {
- return deactivateEmployee(serviceRole, userId, companyId);
- } else if (userToCompany.data?.role === "supplier") {
- return deactivateSupplier(serviceRole, userId, companyId);
- } else {
- throw new Error("Invalid user role");
- }
-}
-
-export async function deactivateSupplier(
- serviceRole: SupabaseClient<Database>,
- userId: string,
- companyId: string
-): Promise<Result> {
- const currentPermissions = await serviceRole
- .from("userPermission")
- .select("*")
- .eq("id", userId)
- .maybeSingle();
-
- if (currentPermissions.error) {
- return error(currentPermissions.error, "Failed to get user permissions");
- }
-
- const permissions = Object.entries(
- (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
- ).reduce<Record<string, string[]>>((acc, [key, value]) => {
- acc[key] = value.filter((id) => id !== companyId);
- return acc;
- }, {});
-
- const [updatePermissions, userToCompanyDelete, supplierAccountDelete] =
- await Promise.all([
- serviceRole
- .from("userPermission")
- .update({ permissions })
- .eq("id", userId),
- serviceRole
- .from("userToCompany")
- .delete()
- .eq("userId", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("supplierAccount")
- .delete()
- .eq("id", userId)
- .eq("companyId", companyId),
- serviceRole
- .from("search")
- .delete()
- .eq("uuid", userId)
- .eq("companyId", companyId),
- ]);
-
- if (updatePermissions.error) {
- return error(updatePermissions.error, "Failed to update user permissions");
- }
-
- if (userToCompanyDelete.error) {
- return error(
- userToCompanyDelete.error,
- "Failed to remove user from company"
- );
- }
-
- if (supplierAccountDelete.error) {
- return error(
- supplierAccountDelete.error,
- "Failed to remove supplier account"
- );
- }
-
- return success("Sucessfully deactivated supplier");
-}
-
export async function getClaims(
client: SupabaseClient<Database>,
uid: string,
diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsx
index afb608d1dd..3863c6a2cc 100644
--- a/apps/erp/app/routes/_public+/invite.$code.tsx
+++ b/apps/erp/app/routes/_public+/invite.$code.tsx
@@ -85,10 +85,7 @@ export default function Invite() {
if (!success) {
return (
- <VStack
- spacing={4}
- className="max-w-lg pt-[16dvh] items-center text-center"
- >
+ <VStack spacing={4} className="max-w-lg items-center text-center">
<div className="flex justify-center mb-4">
<img src="/carbon-logo-mark.svg" alt="Carbon Logo" className="w-36" />
</div>
@@ -139,7 +136,7 @@ export default function Invite() {
</Form>
</VStack>
- <p className="text-xs text-muted-foreground absolute bottom-8 left-1/2 -translate-x-1/2 text-center">
+ <p className="text-xs text-muted-foreground text-center">
By accepting the invite, you agree to the{" "}
<Link to="https://carbonos.dev/terms" className="underline">
Terms of Service
diff --git a/apps/erp/app/routes/_public+/magic-link.tsx b/apps/erp/app/routes/_public+/magic-link.tsx
index f4b31e849a..5f2cce1713 100644
--- a/apps/erp/app/routes/_public+/magic-link.tsx
+++ b/apps/erp/app/routes/_public+/magic-link.tsx
@@ -27,7 +27,7 @@ export default function ConfirmMagicLink() {
return (
<AnimatePresence>
- <VStack spacing={4} className="max-w-lg items-center text-center">
+ <VStack spacing={2} className="max-w-lg items-center text-center">
<motion.img
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
diff --git a/apps/erp/app/routes/api+/assign.ts b/apps/erp/app/routes/api+/assign.ts
index 0fb9b743da..415e9a4e73 100644
--- a/apps/erp/app/routes/api+/assign.ts
+++ b/apps/erp/app/routes/api+/assign.ts
@@ -5,7 +5,6 @@ import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { assign } from "~/modules/shared/shared.server";
-import type { notifyTask } from "~/trigger/notify";
export const config = {
runtime: "nodejs",
@@ -61,7 +60,7 @@ export async function action({ request }: ActionFunctionArgs) {
const notificationEvent = getNotificationEvent(table);
if (notificationEvent) {
try {
- await tasks.trigger<typeof notifyTask>("notify", {
+ await tasks.trigger("notify", {
companyId,
documentId: id,
event: notificationEvent,
diff --git a/apps/erp/app/routes/api+/autodesk.upload.ts b/apps/erp/app/routes/api+/autodesk.upload.ts
index 24dfefe9d8..9c13e410d7 100644
--- a/apps/erp/app/routes/api+/autodesk.upload.ts
+++ b/apps/erp/app/routes/api+/autodesk.upload.ts
@@ -1,10 +1,10 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { autodeskUploadTask } from "@carbon/jobs/trigger/autodesk-upload";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { upsertModelUpload } from "~/modules/shared";
-import type { autodeskUploadTask } from "~/trigger/autodesk-upload";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
index e87b3f83aa..dd7e343113 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts
@@ -2,8 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
-import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { Onshape as OnshapeConfig, OnshapeClient } from "@carbon/integrations";
import { getIntegration } from "~/modules/settings/settings.service";
import { getReadableIdWithRevision } from "~/utils/string";
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
index 833d96233f..ce285d9139 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.elements.ts
@@ -2,8 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
-import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { Onshape as OnshapeConfig, OnshapeClient } from "@carbon/integrations";
import { getIntegration } from "~/modules/settings/settings.service";
export const shouldRevalidate: ShouldRevalidateFunction = () => {
diff --git a/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
index 86d1ec923d..2216b2d13d 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.d.$did.versions.ts
@@ -2,8 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
-import { OnshapeClient } from "~/integrations/onshape/lib/client";
+import { Onshape as OnshapeConfig, OnshapeClient } from "@carbon/integrations";
import { getIntegration } from "~/modules/settings/settings.service";
export const shouldRevalidate: ShouldRevalidateFunction = () => {
diff --git a/apps/erp/app/routes/api+/integrations.onshape.documents.ts b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
index 288da9b697..132f00b7de 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.documents.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.documents.ts
@@ -1,9 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { OnshapeClient, Onshape as OnshapeConfig } from "@carbon/integrations";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
-import { Onshape as OnshapeConfig } from "~/integrations/onshape/config";
-import { OnshapeClient } from "~/integrations/onshape/lib/client";
import { getIntegration } from "~/modules/settings/settings.service";
export const shouldRevalidate: ShouldRevalidateFunction = () => {
diff --git a/apps/erp/app/routes/api+/integrations.onshape.sync.ts b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
index 8de031b259..174e8d13b2 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.sync.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
@@ -1,7 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { onShapeDataValidator } from "@carbon/integrations";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { onShapeDataValidator } from "~/integrations/onshape/lib/data";
export const config = {
runtime: "nodejs",
diff --git a/apps/erp/app/routes/api+/messaging.notify.ts b/apps/erp/app/routes/api+/messaging.notify.ts
index 0f84645557..37f0612a8d 100644
--- a/apps/erp/app/routes/api+/messaging.notify.ts
+++ b/apps/erp/app/routes/api+/messaging.notify.ts
@@ -1,11 +1,11 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { notifyTask } from "@carbon/jobs/trigger/notify";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { z } from "zod";
-import type { notifyTask } from "~/trigger/notify";
export const config = {
runtime: "nodejs",
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index 08698ec712..57d62e790f 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -1,8 +1,8 @@
// import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import type { modelThumbnailTask } from "@carbon/jobs/trigger/model-thumbnail";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import type { modelThumbnailTask } from "~/trigger/model-thumbnail";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
index 34a045f02d..015208c502 100644
--- a/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/sales.digital-quote.$id.tsx
@@ -1,4 +1,5 @@
import { assertIsPost, getCarbonServiceRole, notFound } from "@carbon/auth";
+import type { notifyTask } from "@carbon/jobs/trigger/notify";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
@@ -9,7 +10,6 @@ import {
selectedLinesValidator,
} from "~/modules/sales";
import { getCompanySettings } from "~/modules/settings";
-import type { notifyTask } from "~/trigger/notify";
export const config = {
runtime: "nodejs",
diff --git a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
index 4ab37278e6..62d5c84e67 100644
--- a/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
+++ b/apps/erp/app/routes/api+/webhook.paperless-parts.$companyId.ts
@@ -1,10 +1,10 @@
import { getCarbonServiceRole } from "@carbon/auth";
+import type { paperlessPartsTask } from "@carbon/jobs/trigger/paperless-parts";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import crypto from "crypto";
import { z } from "zod";
import { getIntegration } from "~/modules/settings/settings.service";
-import type { paperlessPartsTask } from "~/trigger/paperless-parts";
export const config = {
runtime: "nodejs",
diff --git a/apps/erp/app/routes/api+/webhook.stripe.ts b/apps/erp/app/routes/api+/webhook.stripe.ts
index d4bec4104b..3bc7944ff8 100644
--- a/apps/erp/app/routes/api+/webhook.stripe.ts
+++ b/apps/erp/app/routes/api+/webhook.stripe.ts
@@ -3,11 +3,13 @@ import {
getStripeCustomerId,
processStripeEvent,
syncStripeDataToKV,
-} from "@carbon/lib/stripe.server";
+} from "@carbon/stripe/stripe.server";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { path } from "~/utils/path";
+export const config = { runtime: "nodejs" };
+
export async function loader({ request }: LoaderFunctionArgs) {
const { companyId } = await requirePermissions(request, {});
diff --git a/apps/erp/app/routes/onboarding+/_index.tsx b/apps/erp/app/routes/onboarding+/_index.tsx
index 8065c7de7b..be15ac884e 100644
--- a/apps/erp/app/routes/onboarding+/_index.tsx
+++ b/apps/erp/app/routes/onboarding+/_index.tsx
@@ -16,7 +16,7 @@ export default function GetStarted() {
return (
<AnimatePresence>
- <VStack spacing={4} className="max-w-lg p-4 items-center text-center">
+ <VStack spacing={2} className="max-w-lg p-4 items-center text-center">
<motion.img
initial={{ opacity: 0, scale: 0.4 }}
animate={{ opacity: 1, scale: 1 }}
@@ -38,7 +38,7 @@ export default function GetStarted() {
<motion.p
{...fade}
transition={{ duration: 1.2, ease: "easeInOut", delay: 1.7 }}
- className="text-muted-foreground text-balance text-sm pb-4"
+ className="text-muted-foreground text-balance text-base pb-4"
>
The new standard for tech-enabled manufacturing
</motion.p>
diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsx
index fd56471df4..31e4574416 100644
--- a/apps/erp/app/routes/onboarding+/_layout.tsx
+++ b/apps/erp/app/routes/onboarding+/_layout.tsx
@@ -5,8 +5,8 @@ import { getLocationsList } from "~/modules/resources";
import { getCompany } from "~/modules/settings";
import { onboardingSequence, path } from "~/utils/path";
-import { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.server";
import { VStack } from "@carbon/react";
+import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
export const shouldRevalidate: ShouldRevalidateFunction = () => true;
diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsx
index 1dd72c795b..c1ce17095a 100644
--- a/apps/erp/app/routes/onboarding+/plan.tsx
+++ b/apps/erp/app/routes/onboarding+/plan.tsx
@@ -1,6 +1,5 @@
import { getUser } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { getCheckoutUrl } from "@carbon/lib/stripe.server";
import {
Badge,
Button,
@@ -12,6 +11,7 @@ import {
CardTitle,
IconButton,
} from "@carbon/react";
+import { getCheckoutUrl } from "@carbon/stripe/stripe.server";
import { useLocale } from "@react-aria/i18n";
import { Form, useFetcher, useLoaderData } from "@remix-run/react";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index e7122df9ab..943de70dff 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -27,7 +27,7 @@ import {
} from "~/modules/users/users.server";
import { path } from "~/utils/path";
-import { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.server";
+import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import posthog from "posthog-js";
import { LuArrowUpRight, LuX } from "react-icons/lu";
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.accounting.tsx b/apps/erp/app/routes/x+/customer+/$customerId.accounting.tsx
index ce800e0350..6f9e3c9c27 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.accounting.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.accounting.tsx
@@ -69,7 +69,7 @@ export default function CustomerAccountingRoute() {
if (!routeData?.customer) return null;
const initialValues = {
- id: routeData?.customer?.id ?? undefined,
+ id: routeData?.customer?.id ?? "",
customerTypeId: routeData?.customer?.customerTypeId ?? undefined,
taxId: routeData?.customer?.taxId ?? "",
};
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.details.tsx b/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
index f9f457f99b..dec751e816 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.details.tsx
@@ -61,6 +61,7 @@ export default function CustomerEditRoute() {
const initialValues = {
...routeData.customer,
+ id: routeData?.customer?.id ?? undefined,
name: routeData?.customer?.name ?? "",
customerTypeId: routeData?.customer?.customerTypeId ?? undefined,
customerStatusId: routeData?.customer?.customerStatusId ?? undefined,
diff --git a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
index 3663433901..bbd14157e2 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
@@ -1,10 +1,10 @@
import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { tasks } from "@trigger.dev/sdk/v3";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
import { upsertJobMethod } from "~/modules/production";
-import type { recalculateTask } from "~/trigger/recalculate";
import { path, requestReferrer } from "~/utils/path";
export const config = {
diff --git a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
index b4cec3f7bc..1a10bafdbc 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -133,6 +133,7 @@ export default function JobMakeMethodRoute() {
<JobBillOfProcess
key={`bop:${methodId}`}
jobMakeMethodId={methodId}
+ // @ts-ignore
operations={operations}
locationId={routeData?.job?.locationId ?? ""}
tags={tags}
@@ -141,6 +142,7 @@ export default function JobMakeMethodRoute() {
key={`bom:${methodId}`}
jobMakeMethodId={methodId}
materials={materials}
+ // @ts-ignore
operations={operations}
/>
@@ -154,7 +156,9 @@ export default function JobMakeMethodRoute() {
<Await resolve={productionData}>
{(resolvedProductionData) => (
<JobEstimatesVsActuals
+ // @ts-ignore
materials={materials ?? []}
+ // @ts-ignore
operations={operations}
productionEvents={resolvedProductionData.events}
productionQuantities={resolvedProductionData.quantities}
diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsx
index f8af2980d2..d92a46efef 100644
--- a/apps/erp/app/routes/x+/job+/new.tsx
+++ b/apps/erp/app/routes/x+/job+/new.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { parseDate } from "@internationalized/date";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
@@ -12,7 +13,6 @@ import { jobValidator, upsertJob, upsertJobMethod } from "~/modules/production";
import { JobForm } from "~/modules/production/ui/Jobs";
import { getNextSequence } from "~/modules/settings";
import type { MethodItemType } from "~/modules/shared";
-import type { recalculateTask } from "~/trigger/recalculate";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index 82326ea34d..c88ae176eb 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -1,12 +1,12 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import {
recalculateJobRequirements,
upsertJobMethod,
} from "~/modules/production";
-import type { recalculateTask } from "~/trigger/recalculate";
export const config = {
runtime: "nodejs",
diff --git a/apps/erp/app/routes/x+/part+/new.tsx b/apps/erp/app/routes/x+/part+/new.tsx
index 2f83fa7da5..d75c3d0792 100644
--- a/apps/erp/app/routes/x+/part+/new.tsx
+++ b/apps/erp/app/routes/x+/part+/new.tsx
@@ -2,12 +2,12 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import type { modelThumbnailTask } from "@carbon/jobs/trigger/model-thumbnail";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { partValidator, upsertPart } from "~/modules/items";
import { PartForm } from "~/modules/items/ui/Parts";
-import type { modelThumbnailTask } from "~/trigger/model-thumbnail";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index 656a593b71..b26b9b99d8 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -8,6 +8,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { PurchaseOrderEmail } from "@carbon/documents/email";
import { validationError, validator } from "@carbon/form";
+import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend"; // Assuming you have a sendEmail task defined
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
import { redirect, type ActionFunctionArgs } from "@vercel/remix";
@@ -26,7 +27,6 @@ import {
import { getCompany } from "~/modules/settings";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$orderId[.]pdf";
-import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have a sendEmail task defined
import { path, requestReferrer } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index 67504994ba..1048acda1c 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { QuoteEmail } from "@carbon/documents/email";
import { validationError, validator } from "@carbon/form";
+import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend"; // Assuming you have this task defined
import { getLocalTimeZone, now } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
@@ -19,7 +20,6 @@ import { getCompany, getCompanySettings } from "~/modules/settings";
import { upsertExternalLink } from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
-import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have this task defined
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
diff --git a/apps/erp/app/routes/x+/receipt+/lines.update.tsx b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
index 09e1d28cab..9de53dc647 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
@@ -31,14 +31,6 @@ export async function action({ request }: ActionFunctionArgs) {
.in("id", ids as string[])
.eq("companyId", companyId);
- if (field === "receivedQuantity") {
- await client
- .from("itemTracking")
- .delete()
- .in("sourceDocumentLineId", ids as string[])
- .gte("index", Number(value) - 1);
- }
-
return json(update);
default:
return json({
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index ba28253c9d..25f7dcb131 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { SalesInvoiceEmail } from "@carbon/documents/email";
import { validator } from "@carbon/form";
+import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
import { type ActionFunctionArgs } from "@vercel/remix";
@@ -18,7 +19,6 @@ import { getCustomerContact, salesConfirmValidator } from "~/modules/sales";
import { getCompany } from "~/modules/settings";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/sales-invoice+/$id[.]pdf";
-import type { sendEmailResendTask } from "~/trigger/send-email-resend";
import { stripSpecialCharacters } from "~/utils/string";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
index 9bd671048d..1178fdd6ae 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { parseDate } from "@internationalized/date";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
@@ -13,7 +14,6 @@ import {
upsertJobMethod,
} from "~/modules/production";
import { getNextSequence } from "~/modules/settings";
-import type { recalculateTask } from "~/trigger/recalculate";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index f19d077964..c288e7635a 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { SalesOrderEmail } from "@carbon/documents/email";
import { validator } from "@carbon/form";
+import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";
import { getLocalTimeZone, today } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk/v3";
@@ -20,7 +21,6 @@ import {
import { getCompany } from "~/modules/settings";
import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";
-import type { sendEmailResendTask } from "~/trigger/send-email-resend";
import { stripSpecialCharacters } from "~/utils/string";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.lines.jobs.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.lines.jobs.tsx
index 2a734451b3..5b94a98046 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.lines.jobs.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.lines.jobs.tsx
@@ -1,10 +1,10 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { salesOrderToJobsTask } from "@carbon/jobs/trigger/sales-order-to-jobs";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import type { salesOrderToJobsTask } from "~/trigger/sales-order-to-jobs";
import { path, requestReferrer } from "~/utils/path";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
index c8d318ce07..c6035e11f1 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -1,11 +1,11 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { modelThumbnailTask } from "@carbon/jobs/trigger/model-thumbnail";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import { nanoid } from "nanoid";
import { salesRfqDragValidator, upsertSalesRFQLine } from "~/modules/sales";
-import type { modelThumbnailTask } from "~/trigger/model-thumbnail";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.status.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.status.tsx
index ba36f58f08..9de347752d 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.status.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.status.tsx
@@ -1,13 +1,13 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type { notifyTask } from "@carbon/jobs/trigger/notify";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { salesRFQStatusType, updateSalesRFQStatus } from "~/modules/sales";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import type { notifyTask } from "~/trigger/notify";
import { path } from "~/utils/path";
export const config = {
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index 026d71c8c3..4edeb4ef18 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -2,9 +2,9 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { integrations as availableIntegrations } from "@carbon/integrations";
import { redirect, useLoaderData, useNavigate } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
-import { integrations as availableIntegrations } from "~/integrations";
import {
IntegrationForm,
getIntegration,
diff --git a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
index 2ad14f8a5c..66c22463c3 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
@@ -1,9 +1,9 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { integrations as availableIntegrations } from "@carbon/integrations";
import { redirect } from "@remix-run/react";
import type { ActionFunctionArgs } from "@vercel/remix";
-import { integrations as availableIntegrations } from "~/integrations";
import { deactivateIntegration } from "~/modules/settings";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/settings+/integrations.tsx b/apps/erp/app/routes/x+/settings+/integrations.tsx
index a3a48b606a..62d441de26 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.tsx
@@ -1,9 +1,9 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { integrations as availableIntegrations } from "@carbon/integrations";
import { Outlet, useLoaderData } from "@remix-run/react";
import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
-import { integrations as availableIntegrations } from "~/integrations";
import { IntegrationsList, getIntegrations } from "~/modules/settings";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/shipment+/lines.update.tsx b/apps/erp/app/routes/x+/shipment+/lines.update.tsx
index f3242c34da..f1c0b2339d 100644
--- a/apps/erp/app/routes/x+/shipment+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/shipment+/lines.update.tsx
@@ -31,14 +31,6 @@ export async function action({ request }: ActionFunctionArgs) {
.in("id", ids as string[])
.eq("companyId", companyId);
- if (field === "shippedQuantity") {
- await client
- .from("itemTracking")
- .delete()
- .in("sourceDocumentLineId", ids as string[])
- .gte("index", Number(value) - 1);
- }
-
return json(update);
default:
return json({
diff --git a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
index f7361b6cb3..be857b6b70 100644
--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
@@ -1,8 +1,8 @@
import { validationError, validator } from "@carbon/form";
+import type { updatePermissionsTask } from "@carbon/jobs/trigger/update-permissions";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import type { updatePermissionsTask } from "~/trigger/update-permissions";
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsx
index 10d2bd46c4..eda6e2b86a 100644
--- a/apps/erp/app/routes/x+/users+/deactivate.tsx
+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx
@@ -1,13 +1,13 @@
import { error, safeRedirect, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { deactivateUser } from "@carbon/auth/users.server";
import { validationError, validator } from "@carbon/form";
+import type { userAdminTask } from "@carbon/jobs/trigger/user-admin";
import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { deactivateUsersValidator } from "~/modules/users";
-import { deactivateUser } from "~/modules/users/users.server";
-import type { userAdminTask } from "~/trigger/user-admin";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/routes/x+/users+/revoke-invite.tsx b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
index 13431fe1e4..fa96375a76 100644
--- a/apps/erp/app/routes/x+/users+/revoke-invite.tsx
+++ b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
@@ -1,12 +1,12 @@
import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { deactivateUser } from "@carbon/auth/users.server";
import { validationError, validator } from "@carbon/form";
+import type { userAdminTask } from "@carbon/jobs/trigger/user-admin";
import { tasks } from "@trigger.dev/sdk/v3";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { revokeInviteValidator } from "~/modules/users";
-import { deactivateUser } from "~/modules/users/users.server";
-import type { userAdminTask } from "~/trigger/user-admin";
export const config = { runtime: "nodejs" };
diff --git a/apps/erp/app/styles/tailwind.css b/apps/erp/app/styles/tailwind.css
index c117b07fd8..d5ee358302 100644
--- a/apps/erp/app/styles/tailwind.css
+++ b/apps/erp/app/styles/tailwind.css
@@ -201,7 +201,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.2s infinite ease-in-out;
background-color: #4faade;
}
@@ -215,7 +215,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.4s infinite ease-in-out;
background-color: #6041d0;
}
diff --git a/apps/erp/app/trigger/update-permissions.ts b/apps/erp/app/trigger/update-permissions.ts
deleted file mode 100644
index 7fc958b301..0000000000
--- a/apps/erp/app/trigger/update-permissions.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { task } from "@trigger.dev/sdk/v3";
-import { z } from "zod";
-
-import { getCarbonServiceRole } from "@carbon/auth";
-import { updatePermissions } from "~/modules/users/users.server";
-
-const serviceRole = getCarbonServiceRole();
-export const permissionsUpdateSchema = z.object({
- id: z.string(),
- addOnly: z.boolean(),
- permissions: z.record(
- z.string(),
- z.object({
- view: z.boolean(),
- create: z.boolean(),
- update: z.boolean(),
- delete: z.boolean(),
- })
- ),
- companyId: z.string(),
-});
-
-export const updatePermissionsTask = task({
- id: "update-permissions",
- run: async (payload: z.infer<typeof permissionsUpdateSchema>) => {
- console.info(`🔰 Permission Update for ${payload.id}`);
- const { success, message } = await updatePermissions(serviceRole, payload);
- if (success) {
- console.info(`✅ Permission Update for ${payload.id}`);
- } else {
- console.error(`❌ Permission Update for ${payload.id}: ${message}`);
- }
- return { success, message };
- },
-});
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index b712355872..f914029961 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -18,8 +18,6 @@ export const path = {
accountingSubcategories: (id: string) =>
generatePath(`${api}/accounting/subcategories?accountCategoryId=${id}`),
assign: `${api}/assign`,
- autodeskToken: `${api}/autodesk/token`,
- autodeskUpload: `${api}/autodesk/upload`,
batchNumbers: (itemId: string) =>
generatePath(`${api}/inventory/batch-numbers?itemId=${itemId}`),
billOfMaterials: (methodId: string, withOperations: boolean = false) =>
diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.ts
index dde9802923..7207b702ac 100644
--- a/apps/erp/app/utils/query.ts
+++ b/apps/erp/app/utils/query.ts
@@ -70,9 +70,9 @@ export function getGenericFilter<
) {
switch (operator) {
case "eq":
- return query.eq(column, value);
+ return query.eq(column, value as any);
case "neq":
- return query.neq(column, value);
+ return query.neq(column, value as any);
case "gt":
return query.gt(column, getSafeNumber(value));
case "gte":
@@ -86,7 +86,7 @@ export function getGenericFilter<
case "startsWith":
return query.ilike(column, `${value}%`);
case "in":
- return query.in(column, value.split(","));
+ return query.in(column, value.split(",") as any);
default:
throw badRequest(`Invalid filter operator: ${operator}`);
}
diff --git a/apps/erp/package.json b/apps/erp/package.json
index bbf0c0b0c6..21878fcc91 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -8,6 +8,7 @@
"@carbon/documents": "*",
"@carbon/form": "*",
"@carbon/kv": "*",
+ "@carbon/jobs": "*",
"@carbon/lib": "*",
"@carbon/notifications": "*",
"@carbon/react": "*",
@@ -57,6 +58,7 @@
"localforage": "^1.10.0",
"lodash.debounce": "^4.0.8",
"lodash.words": "^4.2.0",
+ "monaco-editor": "^0.44.0",
"motion-number": "0.1.7",
"nanoid": "5.0.4",
"nanostores": "^0.9.3",
@@ -71,6 +73,7 @@
"react-dropzone": "^14.2.3",
"react-hotkeys-hook": "~4.5.0",
"react-icons": "^5.4.0",
+ "react-intersection-observer": "^9.13.1",
"react-pdf": "^7.7.1",
"react-use-measure": "^2.1.1",
"recharts": "^2.15.0",
@@ -107,12 +110,8 @@
"scripts": {
"build": "remix vite:build",
"clean": "rimraf .cache .turbo node_modules dist build",
- "dev": "run-p dev:remix dev:trigger",
+ "dev": "remix vite:dev",
"dev:novu": "npx novu@latest dev --port 3000",
- "dev:remix": "remix vite:dev",
- "dev:trigger": "npx --yes [email protected] dev",
- "dev:stripe": "tsx ./stripe.dev.ts",
- "register:stripe": "tsx ./stripe.register.ts",
"sync:novu": "npx novu@latest sync ",
"lint": "TIMING=1 eslint \"app/**/*.ts*\"",
"start": "remix-serve ./build/server/index.js",
diff --git a/apps/erp/tsconfig.json b/apps/erp/tsconfig.json
index 6be6e78d8d..eaf85db4d8 100644
--- a/apps/erp/tsconfig.json
+++ b/apps/erp/tsconfig.json
@@ -4,8 +4,7 @@
"**/*.ts",
"**/*.tsx",
"app/modules/documents/documents.service.ts",
- "app/types/global.d.ts",
- "trigger.config.ts"
+ "app/types/global.d.ts"
],
"compilerOptions": {
"lib": ["dom", "dom.iterable", "ESNext"],
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index 5cd87ff5ef..32f0e202d4 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -3,8 +3,8 @@ import {
destroyAuthSession,
requireAuthSession,
} from "@carbon/auth/session.server";
-import { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.server";
import { SidebarProvider, TooltipProvider, useMount } from "@carbon/react";
+import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
import type { ShouldRevalidateFunction } from "@remix-run/react";
import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.css
index 387f62ce56..b20c360888 100644
--- a/apps/mes/app/styles/tailwind.css
+++ b/apps/mes/app/styles/tailwind.css
@@ -165,7 +165,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.2s infinite ease-in-out;
background-color: #4faade;
}
@@ -179,7 +179,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.4s infinite ease-in-out;
background-color: #6041d0;
}
diff --git a/apps/starter/app/styles/tailwind.css b/apps/starter/app/styles/tailwind.css
index 6711a1e203..2c0e04ecb9 100644
--- a/apps/starter/app/styles/tailwind.css
+++ b/apps/starter/app/styles/tailwind.css
@@ -175,7 +175,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.2s infinite ease-in-out;
background-color: #4faade;
}
@@ -189,7 +189,7 @@ p.is-editor-empty:first-child:before {
}
.hexagon + .hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.4s infinite ease-in-out;
background-color: #6041d0;
}
diff --git a/apps/university/app/styles/tailwind.css b/apps/university/app/styles/tailwind.css
index 5a7db76a08..9be3cac92d 100644
--- a/apps/university/app/styles/tailwind.css
+++ b/apps/university/app/styles/tailwind.css
@@ -181,7 +181,7 @@ a.active {
}
.hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.2s infinite ease-in-out;
background-color: #4faade;
}
@@ -195,7 +195,7 @@ a.active {
}
.hexagon + .hexagon + .hexagon {
- margin-left: 16px;
+ margin-left: 8px;
animation: hexloader 1.4s 0.4s infinite ease-in-out;
background-color: #6041d0;
}
diff --git a/package-lock.json b/package-lock.json
index c62c063160..d7a135afc6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,10 +10,6 @@
"ci",
"packages/*"
],
- "dependencies": {
- "@xyflow/react": "^12.2.0",
- "react-intersection-observer": "^9.13.1"
- },
"devDependencies": {
"csv-parse": "^5.5.0",
"eslint": "^8.23.1",
@@ -37,6 +33,7 @@
"@carbon/database": "*",
"@carbon/documents": "*",
"@carbon/form": "*",
+ "@carbon/jobs": "*",
"@carbon/kv": "*",
"@carbon/lib": "*",
"@carbon/notifications": "*",
@@ -87,6 +84,7 @@
"localforage": "^1.10.0",
"lodash.debounce": "^4.0.8",
"lodash.words": "^4.2.0",
+ "monaco-editor": "^0.44.0",
"motion-number": "0.1.7",
"nanoid": "5.0.4",
"nanostores": "^0.9.3",
@@ -101,6 +99,7 @@
"react-dropzone": "^14.2.3",
"react-hotkeys-hook": "~4.5.0",
"react-icons": "^5.4.0",
+ "react-intersection-observer": "^9.13.1",
"react-pdf": "^7.7.1",
"react-use-measure": "^2.1.1",
"recharts": "^2.15.0",
@@ -1726,10 +1725,18 @@
"resolved": "packages/form",
"link": true
},
+ "node_modules/@carbon/integrations": {
+ "resolved": "packages/integrations",
+ "link": true
+ },
"node_modules/@carbon/jest": {
"resolved": "packages/jest",
"link": true
},
+ "node_modules/@carbon/jobs": {
+ "resolved": "packages/jobs",
+ "link": true
+ },
"node_modules/@carbon/kv": {
"resolved": "packages/kv",
"link": true
@@ -1754,6 +1761,10 @@
"resolved": "packages/remix",
"link": true
},
+ "node_modules/@carbon/stripe": {
+ "resolved": "packages/stripe",
+ "link": true
+ },
"node_modules/@carbon/tailwind": {
"resolved": "packages/tailwind",
"link": true
@@ -11599,6 +11610,7 @@
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
"integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "dev": true,
"dependencies": {
"@types/d3-selection": "*"
}
@@ -11696,7 +11708,8 @@
"node_modules/@types/d3-selection": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
- "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w=="
+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
+ "dev": true
},
"node_modules/@types/d3-shape": {
"version": "3.1.7",
@@ -11725,6 +11738,7 @@
"version": "3.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
"integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "dev": true,
"dependencies": {
"@types/d3-selection": "*"
}
@@ -11733,6 +11747,7 @@
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
"integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
+ "dev": true,
"dependencies": {
"@types/d3-interpolate": "*",
"@types/d3-selection": "*"
@@ -13313,34 +13328,6 @@
"resolved": "https://registry.npmjs.org/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz",
"integrity": "sha512-BEO6al7BYqcnfX15W2cnGR+Q566ACXAT9UQykORCWW80lmkpWsnEob6zJS1ZVBKsSJC8+7vJkHwlp+lXG1UCdw=="
},
- "node_modules/@xyflow/react": {
- "version": "12.4.2",
- "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.4.2.tgz",
- "integrity": "sha512-AFJKVc/fCPtgSOnRst3xdYJwiEcUN9lDY7EO/YiRvFHYCJGgfzg+jpvZjkTOnBLGyrMJre9378pRxAc3fsR06A==",
- "dependencies": {
- "@xyflow/system": "0.0.50",
- "classcat": "^5.0.3",
- "zustand": "^4.4.0"
- },
- "peerDependencies": {
- "react": ">=17",
- "react-dom": ">=17"
- }
- },
- "node_modules/@xyflow/system": {
- "version": "0.0.50",
- "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.50.tgz",
- "integrity": "sha512-HVUZd4LlY88XAaldFh2nwVxDOcdIBxGpQ5txzwfJPf+CAjj2BfYug1fHs2p4yS7YO8H6A3EFJQovBE8YuHkAdg==",
- "dependencies": {
- "@types/d3-drag": "^3.0.7",
- "@types/d3-selection": "^3.0.10",
- "@types/d3-transition": "^3.0.8",
- "@types/d3-zoom": "^3.0.8",
- "d3-drag": "^3.0.0",
- "d3-selection": "^3.0.0",
- "d3-zoom": "^3.0.0"
- }
- },
"node_modules/@zxing/text-encoding": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz",
@@ -15095,11 +15082,6 @@
"url": "https://polar.sh/cva"
}
},
- "node_modules/classcat": {
- "version": "5.0.5",
- "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
- "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="
- },
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
@@ -24932,6 +24914,11 @@
"resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.3.tgz",
"integrity": "sha512-ySViT69/76t8VhE1xXHK6Ch4NcDd26gx0MzKXLO+F7NOtnqH68d9zF94nT8ZWSxXh8ELOERsnJO/sWt1xZYw5A=="
},
+ "node_modules/monaco-editor": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.44.0.tgz",
+ "integrity": "sha512-5SmjNStN6bSuSE5WPT2ZV+iYn1/yI9sd4Igtk23ChvqB7kDk9lZbB9F5frsuvpB+2njdIeGGFf2G4gbE6rCC9Q=="
+ },
"node_modules/morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
@@ -28916,9 +28903,9 @@
}
},
"node_modules/react-intersection-observer": {
- "version": "9.15.1",
- "resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.15.1.tgz",
- "integrity": "sha512-vGrqYEVWXfH+AGu241uzfUpNK4HAdhCkSAyFdkMb9VWWXs6mxzBLpWCxEy9YcnDNY2g9eO6z7qUtTBdA9hc8pA==",
+ "version": "9.16.0",
+ "resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.16.0.tgz",
+ "integrity": "sha512-w9nJSEp+DrW9KmQmeWHQyfaP6b03v+TdXynaoA964Wxt7mdR3An11z4NNCQgL4gKSK7y1ver2Fq+JKH6CWEzUA==",
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -35506,9 +35493,9 @@
"integrity": "sha512-tT/oChyDXelLo2A+UVnlW9GU7CsvFMaEnd9kVFsaiCQonFAXd3xrHhkLYu+suwwosrAEQ746xBU+HvYtm1Zs2Q=="
},
"node_modules/zod": {
- "version": "3.24.1",
- "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.1.tgz",
- "integrity": "sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==",
+ "version": "3.25.74",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.74.tgz",
+ "integrity": "sha512-J8poo92VuhKjNknViHRAIuuN6li/EwFbAC8OedzI8uxpEPGiXHGQu9wemIAioIpqgfB4SySaJhdk0mH5Y4ICBg==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
@@ -35804,6 +35791,14 @@
"dev": true,
"license": "Apache-2.0"
},
+ "packages/integrations": {
+ "name": "@carbon/integrations",
+ "version": "*",
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "typescript": "^5.2.2"
+ }
+ },
"packages/jest": {
"name": "@carbon/jest",
"version": "*",
@@ -35814,6 +35809,30 @@
"eslint-config-carbon": "*"
}
},
+ "packages/jobs": {
+ "name": "@carbon/jobs",
+ "version": "0.0.1",
+ "dependencies": {
+ "@carbon/auth": "*",
+ "@carbon/database": "*",
+ "@carbon/documents": "*",
+ "@carbon/lib": "*",
+ "@carbon/notifications": "*",
+ "@internationalized/date": "^3.5.2",
+ "@novu/node": "^2.0.1",
+ "@react-email/components": "0.0.16",
+ "@supabase/functions-js": "2.1.5",
+ "@supabase/supabase-js": "^2.40.0",
+ "@trigger.dev/sdk": "3.3.12",
+ "nanoid": "5.0.4",
+ "resend": "^3.1.0",
+ "zod": "^3.24.1"
+ },
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "typescript": "^5.2.2"
+ }
+ },
"packages/kv": {
"name": "@carbon/kv",
"version": "*",
@@ -35842,8 +35861,8 @@
"@carbon/kv": "*",
"@slack/web-api": "~7.6.0",
"@supabase/supabase-js": "^2.40.0",
- "resend": "^3.1.0",
- "stripe": "^18.3.0"
+ "@trigger.dev/sdk": "3.3.12",
+ "resend": "^3.1.0"
},
"devDependencies": {
"@carbon/logger": "*",
@@ -36012,6 +36031,32 @@
"zod-form-data": "*"
}
},
+ "packages/stripe": {
+ "name": "@carbon/stripe",
+ "version": "*",
+ "dependencies": {
+ "@carbon/auth": "*",
+ "@carbon/database": "*",
+ "@carbon/jobs": "*",
+ "@carbon/kv": "*",
+ "@supabase/supabase-js": "^2.40.0",
+ "@trigger.dev/sdk": "3.3.12",
+ "stripe": "^18.3.0"
+ },
+ "devDependencies": {
+ "@carbon/logger": "*",
+ "@carbon/tsconfig": "*",
+ "@types/node": "^20.12.5",
+ "dotenv": "16.3.1",
+ "eslint": "^8.23.1",
+ "eslint-config-carbon": "*",
+ "rimraf": "^5.0.5",
+ "tsup": "^6.5.0",
+ "tsx": "^4.13.2",
+ "typescript": "^5.2.2",
+ "zod": "^3.24.2"
+ }
+ },
"packages/tailwind": {
"name": "@carbon/tailwind",
"version": "*",
diff --git a/package.json b/package.json
index 22aaef76aa..3aca2241af 100755
--- a/package.json
+++ b/package.json
@@ -46,7 +46,10 @@
"db:stop": "npm run db:stop -w @carbon/database",
"db:types": "npm run db:types -w @carbon/database",
"deploy": "turbo run deploy",
- "dev": "turbo run dev --filter=./apps/erp --filter=./packages/",
+ "dev": "run-p dev:erp dev:jobs dev:stripe",
+ "dev:erp": "turbo run dev --filter=./apps/erp --filter=./packages/ ",
+ "dev:jobs": "npm run -w @carbon/jobs dev:jobs",
+ "dev:stripe": "npm run -w @carbon/stripe dev:stripe",
"dev:mes": "turbo run dev --filter=./apps/mes",
"dev:starter": "turbo run dev --filter=./apps/starter --filter=./packages/",
"dev:university": "turbo run dev --filter=./apps/university --filter=./packages/",
@@ -60,16 +63,13 @@
"postdb:build": "run-s generate:types generate:swagger",
"prepare": "npx husky install",
"setup": "turbo run setup",
- "test": "turbo run test"
+ "test": "turbo run test",
+ "types": "turbo run types"
},
"workspaces": [
"apps/*",
"ci",
"packages/*"
],
- "dependencies": {
- "@xyflow/react": "^12.2.0",
- "react-intersection-observer": "^9.13.1"
- },
"packageManager": "[email protected]"
}
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 009f331214..6a09782c50 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -1,6 +1,5 @@
{
"name": "@carbon/auth",
- "dependencies": {},
"devDependencies": {
"@carbon/tsconfig": "*",
"@carbon/utils": "*",
diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.ts
index 5851fbce6b..698a72bb20 100644
--- a/packages/auth/src/services/users.server.ts
+++ b/packages/auth/src/services/users.server.ts
@@ -1,7 +1,9 @@
-import type { Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
+import type { SupabaseClient } from "@supabase/supabase-js";
import { getCarbonServiceRole } from "../lib/supabase";
-import type { Permission } from "../types";
+import type { Permission, Result } from "../types";
+import { error, success } from "../utils/result";
import {
getClaims,
getPermissionCacheKey,
@@ -57,3 +59,254 @@ export async function getUserClaims(userId: string, companyId: string) {
return claims;
}
}
+
+export async function deactivateCustomer(
+ serviceRole: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+): Promise<Result> {
+ const currentPermissions = await serviceRole
+ .from("userPermission")
+ .select("*")
+ .eq("id", userId)
+ .maybeSingle();
+
+ if (currentPermissions.error) {
+ return error(currentPermissions.error, "Failed to get user permissions");
+ }
+
+ const permissions = Object.entries(
+ (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
+ ).reduce<Record<string, string[]>>((acc, [key, value]) => {
+ acc[key] = value.filter((id) => id !== companyId);
+ return acc;
+ }, {});
+
+ const [updatePermissions, userToCompanyDelete, customerAccountDelete] =
+ await Promise.all([
+ serviceRole
+ .from("userPermission")
+ .update({ permissions })
+ .eq("id", userId),
+ serviceRole
+ .from("userToCompany")
+ .delete()
+ .eq("userId", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("customerAccount")
+ .delete()
+ .eq("id", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("search")
+ .delete()
+ .eq("uuid", userId)
+ .eq("companyId", companyId),
+ ]);
+
+ if (updatePermissions.error) {
+ return error(updatePermissions.error, "Failed to update user permissions");
+ }
+
+ if (userToCompanyDelete.error) {
+ return error(
+ userToCompanyDelete.error,
+ "Failed to remove user from company"
+ );
+ }
+
+ if (customerAccountDelete.error) {
+ return error(
+ customerAccountDelete.error,
+ "Failed to remove customer account"
+ );
+ }
+
+ return success("Sucessfully deactivated customer");
+}
+
+export async function deactivateEmployee(
+ serviceRole: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+): Promise<Result> {
+ const currentPermissions = await serviceRole
+ .from("userPermission")
+ .select("*")
+ .eq("id", userId)
+ .maybeSingle();
+
+ if (currentPermissions.error) {
+ return error(currentPermissions.error, "Failed to get user permissions");
+ }
+
+ const permissions = Object.entries(
+ (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
+ ).reduce<Record<string, string[]>>((acc, [key, value]) => {
+ acc[key] = value.filter((id) => id !== companyId);
+ return acc;
+ }, {});
+
+ const [updatePermissions, userToCompanyDelete, employeeDelete] =
+ await Promise.all([
+ serviceRole
+ .from("userPermission")
+ .update({ permissions })
+ .eq("id", userId),
+ serviceRole
+ .from("userToCompany")
+ .delete()
+ .eq("userId", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("employee")
+ .delete()
+ .eq("id", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("search")
+ .delete()
+ .eq("uuid", userId)
+ .eq("companyId", companyId),
+ serviceRole.from("employeeJob").delete().eq("id", userId),
+ ]);
+
+ if (updatePermissions.error) {
+ return error(updatePermissions.error, "Failed to update user permissions");
+ }
+
+ if (userToCompanyDelete.error) {
+ return error(
+ userToCompanyDelete.error,
+ "Failed to remove user from company"
+ );
+ }
+
+ if (employeeDelete.error) {
+ return error(employeeDelete.error, "Failed to remove employee");
+ }
+
+ return success("Sucessfully deactivated employee");
+}
+
+export async function deactivateUser(
+ serviceRole: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+) {
+ const userToCompany = await serviceRole
+ .from("userToCompany")
+ .select("role")
+ .eq("userId", userId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (userToCompany.error) {
+ // maybe they are invited but not added to the company yet
+ const user = await serviceRole
+ .from("user")
+ .select("*")
+ .eq("id", userId)
+ .single();
+ if (user.error) {
+ return error(user.error, "Failed to get user");
+ }
+
+ const invite = await serviceRole
+ .from("invite")
+ .select("*")
+ .eq("email", user.data?.email)
+ .eq("companyId", companyId)
+ .single();
+ if (invite.error) {
+ return error(invite.error, "Failed to get invite");
+ }
+
+ if (invite.data?.role === "customer") {
+ return deactivateCustomer(serviceRole, userId, companyId);
+ } else if (invite.data?.role === "employee") {
+ return deactivateEmployee(serviceRole, userId, companyId);
+ } else if (invite.data?.role === "supplier") {
+ return deactivateSupplier(serviceRole, userId, companyId);
+ } else {
+ throw new Error("Invalid user role");
+ }
+ }
+
+ if (userToCompany.data?.role === "customer") {
+ return deactivateCustomer(serviceRole, userId, companyId);
+ } else if (userToCompany.data?.role === "employee") {
+ return deactivateEmployee(serviceRole, userId, companyId);
+ } else if (userToCompany.data?.role === "supplier") {
+ return deactivateSupplier(serviceRole, userId, companyId);
+ } else {
+ throw new Error("Invalid user role");
+ }
+}
+
+export async function deactivateSupplier(
+ serviceRole: SupabaseClient<Database>,
+ userId: string,
+ companyId: string
+): Promise<Result> {
+ const currentPermissions = await serviceRole
+ .from("userPermission")
+ .select("*")
+ .eq("id", userId)
+ .maybeSingle();
+
+ if (currentPermissions.error) {
+ return error(currentPermissions.error, "Failed to get user permissions");
+ }
+
+ const permissions = Object.entries(
+ (currentPermissions.data?.permissions ?? {}) as Record<string, string[]>
+ ).reduce<Record<string, string[]>>((acc, [key, value]) => {
+ acc[key] = value.filter((id) => id !== companyId);
+ return acc;
+ }, {});
+
+ const [updatePermissions, userToCompanyDelete, supplierAccountDelete] =
+ await Promise.all([
+ serviceRole
+ .from("userPermission")
+ .update({ permissions })
+ .eq("id", userId),
+ serviceRole
+ .from("userToCompany")
+ .delete()
+ .eq("userId", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("supplierAccount")
+ .delete()
+ .eq("id", userId)
+ .eq("companyId", companyId),
+ serviceRole
+ .from("search")
+ .delete()
+ .eq("uuid", userId)
+ .eq("companyId", companyId),
+ ]);
+
+ if (updatePermissions.error) {
+ return error(updatePermissions.error, "Failed to update user permissions");
+ }
+
+ if (userToCompanyDelete.error) {
+ return error(
+ userToCompanyDelete.error,
+ "Failed to remove user from company"
+ );
+ }
+
+ if (supplierAccountDelete.error) {
+ return error(
+ supplierAccountDelete.error,
+ "Failed to remove supplier account"
+ );
+ }
+
+ return success("Sucessfully deactivated supplier");
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b4448c312e..99f19e26b2 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -41655,6 +41655,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.admin",
},
+ {
+ $ref: "#/parameters/rowFilter.user.acknowledgedUniversity",
+ },
{
$ref: "#/parameters/select",
},
@@ -41750,6 +41753,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.admin",
},
+ {
+ $ref: "#/parameters/rowFilter.user.acknowledgedUniversity",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -41799,6 +41805,9 @@ export default {
{
$ref: "#/parameters/rowFilter.user.admin",
},
+ {
+ $ref: "#/parameters/rowFilter.user.acknowledgedUniversity",
+ },
{
$ref: "#/parameters/body.user",
},
@@ -76994,7 +77003,15 @@ export default {
type: "object",
},
user: {
- required: ["id", "email", "firstName", "lastName", "about", "createdAt"],
+ required: [
+ "id",
+ "email",
+ "firstName",
+ "lastName",
+ "about",
+ "createdAt",
+ "acknowledgedUniversity",
+ ],
properties: {
id: {
description: "Note:\nThis is a Primary Key.<pk/>",
@@ -77052,6 +77069,11 @@ export default {
format: "boolean",
type: "boolean",
},
+ acknowledgedUniversity: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
},
type: "object",
},
@@ -104420,6 +104442,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.user.acknowledgedUniversity": {
+ name: "acknowledgedUniversity",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.externalLink": {
name: "externalLink",
description: "externalLink",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index ba7537883b..4829f3acd6 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -39854,14 +39854,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -42096,14 +42096,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index ba7537883b..4829f3acd6 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -39854,14 +39854,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -42096,14 +42096,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/trigger/index.ts b/packages/database/supabase/functions/trigger/index.ts
index 25dd33d48d..094ff4b187 100644
--- a/packages/database/supabase/functions/trigger/index.ts
+++ b/packages/database/supabase/functions/trigger/index.ts
@@ -1,7 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { tasks } from "npm:@trigger.dev/[email protected]/v3";
import { z } from "npm:zod@^3.24.1";
-import type { notifyTask } from "../../../../../apps/erp/app/trigger/notify.ts";
+import type { notifyTask } from "../../../../jobs/trigger/notify.ts";
import { corsHeaders } from "../lib/headers.ts";
diff --git a/packages/documents/src/email/GetStartedEmail.tsx b/packages/documents/src/email/GetStartedEmail.tsx
new file mode 100644
index 0000000000..23e92a87c6
--- /dev/null
+++ b/packages/documents/src/email/GetStartedEmail.tsx
@@ -0,0 +1,182 @@
+import {
+ Body,
+ Container,
+ Heading,
+ Preview,
+ Text,
+} from "@react-email/components";
+import { Logo } from "./components/Logo";
+import {
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
+
+interface Props {
+ firstName?: string;
+ universityUrl?: string;
+}
+
+export const GetStartedEmail = ({
+ firstName = "Huckleberry",
+ universityUrl = "https://learn.carbonos.dev",
+}: Props) => {
+ const text = `Hi ${firstName}, Just checking in to help you get started. Here are a few things you can try today.`;
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
+
+ return (
+ <EmailThemeProvider preview={<Preview>{text}</Preview>}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`my-[40px] mx-auto p-[20px] max-w-[600px] ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: 1,
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Logo />
+ <Heading
+ className={`text-[21px] font-normal text-center p-0 my-[30px] mx-0 ${themeClasses.heading}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Get started with Carbon
+ </Heading>
+
+ <br />
+
+ <span
+ className={`font-medium ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Hi {firstName},
+ </span>
+
+ <Text
+ className={themeClasses.text}
+ style={{ color: lightStyles.text.color }}
+ >
+ Just checking in to help you get started. Here are a few things you
+ can learn more about today:
+ </Text>
+ <br />
+ <ul
+ className={`list-none pl-0 text-[14px] ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a
+ href={`${universityUrl}/course/carbon-overview/the-basics`}
+ >
+ The Basics
+ </a>
+ </strong>{" "}
+ – Learn about the essential building blocks of Carbon: tables,
+ forms, documents, and custom fields.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a
+ href={`${universityUrl}/course/getting-started/setting-up-company`}
+ >
+ Setting up Your Company
+ </a>
+ </strong>{" "}
+ – Learn how to set up your company in Carbon.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a
+ href={`${universityUrl}/course/parts-materials/defining-item`}
+ >
+ Defining Items
+ </a>
+ </strong>{" "}
+ – Learn how to define and manage different types of items in
+ Carbon.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a
+ href={`${universityUrl}/course/selling/quoting-estimating`}
+ >
+ Quoting and Estimating
+ </a>
+ </strong>{" "}
+ – Learn how to create quotes, estimates, and convert them to
+ orders.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a
+ href={`${universityUrl}/course/manufacturing/managing-production`}
+ >
+ Managing Production
+ </a>
+ </strong>{" "}
+ – Learn how to manage the complete production lifecycle from job
+ creation to completion.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a href={`${universityUrl}/course/buying/purchasing-basics`}>
+ Purchasing Basics
+ </a>
+ </strong>{" "}
+ – Learn how to manage the complete purchasing lifecycle from
+ purchase order to receipt.
+ </Text>
+ </li>
+ <li className="mb-2">
+ <Text>
+ <strong>
+ <a href={`${universityUrl}/course/developing/using-api`}>
+ Using the API
+ </a>
+ </strong>{" "}
+ – Learn how to use the Carbon API to build custom applications.
+ </Text>
+ </li>
+ </ul>
+ <br />
+ <Text
+ className={`text-[14px] ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Let us know if you have any thoughts or feedback—we'd love to hear
+ from you.
+ </Text>
+ <br />
+ <Text
+ className={`text-[14px] ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Best,
+ <br />
+ The Carbon Team
+ </Text>
+
+ <br />
+ </Container>
+ </Body>
+ </EmailThemeProvider>
+ );
+};
+
+export default GetStartedEmail;
diff --git a/packages/documents/src/email/InviteEmail.tsx b/packages/documents/src/email/InviteEmail.tsx
index bd2d2acf0d..4ceb485f43 100644
--- a/packages/documents/src/email/InviteEmail.tsx
+++ b/packages/documents/src/email/InviteEmail.tsx
@@ -1,17 +1,19 @@
import {
Body,
- Button,
Container,
- Font,
Heading,
- Html,
Link,
Preview,
Section,
- Tailwind,
Text,
} from "@react-email/components";
import { Logo } from "./components/Logo";
+import {
+ Button,
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
interface Props {
email?: string;
@@ -26,94 +28,107 @@ interface Props {
export const InviteEmail = ({
invitedByEmail = "[email protected]",
invitedByName = "Tom Sawyer",
- email = "[email protected]",
+ email = "[email protected]",
companyName = "Tombstone",
inviteLink = "https://carbonos.dev/invite/1234567890",
ip = "38.38.38.38",
location = "Tombstone, AZ",
}: Props) => {
+ const preview = <Preview>{`Join ${companyName} on Carbon`}</Preview>;
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
+
return (
- <Html>
- <Tailwind>
- <head>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
- format: "woff2",
- }}
- fontWeight={400}
- fontStyle="normal"
- />
+ <EmailThemeProvider preview={preview}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`my-[40px] mx-auto p-[20px] max-w-[600px] ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: 1,
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Logo />
+ <Heading
+ className={`mx-0 my-[30px] p-0 text-[24px] font-normal ${themeClasses.text} text-center`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Join <strong>{companyName}</strong> on <strong>Carbon</strong>
+ </Heading>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
- format: "woff2",
- }}
- fontWeight={500}
- fontStyle="normal"
- />
- </head>
- <Preview>{`Join ${companyName} on Carbon`}</Preview>
+ <Text
+ className={`text-[14px] leading-[24px] ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {invitedByName} (
+ <Link
+ href={`mailto:${invitedByEmail}`}
+ className={`${themeClasses.text} no-underline`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {invitedByEmail}
+ </Link>
+ ) has invited you to join <strong>{companyName}</strong> on{" "}
+ <strong>Carbon</strong>.
+ </Text>
+ <Section className="mb-[42px] mt-[32px] text-center">
+ <Button href={inviteLink}>Accept Invite</Button>
+ </Section>
- <Body className="bg-[#fff] my-auto mx-auto font-sans">
- <Container
- className="border-transparent md:border-[#E8E7E1] my-[40px] mx-auto p-[20px] max-w-[600px]"
- style={{ borderStyle: "solid", borderWidth: 1 }}
+ <Text
+ className={`text-[14px] leading-[24px] ${themeClasses.mutedText} break-all`}
+ style={{ color: lightStyles.mutedText.color }}
>
- <Logo />
- <Heading className="mx-0 my-[30px] p-0 text-[24px] font-normal text-[#121212] text-center">
- Join <strong>{companyName}</strong> on <strong>Carbon</strong>
- </Heading>
+ You can accept this invite by clicking the button above or by
+ copying and pasting the following link into your browser:{" "}
+ <Link
+ href={inviteLink}
+ className={`${themeClasses.mutedText} underline`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ {inviteLink}
+ </Link>
+ </Text>
- <Text className="text-[14px] leading-[24px] text-[#121212]">
- {invitedByName} (
- <Link
- href={`mailto:${invitedByEmail}`}
- className="text-[#121212] no-underline"
+ <br />
+ <Section>
+ <Text
+ className={`text-[12px] leading-[24px] ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ This invitation was intended for{" "}
+ <span
+ className={themeClasses.text}
+ style={{ color: lightStyles.text.color }}
>
- {invitedByEmail}
- </Link>
- ) has invited you to join <strong>{companyName}</strong> on{" "}
- <strong>Carbon</strong>.
- </Text>
- <Section className="mb-[42px] mt-[32px] text-center">
- <Button
- className="bg-black text-foreground text-[14px] text-white font-medium no-underline text-center px-6 py-3 border border-solid border-[#121212] rounded-lg"
- href={inviteLink}
+ {email}
+ </span>
+ . This invite was sent from{" "}
+ <span
+ className={themeClasses.text}
+ style={{ color: lightStyles.text.color }}
>
- Accept Invite
- </Button>
- </Section>
-
- <Text className="text-[14px] leading-[24px] text-[#707070] break-all">
- You can accept this invite by clicking the button above or by
- copying and pasting the following link into your browser:{" "}
- <Link href={inviteLink} className="text-[#707070] underline">
- {inviteLink}
- </Link>
+ {ip}
+ </span>{" "}
+ located in{" "}
+ <span
+ className={themeClasses.text}
+ style={{ color: lightStyles.text.color }}
+ >
+ {location}
+ </span>
+ . If you were not expecting this invitation, you can ignore this
+ email. If you are concerned about your account's safety, please
+ reply to this email to get in touch with us.
</Text>
-
- <br />
- <Section>
- <Text className="text-[12px] leading-[24px] text-[#666666]">
- This invitation was intended for{" "}
- <span className="text-[#121212] ">{email}</span>. This invite
- was sent from <span className="text-[#121212] ">{ip}</span>{" "}
- located in <span className="text-[#121212] ">{location}</span>.{" "}
- If you were not expecting this invitation, you can ignore this
- email. If you are concerned about your account's safety, please
- reply to this email to get in touch with us.
- </Text>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
);
};
diff --git a/packages/documents/src/email/PurchaseOrderEmail.tsx b/packages/documents/src/email/PurchaseOrderEmail.tsx
index fabaa00588..3f75e24029 100644
--- a/packages/documents/src/email/PurchaseOrderEmail.tsx
+++ b/packages/documents/src/email/PurchaseOrderEmail.tsx
@@ -4,15 +4,11 @@ import {
Body,
Column,
Container,
- Font,
Hr,
- Html,
Img,
- Link,
Preview,
Row,
Section,
- Tailwind,
Text,
} from "@react-email/components";
import type { Email } from "../types";
@@ -21,6 +17,12 @@ import {
getLineDescriptionDetails,
getTotal,
} from "../utils/purchase-order";
+import { getCurrencyFormatter } from "../utils/shared";
+import {
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
interface PurchaseOrderEmailProps extends Email {
purchaseOrder: Database["public"]["Views"]["purchaseOrders"]["Row"];
@@ -31,6 +33,7 @@ interface PurchaseOrderEmailProps extends Email {
const PurchaseOrderEmail = ({
company,
+ locale,
purchaseOrder,
purchaseOrderLines,
purchaseOrderLocations,
@@ -56,248 +59,247 @@ const PurchaseOrderEmail = ({
customerCountryName,
} = purchaseOrderLocations;
- const reSubject = `Re: ${purchaseOrder.purchaseOrderId} from ${company.name}`;
-
- return (
- <Html>
- <Preview>{`${purchaseOrder.purchaseOrderId} from ${company.name}`}</Preview>
- <Tailwind>
- <head>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
- format: "woff2",
- }}
- fontWeight={400}
- fontStyle="normal"
- />
+ const formatter = getCurrencyFormatter(company.baseCurrencyCode, locale);
+ const preview = (
+ <Preview>{`${purchaseOrder.purchaseOrderId} from ${company.name}`}</Preview>
+ );
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
- format: "woff2",
- }}
- fontWeight={500}
- fontStyle="normal"
- />
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-800-normal.woff2",
- format: "woff2",
- }}
- fontWeight={800}
- fontStyle="normal"
- />
- </head>
+ const paymentTerm = paymentTerms?.find(
+ (term) => term.id === purchaseOrder.paymentTermId
+ );
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-5 px-0 w-[660px] max-w-full">
- <Section>
- <Row>
- <Column>
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="auto"
- height="42"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
- )}
- </Column>
- <Column className="text-right">
- <Text className="text-3xl font-light text-gray-500">
- Purchase Order
+ return (
+ <EmailThemeProvider preview={preview}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`mx-auto py-5 px-0 w-[660px] max-w-full ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: "1px",
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Section>
+ <Row>
+ <Column>
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
</Text>
- </Column>
- </Row>
- </Section>
- <Section>
- <Text className="text-left text-sm font-medium text-gray-900 my-9">
- {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
- please see the attached purchase order and let me know if you
- have any questions.
- </Text>
- </Section>
- <Section className="bg-gray-50 rounded-lg text-xs">
- <Row>
- <Column className="p-5" colSpan={2}>
- <Section>
+ )}
+ </Column>
+ <Column className="text-right">
+ <Text
+ className={`text-3xl font-light ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Purchase Order
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ <Text
+ className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
+ please see the attached purchase order and let me know if you have
+ any questions.
+ </Text>
+ </Section>
+ <Section className="bg-gray-50 rounded-lg text-xs">
+ <Row>
+ <Column className="p-5" colSpan={2}>
+ <Section>
+ {paymentTerm && (
<Row>
<Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Buyer
- </Text>
- <Link
- href={`mailto:${sender.email}?subject=${reSubject}`}
- className="text-blue-600 underline"
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
>
- {`${sender.firstName} ${sender.lastName}`}
- </Link>
- </Column>
- </Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
Payment Terms
</Text>
- <Text>
- {
- paymentTerms?.find(
- (term) => term.id === purchaseOrder.paymentTermId
- )?.name
- }
- </Text>
+ <Text>{paymentTerm.name}</Text>
</Column>
</Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Order ID
- </Text>
- <Text>{purchaseOrder.purchaseOrderId}</Text>
- </Column>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Requested Date
- </Text>
- <Text>{purchaseOrder.receiptRequestedDate ?? "-"}</Text>
- </Column>
- </Row>
- </Section>
- </Column>
- <Column className="p-5" colSpan={2}>
- <Text className="text-gray-600 uppercase text-[10px]">
- Ship To
- </Text>
- {dropShipment ? (
- <>
- <Text>{customerName}</Text>
- {customerAddressLine1 && (
- <Text>{customerAddressLine1}</Text>
- )}
- {customerAddressLine2 && (
- <Text>{customerAddressLine2}</Text>
- )}
- <Text>
- {formatCityStatePostalCode(
- customerCity,
- customerStateProvince,
- customerPostalCode
- )}
+ )}
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Order ID
</Text>
- <Text>{customerCountryName}</Text>
- </>
- ) : (
- <>
- <Text>{company.name}</Text>
- <Text>{deliveryName}</Text>
- {deliveryAddressLine1 && (
- <Text>{deliveryAddressLine1}</Text>
- )}
- {deliveryAddressLine2 && (
- <Text>{deliveryAddressLine2}</Text>
- )}
- <Text>
- {formatCityStatePostalCode(
- deliveryCity,
- deliveryStateProvince,
- deliveryPostalCode
- )}
+ <Text>{purchaseOrder.purchaseOrderId}</Text>
+ </Column>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Requested Date
</Text>
- <Text>{deliveryCountryName}</Text>
- </>
- )}
- </Column>
- </Row>
- </Section>
- <Section className="mt-8 mb-4">
- <Text className="text-gray-600 uppercase text-[10px] pl-5">
- Purchase Order Lines
- </Text>
- </Section>
- <Section>
- {purchaseOrderLines.map((line) => (
- <Row key={line.id} className="mb-2.5 pl-5">
- <Column>
- <Text className="text-xs font-semibold">
- {getLineDescription(line)}
- </Text>
- {getLineDescriptionDetails(line)
- ?.split("\n")
- .map((l, i) => (
- <Text key={i} className="text-xs text-gray-600">
- {l}
- </Text>
- ))}
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.purchaseOrderLineType === "Comment"
- ? ""
- : `(${line.purchaseQuantity} ${line.purchaseUnitOfMeasureCode})`}
+ <Text>{purchaseOrder.receiptRequestedDate ?? "-"}</Text>
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ <Column className="p-5" colSpan={2}>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Ship To
+ </Text>
+ {dropShipment ? (
+ <>
+ <Text>{customerName}</Text>
+ {customerAddressLine1 && (
+ <Text>{customerAddressLine1}</Text>
+ )}
+ {customerAddressLine2 && (
+ <Text>{customerAddressLine2}</Text>
+ )}
+ <Text>
+ {formatCityStatePostalCode(
+ customerCity,
+ customerStateProvince,
+ customerPostalCode
+ )}
</Text>
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.purchaseOrderLineType === "Comment"
- ? "-"
- : line.unitPrice
- ? `$${line.unitPrice.toFixed(2)}`
- : "-"}
+ <Text>{customerCountryName}</Text>
+ </>
+ ) : (
+ <>
+ <Text>{company.name}</Text>
+ <Text>{deliveryName}</Text>
+ {deliveryAddressLine1 && (
+ <Text>{deliveryAddressLine1}</Text>
+ )}
+ {deliveryAddressLine2 && (
+ <Text>{deliveryAddressLine2}</Text>
+ )}
+ <Text>
+ {formatCityStatePostalCode(
+ deliveryCity,
+ deliveryStateProvince,
+ deliveryPostalCode
+ )}
</Text>
- </Column>
- </Row>
- ))}
- </Section>
- <Hr className="my-8" />
- <Section className="text-right">
- <Row>
- <Column className="pr-8">
- <Text className="text-[10px] font-semibold text-gray-600">
- TOTAL
+ <Text>{deliveryCountryName}</Text>
+ </>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ <Section className="mt-8 mb-4">
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px] pl-5`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Purchase Order Lines
+ </Text>
+ </Section>
+ <Section>
+ {purchaseOrderLines.map((line) => (
+ <Row key={line.id} className="mb-2.5 pl-5">
+ <Column>
+ <Text className="text-xs font-semibold">
+ {getLineDescription(line)}
</Text>
+ {getLineDescriptionDetails(line)
+ ?.split("\n")
+ .map((l, i) => (
+ <Text
+ key={i}
+ className={`text-xs ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ {l}
+ </Text>
+ ))}
</Column>
- <Column className="border-l border-gray-200 h-12"></Column>
- <Column className="w-[90px] pr-5">
- <Text className="text-base font-semibold whitespace-nowrap">
- {`$${getTotal(purchaseOrderLines)}`}
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.purchaseOrderLineType === "Comment"
+ ? ""
+ : `(${line.purchaseQuantity} ${line.purchaseUnitOfMeasureCode})`}
</Text>
</Column>
- </Row>
- </Section>
- <Hr className="mb-20" />
- <Section>
- <Row>
- <Column className="text-center">
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="60"
- height="auto"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
- )}
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.purchaseOrderLineType === "Comment"
+ ? "-"
+ : line.unitPrice
+ ? formatter.format(line.unitPrice)
+ : "-"}
+ </Text>
</Column>
</Row>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ ))}
+ </Section>
+ <Hr className="my-8" />
+ <Section className="text-right">
+ <Row>
+ <Column className="pr-8">
+ <Text
+ className={`text-[10px] font-semibold ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ TOTAL
+ </Text>
+ </Column>
+ <Column className="border-l border-gray-200 h-12"></Column>
+ <Column className="w-[90px] pr-5">
+ <Text className="text-base font-semibold whitespace-nowrap">
+ {formatter.format(getTotal(purchaseOrderLines))}
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Hr className="mb-20" />
+ <Section>
+ <Row>
+ <Column className="text-center">
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
);
};
diff --git a/packages/documents/src/email/QuoteEmail.tsx b/packages/documents/src/email/QuoteEmail.tsx
index 5c2b482ba5..832274614c 100644
--- a/packages/documents/src/email/QuoteEmail.tsx
+++ b/packages/documents/src/email/QuoteEmail.tsx
@@ -3,17 +3,19 @@ import {
Body,
Column,
Container,
- Font,
- Html,
Img,
- Link,
Preview,
Row,
Section,
- Tailwind,
Text,
} from "@react-email/components";
import type { CompanySettings, Email } from "../types";
+import {
+ Button,
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
interface QuoteEmailProps extends Email {
quote: Database["public"]["Tables"]["quote"]["Row"];
@@ -27,168 +29,149 @@ const QuoteEmail = ({
recipient,
sender,
}: QuoteEmailProps) => {
- const reSubject = `Re: ${quote.quoteId} from ${company.name}`;
const digitalQuoteUrl =
companySettings.digitalQuoteEnabled && !!quote.externalLinkId
? `https://app.carbonos.dev/share/quote/${quote.externalLinkId}` // the VERCEL_URL variable was giving us a preview branch
: undefined;
- return (
- <Html lang="en">
- <Preview>{`${quote.quoteId} from ${company.name}`}</Preview>
-
- <Tailwind>
- <head>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
- format: "woff2",
- }}
- fontWeight={400}
- fontStyle="normal"
- />
+ const preview = <Preview>{`${quote.quoteId} from ${company.name}`}</Preview>;
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
- format: "woff2",
- }}
- fontWeight={500}
- fontStyle="normal"
- />
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-800-normal.woff2",
- format: "woff2",
- }}
- fontWeight={800}
- fontStyle="normal"
- />
- </head>
- <Body className="bg-white font-sans">
- <Container className="mx-auto my-[20px] w-[660px] max-w-full">
- <Section>
- <Row>
- <Column>
- {company.logoLight ? (
- <Img
- src={company.logoLight}
- width="auto"
- height="42"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-[32px] font-bold text-gray-900">
- {company.name}
- </Text>
- )}
- </Column>
-
- <Column className="text-right">
- <Text className="text-[32px] font-light text-gray-500">
- Quote
- </Text>
- </Column>
- </Row>
- </Section>
- <Section>
- {digitalQuoteUrl ? (
- <>
- <Text className="mt-9 mb-4 text-left text-sm font-medium text-gray-900">
- {recipient.firstName
- ? `Hi ${recipient.firstName}, `
- : "Hi, "}
- we are pleased to provide you with your digital quote, which
- is available for review here:
+ return (
+ <EmailThemeProvider preview={preview}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`mx-auto py-5 px-0 w-[660px] max-w-full ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: "1px",
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Section>
+ <Row>
+ <Column>
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
</Text>
- <Link href={digitalQuoteUrl}>
- <Text className="inline-flex items-center justify-center rounded-md bg-black px-4 py-2 text-sm font-medium text-white shadow hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-black focus:ring-offset-2">
- View Digital Quote
- </Text>
- </Link>
- </>
- ) : (
- <Text className="mt-9 mb-10 text-left text-sm font-medium text-gray-900">
+ )}
+ </Column>
+ <Column className="text-right">
+ <Text
+ className={`text-3xl font-light ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Quote
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ {digitalQuoteUrl ? (
+ <>
+ <Text
+ className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
+ style={{ color: lightStyles.text.color }}
+ >
{recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
- please see the attached quote and let me know if you have any
- questions.
+ we are pleased to provide you with your digital quote, which
+ is available for review here:
</Text>
- )}
- </Section>
- <Section className="rounded-lg bg-gray-50 text-xs">
- <Row>
- <Column className="p-5" colSpan={2}>
- <Section>
- <Row>
- <Column>
- <Text className="text-[10px] uppercase text-gray-600">
- Quoter
- </Text>
- <Link
- className="text-blue-600 underline"
- href={`mailto:${sender.email}?subject=${reSubject}`}
- >
- {`${sender.firstName} ${sender.lastName}`}
- </Link>
- </Column>
- </Row>
+ <Button href={digitalQuoteUrl} className="mb-4">
+ View Digital Quote
+ </Button>
+ </>
+ ) : (
+ <Text
+ className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
+ please see the attached quote and let me know if you have any
+ questions.
+ </Text>
+ )}
+ </Section>
+ <Section className="bg-gray-50 rounded-lg text-xs">
+ <Row>
+ <Column className="p-5" colSpan={2}>
+ <Section>
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Reference Number
+ </Text>
+ <Text>{quote.customerReference ?? "-"}</Text>
+ </Column>
+ </Row>
- <Row>
- <Column>
- <Text className="text-[10px] uppercase text-gray-600">
- Reference Number
- </Text>
- <Text>{quote.customerReference ?? "-"}</Text>
- </Column>
- </Row>
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Quote ID
+ </Text>
+ <Text>{quote.quoteId}</Text>
+ </Column>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Expiration Date
+ </Text>
+ <Text>{quote.expirationDate ?? "-"}</Text>
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ </Row>
+ </Section>
- <Row>
- <Column>
- <Text className="text-[10px] uppercase text-gray-600">
- Quote ID
- </Text>
- <Text>{quote.quoteId}</Text>
- </Column>
- <Column>
- <Text className="text-[10px] uppercase text-gray-600">
- Expiration Date
- </Text>
- <Text>{quote.expirationDate ?? "-"}</Text>
- </Column>
- </Row>
- </Section>
- </Column>
- </Row>
- </Section>
-
- <Section>
- <Row>
- <Column className="text-center">
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="60"
- height="auto"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-[32px] font-bold text-gray-900">
- {company.name}
- </Text>
- )}
- </Column>
- </Row>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ <Section>
+ <Row>
+ <Column className="text-center">
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
);
};
diff --git a/packages/documents/src/email/SalesInvoiceEmail.tsx b/packages/documents/src/email/SalesInvoiceEmail.tsx
index 4ef5110504..2800304fca 100644
--- a/packages/documents/src/email/SalesInvoiceEmail.tsx
+++ b/packages/documents/src/email/SalesInvoiceEmail.tsx
@@ -4,15 +4,11 @@ import {
Body,
Column,
Container,
- Font,
Hr,
- Html,
Img,
- Link,
Preview,
Row,
Section,
- Tailwind,
Text,
} from "@react-email/components";
import type { Email } from "../types";
@@ -23,6 +19,11 @@ import {
getTotal,
} from "../utils/sales-invoice";
import { getCurrencyFormatter } from "../utils/shared";
+import {
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
interface SalesInvoiceEmailProps extends Email {
salesInvoice: Database["public"]["Views"]["salesInvoices"]["Row"];
@@ -53,234 +54,259 @@ const SalesInvoiceEmail = ({
invoiceCountryName,
} = salesInvoiceLocations;
- const reSubject = `Re: ${salesInvoice.invoiceId} from ${company.name}`;
-
const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
const formatter = getCurrencyFormatter(currencyCode, locale);
+ const preview = (
+ <Preview>{`${salesInvoice.invoiceId} from ${company.name}`}</Preview>
+ );
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
return (
- <Html>
- <Preview>{`${salesInvoice.invoiceId} from ${company.name}`}</Preview>
- <Tailwind>
- <head>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
- format: "woff2",
- }}
- fontWeight={400}
- fontStyle="normal"
- />
+ <EmailThemeProvider preview={preview}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`mx-auto py-5 px-0 w-[660px] max-w-full ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: "1px",
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Section>
+ <Row>
+ <Column>
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ <Column className="text-right">
+ <Text
+ className={`text-3xl font-light ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Sales Invoice
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ <Text
+ className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
+ please see the attached invoice and let me know if you have any
+ questions.
+ </Text>
+ </Section>
+ <Section className={`bg-gray-50 rounded-lg text-xs`}>
+ <Row>
+ <Column className="p-5" colSpan={2}>
+ <Section>
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Payment Terms
+ </Text>
+ <Text>
+ {
+ paymentTerms?.find(
+ (term) => term.id === salesInvoice.paymentTermId
+ )?.name
+ }
+ </Text>
+ </Column>
+ </Row>
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Invoice ID
+ </Text>
+ <Text>{salesInvoice.invoiceId}</Text>
+ </Column>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Due Date
+ </Text>
+ <Text>{salesInvoice.dateDue ?? "-"}</Text>
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ <Column className="p-5" colSpan={2}>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Ship To
+ </Text>
+ <Text>{invoiceCustomerName}</Text>
+ {invoiceAddressLine1 && <Text>{invoiceAddressLine1}</Text>}
+ {invoiceAddressLine2 && <Text>{invoiceAddressLine2}</Text>}
+ <Text>
+ {formatCityStatePostalCode(
+ invoiceCity,
+ invoiceStateProvince,
+ invoicePostalCode
+ )}
+ </Text>
+ <Text>{invoiceCountryName}</Text>
+ </Column>
+ </Row>
+ </Section>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
- format: "woff2",
- }}
- fontWeight={500}
- fontStyle="normal"
- />
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-800-normal.woff2",
- format: "woff2",
- }}
- fontWeight={800}
- fontStyle="normal"
- />
- </head>
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-5 px-0 w-[660px] max-w-full">
- <Section>
- <Row>
+ <Section>
+ <Row className="mb-2.5 pl-5">
+ <Column>
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Description
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Quantity
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Unit Price
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Subtotal
+ </Text>
+ </Column>
+ </Row>
+ {salesInvoiceLines.map((line) => (
+ <Row key={line.id} className="mb-2.5 pl-5">
<Column>
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="auto"
- height="42"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
- )}
- </Column>
- <Column className="text-right">
- <Text className="text-3xl font-light text-gray-500">
- Sales Invoice
+ <Text className="text-xs font-semibold">
+ {getLineDescription(line)}
</Text>
+ {getLineDescriptionDetails(line)
+ ?.split("\n")
+ .map((l, i) => (
+ <Text
+ key={i}
+ className={`text-xs ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ {l}
+ </Text>
+ ))}
</Column>
- </Row>
- </Section>
- <Section>
- <Text className="text-left text-sm font-medium text-gray-900 my-9">
- {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
- please see the attached invoice and let me know if you have any
- questions.
- </Text>
- </Section>
- <Section className="bg-gray-50 rounded-lg text-xs">
- <Row>
- <Column className="p-5" colSpan={2}>
- <Section>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Seller
- </Text>
- <Link
- href={`mailto:${sender.email}?subject=${reSubject}`}
- className="text-blue-600 underline"
- >
- {`${sender.firstName} ${sender.lastName}`}
- </Link>
- </Column>
- </Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Payment Terms
- </Text>
- <Text>
- {
- paymentTerms?.find(
- (term) => term.id === salesInvoice.paymentTermId
- )?.name
- }
- </Text>
- </Column>
- </Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Invoice ID
- </Text>
- <Text>{salesInvoice.invoiceId}</Text>
- </Column>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Due Date
- </Text>
- <Text>{salesInvoice.dateDue ?? "-"}</Text>
- </Column>
- </Row>
- </Section>
- </Column>
- <Column className="p-5" colSpan={2}>
- <Text className="text-gray-600 uppercase text-[10px]">
- Ship To
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? ""
+ : `${line.quantity}`}
</Text>
- <Text>{invoiceCustomerName}</Text>
- {invoiceAddressLine1 && <Text>{invoiceAddressLine1}</Text>}
- {invoiceAddressLine2 && <Text>{invoiceAddressLine2}</Text>}
- <Text>
- {formatCityStatePostalCode(
- invoiceCity,
- invoiceStateProvince,
- invoicePostalCode
- )}
- </Text>
- <Text>{invoiceCountryName}</Text>
</Column>
- </Row>
- </Section>
- <Section className="mt-8 mb-4">
- <Text className="text-gray-600 uppercase text-[10px] pl-5">
- Sales Invoice Lines
- </Text>
- </Section>
- <Section>
- {salesInvoiceLines.map((line) => (
- <Row key={line.id} className="mb-2.5 pl-5">
- <Column>
- <Text className="text-xs font-semibold">
- {getLineDescription(line)}
- </Text>
- {getLineDescriptionDetails(line)
- ?.split("\n")
- .map((l, i) => (
- <Text key={i} className="text-xs text-gray-600">
- {l}
- </Text>
- ))}
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.invoiceLineType === "Comment"
- ? ""
- : `(${line.quantity} ${line.unitOfMeasureCode})`}
- </Text>
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.invoiceLineType === "Comment"
- ? "-"
- : formatter.format(line.convertedUnitPrice ?? 0)}
- </Text>
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.invoiceLineType === "Comment"
- ? "-"
- : formatter.format(getLineTotal(line))}
- </Text>
- </Column>
- </Row>
- ))}
- </Section>
- <Hr className="my-8" />
- <Section className="text-right">
- <Row>
- <Column className="pr-8">
- <Text className="text-[10px] font-semibold text-gray-600">
- TOTAL
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? "-"
+ : formatter.format(line.convertedUnitPrice ?? 0)}
</Text>
</Column>
- <Column className="border-l border-gray-200 h-12"></Column>
- <Column className="w-[90px] pr-5">
- <Text className="text-base font-semibold whitespace-nowrap">
- {formatter.format(
- getTotal(
- salesInvoiceLines,
- salesInvoice,
- salesInvoiceShipment
- )
- )}
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.invoiceLineType === "Comment"
+ ? "-"
+ : formatter.format(getLineTotal(line))}
</Text>
</Column>
</Row>
- </Section>
- <Hr className="mb-20" />
- <Section>
- <Row>
- <Column className="text-center">
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="60"
- height="auto"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
+ ))}
+ </Section>
+ <Hr className="my-8" />
+ <Section className="text-right">
+ <Row>
+ <Column className="pr-8">
+ <Text
+ className={`text-[10px] font-semibold ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ TOTAL
+ </Text>
+ </Column>
+ <Column className={`border-l border-gray-200 h-12`}></Column>
+ <Column className="w-[90px] pr-5">
+ <Text className="text-base font-semibold whitespace-nowrap">
+ {formatter.format(
+ getTotal(
+ salesInvoiceLines,
+ salesInvoice,
+ salesInvoiceShipment
+ )
)}
- </Column>
- </Row>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Hr className="mb-20" />
+ <Section>
+ <Row>
+ <Column className="text-center">
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
);
};
diff --git a/packages/documents/src/email/SalesOrderEmail.tsx b/packages/documents/src/email/SalesOrderEmail.tsx
index 50299a9515..d132c4c028 100644
--- a/packages/documents/src/email/SalesOrderEmail.tsx
+++ b/packages/documents/src/email/SalesOrderEmail.tsx
@@ -4,15 +4,11 @@ import {
Body,
Column,
Container,
- Font,
Hr,
- Html,
Img,
- Link,
Preview,
Row,
Section,
- Tailwind,
Text,
} from "@react-email/components";
import type { Email } from "../types";
@@ -23,6 +19,11 @@ import {
getTotal,
} from "../utils/sales-order";
import { getCurrencyFormatter } from "../utils/shared";
+import {
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
interface SalesOrderEmailProps extends Email {
salesOrder: Database["public"]["Views"]["salesOrders"]["Row"];
@@ -58,227 +59,251 @@ const SalesOrderEmail = ({
// paymentCountryName,
} = salesOrderLocations;
- const reSubject = `Re: ${salesOrder.salesOrderId} from ${company.name}`;
-
const formatter = getCurrencyFormatter(company.baseCurrencyCode, locale);
+ const preview = (
+ <Preview>{`${salesOrder.salesOrderId} from ${company.name}`}</Preview>
+ );
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
+ const paymentTerm = paymentTerms?.find(
+ (term) => term.id === salesOrder.paymentTermId
+ );
return (
- <Html>
- <Preview>{`${salesOrder.salesOrderId} from ${company.name}`}</Preview>
- <Tailwind>
- <head>
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
- format: "woff2",
- }}
- fontWeight={400}
- fontStyle="normal"
- />
-
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
- format: "woff2",
- }}
- fontWeight={500}
- fontStyle="normal"
- />
- <Font
- fontFamily="Geist"
- fallbackFontFamily="Helvetica"
- webFont={{
- url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-800-normal.woff2",
- format: "woff2",
- }}
- fontWeight={800}
- fontStyle="normal"
- />
- </head>
- <Body className="bg-white font-sans">
- <Container className="mx-auto py-5 px-0 w-[660px] max-w-full">
- <Section>
- <Row>
- <Column>
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="auto"
- height="42"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
- )}
- </Column>
- <Column className="text-right">
- <Text className="text-3xl font-light text-gray-500">
- Sales Order
+ <EmailThemeProvider preview={preview}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`mx-auto py-5 px-0 w-[660px] max-w-full ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: "1px",
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Section>
+ <Row>
+ <Column>
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="auto"
+ height="42"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
</Text>
- </Column>
- </Row>
- </Section>
- <Section>
- <Text className="text-left text-sm font-medium text-gray-900 my-9">
- {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
- please see the attached sales order and let me know if you have
- any questions.
- </Text>
- </Section>
- <Section className="bg-gray-50 rounded-lg text-xs">
- <Row>
- <Column className="p-5" colSpan={2}>
- <Section>
+ )}
+ </Column>
+ <Column className="text-right">
+ <Text
+ className={`text-3xl font-light ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Sales Order
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Section>
+ <Text
+ className={`text-left text-sm font-medium ${themeClasses.text} my-9`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {recipient.firstName ? `Hi ${recipient.firstName}, ` : "Hi, "}
+ please see the attached sales order and let me know if you have
+ any questions.
+ </Text>
+ </Section>
+ <Section className={`bg-gray-50 rounded-lg text-xs`}>
+ <Row>
+ <Column className="p-5" colSpan={2}>
+ <Section>
+ {paymentTerm && (
<Row>
<Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Seller
- </Text>
- <Link
- href={`mailto:${sender.email}?subject=${reSubject}`}
- className="text-blue-600 underline"
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
>
- {`${sender.firstName} ${sender.lastName}`}
- </Link>
- </Column>
- </Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
Payment Terms
</Text>
- <Text>
- {
- paymentTerms?.find(
- (term) => term.id === salesOrder.paymentTermId
- )?.name
- }
- </Text>
- </Column>
- </Row>
- <Row>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Order ID
- </Text>
- <Text>{salesOrder.salesOrderId}</Text>
- </Column>
- <Column>
- <Text className="text-gray-600 uppercase text-[10px]">
- Requested Date
- </Text>
- <Text>{salesOrder.receiptRequestedDate ?? "-"}</Text>
+ <Text>{paymentTerm?.name}</Text>
</Column>
</Row>
- </Section>
- </Column>
- <Column className="p-5" colSpan={2}>
- <Text className="text-gray-600 uppercase text-[10px]">
- Ship To
- </Text>
- <Text>{customerName}</Text>
- {customerAddressLine1 && <Text>{customerAddressLine1}</Text>}
- {customerAddressLine2 && <Text>{customerAddressLine2}</Text>}
- <Text>
- {formatCityStatePostalCode(
- customerCity,
- customerStateProvince,
- customerPostalCode
- )}
+ )}
+ <Row>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Order ID
+ </Text>
+ <Text>{salesOrder.salesOrderId}</Text>
+ </Column>
+ <Column>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Requested Date
+ </Text>
+ <Text>{salesOrder.receiptRequestedDate ?? "-"}</Text>
+ </Column>
+ </Row>
+ </Section>
+ </Column>
+ <Column className="p-5" colSpan={2}>
+ <Text
+ className={`${themeClasses.mutedText} uppercase text-[10px]`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Ship To
+ </Text>
+ <Text>{customerName}</Text>
+ {customerAddressLine1 && <Text>{customerAddressLine1}</Text>}
+ {customerAddressLine2 && <Text>{customerAddressLine2}</Text>}
+ <Text>
+ {formatCityStatePostalCode(
+ customerCity,
+ customerStateProvince,
+ customerPostalCode
+ )}
+ </Text>
+ <Text>{customerCountryName}</Text>
+ </Column>
+ </Row>
+ </Section>
+
+ <Section>
+ <Row className="mb-2.5 pl-5">
+ <Column>
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Description
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Quantity
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Unit Price
+ </Text>
+ </Column>
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text
+ className={`text-xs uppercase ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ Subtotal
+ </Text>
+ </Column>
+ </Row>
+ {salesOrderLines.map((line) => (
+ <Row key={line.id} className="mb-2.5 pl-5">
+ <Column>
+ <Text className="text-xs font-semibold">
+ {getLineDescription(line)}
</Text>
- <Text>{customerCountryName}</Text>
+ {getLineDescriptionDetails(line)
+ ?.split("\n")
+ .map((l, i) => (
+ <Text
+ key={i}
+ className={`text-xs ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ {l}
+ </Text>
+ ))}
</Column>
- </Row>
- </Section>
- <Section className="mt-8 mb-4">
- <Text className="text-gray-600 uppercase text-[10px] pl-5">
- Sales Order Lines
- </Text>
- </Section>
- <Section>
- {salesOrderLines.map((line) => (
- <Row key={line.id} className="mb-2.5 pl-5">
- <Column>
- <Text className="text-xs font-semibold">
- {getLineDescription(line)}
- </Text>
- {getLineDescriptionDetails(line)
- ?.split("\n")
- .map((l, i) => (
- <Text key={i} className="text-xs text-gray-600">
- {l}
- </Text>
- ))}
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.salesOrderLineType === "Comment"
- ? ""
- : `(${line.saleQuantity} ${line.unitOfMeasureCode})`}
- </Text>
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.salesOrderLineType === "Comment"
- ? "-"
- : formatter.format(line.unitPrice ?? 0)}
- </Text>
- </Column>
- <Column className="text-right pr-5 align-top w-[100px]">
- <Text className="text-xs font-semibold">
- {line.salesOrderLineType === "Comment"
- ? "-"
- : formatter.format(getLineTotal(line))}
- </Text>
- </Column>
- </Row>
- ))}
- </Section>
- <Hr className="my-8" />
- <Section className="text-right">
- <Row>
- <Column className="pr-8">
- <Text className="text-[10px] font-semibold text-gray-600">
- TOTAL
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.salesOrderLineType === "Comment"
+ ? ""
+ : `${line.saleQuantity}`}
</Text>
</Column>
- <Column className="border-l border-gray-200 h-12"></Column>
- <Column className="w-[90px] pr-5">
- <Text className="text-base font-semibold whitespace-nowrap">
- {formatter.format(getTotal(salesOrderLines, salesOrder))}
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.salesOrderLineType === "Comment"
+ ? "-"
+ : formatter.format(line.unitPrice ?? 0)}
</Text>
</Column>
- </Row>
- </Section>
- <Hr className="mb-20" />
- <Section>
- <Row>
- <Column className="text-center">
- {company.logoLightIcon ? (
- <Img
- src={company.logoLightIcon}
- width="60"
- height="auto"
- alt={`${company.name} Logo`}
- />
- ) : (
- <Text className="text-3xl font-bold text-gray-900">
- {company.name}
- </Text>
- )}
+ <Column className="text-right pr-5 align-top w-[100px]">
+ <Text className="text-xs font-semibold">
+ {line.salesOrderLineType === "Comment"
+ ? "-"
+ : formatter.format(getLineTotal(line))}
+ </Text>
</Column>
</Row>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
+ ))}
+ </Section>
+ <Hr className="my-8" />
+ <Section className="text-right">
+ <Row>
+ <Column className="pr-8">
+ <Text
+ className={`text-[10px] font-semibold ${themeClasses.mutedText}`}
+ style={{ color: lightStyles.mutedText.color }}
+ >
+ TOTAL
+ </Text>
+ </Column>
+ <Column className={`border-l border-gray-200 h-12`}></Column>
+ <Column className="w-[90px] pr-5">
+ <Text className="text-base font-semibold whitespace-nowrap">
+ {formatter.format(getTotal(salesOrderLines, salesOrder))}
+ </Text>
+ </Column>
+ </Row>
+ </Section>
+ <Hr className="mb-20" />
+ <Section>
+ <Row>
+ <Column className="text-center">
+ {company.logoLightIcon ? (
+ <Img
+ src={company.logoLightIcon}
+ width="60"
+ height="auto"
+ alt={`${company.name} Logo`}
+ />
+ ) : (
+ <Text
+ className={`text-3xl font-bold ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ {company.name}
+ </Text>
+ )}
+ </Column>
+ </Row>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
);
};
diff --git a/packages/documents/src/email/WelcomeEmail.tsx b/packages/documents/src/email/WelcomeEmail.tsx
new file mode 100644
index 0000000000..7fc1bdd808
--- /dev/null
+++ b/packages/documents/src/email/WelcomeEmail.tsx
@@ -0,0 +1,92 @@
+import {
+ Body,
+ Container,
+ Heading,
+ Link,
+ Preview,
+ Section,
+ Text,
+} from "@react-email/components";
+import { Logo } from "./components/Logo";
+import {
+ Button,
+ EmailThemeProvider,
+ getEmailInlineStyles,
+ getEmailThemeClasses,
+} from "./components/Theme";
+
+interface Props {
+ firstName?: string;
+}
+
+export const WelcomeEmail = ({ firstName = "Huckleberry" }: Props) => {
+ const text = `Hi ${firstName}, Welcome to Carbon! I'm Brad, one of the founders. It's really important to us that you have a great experience as you get started.`;
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
+
+ return (
+ <EmailThemeProvider preview={<Preview>{text}</Preview>}>
+ <Body
+ className={`my-auto mx-auto font-sans ${themeClasses.body}`}
+ style={lightStyles.body}
+ >
+ <Container
+ className={`my-[40px] mx-auto p-[20px] max-w-[600px] ${themeClasses.container}`}
+ style={{
+ borderStyle: "solid",
+ borderWidth: 1,
+ borderColor: lightStyles.container.borderColor,
+ }}
+ >
+ <Logo />
+ <Heading
+ className={`text-[21px] font-normal text-center p-0 my-[30px] mx-0 ${themeClasses.heading}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Welcome to Carbon
+ </Heading>
+
+ <br />
+
+ <span
+ className={`font-medium ${themeClasses.text}`}
+ style={{ color: lightStyles.text.color }}
+ >
+ Hi {firstName},
+ </span>
+ <Text
+ className={themeClasses.text}
+ style={{ color: lightStyles.text.color }}
+ >
+ Welcome to Carbon! I'm Brad, one of the founders.
+ <br />
+ <br />
+ We built Carbon after years of building end-to-end systems for
+ different types of manufacturers, learning first-hand the challenges
+ and limitations of existing systems. Carbon is self-funded and built
+ together with our customers, so it's important to us that you know
+ we're here when you need us.
+ <br />
+ <br />
+ Feel free to email me at{" "}
+ <Link href="mailto:[email protected]">[email protected]</Link> if
+ you have any questions. I'm happy to to help you get started and
+ answer any questions about the things that makes your business
+ unique.
+ <br />
+ <br />
+ In the meantime, you can start by exploring{" "}
+ <Link href="https://learn.carbonos.dev">Carbon University</Link> to
+ get a feel for the platform.
+ </Text>
+
+ <Section className="text-center mt-[50px] mb-[50px]">
+ <Button href="https://learn.carbonos.dev">Get started</Button>
+ </Section>
+ </Container>
+ </Body>
+ </EmailThemeProvider>
+ );
+};
+
+export default WelcomeEmail;
diff --git a/packages/documents/src/email/components/Button.tsx b/packages/documents/src/email/components/Button.tsx
new file mode 100644
index 0000000000..fbcac26249
--- /dev/null
+++ b/packages/documents/src/email/components/Button.tsx
@@ -0,0 +1,49 @@
+import { Button as ReactEmailButton } from "@react-email/components";
+import React from "react";
+import { getEmailInlineStyles, getEmailThemeClasses } from "./Theme";
+
+interface ButtonProps {
+ href: string;
+ children: React.ReactNode;
+ variant?: "primary" | "secondary";
+ className?: string;
+}
+
+export function Button({
+ href,
+ children,
+ variant = "primary",
+ className = "",
+}: ButtonProps) {
+ const themeClasses = getEmailThemeClasses();
+ const lightStyles = getEmailInlineStyles("light");
+
+ const baseClasses =
+ "bg-transparent text-[14px] font-medium no-underline text-center px-6 py-3 border border-solid";
+ const variantClasses =
+ variant === "primary"
+ ? themeClasses.button
+ : "border-gray-300 text-gray-600";
+
+ // Inline styles for maximum email client compatibility
+ const buttonStyle =
+ variant === "primary"
+ ? {
+ color: lightStyles.button.color,
+ borderColor: lightStyles.button.borderColor,
+ }
+ : {
+ color: "#6b7280",
+ borderColor: "#d1d5db",
+ };
+
+ return (
+ <ReactEmailButton
+ className={`${baseClasses} ${variantClasses} ${className}`}
+ href={href}
+ style={buttonStyle}
+ >
+ {children}
+ </ReactEmailButton>
+ );
+}
diff --git a/packages/documents/src/email/components/Theme.tsx b/packages/documents/src/email/components/Theme.tsx
new file mode 100644
index 0000000000..f7f765f7f2
--- /dev/null
+++ b/packages/documents/src/email/components/Theme.tsx
@@ -0,0 +1,310 @@
+// credit: [email protected]
+import { Font, Head, Html, Tailwind } from "@react-email/components";
+import React from "react";
+
+// Re-export Button component for convenience
+export { Button } from "./Button";
+
+// Email-optimized theme colors (avoiding pure white/black for better email client compatibility)
+export const emailTheme = {
+ light: {
+ background: "#ffffff",
+ foreground: "#0e0e0e", // Slightly off-black to prevent auto-inversion
+ muted: "#6b7280",
+ border: "#e5e7eb",
+ accent: "#0e0e0e",
+ secondary: "#9ca3af",
+ },
+ dark: {
+ background: "#0C0C0C",
+ foreground: "#fefefe", // Slightly off-white to prevent auto-inversion
+ muted: "#a1a1aa",
+ border: "#1D1D1D",
+ accent: "#fefefe",
+ secondary: "#6b7280",
+ },
+} as const;
+
+// Industry-standard dark mode CSS for email clients
+export const getEmailDarkModeCSS = () => {
+ return `
+ /* Root CSS for email dark mode support */
+ :root {
+ color-scheme: light dark;
+ supported-color-schemes: light dark;
+ }
+
+ /* Apple Mail, iOS Mail, and some webview clients */
+ @media (prefers-color-scheme: dark) {
+ .email-body {
+ background-color: ${emailTheme.dark.background} !important;
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ .email-container {
+ border-color: ${emailTheme.dark.border} !important;
+ }
+ .email-text {
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ .email-muted {
+ color: ${emailTheme.dark.muted} !important;
+ }
+ .email-secondary {
+ color: ${emailTheme.dark.secondary} !important;
+ }
+ .email-accent {
+ color: ${emailTheme.dark.accent} !important;
+ border-color: ${emailTheme.dark.accent} !important;
+ }
+ .email-border {
+ border-color: ${emailTheme.dark.border} !important;
+ }
+
+ /* Image swapping for dark mode */
+ .dark-mode-hide {
+ display: none !important;
+ }
+ .dark-mode-show {
+ display: block !important;
+ }
+ }
+
+ /* Gmail Desktop Dark Mode - Multiple targeting approaches */
+ @media (prefers-color-scheme: dark) {
+ /* Gmail specific selectors */
+ .gmail_dark .email-body,
+ .gmail_dark_theme .email-body,
+ [data-darkmode="true"] .email-body {
+ background-color: ${emailTheme.dark.background} !important;
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ .gmail_dark .email-container,
+ .gmail_dark_theme .email-container,
+ [data-darkmode="true"] .email-container {
+ border-color: ${emailTheme.dark.border} !important;
+ }
+ .gmail_dark .email-text,
+ .gmail_dark_theme .email-text,
+ [data-darkmode="true"] .email-text {
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ .gmail_dark .email-muted,
+ .gmail_dark_theme .email-muted,
+ [data-darkmode="true"] .email-muted {
+ color: ${emailTheme.dark.muted} !important;
+ }
+ .gmail_dark .email-accent,
+ .gmail_dark_theme .email-accent,
+ [data-darkmode="true"] .email-accent {
+ color: ${emailTheme.dark.accent} !important;
+ border-color: ${emailTheme.dark.accent} !important;
+ }
+ }
+
+ /* Gmail Desktop conditional dark mode targeting */
+ @media screen and (prefers-color-scheme: dark) {
+ /* More aggressive Gmail desktop targeting */
+ div[style*="background"] .email-body,
+ .ii .email-body {
+ background-color: ${emailTheme.dark.background} !important;
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ div[style*="background"] .email-container,
+ .ii .email-container {
+ border-color: ${emailTheme.dark.border} !important;
+ }
+ div[style*="background"] .email-text,
+ .ii .email-text {
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ div[style*="background"] .email-muted,
+ .ii .email-muted {
+ color: ${emailTheme.dark.muted} !important;
+ }
+ div[style*="background"] .email-accent,
+ .ii .email-accent {
+ color: ${emailTheme.dark.accent} !important;
+ border-color: ${emailTheme.dark.accent} !important;
+ }
+ }
+
+ /* Outlook Web App and Outlook mobile targeting */
+ [data-ogsc] .email-text {
+ color: ${emailTheme.dark.foreground} !important;
+ }
+ [data-ogsc] .email-muted {
+ color: ${emailTheme.dark.muted} !important;
+ }
+ [data-ogsc] .email-accent {
+ color: ${emailTheme.dark.accent} !important;
+ border-color: ${emailTheme.dark.accent} !important;
+ }
+ [data-ogsc] .dark-mode-hide {
+ display: none !important;
+ }
+ [data-ogsc] .dark-mode-show {
+ display: block !important;
+ }
+
+ /* Outlook background targeting */
+ [data-ogsb] .email-body {
+ background-color: ${emailTheme.dark.background} !important;
+ }
+ [data-ogsb] .email-container {
+ border-color: ${emailTheme.dark.border} !important;
+ }
+ `;
+};
+
+// Comprehensive email theme provider that wraps everything
+interface EmailThemeProviderProps {
+ children: React.ReactNode;
+ preview?: React.ReactNode;
+ additionalHeadContent?: React.ReactNode;
+ disableDarkMode?: boolean;
+}
+
+export function EmailThemeProvider({
+ children,
+ preview,
+ additionalHeadContent,
+ disableDarkMode = false,
+}: EmailThemeProviderProps) {
+ return (
+ <Html className={disableDarkMode ? "disable-dark-mode" : ""}>
+ <Tailwind>
+ <Head>
+ {/* Essential meta tags for email dark mode support */}
+ {!disableDarkMode && (
+ <>
+ <meta name="color-scheme" content="light dark" />
+ <meta name="supported-color-schemes" content="light dark" />
+
+ {/* Additional Gmail dark mode hints */}
+ <meta
+ name="theme-color"
+ content="#0C0C0C"
+ media="(prefers-color-scheme: dark)"
+ />
+ <meta
+ name="theme-color"
+ content="#ffffff"
+ media="(prefers-color-scheme: light)"
+ />
+ <meta name="msapplication-navbutton-color" content="#0C0C0C" />
+
+ {/* Dark mode styles */}
+ <style>{getEmailDarkModeCSS()}</style>
+ </>
+ )}
+
+ {/* Force light mode when dark mode is disabled */}
+ {disableDarkMode && (
+ <>
+ <meta name="color-scheme" content="light only" />
+ <meta name="supported-color-schemes" content="light" />
+ <meta name="theme-color" content="#ffffff" />
+ <style>{`
+ /* Force light mode styles */
+ :root {
+ color-scheme: light only;
+ supported-color-schemes: light;
+ }
+
+ /* Override any potential dark mode styles */
+ * {
+ color-scheme: light !important;
+ }
+ `}</style>
+ </>
+ )}
+
+ {/* Default fonts for all emails */}
+ <Font
+ fontFamily="Geist"
+ fallbackFontFamily="Helvetica"
+ webFont={{
+ url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-400-normal.woff2",
+ format: "woff2",
+ }}
+ fontWeight={400}
+ fontStyle="normal"
+ />
+
+ <Font
+ fontFamily="Geist"
+ fallbackFontFamily="Helvetica"
+ webFont={{
+ url: "https://cdn.jsdelivr.net/npm/@fontsource/[email protected]/files/geist-sans-latin-500-normal.woff2",
+ format: "woff2",
+ }}
+ fontWeight={500}
+ fontStyle="normal"
+ />
+
+ {/* Additional head content */}
+ {additionalHeadContent}
+ </Head>
+ {preview}
+ {children}
+ </Tailwind>
+ </Html>
+ );
+}
+
+// Email-optimized theme classes (no Tailwind dependencies)
+export function getEmailThemeClasses() {
+ return {
+ // Base classes that work across email clients
+ body: "email-body",
+ container: "email-container",
+ heading: "email-text",
+ text: "email-text",
+ mutedText: "email-muted",
+ secondaryText: "email-secondary",
+ button: "email-accent",
+ border: "email-border",
+ link: "email-text",
+ mutedLink: "email-muted",
+
+ // Dark mode image control
+ hideInDark: "dark-mode-hide",
+ showInDark: "dark-mode-show",
+ };
+}
+
+// Utility to get inline styles (fallback for older email clients)
+export function getEmailInlineStyles(mode: "light" | "dark" = "light") {
+ const theme = emailTheme[mode];
+ return {
+ body: {
+ backgroundColor: theme.background,
+ color: theme.foreground,
+ },
+ container: {
+ borderColor: theme.border,
+ },
+ text: {
+ color: theme.foreground,
+ },
+ mutedText: {
+ color: theme.muted,
+ },
+ secondaryText: {
+ color: theme.secondary,
+ },
+ button: {
+ color: theme.accent,
+ borderColor: theme.accent,
+ },
+ };
+}
+
+// Simplified theme hook
+export function useEmailTheme() {
+ return {
+ classes: getEmailThemeClasses(),
+ lightStyles: getEmailInlineStyles("light"),
+ darkStyles: getEmailInlineStyles("dark"),
+ };
+}
diff --git a/packages/documents/src/email/index.ts b/packages/documents/src/email/index.ts
index e4700e8312..ce4d7e6752 100644
--- a/packages/documents/src/email/index.ts
+++ b/packages/documents/src/email/index.ts
@@ -1,13 +1,17 @@
+import GetStartedEmail from "./GetStartedEmail";
import InviteEmail from "./InviteEmail";
import PurchaseOrderEmail from "./PurchaseOrderEmail";
import QuoteEmail from "./QuoteEmail";
import SalesInvoiceEmail from "./SalesInvoiceEmail";
import SalesOrderEmail from "./SalesOrderEmail";
+import WelcomeEmail from "./WelcomeEmail";
export {
+ GetStartedEmail,
InviteEmail,
PurchaseOrderEmail,
QuoteEmail,
SalesInvoiceEmail,
SalesOrderEmail,
+ WelcomeEmail,
};
diff --git a/packages/form/src/components/Combobox.tsx b/packages/form/src/components/Combobox.tsx
index 970f6e0bb6..3d1c4b66cd 100644
--- a/packages/form/src/components/Combobox.tsx
+++ b/packages/form/src/components/Combobox.tsx
@@ -12,16 +12,20 @@ import { useControlField, useField } from "../hooks";
export type ComboboxProps = Omit<ComboboxBaseProps, "onChange"> & {
name: string;
- label?: string | JSX.Element;
+ label?: string;
isLoading?: boolean;
isOptional?: boolean;
helperText?: string;
onChange?: (
- newValue: { value: string; label: string | JSX.Element } | null
+ newValue: { value: string; label: string | React.ReactNode } | null
) => void;
inline?: (
value: string,
- options: { value: string; label: string | JSX.Element; helper?: string }[]
+ options: {
+ value: string;
+ label: string | React.ReactNode;
+ helper?: string;
+ }[]
) => React.ReactNode;
};
diff --git a/packages/integrations/.eslintrc.js b/packages/integrations/.eslintrc.js
new file mode 100644
index 0000000000..1308cba140
--- /dev/null
+++ b/packages/integrations/.eslintrc.js
@@ -0,0 +1,4 @@
+module.exports = {
+ root: true,
+ extends: ["carbon"],
+};
diff --git a/packages/integrations/package.json b/packages/integrations/package.json
new file mode 100644
index 0000000000..338234e87c
--- /dev/null
+++ b/packages/integrations/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@carbon/integrations",
+ "version": "*",
+ "exports": {
+ ".": "./src/index.ts",
+ "./exchange-rates/exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts"
+ },
+ "jest": {
+ "preset": "@carbon/jest/node"
+ },
+ "private": true,
+ "scripts": {
+ "clean": "rimraf .turbo node_modules dist",
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts --external react",
+ "lint": "TIMING=1 eslint \"src/**/*.ts*\"",
+ "test": "jest"
+ },
+ "dependencies": {},
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "typescript": "^5.2.2"
+ }
+}
diff --git a/apps/erp/app/integrations/exchange-rates/config.tsx b/packages/integrations/src/exchange-rates/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/exchange-rates/config.tsx
rename to packages/integrations/src/exchange-rates/config.tsx
diff --git a/apps/erp/app/integrations/exchange-rates/exchange-rates.server.ts b/packages/integrations/src/exchange-rates/exchange-rates.server.ts
similarity index 100%
rename from apps/erp/app/integrations/exchange-rates/exchange-rates.server.ts
rename to packages/integrations/src/exchange-rates/exchange-rates.server.ts
diff --git a/apps/erp/app/integrations/index.ts b/packages/integrations/src/index.ts
similarity index 65%
rename from apps/erp/app/integrations/index.ts
rename to packages/integrations/src/index.ts
index 2a4b4e0397..b30c4c6275 100644
--- a/apps/erp/app/integrations/index.ts
+++ b/packages/integrations/src/index.ts
@@ -7,6 +7,9 @@ import { Slack } from "./slack/config";
import { Xero } from "./xero/config";
import { Zapier } from "./zapier/config";
+export { Resend } from "./resend/config";
+export type { IntegrationConfig } from "./types";
+
export const integrations = [
ExchangeRates,
Resend,
@@ -17,3 +20,8 @@ export const integrations = [
Xero,
Zapier,
];
+
+export { Onshape, Logo as OnshapeLogo } from "./onshape/config";
+export * from "./onshape/lib";
+
+export { PaperlessPartsClient } from "./paperless-parts/lib/client";
diff --git a/apps/erp/app/integrations/onshape/config.tsx b/packages/integrations/src/onshape/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/onshape/config.tsx
rename to packages/integrations/src/onshape/config.tsx
diff --git a/apps/erp/app/integrations/onshape/lib/client.ts b/packages/integrations/src/onshape/lib/client.ts
similarity index 100%
rename from apps/erp/app/integrations/onshape/lib/client.ts
rename to packages/integrations/src/onshape/lib/client.ts
diff --git a/apps/erp/app/integrations/onshape/lib/data.ts b/packages/integrations/src/onshape/lib/data.ts
similarity index 64%
rename from apps/erp/app/integrations/onshape/lib/data.ts
rename to packages/integrations/src/onshape/lib/data.ts
index 2f41051ee8..8650078324 100644
--- a/apps/erp/app/integrations/onshape/lib/data.ts
+++ b/packages/integrations/src/onshape/lib/data.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
-import { itemReplenishmentSystems } from "~/modules/items/items.models";
-import { methodType } from "~/modules/shared/shared.models";
+
+const methodType = ["Buy", "Make", "Pick"] as const;
+const replenishmentSystems = ["Buy", "Make", "Buy and Make"] as const;
export const onShapeDataValidator = z
.object({
@@ -10,7 +11,7 @@ export const onShapeDataValidator = z
revision: z.string().optional(),
name: z.string(),
quantity: z.number(),
- replenishmentSystem: z.enum(itemReplenishmentSystems),
+ replenishmentSystem: z.enum(replenishmentSystems),
defaultMethodType: z.enum(methodType),
data: z.record(z.string(), z.any()),
})
diff --git a/packages/integrations/src/onshape/lib/index.ts b/packages/integrations/src/onshape/lib/index.ts
new file mode 100644
index 0000000000..3d6600311d
--- /dev/null
+++ b/packages/integrations/src/onshape/lib/index.ts
@@ -0,0 +1,2 @@
+export * from "./client";
+export * from "./data";
diff --git a/apps/erp/app/integrations/paperless-parts/config.tsx b/packages/integrations/src/paperless-parts/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/paperless-parts/config.tsx
rename to packages/integrations/src/paperless-parts/config.tsx
diff --git a/apps/erp/app/integrations/paperless-parts/lib/client.ts b/packages/integrations/src/paperless-parts/lib/client.ts
similarity index 100%
rename from apps/erp/app/integrations/paperless-parts/lib/client.ts
rename to packages/integrations/src/paperless-parts/lib/client.ts
diff --git a/apps/erp/app/integrations/quickbooks/config.tsx b/packages/integrations/src/quickbooks/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/quickbooks/config.tsx
rename to packages/integrations/src/quickbooks/config.tsx
diff --git a/apps/erp/app/integrations/resend/config.tsx b/packages/integrations/src/resend/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/resend/config.tsx
rename to packages/integrations/src/resend/config.tsx
diff --git a/apps/erp/app/integrations/slack/config.tsx b/packages/integrations/src/slack/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/slack/config.tsx
rename to packages/integrations/src/slack/config.tsx
diff --git a/apps/erp/app/integrations/types.ts b/packages/integrations/src/types.ts
similarity index 100%
rename from apps/erp/app/integrations/types.ts
rename to packages/integrations/src/types.ts
diff --git a/apps/erp/app/integrations/xero/config.tsx b/packages/integrations/src/xero/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/xero/config.tsx
rename to packages/integrations/src/xero/config.tsx
diff --git a/apps/erp/app/integrations/zapier/config.tsx b/packages/integrations/src/zapier/config.tsx
similarity index 100%
rename from apps/erp/app/integrations/zapier/config.tsx
rename to packages/integrations/src/zapier/config.tsx
diff --git a/packages/integrations/tsconfig.json b/packages/integrations/tsconfig.json
new file mode 100644
index 0000000000..e8a0e95a8d
--- /dev/null
+++ b/packages/integrations/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "compilerOptions": {
+ "lib": ["dom", "ES2015"]
+ },
+ "include": ["src", "../../apps/erp/app/components/OnshapeSync.tsx"],
+ "exclude": ["node_modules"],
+ "extends": "@carbon/tsconfig/react-library.json"
+}
diff --git a/packages/jobs/.eslintrc.cjs b/packages/jobs/.eslintrc.cjs
new file mode 100644
index 0000000000..1308cba140
--- /dev/null
+++ b/packages/jobs/.eslintrc.cjs
@@ -0,0 +1,4 @@
+module.exports = {
+ root: true,
+ extends: ["carbon"],
+};
diff --git a/packages/jobs/client.ts b/packages/jobs/client.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
new file mode 100644
index 0000000000..a756d07329
--- /dev/null
+++ b/packages/jobs/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "@carbon/jobs",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev:jobs": "npx --yes [email protected] dev",
+ "deploy": "trigger deploy",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@trigger.dev/sdk": "3.3.12",
+ "@carbon/auth": "*",
+ "@carbon/database": "*",
+ "@carbon/documents": "*",
+ "@carbon/lib": "*",
+ "@carbon/notifications": "*",
+ "@internationalized/date": "^3.5.2",
+ "@novu/node": "^2.0.1",
+ "@react-email/components": "0.0.16",
+ "@supabase/functions-js": "2.1.5",
+ "@supabase/supabase-js": "^2.40.0",
+ "nanoid": "5.0.4",
+ "resend": "^3.1.0",
+ "zod": "^3.24.1"
+ },
+ "devDependencies": {
+ "@carbon/tsconfig": "*",
+ "typescript": "^5.2.2"
+ }
+}
diff --git a/apps/erp/trigger.config.ts b/packages/jobs/trigger.config.ts
similarity index 93%
rename from apps/erp/trigger.config.ts
rename to packages/jobs/trigger.config.ts
index c9ad3a517f..4fefb70319 100644
--- a/apps/erp/trigger.config.ts
+++ b/packages/jobs/trigger.config.ts
@@ -15,5 +15,5 @@ export default defineConfig({
randomize: true,
},
},
- dirs: ["app/trigger"],
+ dirs: ["./trigger"],
});
diff --git a/apps/erp/app/trigger/autodesk-poll.ts b/packages/jobs/trigger/autodesk-poll.ts
similarity index 68%
rename from apps/erp/app/trigger/autodesk-poll.ts
rename to packages/jobs/trigger/autodesk-poll.ts
index a87a45e335..d240653eef 100644
--- a/apps/erp/app/trigger/autodesk-poll.ts
+++ b/packages/jobs/trigger/autodesk-poll.ts
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { getAutodeskToken, getManifest } from "@carbon/auth/autodesk.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
import { task } from "@trigger.dev/sdk/v3";
-import { upsertModelUpload } from "~/modules/shared";
const serviceRole = getCarbonServiceRole();
@@ -52,3 +53,26 @@ export const autodeskPollTask = task({
return { success: true, id, autodeskUrn };
},
});
+
+async function upsertModelUpload(
+ client: SupabaseClient<Database>,
+ upload:
+ | {
+ id: string;
+ modelPath: string;
+ companyId: string;
+ createdBy: string;
+ }
+ | {
+ id: string;
+ name: string;
+ size: number;
+ autodeskUrn?: string | null;
+ thumbnailPath: string;
+ }
+) {
+ if ("createdBy" in upload) {
+ return client.from("modelUpload").insert(upload);
+ }
+ return client.from("modelUpload").update(upload).eq("id", upload.id);
+}
diff --git a/apps/erp/app/trigger/autodesk-upload.ts b/packages/jobs/trigger/autodesk-upload.ts
similarity index 100%
rename from apps/erp/app/trigger/autodesk-upload.ts
rename to packages/jobs/trigger/autodesk-upload.ts
diff --git a/apps/erp/app/trigger/expire-quotes.ts b/packages/jobs/trigger/cleanup.ts
similarity index 66%
rename from apps/erp/app/trigger/expire-quotes.ts
rename to packages/jobs/trigger/cleanup.ts
index 057c548e7e..7c0470029d 100644
--- a/apps/erp/app/trigger/expire-quotes.ts
+++ b/packages/jobs/trigger/cleanup.ts
@@ -12,17 +12,16 @@ import { schedules } from "@trigger.dev/sdk/v3";
const serviceRole = getCarbonServiceRole();
const novu = new Novu(NOVU_SECRET_KEY!);
-export const expireQuotes = schedules.task({
- id: "expire-quotes",
+export const cleanup = schedules.task({
+ id: "cleanup",
// Run at 7am, 12pm, and 5pm every day
cron: "0 7,12,17 * * *",
run: async () => {
- console.log(
- `🕒 Quote Expiration Check Started: ${new Date().toISOString()}`
- );
+ console.log(`🧹 Starting cleanup tasks: ${new Date().toISOString()}`);
try {
- // Fetch expired quotes that are in sent status and have a sales person assigned
+ // Clean up expired quotes
+ console.log("Checking for expired quotes...");
const [expiredQuotes, expiredSupplierQuotes] = await Promise.all([
serviceRole
.from("quote")
@@ -82,7 +81,6 @@ export const expireQuotes = schedules.task({
if (!expiredQuotes?.data?.length) {
console.log("No expired quotes found requiring notification");
- return;
} else {
console.log(`Found ${expiredQuotes.data.length} expired quotes`);
const expireQuotes = await serviceRole
@@ -101,45 +99,46 @@ export const expireQuotes = schedules.task({
);
return;
}
- }
- const notificationPayloads: TriggerPayload[] = expiredQuotes.data
- .filter((quote) => Boolean(quote.salesPersonId))
- .map((quote) => {
- return {
- workflow: NotificationWorkflow.Expiration,
- payload: {
- documentId: quote.id,
- event: NotificationEvent.QuoteExpired,
- recordId: quote.id,
- description: `Quote ${quote.quoteId} has expired`,
- },
- user: {
- subscriberId: getSubscriberId({
- companyId: quote.companyId,
- userId: quote.salesPersonId!,
- }),
- },
- };
- });
+ const notificationPayloads: TriggerPayload[] = expiredQuotes.data
+ .filter((quote) => Boolean(quote.salesPersonId))
+ .map((quote) => {
+ return {
+ workflow: NotificationWorkflow.Expiration,
+ payload: {
+ documentId: quote.id,
+ event: NotificationEvent.QuoteExpired,
+ recordId: quote.id,
+ description: `Quote ${quote.quoteId} has expired`,
+ },
+ user: {
+ subscriberId: getSubscriberId({
+ companyId: quote.companyId,
+ userId: quote.salesPersonId!,
+ }),
+ },
+ };
+ });
- if (notificationPayloads.length > 0) {
- console.log(`Triggering ${notificationPayloads.length} notifications`);
- try {
- await triggerBulk(novu, notificationPayloads.flat());
- } catch (error) {
- console.error("Error triggering notifications");
- console.error(error);
+ if (notificationPayloads.length > 0) {
+ console.log(
+ `Triggering ${notificationPayloads.length} notifications`
+ );
+ try {
+ await triggerBulk(novu, notificationPayloads.flat());
+ } catch (error) {
+ console.error("Error triggering notifications");
+ console.error(error);
+ }
+ } else {
+ console.log("No notifications to trigger");
}
- } else {
- console.log("No notifications to trigger");
}
- console.log(
- `🕒 Quote Expiration Check Completed: ${new Date().toISOString()}`
- );
+
+ console.log(`🧹 Cleanup tasks completed: ${new Date().toISOString()}`);
} catch (error) {
console.error(
- `Unexpected error in quote expiration task: ${
+ `Unexpected error in cleanup tasks: ${
error instanceof Error ? error.message : String(error)
}`
);
diff --git a/apps/erp/app/trigger/model-thumbnail.ts b/packages/jobs/trigger/model-thumbnail.ts
similarity index 100%
rename from apps/erp/app/trigger/model-thumbnail.ts
rename to packages/jobs/trigger/model-thumbnail.ts
diff --git a/apps/erp/app/trigger/mrp.ts b/packages/jobs/trigger/mrp.ts
similarity index 85%
rename from apps/erp/app/trigger/mrp.ts
rename to packages/jobs/trigger/mrp.ts
index cbf9ea7a71..2f45890c70 100644
--- a/apps/erp/app/trigger/mrp.ts
+++ b/packages/jobs/trigger/mrp.ts
@@ -1,6 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { schedules } from "@trigger.dev/sdk/v3";
-import { runMRP } from "~/modules/production/production.service";
const serviceRole = getCarbonServiceRole();
@@ -27,12 +26,15 @@ export const mrp = schedules.task({
}
for await (const company of companies.data) {
try {
- const result = await runMRP(serviceRole, {
- type: "company",
- id: company.id,
- companyId: company.id,
- userId: "system",
+ const result = await serviceRole.functions.invoke("mrp", {
+ body: {
+ type: "company",
+ id: company.id,
+ companyId: company.id,
+ userId: "system",
+ },
});
+
if (result.error) {
console.error(
`❌ Failed to run MRP for company ${company.name}: ${
diff --git a/apps/erp/app/trigger/notify.ts b/packages/jobs/trigger/notify.ts
similarity index 100%
rename from apps/erp/app/trigger/notify.ts
rename to packages/jobs/trigger/notify.ts
diff --git a/packages/jobs/trigger/onboard.ts b/packages/jobs/trigger/onboard.ts
new file mode 100644
index 0000000000..d2888718fd
--- /dev/null
+++ b/packages/jobs/trigger/onboard.ts
@@ -0,0 +1,89 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import type { Database } from "@carbon/database";
+import { GetStartedEmail, WelcomeEmail } from "@carbon/documents/email";
+import { resend } from "@carbon/lib/resend.server";
+import { render } from "@react-email/components";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { task, wait } from "@trigger.dev/sdk/v3";
+
+export const onboardTask = task({
+ id: "onboard",
+ run: async (payload: { companyId: string; userId: string }) => {
+ const { companyId, userId } = payload;
+
+ const client = getCarbonServiceRole();
+
+ const [company, user] = await Promise.all([
+ client.from("company").select("*").eq("id", companyId).single(),
+ client.from("user").select("*").eq("id", userId).single(),
+ ]);
+
+ if (company.error) {
+ console.error("Could not find company", company.error);
+ throw new Error(company.error.message);
+ }
+
+ if (user.error) {
+ console.error("Could not find user", user.error);
+ throw new Error(user.error.message);
+ }
+
+ await resend.contacts.create({
+ email: user.data.email,
+ firstName: user.data.firstName,
+ lastName: user.data.lastName,
+ unsubscribed: false,
+ audienceId: process.env.RESEND_AUDIENCE_ID!,
+ });
+
+ const sendOnboardingEmail = await shouldSendOnboardingEmailsToUser(
+ client,
+ userId
+ );
+
+ if (sendOnboardingEmail) {
+ await resend.emails.send({
+ from: "Brad from Carbon <[email protected]>",
+ to: user.data.email,
+ subject: `Welcome to Carbon`,
+ html: await render(
+ WelcomeEmail({
+ firstName: user.data.firstName,
+ })
+ ),
+ });
+ }
+
+ await wait.for({ minutes: 1 });
+
+ if (sendOnboardingEmail) {
+ await resend.emails.send({
+ from: "Brad from Carbon <[email protected]>",
+ to: user.data.email,
+ subject: `Get the most out of Carbon`,
+ html: render(
+ GetStartedEmail({
+ firstName: user.data.firstName,
+ universityUrl: "https://learn.carbonos.dev",
+ })
+ ),
+ });
+ }
+ },
+});
+
+async function shouldSendOnboardingEmailsToUser(
+ client: SupabaseClient<Database>,
+ userId: string
+) {
+ const userToCompany = await client
+ .from("userToCompany")
+ .select("*")
+ .eq("userId", userId);
+
+ if (userToCompany.error) {
+ return true;
+ }
+
+ return userToCompany.data.length <= 1;
+}
diff --git a/apps/erp/app/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
similarity index 92%
rename from apps/erp/app/trigger/paperless-parts.ts
rename to packages/jobs/trigger/paperless-parts.ts
index de0d9d0315..cf93843bcf 100644
--- a/apps/erp/app/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -1,10 +1,6 @@
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getCarbonServiceRole } from "@carbon/auth";
-import { PaperlessPartsClient } from "~/integrations/paperless-parts/lib/client";
-import type { Result } from "~/types";
-
const payloadSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("quote.created"),
@@ -49,15 +45,15 @@ const paperlessPartsSchema = z.object({
export const paperlessPartsTask = task({
id: "paperless-parts",
run: async (payload: z.infer<typeof paperlessPartsSchema>) => {
- let result: Result;
+ let result: { success: boolean; message: string };
console.info(
`🔰 Paperless Parts webhook received: ${payload.payload.type}`
);
console.info(`📦 Payload:`, payload);
- const carbon = getCarbonServiceRole();
- const paperless = new PaperlessPartsClient(payload.apiKey);
+ // const carbon = getCarbonServiceRole();
+ // const paperless = new PaperlessPartsClient(payload.apiKey);
switch (payload.payload.type) {
case "quote.created":
diff --git a/apps/erp/app/trigger/post-transaction.ts b/packages/jobs/trigger/post-transaction.ts
similarity index 98%
rename from apps/erp/app/trigger/post-transaction.ts
rename to packages/jobs/trigger/post-transaction.ts
index bde6b13b5a..3fd1eba91a 100644
--- a/apps/erp/app/trigger/post-transaction.ts
+++ b/packages/jobs/trigger/post-transaction.ts
@@ -2,7 +2,6 @@ import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
import { getCarbonServiceRole } from "@carbon/auth";
-import type { Result } from "~/types";
const serviceRole = getCarbonServiceRole();
@@ -20,7 +19,7 @@ export const postTransactionTask = task({
`🔰 User admin update ${payload.type} for ${payload.documentId}`
);
- let result: Result;
+ let result: { success: boolean; message: string };
switch (payload.type) {
case "receipt":
diff --git a/apps/erp/app/trigger/recalculate.ts b/packages/jobs/trigger/recalculate.ts
similarity index 78%
rename from apps/erp/app/trigger/recalculate.ts
rename to packages/jobs/trigger/recalculate.ts
index 615666f3ab..912cf08f0e 100644
--- a/apps/erp/app/trigger/recalculate.ts
+++ b/packages/jobs/trigger/recalculate.ts
@@ -2,11 +2,6 @@ import { getCarbonServiceRole } from "@carbon/auth";
import type { FunctionsResponse } from "@supabase/functions-js";
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import type { Result } from "~/types";
-import {
- recalculateJobMakeMethodRequirements,
- recalculateJobRequirements,
-} from "../modules/production/production.service";
const recalculateSchema = z.object({
type: z.enum(["jobRequirements", "jobMakeMethodRequirements"]),
@@ -21,7 +16,7 @@ export const recalculateTask = task({
console.info(`🔰 Type: ${payload.type}, id: ${payload.id}`);
const serviceRole = getCarbonServiceRole();
- let result: Result;
+ let result: { success: boolean; message: string };
let calculateQuantities: FunctionsResponse<{ success: boolean }>;
switch (payload.type) {
@@ -75,3 +70,35 @@ export const recalculateTask = task({
return result;
},
});
+
+async function recalculateJobRequirements(
+ client,
+ params: {
+ id: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("scheduler", {
+ body: {
+ type: "requirements",
+ ...params,
+ },
+ });
+}
+
+async function recalculateJobMakeMethodRequirements(
+ client,
+ params: {
+ id: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("scheduler", {
+ body: {
+ type: "make-method-requirements",
+ ...params,
+ },
+ });
+}
diff --git a/apps/erp/app/trigger/sales-order-to-jobs.ts b/packages/jobs/trigger/sales-order-to-jobs.ts
similarity index 57%
rename from apps/erp/app/trigger/sales-order-to-jobs.ts
rename to packages/jobs/trigger/sales-order-to-jobs.ts
index fed9543c44..e2fc2556ee 100644
--- a/apps/erp/app/trigger/sales-order-to-jobs.ts
+++ b/packages/jobs/trigger/sales-order-to-jobs.ts
@@ -1,19 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { parseDate } from "@internationalized/date";
-import { task, tasks } from "@trigger.dev/sdk/v3";
+import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getItemManufacturing, getItemReplenishment } from "~/modules/items";
-import {
- getOpportunity,
- getSalesOrder,
- getSalesOrderLines,
-} from "~/modules/sales";
-import { getNextSequence } from "~/modules/settings";
-import {
- upsertJob,
- upsertJobMethod,
-} from "../modules/production/production.service";
-import type { recalculateTask } from "./recalculate";
const salesOrderToJobsSchema = z.object({
orderId: z.string(),
@@ -28,10 +16,20 @@ export const salesOrderToJobsTask = task({
const { orderId, companyId, userId } = payload;
const serviceRole = getCarbonServiceRole();
- const [salesOrder, salesOrderLines] = await Promise.all([
- getSalesOrder(serviceRole, orderId),
- getSalesOrderLines(serviceRole, orderId),
- ]);
+
+ // Implement getSalesOrder
+ const salesOrder = await serviceRole
+ .from("salesOrder")
+ .select("*")
+ .eq("id", orderId)
+ .single();
+
+ // Implement getSalesOrderLines
+ const salesOrderLines = await serviceRole
+ .from("salesOrderLines")
+ .select("*")
+ .eq("salesOrderId", orderId)
+ .order("itemReadableId", { ascending: true });
if (companyId !== salesOrder.data?.companyId) {
console.error("Company ID mismatch");
@@ -56,20 +54,25 @@ export const salesOrderToJobsTask = task({
return;
}
- const opportunity = await getOpportunity(
- serviceRole,
- salesOrder.data?.opportunityId ?? null
- );
+ // Implement getOpportunity
+ const opportunity = await serviceRole
+ .from("opportunity")
+ .select("*, quotes(*), salesOrders(*)")
+ .eq("id", salesOrder.data?.opportunityId ?? "")
+ .single();
+
const quoteId = opportunity.data?.quotes[0]?.id;
const salesOrderId = opportunity.data?.salesOrders[0]?.id;
for await (const line of lines) {
if (line.methodType === "Make" && line.itemId) {
- const itemManufacturing = await getItemManufacturing(
- serviceRole,
- line.itemId,
- companyId
- );
+ // Implement getItemManufacturing
+ const itemManufacturing = await serviceRole
+ .from("itemReplenishment")
+ .select("*")
+ .eq("itemId", line.itemId)
+ .eq("companyId", companyId)
+ .single();
const lotSize = itemManufacturing.data?.lotSize ?? 0;
const totalQuantity = line.saleQuantity ?? 0;
@@ -80,10 +83,20 @@ export const salesOrderToJobsTask = task({
const jobsToCreate = Math.max(1, totalJobs);
for await (const index of Array.from({ length: jobsToCreate }).keys()) {
- const [nextSequence, manufacturing] = await Promise.all([
- getNextSequence(serviceRole, "job", companyId),
- getItemReplenishment(serviceRole, line.itemId, companyId),
- ]);
+ // Implement getNextSequence
+ const nextSequence = await serviceRole.rpc("get_next_sequence", {
+ sequence_name: "job",
+ company_id: companyId,
+ });
+
+ // Implement getItemReplenishment
+ const manufacturing = await serviceRole
+ .from("itemReplenishment")
+ .select("*")
+ .eq("itemId", line.itemId)
+ .eq("companyId", companyId)
+ .single();
+
if (!nextSequence.data) {
console.error("Failed to get next job id");
continue;
@@ -121,12 +134,17 @@ export const salesOrderToJobsTask = task({
unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
};
- const createJob = await upsertJob(serviceRole, {
- ...data,
- jobId: nextSequence.data,
- companyId,
- createdBy: userId,
- });
+ // Implement upsertJob
+ const createJob = await serviceRole
+ .from("job")
+ .insert({
+ ...data,
+ jobId: nextSequence.data,
+ companyId,
+ createdBy: userId,
+ })
+ .select("id")
+ .single();
if (createJob.error) {
console.error("Failed to create job");
@@ -135,14 +153,17 @@ export const salesOrderToJobsTask = task({
}
if (quoteId) {
- const upsertMethod = await upsertJobMethod(
- serviceRole,
- "quoteLineToJob",
+ // Implement upsertJobMethod for quote line
+ const upsertMethod = await serviceRole.functions.invoke(
+ "get-method",
{
- sourceId: `${quoteId}:${line.id}`,
- targetId: createJob.data.id,
- companyId,
- userId,
+ body: {
+ type: "quoteLineToJob",
+ sourceId: `${quoteId}:${line.id}`,
+ targetId: createJob.data.id,
+ companyId,
+ createdBy: userId,
+ },
}
);
@@ -152,14 +173,17 @@ export const salesOrderToJobsTask = task({
continue;
}
} else {
- const upsertMethod = await upsertJobMethod(
- serviceRole,
- "itemToJob",
+ // Implement upsertJobMethod for item
+ const upsertMethod = await serviceRole.functions.invoke(
+ "get-method",
{
- sourceId: data.itemId,
- targetId: createJob.data.id,
- companyId,
- userId,
+ body: {
+ type: "itemToJob",
+ sourceId: data.itemId,
+ targetId: createJob.data.id,
+ companyId,
+ createdBy: userId,
+ },
}
);
@@ -170,11 +194,22 @@ export const salesOrderToJobsTask = task({
}
}
- await tasks.trigger<typeof recalculateTask>("recalculate", {
- type: "jobRequirements",
- id: createJob.data.id,
- companyId,
- userId,
+ await serviceRole.functions.invoke("recalculate", {
+ body: {
+ type: "jobRequirements",
+ id: createJob.data.id,
+ companyId,
+ userId,
+ },
+ });
+
+ await serviceRole.functions.invoke("scheduler", {
+ body: {
+ type: "requirements",
+ id: createJob.data.id,
+ companyId,
+ userId,
+ },
});
}
}
diff --git a/apps/erp/app/trigger/send-email-resend.ts b/packages/jobs/trigger/send-email-resend.ts
similarity index 91%
rename from apps/erp/app/trigger/send-email-resend.ts
rename to packages/jobs/trigger/send-email-resend.ts
index e426b48891..05898fbe0f 100644
--- a/apps/erp/app/trigger/send-email-resend.ts
+++ b/packages/jobs/trigger/send-email-resend.ts
@@ -1,7 +1,6 @@
+import { Resend as ResendConfig } from "@carbon/integrations";
import { task } from "@trigger.dev/sdk/v3";
-import { nanoid } from "nanoid";
import { Resend } from "resend";
-import { Resend as ResendConfig } from "~/integrations/resend/config";
import { getCarbonServiceRole } from "@carbon/auth";
@@ -55,9 +54,6 @@ export const sendEmailResendTask = task({
html: payload.html,
text: payload.text,
attachments: payload.attachments,
- headers: {
- "X-Entity-Ref-ID": nanoid(7),
- },
};
console.info(`📬 Resend Email Job`);
diff --git a/apps/erp/app/trigger/update-exchange-rates.ts b/packages/jobs/trigger/update-exchange-rates.ts
similarity index 85%
rename from apps/erp/app/trigger/update-exchange-rates.ts
rename to packages/jobs/trigger/update-exchange-rates.ts
index 43097bed7f..1880580f57 100644
--- a/apps/erp/app/trigger/update-exchange-rates.ts
+++ b/packages/jobs/trigger/update-exchange-rates.ts
@@ -1,8 +1,71 @@
import { EXCHANGE_RATES_API_KEY, getCarbonServiceRole } from "@carbon/auth";
+import type { Rates } from "@carbon/integrations/exchange-rates/exchange-rates.server";
+import { getExchangeRatesClient } from "@carbon/integrations/exchange-rates/exchange-rates.server";
import { schedules } from "@trigger.dev/sdk/v3";
-import type { Rates } from "~/integrations/exchange-rates/exchange-rates.server";
-import { getExchangeRatesClient } from "~/integrations/exchange-rates/exchange-rates.server";
-import type { CurrencyCode } from "~/modules/accounting";
+
+type CurrencyCode =
+ | "EUR"
+ | "USD"
+ | "GBP"
+ | "JPY"
+ | "CHF"
+ | "CAD"
+ | "AUD"
+ | "CNY"
+ | "INR"
+ | "MXN"
+ | "BRL"
+ | "RUB"
+ | "ZAR"
+ | "TRY"
+ | "SEK"
+ | "NOK"
+ | "DKK"
+ | "SGD"
+ | "HKD"
+ | "TWD"
+ | "THB"
+ | "MYR"
+ | "PHP"
+ | "IDR"
+ | "VND"
+ | "KRW"
+ | "TND"
+ | "MAD"
+ | "AED"
+ | "SAR"
+ | "QAR"
+ | "KWD"
+ | "BHD"
+ | "OMR"
+ | "JOD"
+ | "LYD"
+ | "EGP"
+ | "ILS"
+ | "KZT"
+ | "KGS"
+ | "UZS"
+ | "TJS"
+ | "AZN"
+ | "TMT"
+ | "UYU"
+ | "BYN"
+ | "KZT"
+ | "KGS"
+ | "UZS"
+ | "TJS"
+ | "AZN"
+ | "TMT"
+ | "UYU"
+ | "BYN"
+ | "KZT"
+ | "KGS"
+ | "UZS"
+ | "TJS"
+ | "AZN"
+ | "TMT"
+ | "UYU"
+ | "BYN";
const serviceRole = getCarbonServiceRole();
diff --git a/packages/jobs/trigger/update-permissions.ts b/packages/jobs/trigger/update-permissions.ts
new file mode 100644
index 0000000000..18be3cab41
--- /dev/null
+++ b/packages/jobs/trigger/update-permissions.ts
@@ -0,0 +1,184 @@
+import { task } from "@trigger.dev/sdk/v3";
+import { z } from "zod";
+
+import {
+ error,
+ getCarbonServiceRole,
+ getClaims,
+ getPermissionCacheKey,
+ Result,
+ success,
+} from "@carbon/auth";
+import { Database } from "@carbon/database";
+import { redis } from "@carbon/kv";
+import { SupabaseClient } from "@supabase/supabase-js";
+
+const serviceRole = getCarbonServiceRole();
+export const permissionsUpdateSchema = z.object({
+ id: z.string(),
+ addOnly: z.boolean(),
+ permissions: z.record(
+ z.string(),
+ z.object({
+ view: z.boolean(),
+ create: z.boolean(),
+ update: z.boolean(),
+ delete: z.boolean(),
+ })
+ ),
+ companyId: z.string(),
+});
+
+export const updatePermissionsTask = task({
+ id: "update-permissions",
+ run: async (payload: z.infer<typeof permissionsUpdateSchema>) => {
+ console.info(`🔰 Permission Update for ${payload.id}`);
+ const { success, message } = await updatePermissions(serviceRole, payload);
+ if (success) {
+ console.info(`✅ Permission Update for ${payload.id}`);
+ } else {
+ console.error(`❌ Permission Update for ${payload.id}: ${message}`);
+ }
+ return { success, message };
+ },
+});
+
+export async function updatePermissions(
+ client: SupabaseClient<Database>,
+ {
+ id,
+ permissions,
+ companyId,
+ addOnly = false,
+ }: z.infer<typeof permissionsUpdateSchema>
+): Promise<Result> {
+ if (await client.rpc("is_claims_admin")) {
+ const claims = await getClaims(client, id);
+
+ if (claims.error) return error(claims.error, "Failed to get claims");
+
+ const updatedPermissions = (
+ typeof claims.data !== "object" ||
+ Array.isArray(claims.data) ||
+ claims.data === null
+ ? {}
+ : claims.data
+ ) as Record<string, string[]>;
+ delete updatedPermissions["role"];
+
+ // add any missing claims to the current claims
+ Object.keys(permissions).forEach((name) => {
+ const module = name.toLowerCase();
+ if (!(`${module}_view` in updatedPermissions)) {
+ updatedPermissions[`${module}_view`] = [];
+ }
+ if (!(`${module}_create` in updatedPermissions)) {
+ updatedPermissions[`${module}_create`] = [];
+ }
+ if (!(`${module}_update` in updatedPermissions)) {
+ updatedPermissions[`${module}_update`] = [];
+ }
+ if (!(`${module}_delete` in updatedPermissions)) {
+ updatedPermissions[`${module}_delete`] = [];
+ }
+ });
+
+ if (addOnly) {
+ Object.entries(permissions).forEach(([name, permission]) => {
+ const module = name.toLowerCase();
+ if (
+ permission.view &&
+ !updatedPermissions[`${module}_view`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_view`].push(companyId);
+ }
+ if (
+ permission.create &&
+ !updatedPermissions[`${module}_create`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_create`].push(companyId);
+ }
+ if (
+ permission.update &&
+ !updatedPermissions[`${module}_update`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_update`].push(companyId);
+ }
+ if (
+ permission.delete &&
+ !updatedPermissions[`${module}_delete`]?.includes(companyId)
+ ) {
+ updatedPermissions[`${module}_delete`].push(companyId);
+ }
+ });
+ } else {
+ Object.entries(permissions).forEach(([name, permission]) => {
+ const module = name.toLowerCase();
+ if (permission.view) {
+ if (!updatedPermissions[`${module}_view`]?.includes(companyId)) {
+ updatedPermissions[`${module}_view`] = [
+ ...updatedPermissions[`${module}_view`],
+ companyId,
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_view`] = (
+ updatedPermissions[`${module}_view`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.create) {
+ if (!updatedPermissions[`${module}_create`]?.includes(companyId)) {
+ updatedPermissions[`${module}_create`] = [
+ ...updatedPermissions[`${module}_create`],
+ companyId,
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_create`] = (
+ updatedPermissions[`${module}_create`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.update) {
+ if (!updatedPermissions[`${module}_update`]?.includes(companyId)) {
+ updatedPermissions[`${module}_update`] = [
+ ...updatedPermissions[`${module}_update`],
+ companyId,
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_update`] = (
+ updatedPermissions[`${module}_update`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+
+ if (permission.delete) {
+ if (!updatedPermissions[`${module}_delete`]?.includes(companyId)) {
+ updatedPermissions[`${module}_delete`] = [
+ ...updatedPermissions[`${module}_delete`],
+ companyId,
+ ];
+ }
+ } else {
+ updatedPermissions[`${module}_delete`] = (
+ updatedPermissions[`${module}_delete`] as string[]
+ ).filter((c: string) => c !== companyId);
+ }
+ });
+ }
+
+ const permissionsUpdate = await getCarbonServiceRole()
+ .from("userPermission")
+ .update({ permissions: updatedPermissions })
+ .eq("id", id);
+ if (permissionsUpdate.error)
+ return error(permissionsUpdate.error, "Failed to update claims");
+
+ await redis.del(getPermissionCacheKey(id));
+
+ return success("Permissions updated");
+ } else {
+ return error(null, "You do not have permission to update permissions");
+ }
+}
diff --git a/apps/erp/app/trigger/user-admin.ts b/packages/jobs/trigger/user-admin.ts
similarity index 95%
rename from apps/erp/app/trigger/user-admin.ts
rename to packages/jobs/trigger/user-admin.ts
index 16e06fe874..8b833d994c 100644
--- a/apps/erp/app/trigger/user-admin.ts
+++ b/packages/jobs/trigger/user-admin.ts
@@ -1,13 +1,12 @@
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
-import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";
+import { Result, getAppUrl, getCarbonServiceRole } from "@carbon/auth";
+import { deactivateUser } from "@carbon/auth/users.server";
import { InviteEmail } from "@carbon/documents/email";
import { resend } from "@carbon/lib/resend.server";
import { render } from "@react-email/components";
import { nanoid } from "nanoid";
-import { deactivateUser } from "~/modules/users/users.server";
-import type { Result } from "~/types";
const serviceRole = getCarbonServiceRole();
export const userAdminSchema = z.discriminatedUnion("type", [
diff --git a/packages/jobs/tsconfig.json b/packages/jobs/tsconfig.json
new file mode 100644
index 0000000000..82bf6bba2a
--- /dev/null
+++ b/packages/jobs/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "compilerOptions": {
+ "lib": ["ES2015"],
+ "outDir": "./dist",
+ "rootDir": "./trigger",
+ "allowImportingTsExtensions": true
+ },
+ "exclude": ["node_modules"],
+ "extends": "@carbon/tsconfig/base.json",
+ "include": ["trigger"]
+}
diff --git a/packages/lib/package.json b/packages/lib/package.json
index e440c76772..aa32bef915 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -1,13 +1,14 @@
{
"name": "@carbon/lib",
+ "type": "module",
"dependencies": {
"@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/kv": "*",
"@slack/web-api": "~7.6.0",
"@supabase/supabase-js": "^2.40.0",
- "resend": "^3.1.0",
- "stripe": "^18.3.0"
+ "@trigger.dev/sdk": "3.3.12",
+ "resend": "^3.1.0"
},
"devDependencies": {
"@carbon/logger": "*",
@@ -23,8 +24,7 @@
},
"exports": {
"./resend.server": "./src/resend.server.ts",
- "./slack.server": "./src/slack.server.ts",
- "./stripe.server": "./src/stripe.server.ts"
+ "./slack.server": "./src/slack.server.ts"
},
"private": true,
"scripts": {
diff --git a/packages/stripe/.eslintrc.js b/packages/stripe/.eslintrc.js
new file mode 100644
index 0000000000..1308cba140
--- /dev/null
+++ b/packages/stripe/.eslintrc.js
@@ -0,0 +1,4 @@
+module.exports = {
+ root: true,
+ extends: ["carbon"],
+};
diff --git a/packages/stripe/package.json b/packages/stripe/package.json
new file mode 100644
index 0000000000..2606f7d7c3
--- /dev/null
+++ b/packages/stripe/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "@carbon/stripe",
+ "dependencies": {
+ "@carbon/auth": "*",
+ "@carbon/database": "*",
+ "@carbon/jobs": "*",
+ "@carbon/kv": "*",
+ "@supabase/supabase-js": "^2.40.0",
+ "@trigger.dev/sdk": "3.3.12",
+ "stripe": "^18.3.0"
+ },
+ "devDependencies": {
+ "@carbon/logger": "*",
+ "@carbon/tsconfig": "*",
+ "@types/node": "^20.12.5",
+ "dotenv": "16.3.1",
+ "eslint": "^8.23.1",
+ "eslint-config-carbon": "*",
+ "rimraf": "^5.0.5",
+ "tsup": "^6.5.0",
+ "tsx": "^4.13.2",
+ "typescript": "^5.2.2",
+ "zod": "^3.24.2"
+ },
+ "exports": {
+ "./stripe.server": "./src/stripe.server.ts"
+ },
+ "private": true,
+ "scripts": {
+ "clean": "rimraf .turbo node_modules dist",
+ "dev": "tsup --watch",
+ "lint": "TIMING=1 eslint \"src/**/*.ts*\"",
+ "dev:stripe": "tsx ./stripe.dev.ts",
+ "register:stripe": "tsx ./stripe.register.ts"
+ },
+ "sideEffects": false,
+ "version": "*"
+}
diff --git a/packages/lib/src/stripe.server.ts b/packages/stripe/src/stripe.server.ts
similarity index 75%
rename from packages/lib/src/stripe.server.ts
rename to packages/stripe/src/stripe.server.ts
index 67b9c2adef..f2bbc683eb 100644
--- a/packages/lib/src/stripe.server.ts
+++ b/packages/stripe/src/stripe.server.ts
@@ -2,6 +2,7 @@ import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";
import type { Database } from "@carbon/database";
import { redis } from "@carbon/kv";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { tasks } from "@trigger.dev/sdk/v3";
import { Stripe } from "stripe";
import { z } from "zod";
@@ -78,7 +79,7 @@ export async function createStripeCustomer({
email,
name: name ?? undefined,
metadata: {
- owner: userId,
+ userId,
companyId,
},
},
@@ -194,6 +195,7 @@ export async function getCheckoutUrl({
cancel_url: `${getAppUrl()}/api/webhook/stripe`,
payment_method_types: ["card", "us_bank_account", "cashapp"],
metadata: {
+ userId,
companyId,
},
});
@@ -227,46 +229,39 @@ export async function getBillingPortalRedirectUrl({
return portalSession.url;
}
-async function insertCompanyPlan(
+async function upsertCompanyPlan(
client: SupabaseClient<Database>,
companyPlan: {
companyId: string;
- planId: string;
- status: "active" | "inactive";
+ priceId: string;
+ status?: "active" | "inactive";
stripeCustomerId?: string;
stripeSubscriptionId?: string;
stripeSubscriptionStatus?: string;
subscriptionStartDate?: string;
}
) {
- const plan = await getPlanById(client, companyPlan.planId);
+ const plan = await getPlanByPriceId(client, companyPlan.priceId);
if (plan.error) {
+ console.error("upsertCompanyPlan - plan error:", plan.error);
return plan;
}
const companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =
{
id: companyPlan.companyId,
- planId: companyPlan.planId,
+ planId: plan.data.id,
tasksLimit: plan.data.tasksLimit,
aiTokensLimit: plan.data.aiTokensLimit,
usersLimit: 10, // Default value as defined in the migration
- subscriptionStartDate: new Date().toISOString(),
- stripeSubscriptionStatus: companyPlan.status,
+ subscriptionStartDate:
+ companyPlan.subscriptionStartDate || new Date().toISOString(),
+ stripeSubscriptionStatus: companyPlan.stripeSubscriptionStatus,
stripeCustomerId: companyPlan.stripeCustomerId,
stripeSubscriptionId: companyPlan.stripeSubscriptionId,
- trialPeriodEndsAt: plan.data.stripeTrialPeriodDays
- ? new Date(
- Date.now() + plan.data.stripeTrialPeriodDays * 24 * 60 * 60 * 1000
- ).toISOString()
- : null,
};
- return client
- .from("companyPlan")
- .upsert(companyPlanData)
- .select("id")
- .single();
+ return client.from("companyPlan").upsert(companyPlanData);
}
function isAllowedEventType<TEvent extends Stripe.Event>(
@@ -300,65 +295,50 @@ export async function processStripeEvent({
}
const eventType = event.type;
+
if (eventType === "checkout.session.completed") {
const data = event.data.object as Stripe.Checkout.Session;
- const priceId = data.line_items?.data[0]?.price?.id;
- const plan = await getPlanByPriceId(getCarbonServiceRole(), priceId);
const { customer } = data;
- if (typeof customer !== "string") {
- throw new Error("Stripe webhook handler failed");
- }
- try {
- await Promise.all([
- syncStripeDataToKV(customer),
- insertCompanyPlan(getCarbonServiceRole(), {
- companyId: data.metadata.companyId,
- planId: plan.data.id,
- status: "active",
- }),
- ]);
- } catch (error) {
- console.error("Error processing webhook:", error);
- throw new Error("Stripe webhook handler failed");
+ const companyId = data.metadata.companyId;
+ const userId = data.metadata.userId;
+
+ if (!companyId || !userId) {
+ console.error(
+ "Missing required metadata in checkout session:",
+ data.metadata
+ );
+ throw new Error("Missing required metadata in checkout session");
}
- } else if (eventType === "customer.subscription.updated") {
- const subscription = event.data.object as Stripe.Subscription;
- const priceId = subscription.items.data[0].price.id;
- const plan = await getPlanByPriceId(getCarbonServiceRole(), priceId);
- const { customer } = subscription;
+
if (typeof customer !== "string") {
throw new Error("Stripe webhook handler failed");
}
try {
await Promise.all([
- syncStripeDataToKV(customer),
- updateCompanyPlan(getCarbonServiceRole(), {
- planId: plan.data.id,
- companyId: subscription.metadata.companyId,
- stripeCustomerId: customer,
- stripeSubscriptionId: subscription.id,
- stripeSubscriptionStatus: ["active", "trialing"].includes(
- subscription.status
- )
- ? "active"
- : "inactive",
- subscriptionStartDate: new Date(
- subscription.items.data[0].current_period_start * 1000
- ).toISOString(),
+ syncStripeDataToKV(customer, companyId),
+ tasks.trigger("onboard", {
+ companyId,
+ userId,
}),
]);
} catch (error) {
console.error("Error processing webhook:", error);
throw new Error("Stripe webhook handler failed");
}
+ } else {
+ console.log("unhandled event", { eventType });
}
}
-export async function syncStripeDataToKV(customerId: string) {
+export async function syncStripeDataToKV(
+ customerId: string,
+ companyIdFromMetadata?: string
+) {
const key = `stripe:customer:${customerId}`;
- console.log({ key });
+ let companyId = companyIdFromMetadata;
+ const serviceRole = await getCarbonServiceRole();
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
@@ -372,9 +352,19 @@ export async function syncStripeDataToKV(customerId: string) {
return null;
}
+ if (!companyId) {
+ const companyPlan = await serviceRole
+ .from("companyPlan")
+ .select("*")
+ .eq("stripeCustomerId", customerId)
+ .single();
+
+ companyId = companyPlan.data?.id;
+ }
+
const subscription = subscriptions.data[0];
- const subData = KvStripeCustomerSchema.parse({
+ const subDataResult = KvStripeCustomerSchema.safeParse({
subscriptionId: subscription.id,
status: subscription.status,
priceId: subscription.items.data[0].price.id,
@@ -391,14 +381,41 @@ export async function syncStripeDataToKV(customerId: string) {
: null,
});
- const customer = await stripe.customers.retrieve(customerId);
- const companyId = (customer as any).metadata?.companyId;
+ if (!subDataResult.success) {
+ console.error("Failed to parse subscription data:", subDataResult.error);
+ throw new Error("Failed to parse subscription data");
+ }
+
+ const subData = subDataResult.data;
if (companyId) {
- await redis.set(key, subData);
+ const companyPlanData = {
+ companyId,
+ priceId: subData.priceId,
+ status: ["active", "trialing"].includes(subData.status)
+ ? ("active" as const)
+ : ("inactive" as const),
+ stripeCustomerId: customerId,
+ stripeSubscriptionId: subData.subscriptionId,
+ stripeSubscriptionStatus: subData.status,
+ subscriptionStartDate: new Date(
+ subData.currentPeriodStart * 1000
+ ).toISOString(),
+ };
+
+ const [_, companyPlan] = await Promise.all([
+ redis.set(key, subData),
+ upsertCompanyPlan(await getCarbonServiceRole(), companyPlanData),
+ ]);
+
+ if (companyPlan.error) {
+ console.error("Failed to upsert company plan:", companyPlan.error);
+ }
+ } else {
+ console.error("no company id, skipping company plan upsert");
}
- return subData;
+ return subDataResult;
}
export async function updateActiveUsers({
@@ -412,20 +429,3 @@ export async function updateActiveUsers({
quantity: activeUsers,
});
}
-
-export async function updateCompanyPlan(
- client: SupabaseClient<Database>,
- data: {
- companyId: string;
- planId: string;
- stripeCustomerId: string;
- stripeSubscriptionId: string;
- stripeSubscriptionStatus: string;
- subscriptionStartDate: string;
- }
-) {
- // Extract companyId and build the update data without it
- const { companyId, ...updateData } = data;
-
- return client.from("companyPlan").update(updateData).eq("id", companyId);
-}
diff --git a/apps/erp/stripe.dev.ts b/packages/stripe/stripe.dev.ts
similarity index 100%
rename from apps/erp/stripe.dev.ts
rename to packages/stripe/stripe.dev.ts
diff --git a/apps/erp/stripe.register.ts b/packages/stripe/stripe.register.ts
similarity index 100%
rename from apps/erp/stripe.register.ts
rename to packages/stripe/stripe.register.ts
diff --git a/packages/stripe/tsconfig.json b/packages/stripe/tsconfig.json
new file mode 100644
index 0000000000..fc3043b055
--- /dev/null
+++ b/packages/stripe/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "compilerOptions": {
+ "lib": ["ES2015"],
+ "outDir": "./dist",
+ "rootDir": "./src"
+ },
+ "exclude": ["node_modules"],
+ "extends": "@carbon/tsconfig/base.json",
+ "include": ["src"]
+}
diff --git a/packages/stripe/tsup.config.ts b/packages/stripe/tsup.config.ts
new file mode 100644
index 0000000000..971be238af
--- /dev/null
+++ b/packages/stripe/tsup.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from "tsup";
+
+const isProduction = process.env.VERCEL_ENV === "production";
+
+export default defineConfig({
+ clean: true,
+ dts: true,
+ entry: ["src/index.ts"],
+ format: ["cjs", "esm"],
+ minify: isProduction,
+ sourcemap: true,
+});
diff --git a/scripts/setup-env-files.ts b/scripts/setup-env-files.ts
index f486294127..329305e6d0 100644
--- a/scripts/setup-env-files.ts
+++ b/scripts/setup-env-files.ts
@@ -11,7 +11,7 @@ const APPS_DIR = join(process.cwd(), "apps");
const PACKAGES_DIR = join(process.cwd(), "packages");
// List of package folders that need .env symlinks
-const PACKAGE_FOLDERS = ["database", "kv"];
+const PACKAGE_FOLDERS = ["database", "jobs", "kv"];
function createSymlink(targetPath: string, sourcePath: string) {
try {
@@ -30,7 +30,7 @@ function createSymlink(targetPath: string, sourcePath: string) {
// Create symlinks in apps directory
if (existsSync(APPS_DIR)) {
- const apps = ["erp", "mes", "starter"];
+ const apps = ["erp", "mes", "university", "starter"];
apps.forEach((app) => {
const appEnvPath = join(APPS_DIR, app, ".env");
createSymlink(appEnvPath, ROOT_ENV_PATH);