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.

Post Receipts (#38)

Brad Barbinf694c327e73e
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000000..2620d0af96
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,6 @@
+{
+ "deno.cacheOnSave": true,
+ "deno.enablePaths": ["./packages/database/supabase/functions"],
+ "typescript.tsdk": "node_modules/typescript/lib",
+ "deno.enable": true
+}
diff --git a/README.md b/README.md
index 1b84b23f53..40ea0a7567 100644
--- a/README.md
+++ b/README.md
@@ -59,8 +59,6 @@ The monorepo follows the Turborepo covention of grouping packages into one of tw
## Local Development
-<!-- TODO: requirements for Upstash, Supabase, Github -->
-
Make sure that you have [Docker installed](https://docs.docker.com/desktop/install/mac-install/) and [yarn installed](https://yarnpkg.com/lang/en/docs/install/#debian-stable)
on your system since this monorepo uses the yarn package manager.
@@ -73,13 +71,14 @@ After running the steps below you should be able to access the following apps/co
| Supabase Studio | [http://localhost:54323/project/default](http://localhost:54323/project/default) |
| Inbucket | [http://localhost:54324/monitor](http://localhost:54324/monitor) |
| Redis | [redis://localhost:6379](redis://localhost:6379) |
+| Edge Functions | [http://localhost:54321/functions/v1/<function-name>](http://localhost:54321/functions/v1/<function-name>) |
First download and initialize the repository dependencies.
```bash
$ nvm use # use node v18
$ yarn # install dependencies
-$ yarn init # pull and start the containers
+$ yarn db:start # pull and run the containers
```
Copy the environment variables from the initialization script to an `.env` file:
@@ -88,7 +87,7 @@ Copy the environment variables from the initialization script to an `.env` file:
$ cp ./.env.example ./.env
```
-After you've set the enviroment variables to the output of `yarn init` you can run
+After you've set the enviroment variables to the output of `yarn db:start` you can run
```bash
$ yarn db:build # run db migrations and seed script
diff --git a/SCHEMA.md b/SCHEMA.md
index d4eb8820a1..3d44be0c7c 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -1,6 +1,6 @@
# Carbon Database Schema
-This file is generated by `scripts/generate-schema-md.ts` using the migrations in `packages/carbon-database/supabase/migrations`.
+This file is generated by `scripts/generate-schema-md.ts` using the migrations in `packages/database/supabase/migrations`.
@@ -2680,7 +2680,7 @@ CREATE TRIGGER update_equipment_search_result
-## `realtime-users`
+## `realtime`
```sql
BEGIN;
@@ -2691,8 +2691,6 @@ BEGIN;
CREATE publication supabase_realtime;
COMMIT;
--- add a table to the publication
-ALTER publication supabase_realtime ADD TABLE "user";
```
@@ -3396,6 +3394,7 @@ CREATE INDEX "part_description_index" ON "part"("description");
CREATE INDEX "part_partType_index" ON "part"("partType");
CREATE INDEX "part_partGroupId_index" ON "part"("partGroupId");
CREATE INDEX "part_replenishmentSystem_index" ON "part"("replenishmentSystem");
+CREATE INDEX "part_active_blocked_index" ON "part"("active", "blocked");
ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;
@@ -3963,33 +3962,10 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partInv
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
--- CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
--- FOR SELECT
--- USING (
--- coalesce(get_my_claim('parts_view')::boolean, false) = true
--- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
--- AND (
--- "partId" IN (
--- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
--- );
-
--- CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
--- FOR UPDATE
--- USING (
--- coalesce(get_my_claim('parts_update')::boolean, false) = true
--- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
--- AND (
--- "partId" IN (
--- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
--- );
+
+
+
+
```
@@ -4400,7 +4376,7 @@ CREATE TYPE "purchaseOrderType" AS ENUM (
);
CREATE TYPE "purchaseOrderStatus" AS ENUM (
- 'Open',
+ 'Draft',
'In Review',
'In External Review',
'Approved',
@@ -4413,7 +4389,7 @@ CREATE TABLE "purchaseOrder" (
"id" TEXT NOT NULL DEFAULT xid(),
"purchaseOrderId" TEXT NOT NULL,
"type" "purchaseOrderType" NOT NULL,
- "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Open',
+ "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Draft',
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
@@ -4456,9 +4432,9 @@ CREATE TABLE "purchaseOrderLine" (
"assetId" TEXT,
"description" TEXT,
"purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
- "quantityToReceive" NUMERIC(9,2) DEFAULT 0,
+ "quantityToReceive" NUMERIC(9,2) GENERATED ALWAYS AS (CASE WHEN "purchaseOrderLineType" = 'Comment' THEN 0 ELSE GREATEST(("purchaseQuantity" - "quantityReceived"), 0) END) STORED,
"quantityReceived" NUMERIC(9,2) DEFAULT 0,
- "quantityToInvoice" NUMERIC(9,2) DEFAULT 0,
+ "quantityToInvoice" NUMERIC(9,2) GENERATED ALWAYS AS (CASE WHEN "purchaseOrderLineType" = 'Comment' THEN 0 ELSE GREATEST(("purchaseQuantity" - "quantityInvoiced"), 0) END) STORED,
"quantityInvoiced" NUMERIC(9,2) DEFAULT 0,
"unitPrice" NUMERIC(9,2),
"unitOfMeasureCode" TEXT,
@@ -5204,7 +5180,7 @@ ALTER VIEW "parts_view" SET (security_invoker = on);
## `ledgers`
```sql
-CREATE TYPE "accountDocumentLedgerType" AS ENUM (
+CREATE TYPE "generalLedgerDocumentType" AS ENUM (
'Quote',
'Order',
'Invoice',
@@ -5216,13 +5192,13 @@ CREATE TYPE "accountDocumentLedgerType" AS ENUM (
CREATE TABLE "generalLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"accountNumber" TEXT NOT NULL,
"description" TEXT,
"amount" NUMERIC(19, 4) NOT NULL,
- "documentType" "accountDocumentLedgerType",
- "documentNumber" TEXT,
- "externalDocumentNumber" TEXT,
+ "documentType" "generalLedgerDocumentType",
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "generalLedger_pkey" PRIMARY KEY ("id"),
@@ -5295,12 +5271,13 @@ CREATE TYPE "partLedgerDocumentType" AS ENUM (
CREATE TABLE "valueLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"partLedgerType" "partLedgerType" NOT NULL,
"costLedgerType" "costLedgerType" NOT NULL,
"adjustment" BOOLEAN NOT NULL DEFAULT false,
"documentType" "partLedgerDocumentType",
- "documentNumber" TEXT,
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,
"costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,
"actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,
@@ -5319,40 +5296,37 @@ CREATE POLICY "Employees with accounting_view can view the value ledger" ON "val
(get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE TABLE "valueLedgerAccountLedgerRelation" (
+CREATE TABLE "valueLedgerGeneralLedgerRelation" (
"valueLedgerId" TEXT NOT NULL,
"generalLedgerId" TEXT NOT NULL,
- CONSTRAINT "valueLedgerAccountLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),
- CONSTRAINT "valueLedgerAccountLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),
- CONSTRAINT "valueLedgerAccountLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")
);
-ALTER TABLE "valueLedgerAccountLedgerRelation" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "valueLedgerGeneralLedgerRelation" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees with accounting_view can view the value ledger account relations" ON "valueLedgerAccountLedgerRelation"
+CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "valueLedgerGeneralLedgerRelation"
FOR SELECT
USING (
coalesce(get_my_claim('accounting_view')::boolean, false) = true AND
(get_my_claim('role'::text)) = '"employee"'::jsonb
);
+
CREATE TABLE "partLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"entryType" "partLedgerType" NOT NULL,
"documentType" "partLedgerDocumentType",
- "documentNumber" TEXT,
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"partId" TEXT NOT NULL,
"locationId" TEXT,
"shelfId" TEXT,
"quantity" NUMERIC(12, 4) NOT NULL,
- "invoicedQuantity" NUMERIC(12, 4) NOT NULL,
- "remainingQuantity" NUMERIC(12, 4) NOT NULL,
- "salesAmount" NUMERIC(12, 4) NOT NULL,
- "costAmount" NUMERIC(12, 4) NOT NULL,
- "open" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),
@@ -5373,7 +5347,47 @@ CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger"
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+CREATE TABLE "partLedgerValueLedgerRelation" (
+ "partLedgerId" TEXT NOT NULL,
+ "valueLedgerId" TEXT NOT NULL,
+ CONSTRAINT "partLedgerValueLedgerRelation_pkey" PRIMARY KEY ("partLedgerId", "valueLedgerId"),
+ CONSTRAINT "partLedgerValueLedgerRelation_partLedgerId_fkey" FOREIGN KEY ("partLedgerId") REFERENCES "partLedger"("id"),
+ CONSTRAINT "partLedgerValueLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id")
+);
+
+ALTER TABLE "partLedgerValueLedgerRelation" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with accounting_view can view the part ledger/value ledger relations" ON "partLedgerValueLedgerRelation"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE TYPE "supplierLedgerDocumentType" AS ENUM (
+ 'Payment',
+ 'Invoice',
+ 'Credit Memo',
+ 'Finance Charge Memo',
+ 'Reminder',
+ 'Refund'
+);
+
+CREATE TABLE "supplierLedger" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "entryNumber" SERIAL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
+ "documentType" "supplierLedgerDocumentType",
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
+ "supplierId" TEXT NOT NULL,
+ "amount" NUMERIC(19, 4) NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+
+ CONSTRAINT "supplierLedger_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierLedger_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
CREATE OR REPLACE FUNCTION gl_transactions_by_account_number(
@@ -5402,6 +5416,8 @@ $$;
+
+
```
@@ -5420,6 +5436,12 @@ CREATE TYPE "receiptSourceDocument" AS ENUM (
'Manufacturing Output'
);
+CREATE TYPE "receiptStatus" AS ENUM (
+ 'Draft',
+ 'Pending',
+ 'Posted'
+);
+
CREATE TABLE "receipt" (
"id" TEXT NOT NULL DEFAULT xid(),
"receiptId" TEXT NOT NULL,
@@ -5427,8 +5449,11 @@ CREATE TABLE "receipt" (
"sourceDocument" "receiptSourceDocument",
"sourceDocumentId" TEXT,
"sourceDocumentReadableId" TEXT,
+ "externalDocumentId" TEXT,
"supplierId" TEXT,
+ "status" "receiptStatus" NOT NULL DEFAULT 'Draft',
"postingDate" DATE,
+ "invoiced" BOOLEAN DEFAULT FALSE,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -5449,12 +5474,12 @@ CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId");
ALTER TABLE "receipt" ENABLE ROW LEVEL SECURITY;
+-- TODO: this is a workaround to get around a bug with realtime subscriptions not working with the standard RLS
+-- it seems the client is not sending the right JWT token when it subscribes to the realtime channel
CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"
FOR SELECT
- USING (
- coalesce(get_my_claim('inventory_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
+ USING (coalesce(get_my_claim('inventory_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
CREATE POLICY "Employees with inventory_create can insert receipts" ON "receipt"
@@ -5478,6 +5503,8 @@ CREATE POLICY "Employees with inventory_delete can delete receipts" ON "receipt"
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+ALTER publication supabase_realtime ADD TABLE "receipt";
+
CREATE TABLE "receiptLine" (
"id" TEXT NOT NULL DEFAULT xid(),
"receiptId" TEXT NOT NULL,
@@ -5549,6 +5576,8 @@ CREATE VIEW "receipt_quantity_received_by_line" AS
ON l."receiptId" = r."receiptId"
GROUP BY r."sourceDocumentId", l."lineId";
+
+
```
@@ -6232,3 +6261,94 @@ CREATE TRIGGER create_posting_groups_for_supplier_type
```
+
+
+## `accounts-payable`
+
+```sql
+CREATE VIEW "receipts_posted_not_invoiced" AS
+ SELECT
+ r."id",
+ r."receiptId",
+ r."sourceDocument",
+ r."sourceDocumentId",
+ r."sourceDocumentReadableId",
+ r."postingDate",
+ r."supplierId",
+ s."name" AS "supplierName",
+ SUM(l."receivedQuantity" * l."unitPrice") AS "estimatedCost"
+ FROM "receipt" r
+ INNER JOIN "receiptLine" l
+ ON l."receiptId" = r."receiptId"
+ INNER JOIN "supplier" s
+ ON s."id" = r."supplierId"
+ WHERE r."status" = 'Posted'
+ AND r."invoiced" = FALSE
+ AND r."sourceDocument" != 'Manufacturing Consumption'
+ AND r."sourceDocument" != 'Manufacturing Output'
+ AND r."sourceDocument" != 'Inbound Transfer'
+ AND r."sourceDocument" != 'Outbound Transfer'
+
+ GROUP BY
+ r."id",
+ r."receiptId",
+ r."sourceDocument",
+ r."sourceDocumentId",
+ r."sourceDocumentReadableId",
+ r."postingDate",
+ r."supplierId",
+ s."name";
+;
+
+CREATE VIEW "total_receipts_posted_not_invoiced" AS
+ SELECT SUM(l."receivedQuantity" * l."unitPrice") AS "total"
+ FROM "receipt" r
+ INNER JOIN "receiptLine" l
+ ON l."receiptId" = r."receiptId"
+ WHERE r."status" = 'Posted'
+ AND r."invoiced" = FALSE
+ AND r."sourceDocument" != 'Manufacturing Consumption'
+ AND r."sourceDocument" != 'Manufacturing Output'
+ AND r."sourceDocument" != 'Inbound Transfer'
+ AND r."sourceDocument" != 'Outbound Transfer';
+```
+
+
+
+## `quantity-on-hand`
+
+```sql
+CREATE VIEW "part_quantities_view" AS
+ SELECT
+ p."id" AS "partId",
+ loc."id" AS "locationId",
+ COALESCE(SUM(pl."quantity"), 0) AS "quantityOnHand",
+ COALESCE(pol."quantityToReceive", 0) AS "quantityOnPurchaseOrder",
+ 0 AS "quantityOnSalesOrder",
+ 0 AS "quantityOnProdOrder",
+ 0 AS "quantityAvailable"
+ FROM "part" p
+ CROSS JOIN "location" loc
+ LEFT JOIN "partLedger" pl
+ ON pl."partId" = p."id" AND pl."locationId" = loc."id"
+ LEFT JOIN (
+ SELECT
+ pol."partId",
+ pol."locationId",
+ COALESCE(SUM(GREATEST(pol."quantityToReceive", 0)), 0) AS "quantityToReceive"
+ FROM "purchaseOrderLine" pol
+ INNER JOIN "purchaseOrder" po
+ ON pol."purchaseOrderId" = po."id"
+ WHERE po."status" != 'Draft'
+ AND po."status" != 'Rejected'
+ AND po."status" != 'Closed'
+ GROUP BY
+ pol."partId",
+ pol."locationId"
+ ) pol ON pol."partId" = p."id" AND pol."locationId" = loc."id"
+ GROUP BY
+ p."id",
+ loc."id",
+ pol."quantityToReceive"
+```
+
diff --git a/apps/carbon/README.md b/apps/carbon/README.md
index b1923908c1..a12b4db1a1 100644
--- a/apps/carbon/README.md
+++ b/apps/carbon/README.md
@@ -13,7 +13,7 @@ ERP Application built with:
### `app/components`
-Reusable react components that are specific to this project (and remix). Shared components should live in `packages/carbon-react` if they don't rely on some application-specific library. For example, the `Table` relies on some remix internals, so it lives in `app/components`, but the `Date` component is framework agnostic, so it lives in `packages/carbon-react`.
+Reusable react components that are specific to this project (and remix). Shared components should live in `packages/react` if they don't rely on some application-specific library. For example, the `Table` relies on some remix internals, so it lives in `app/components`, but the `Date` component is framework agnostic, so it lives in `packages/react`.
### `app/interfaces`
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
index dfa9ae0cc9..63efce4c06 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -96,7 +96,7 @@ const EditablePurchaseOrderLineNumber =
.from("partInventory")
.select("defaultShelfId")
.eq("partId", partId)
- .eq("locationId", options.defaultLocationId)
+ .eq("locationId", options.defaultLocationId!)
.single(),
client
.from("partCost")
@@ -110,12 +110,6 @@ const EditablePurchaseOrderLineNumber =
return;
}
- console.log({
- partId,
- locationId: options.defaultLocationId,
- shelfId: shelf.data?.defaultShelfId,
- });
-
onUpdate("partId", partId);
onUpdate("description", part.data?.name);
onUpdate("assetId", null);
diff --git a/apps/carbon/app/components/Form/AccountSubcategory.tsx b/apps/carbon/app/components/Form/AccountSubcategory.tsx
index fe82693ebe..bae7d13f80 100644
--- a/apps/carbon/app/components/Form/AccountSubcategory.tsx
+++ b/apps/carbon/app/components/Form/AccountSubcategory.tsx
@@ -1,15 +1,17 @@
import { Select } from "@carbon/react";
import {
FormControl,
- FormLabel,
FormErrorMessage,
FormHelperText,
+ FormLabel,
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField, useControlField } from "remix-validated-form";
-import type { AccountSubcategory as AccountSubcategoryType } from "~/modules/accounting";
-import type { getAccountSubcategoriesByCategory } from "~/modules/accounting";
+import { useControlField, useField } from "remix-validated-form";
+import type {
+ AccountSubcategory as AccountSubcategoryType,
+ getAccountSubcategoriesByCategory,
+} from "~/modules/accounting";
import { mapRowsToOptions } from "~/utils/form";
const AccountSubcategory = ({
diff --git a/apps/carbon/app/components/Form/Color.tsx b/apps/carbon/app/components/Form/Color.tsx
index f3830477fb..4460e35236 100644
--- a/apps/carbon/app/components/Form/Color.tsx
+++ b/apps/carbon/app/components/Form/Color.tsx
@@ -1,17 +1,17 @@
import { useColor } from "@carbon/react";
import {
Box,
+ Button,
FormControl,
+ FormErrorMessage,
FormLabel,
HStack,
useDisclosure,
- Button,
useOutsideClick,
- FormErrorMessage,
} from "@chakra-ui/react";
-import { HexColorInput, HexColorPicker } from "react-colorful";
import { useRef } from "react";
+import { HexColorInput, HexColorPicker } from "react-colorful";
import { useControlField, useField } from "remix-validated-form";
type ColorFieldProps = {
diff --git a/apps/carbon/app/components/Form/CustomerContact.tsx b/apps/carbon/app/components/Form/CustomerContact.tsx
index 55c29d6aa9..78a69b5a8e 100644
--- a/apps/carbon/app/components/Form/CustomerContact.tsx
+++ b/apps/carbon/app/components/Form/CustomerContact.tsx
@@ -8,8 +8,10 @@ import {
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo, useRef } from "react";
import { useControlField, useField } from "remix-validated-form";
-import type { CustomerContact as CustomerContactType } from "~/modules/sales";
-import type { getCustomerContacts } from "~/modules/sales";
+import type {
+ CustomerContact as CustomerContactType,
+ getCustomerContacts,
+} from "~/modules/sales";
import type { SelectProps } from "./Select";
type CustomerContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {
diff --git a/apps/carbon/app/components/Form/CustomerLocation.tsx b/apps/carbon/app/components/Form/CustomerLocation.tsx
index b5bdc0300a..6df2d41bf3 100644
--- a/apps/carbon/app/components/Form/CustomerLocation.tsx
+++ b/apps/carbon/app/components/Form/CustomerLocation.tsx
@@ -8,8 +8,10 @@ import {
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo, useRef } from "react";
import { useControlField, useField } from "remix-validated-form";
-import type { CustomerLocation as CustomerLocationType } from "~/modules/sales";
-import type { getCustomerLocations } from "~/modules/sales";
+import type {
+ CustomerLocation as CustomerLocationType,
+ getCustomerLocations,
+} from "~/modules/sales";
import type { SelectProps } from "./Select";
type CustomerLocationSelectProps = Omit<SelectProps, "options" | "onChange"> & {
diff --git a/apps/carbon/app/components/Form/DatePicker.tsx b/apps/carbon/app/components/Form/DatePicker.tsx
index 5ec6b0b6ad..548b221bfb 100644
--- a/apps/carbon/app/components/Form/DatePicker.tsx
+++ b/apps/carbon/app/components/Form/DatePicker.tsx
@@ -1,7 +1,7 @@
import { DatePicker as CarbonDatePicker } from "@carbon/react";
+import { FormControl, FormErrorMessage, FormLabel } from "@chakra-ui/react";
import type { CalendarDate } from "@internationalized/date";
import { parseDate } from "@internationalized/date";
-import { FormControl, FormErrorMessage, FormLabel } from "@chakra-ui/react";
import { useState } from "react";
import { useField } from "remix-validated-form";
diff --git a/apps/carbon/app/components/Form/RichText.tsx b/apps/carbon/app/components/Form/RichText.tsx
index a2f9ed66a3..c27b0f8871 100644
--- a/apps/carbon/app/components/Form/RichText.tsx
+++ b/apps/carbon/app/components/Form/RichText.tsx
@@ -1,7 +1,6 @@
import { Editor, useEditor } from "@carbon/react";
import type { BoxProps } from "@chakra-ui/react";
-import { Input } from "@chakra-ui/react";
-import { FormControl, FormErrorMessage } from "@chakra-ui/react";
+import { FormControl, FormErrorMessage, Input } from "@chakra-ui/react";
import { useEffect } from "react";
import { useControlField, useField } from "remix-validated-form";
diff --git a/apps/carbon/app/components/Form/Submit.tsx b/apps/carbon/app/components/Form/Submit.tsx
index 74a1a2f7c6..7b12e43792 100644
--- a/apps/carbon/app/components/Form/Submit.tsx
+++ b/apps/carbon/app/components/Form/Submit.tsx
@@ -8,7 +8,7 @@ export const Submit = ({
children,
...props
}: PropsWithChildren<ButtonProps & { formId?: string; text?: string }>) => {
- const isSubmitting = useIsSubmitting();
+ const isSubmitting = useIsSubmitting(formId);
return (
<Button
form={formId}
diff --git a/apps/carbon/app/components/Form/SupplierContact.tsx b/apps/carbon/app/components/Form/SupplierContact.tsx
index b04f4c97f9..7a84967860 100644
--- a/apps/carbon/app/components/Form/SupplierContact.tsx
+++ b/apps/carbon/app/components/Form/SupplierContact.tsx
@@ -1,13 +1,13 @@
import { Select } from "@carbon/react";
import {
FormControl,
- FormLabel,
FormErrorMessage,
FormHelperText,
+ FormLabel,
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField, useControlField } from "remix-validated-form";
+import { useControlField, useField } from "remix-validated-form";
import type { getSupplierContacts } from "~/modules/purchasing";
import { mapRowsToOptions } from "~/utils/form";
diff --git a/apps/carbon/app/components/Form/SupplierLocation.tsx b/apps/carbon/app/components/Form/SupplierLocation.tsx
index 9b62e4e27a..381d5e9ff3 100644
--- a/apps/carbon/app/components/Form/SupplierLocation.tsx
+++ b/apps/carbon/app/components/Form/SupplierLocation.tsx
@@ -8,8 +8,10 @@ import {
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo, useRef } from "react";
import { useControlField, useField } from "remix-validated-form";
-import type { SupplierLocation as SupplierLocationType } from "~/modules/purchasing";
-import type { getSupplierLocations } from "~/modules/purchasing";
+import type {
+ getSupplierLocations,
+ SupplierLocation as SupplierLocationType,
+} from "~/modules/purchasing";
import type { SelectProps } from "./Select";
type SupplierLocationSelectProps = Omit<SelectProps, "options" | "onChange"> & {
diff --git a/apps/carbon/app/components/Form/TimePicker.tsx b/apps/carbon/app/components/Form/TimePicker.tsx
index 5a4689b0ac..f9aade3599 100644
--- a/apps/carbon/app/components/Form/TimePicker.tsx
+++ b/apps/carbon/app/components/Form/TimePicker.tsx
@@ -1,11 +1,11 @@
import { TimePicker as CarbonTimePicker } from "@carbon/react";
+import { FormControl, FormErrorMessage, FormLabel } from "@chakra-ui/react";
import type {
CalendarDateTime,
Time,
ZonedDateTime,
} from "@internationalized/date";
import { parseTime } from "@internationalized/date";
-import { FormControl, FormErrorMessage, FormLabel } from "@chakra-ui/react";
import { useState } from "react";
import { useField } from "remix-validated-form";
diff --git a/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx
index 557f86d409..df3185f6b0 100644
--- a/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/CollapsibleSidebar.tsx
@@ -32,6 +32,7 @@ export const CollapsibleSidebar = ({ children }: PropsWithChildren<{}>) => {
h="calc(100vh - 50px)"
position="sticky"
top={50}
+ zIndex={3}
>
<Tooltip label={sidebar.isOpen ? "Collapse" : "Expand"} placement="right">
<IconButton
diff --git a/apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsx
index 21871bca98..2c62cf69e3 100644
--- a/apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsx
@@ -3,9 +3,9 @@ import {
Box,
IconButton,
Tooltip,
- VStack,
useDisclosure,
useOutsideClick,
+ VStack,
} from "@chakra-ui/react";
import { motion } from "framer-motion";
import type { ReactElement } from "react";
diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsx
index 7505d96bbf..9ea8b0dea5 100644
--- a/apps/carbon/app/components/Search/Search/Search.tsx
+++ b/apps/carbon/app/components/Search/Search/Search.tsx
@@ -3,10 +3,14 @@ import { clip } from "@carbon/utils";
import type { ButtonProps } from "@chakra-ui/react";
import {
Box,
+ Button,
+ Flex,
+ HStack,
Icon,
Input,
InputGroup,
InputLeftElement,
+ Kbd,
List,
ListItem,
Modal,
@@ -14,10 +18,9 @@ import {
ModalContent,
ModalOverlay,
Text,
- VStack,
useDisclosure,
+ VStack,
} from "@chakra-ui/react";
-import { Button, Flex, HStack, Kbd } from "@chakra-ui/react";
import { Link, useNavigate } from "@remix-run/react";
import { useCallback, useEffect, useRef, useState } from "react";
import { AiOutlinePartition } from "react-icons/ai";
@@ -225,9 +228,13 @@ const SearchModal = ({
<Result
key={result.uuid}
result={result}
- selected={selectedIndex === resultIndex}
+ selected={
+ selectedIndex === resultIndex + moduleResults.length
+ }
onClick={onResultClick}
- onHover={() => setSelectedIndex(resultIndex)}
+ onHover={() =>
+ setSelectedIndex(resultIndex + moduleResults.length)
+ }
/>
))}
</List>
diff --git a/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx b/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx
index 8e69095c9f..3b05290200 100644
--- a/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx
+++ b/apps/carbon/app/components/Selectors/CustomerSelect/CustomerSelect.tsx
@@ -1,4 +1,4 @@
-import { Select, createFilter } from "@carbon/react";
+import { createFilter, Select } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useEffect } from "react";
import type { getCustomersList } from "~/modules/sales";
diff --git a/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx b/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx
index d272ecb01b..d89c927bb5 100644
--- a/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx
+++ b/apps/carbon/app/components/Selectors/SupplierSelect/SupplierSelect.tsx
@@ -1,4 +1,4 @@
-import { Select, createFilter } from "@carbon/react";
+import { createFilter, Select } from "@carbon/react";
import { useFetcher } from "@remix-run/react";
import { useEffect } from "react";
import type { getSuppliersList } from "~/modules/purchasing";
diff --git a/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx
index c40a19960d..34395285a6 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx
+++ b/apps/carbon/app/components/Selectors/UserSelect/UserSelect.tsx
@@ -10,18 +10,18 @@
* @see WAI-ARIA Tree View https://www.w3.org/WAI/ARIA/apg/patterns/treeview/
*/
+import { Select } from "@carbon/react";
import { FormLabel } from "@chakra-ui/react";
+import { usePermissions } from "~/hooks";
import Combobox from "./components/Combobox";
import Container from "./components/Container";
import Input from "./components/Input";
import Popover from "./components/Popover";
import SelectionList from "./components/SelectionList";
import TreeSelect from "./components/TreeSelect";
-import type { UserSelectProps } from "./types";
import { UserSelectContext } from "./provider";
+import type { UserSelectProps } from "./types";
import useUserSelect from "./useUserSelect";
-import { usePermissions } from "~/hooks";
-import { Select } from "@carbon/react";
export default function Component(props: UserSelectProps) {
const permissions = usePermissions();
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
index 1db7618463..ab7a4306a5 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx
@@ -10,7 +10,7 @@ import {
Tooltip,
} from "@chakra-ui/react";
import { useMemo } from "react";
-import { MdPlaylistAdd, MdOutlineClear } from "react-icons/md";
+import { MdOutlineClear, MdPlaylistAdd } from "react-icons/md";
import { Avatar } from "~/components";
import useUserSelectContext from "../provider";
import { isGroup } from "../useUserSelect";
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
index 244757de73..48f9a97dab 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
@@ -2,8 +2,8 @@ import { Loading } from "@carbon/react";
import type { IconProps } from "@chakra-ui/react";
import { Box, HStack, Icon, List, ListItem, Text } from "@chakra-ui/react";
import { FaCheck, FaChevronRight } from "react-icons/fa";
-import type { OptionGroup, IndividualOrGroup } from "../types";
import useUserSelectContext from "../provider";
+import type { IndividualOrGroup, OptionGroup } from "../types";
import { useGroupStyles, useOptionStyles } from "./useUserSelectStyles";
const UserTreeSelect = () => {
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 8f93ea58dc..9dd1e20dc7 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -3,17 +3,17 @@ import { clip } from "@carbon/utils";
import type { ThemeTypings } from "@chakra-ui/react";
import {
Box,
+ chakra,
Flex,
Grid,
MenuList,
Table as ChakraTable,
Tbody,
- Thead,
Th,
+ Thead,
Tr,
VisuallyHidden,
VStack,
- chakra,
} from "@chakra-ui/react";
import type {
ColumnDef,
@@ -27,18 +27,18 @@ import {
useReactTable,
} from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { FaSort, FaSortUp, FaSortDown } from "react-icons/fa";
+import { FaSort, FaSortDown, FaSortUp } from "react-icons/fa";
import type {
EditableTableCellComponent,
Position,
} from "~/components/Editable";
import {
- TableHeader,
IndeterminateCheckbox,
Pagination,
+ Row,
+ TableHeader,
usePagination,
useSort,
- Row,
} from "./components";
import type { TableAction } from "./types";
import { getAccessorKey, updateNestedProperty } from "./utils";
diff --git a/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx b/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx
index 4c4777f66d..55e438233c 100644
--- a/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx
+++ b/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx
@@ -7,8 +7,8 @@ import {
IconButton,
Menu,
MenuButton,
- MenuList,
MenuItem,
+ MenuList,
} from "@chakra-ui/react";
import { BsChevronLeft, BsChevronRight } from "react-icons/bs";
diff --git a/apps/carbon/app/components/Table/components/Row/Row.tsx b/apps/carbon/app/components/Table/components/Row/Row.tsx
index 18f7a9aabb..adbfe661ba 100644
--- a/apps/carbon/app/components/Table/components/Row/Row.tsx
+++ b/apps/carbon/app/components/Table/components/Row/Row.tsx
@@ -3,11 +3,11 @@ import { Tr } from "@chakra-ui/react";
import type { Row as RowType } from "@tanstack/react-table";
import type { MutableRefObject } from "react";
import { memo } from "react";
-import Cell from "../Cell";
import type {
EditableTableCellComponent,
Position,
} from "~/components/Editable";
+import Cell from "../Cell";
type RowProps<T> = {
borderColor: string;
diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.ts
index 8baef2ccb3..ee084b09b2 100644
--- a/apps/carbon/app/hooks/index.ts
+++ b/apps/carbon/app/hooks/index.ts
@@ -1,12 +1,14 @@
import { useMovingCellRef } from "./useMovingCellRef";
import { usePermissions } from "./usePermissions";
+import { useRealtime } from "./useRealtime";
import { useRouteData } from "./useRouteData";
-import { useUser } from "./useUser";
import { useUrlParams } from "./useUrlParams";
+import { useUser } from "./useUser";
export {
useMovingCellRef,
usePermissions,
+ useRealtime,
useRouteData,
useUser,
useUrlParams,
diff --git a/apps/carbon/app/hooks/useRealtime.tsx b/apps/carbon/app/hooks/useRealtime.tsx
index 1bd5d65aa2..d13d463140 100644
--- a/apps/carbon/app/hooks/useRealtime.tsx
+++ b/apps/carbon/app/hooks/useRealtime.tsx
@@ -2,29 +2,30 @@ import { useRevalidator } from "@remix-run/react";
import { useEffect } from "react";
import { useSupabase } from "~/lib/supabase";
-export function useRealtime(tables: string[]) {
- const { supabase } = useSupabase();
+export function useRealtime(table: string, filter?: string) {
+ const { accessToken, supabase } = useSupabase();
const revalidator = useRevalidator();
+
useEffect(() => {
- if (!supabase) return;
- const subscriptions = supabase.channel("changes");
+ if (!supabase || !accessToken || !table) return;
+ supabase.realtime.setAuth(accessToken);
- tables.forEach((table) => {
- subscriptions.on(
+ const channel = supabase
+ .channel(`postgres_changes:${table}}`)
+ .on(
"postgres_changes",
{
event: "*",
schema: "public",
table: table,
+ filter: filter,
},
revalidator.revalidate
- );
- });
-
- const channel = subscriptions.subscribe();
+ )
+ .subscribe();
return () => {
if (channel) supabase?.removeChannel(channel);
};
- }, [revalidator.revalidate, supabase, tables]);
+ }, [revalidator.revalidate, supabase, table, filter, accessToken]);
}
diff --git a/apps/carbon/app/lib/supabase/client.ts b/apps/carbon/app/lib/supabase/client.ts
index 9f73f7d1e8..c233c9dc6d 100644
--- a/apps/carbon/app/lib/supabase/client.ts
+++ b/apps/carbon/app/lib/supabase/client.ts
@@ -2,8 +2,11 @@ import type { Database } from "@carbon/database";
import { isBrowser } from "@carbon/utils";
import { createClient } from "@supabase/supabase-js";
-import { SUPABASE_API_URL, SUPABASE_ANON_PUBLIC } from "~/config/env";
-import { SUPABASE_SERVICE_ROLE } from "~/config/env";
+import {
+ SUPABASE_ANON_PUBLIC,
+ SUPABASE_API_URL,
+ SUPABASE_SERVICE_ROLE,
+} from "~/config/env";
const getSupabaseClient = (supabaseKey: string, accessToken?: string) => {
const global = accessToken
@@ -16,13 +19,15 @@ const getSupabaseClient = (supabaseKey: string, accessToken?: string) => {
}
: {};
- return createClient<Database>(SUPABASE_API_URL, supabaseKey, {
+ const client = createClient<Database>(SUPABASE_API_URL, supabaseKey, {
auth: {
autoRefreshToken: false,
persistSession: false,
},
...global,
});
+
+ return client;
};
/**
diff --git a/apps/carbon/app/lib/supabase/provider.tsx b/apps/carbon/app/lib/supabase/provider.tsx
index 327ab538a5..0dab9bb95e 100644
--- a/apps/carbon/app/lib/supabase/provider.tsx
+++ b/apps/carbon/app/lib/supabase/provider.tsx
@@ -4,7 +4,14 @@ import { isBrowser } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { ReactElement } from "react";
-import { createContext, useContext, useState, useMemo, useRef } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import type { AuthSession } from "~/services/auth";
import { getSupabase } from "./client";
@@ -107,7 +114,7 @@ export const SupabaseProvider = ({
session: Partial<AuthSession>;
}) => {
// what root loader data returns
- const { accessToken, expiresIn, expiresAt } = session;
+ const { accessToken, refreshToken, expiresIn, expiresAt } = session;
const [browserSessionExpiresAt, setBrowserSessionExpiresAt] = useState<
number | undefined
>();
@@ -143,6 +150,15 @@ export const SupabaseProvider = ({
setBrowserSessionExpiresAt(expiresAt);
}
+ useEffect(() => {
+ if (!supabase || !accessToken || !refreshToken) return;
+
+ supabase.auth.setSession({
+ access_token: accessToken,
+ refresh_token: refreshToken,
+ });
+ }, [accessToken, refreshToken, supabase]);
+
const value = useMemo(
() => ({ supabase, accessToken }),
[supabase, accessToken]
diff --git a/apps/carbon/app/lib/timezones.ts b/apps/carbon/app/lib/timezones.ts
index b65bd8dc9e..65e4d295f1 100644
--- a/apps/carbon/app/lib/timezones.ts
+++ b/apps/carbon/app/lib/timezones.ts
@@ -1,4 +1,4 @@
-import type { OptionBase, GroupBase } from "@carbon/react";
+import type { GroupBase, OptionBase } from "@carbon/react";
export interface TimeZoneSelection extends OptionBase {
label: string;
diff --git a/apps/carbon/app/modules/accounting/services/accounting.form.ts b/apps/carbon/app/modules/accounting/services/accounting.form.ts
index e5881aa24e..1379bc1645 100644
--- a/apps/carbon/app/modules/accounting/services/accounting.form.ts
+++ b/apps/carbon/app/modules/accounting/services/accounting.form.ts
@@ -2,7 +2,7 @@ import { withZod } from "@remix-validated-form/with-zod";
import { z } from "zod";
import { zfd } from "zod-form-data";
-export const accountDocumentLedgerType = [
+export const generalLedgerDocumentType = [
"Quote",
"Order",
"Invoice",
@@ -126,15 +126,15 @@ export const accountCategoryValidator = withZod(
})
);
-export const accountLedgerValidator = withZod(
+export const generalLedgerValidator = withZod(
z.object({
- postingDate: z.string().min(1, { message: "Posting date is required" }),
+ postingDate: zfd.text(z.string().optional()),
accountNumber: z.string().min(1, { message: "Account is required" }),
description: z.string().optional(),
amount: z.number(),
- documentType: z.union([z.enum(accountDocumentLedgerType), z.undefined()]),
- documentNumber: z.string().optional(),
- externalDocumentNumber: z.string().optional(),
+ documentType: z.union([z.enum(generalLedgerDocumentType), z.undefined()]),
+ documentId: z.string().optional(),
+ externalDocumentId: z.string().optional(),
})
);
@@ -281,19 +281,14 @@ export const defaultAcountValidator = withZod(
export const partLedgerValidator = withZod(
z.object({
- postingDate: z.string().min(1, { message: "Posting date is required" }),
+ postingDate: zfd.text(z.string().optional()),
entryType: z.enum(partLedgerTypes),
documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),
- documentNumber: z.string().optional(),
+ documentId: z.string().optional(),
partId: z.string().min(1, { message: "Part is required" }),
locationId: z.string().optional(),
shelfId: z.string().optional(),
quantity: z.number(),
- invoicedQuantity: z.number(),
- remainingQuantity: z.number(),
- salesAmount: z.number(),
- costAmount: z.number(),
- open: z.boolean(),
})
);
@@ -331,12 +326,12 @@ export const paymentTermValidator = withZod(
export const valueLedgerValidator = withZod(
z.object({
- postingDate: z.string(),
+ postingDate: zfd.text(z.string().optional()),
partLedgerType: z.enum(partLedgerTypes),
costLedgerType: z.enum(costLedgerTypes),
adjustment: z.boolean(),
documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),
- documentNumber: z.string().optional(),
+ documentId: z.string().optional(),
costAmountActual: z.number(),
costAmountExpected: z.number(),
actualCostPostedToGl: z.number(),
diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.ts
index c39e06b2fb..d7ba28b772 100644
--- a/apps/carbon/app/modules/accounting/services/accounting.server.ts
+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts
@@ -1,8 +1,6 @@
import type { Database } from "@carbon/database";
import { getDateNYearsAgo } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import type { ReceiptLine } from "~/modules/inventory";
import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
@@ -10,11 +8,11 @@ import { sanitize } from "~/utils/supabase";
import type { Account, Transaction } from "../types";
import type {
accountCategoryValidator,
- accountLedgerValidator,
accountSubcategoryValidator,
accountValidator,
currencyValidator,
defaultAcountValidator,
+ generalLedgerValidator,
partLedgerValidator,
paymentTermValidator,
valueLedgerValidator,
@@ -389,6 +387,30 @@ export async function getDefaultAccounts(client: SupabaseClient<Database>) {
return client.from("accountDefault").select("*").eq("id", true).single();
}
+export async function getInventoryPostingGroup(
+ client: SupabaseClient<Database>,
+ args: {
+ partGroupId: string | null;
+ locationId: string | null;
+ }
+) {
+ let query = client.from("postingGroupInventory").select("*");
+
+ if (args.partGroupId === null) {
+ query = query.is("partGroupId", null);
+ } else {
+ query = query.eq("partGroupId", args.partGroupId);
+ }
+
+ if (args.locationId === null) {
+ query = query.is("locationId", null);
+ } else {
+ query = query.eq("locationId", args.locationId);
+ }
+
+ return query.single();
+}
+
export async function getInventoryPostingGroups(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
@@ -452,6 +474,30 @@ export async function getPaymentTermsList(client: SupabaseClient<Database>) {
.order("name", { ascending: true });
}
+export async function getPurchasingPostingGroup(
+ client: SupabaseClient<Database>,
+ args: {
+ partGroupId: string | null;
+ supplierTypeId: string | null;
+ }
+) {
+ let query = client.from("postingGroupInventory").select("*");
+
+ if (args.partGroupId === null) {
+ query = query.is("partGroupId", null);
+ } else {
+ query = query.eq("partGroupId", args.partGroupId);
+ }
+
+ if (args.supplierTypeId === null) {
+ query = query.is("supplierTypeId", null);
+ } else {
+ query = query.eq("supplierTypeId", args.supplierTypeId);
+ }
+
+ return query.single();
+}
+
export async function getPurchasingPostingGroups(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
@@ -475,6 +521,30 @@ export async function getPurchasingPostingGroups(
return query;
}
+export async function getPurchasingSalesGroup(
+ client: SupabaseClient<Database>,
+ args: {
+ partGroupId: string | null;
+ customerTypeId: string | null;
+ }
+) {
+ let query = client.from("postingGroupInventory").select("*");
+
+ if (args.partGroupId === null) {
+ query = query.is("partGroupId", null);
+ } else {
+ query = query.eq("partGroupId", args.partGroupId);
+ }
+
+ if (args.customerTypeId === null) {
+ query = query.is("customerTypeId", null);
+ } else {
+ query = query.eq("customerTypeId", args.customerTypeId);
+ }
+
+ return query.single();
+}
+
export async function getSalesPostingGroups(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
@@ -498,54 +568,46 @@ export async function getSalesPostingGroups(
return query;
}
-export async function insertAccountEntries(
+export async function insertGeneralLedgerEntries(
client: SupabaseClient<Database>,
- accountEntries: TypeOfValidator<typeof accountLedgerValidator>[]
+ generalEntries: TypeOfValidator<typeof generalLedgerValidator>[]
) {
- return client
- .from("accountLedger")
- .insert(accountEntries)
- .select("id")
- .single();
+ return client.from("generalLedger").insert(generalEntries);
}
-export async function insertAccountLedger(
+export async function insertGeneralLedgerEntry(
client: SupabaseClient<Database>,
- accountEntry: TypeOfValidator<typeof accountLedgerValidator>
+ generalEntry: TypeOfValidator<typeof generalLedgerValidator>
) {
- return client
- .from("accountLedger")
- .insert([accountEntry])
- .select("id")
- .single();
+ return client.from("generalLedger").insert([generalEntry]);
}
export async function insertPartEntries(
client: SupabaseClient<Database>,
partEntries: TypeOfValidator<typeof partLedgerValidator>[]
) {
- return client.from("partLedger").insert(partEntries).select("id").single();
+ return client.from("partLedger").insert(partEntries);
}
export async function insertPartLedger(
client: SupabaseClient<Database>,
partEntry: TypeOfValidator<typeof partLedgerValidator>
) {
- return client.from("partLedger").insert([partEntry]).select("id").single();
+ return client.from("partLedger").insert([partEntry]);
}
export async function insertValueEntries(
client: SupabaseClient<Database>,
valueEntries: TypeOfValidator<typeof valueLedgerValidator>[]
) {
- return client.from("valueLedger").insert(valueEntries).select("id").single();
+ return client.from("valueLedger").insert(valueEntries);
}
export async function insertValueLedger(
client: SupabaseClient<Database>,
valueEntry: TypeOfValidator<typeof valueLedgerValidator>
) {
- return client.from("valueLedger").insert([valueEntry]).select("id").single();
+ return client.from("valueLedger").insert([valueEntry]);
}
export async function updateDefaultAccounts(
@@ -557,81 +619,6 @@ export async function updateDefaultAccounts(
return client.from("accountDefault").update(defaultAccounts).eq("id", true);
}
-export async function postReceiptWithExpectedCost(receiptId: string) {
- const client = getSupabaseServiceRole();
- const [receipt, receiptLines] = await Promise.all([
- client.from("receipt").select("*").eq("id", receiptId).single(),
- client.from("receiptLine").select("*").eq("receiptId", receiptId),
- ]);
-
- if (receipt.error) return receipt;
- if (receiptLines.error) return receiptLines;
-
- switch (receipt.data?.sourceDocument) {
- case "Purchase Order":
- // TODO: this should all be done as a transaction
- const purchaseOrderLines = await client
- .from("purchaseOrderLine")
- .select("*")
- .eq("purchaseOrderId", receipt.data.sourceDocumentId);
- if (purchaseOrderLines.error) return purchaseOrderLines;
-
- const receiptLinesByLineId = receiptLines.data.reduce<
- Record<string, ReceiptLine>
- >((acc, receiptLine) => {
- if (receiptLine.lineId) {
- acc[receiptLine.lineId] = receiptLine;
- }
- return acc;
- }, {});
-
- // First, update the quantity received on the purchase order lines
- purchaseOrderLines.data.forEach(async (purchaseOrderLine) => {
- const receiptLine = receiptLinesByLineId[purchaseOrderLine.id];
- if (!receiptLine) return;
-
- if (!purchaseOrderLine.purchaseQuantity) return;
-
- const newQuantityReceived =
- (purchaseOrderLine.quantityReceived ?? 0) +
- receiptLine.receivedQuantity;
-
- const newQuantityToReceive =
- (purchaseOrderLine.quantityToReceive ??
- purchaseOrderLine.purchaseQuantity) - receiptLine.receivedQuantity;
-
- const receivedComplete =
- receiptLine.receivedQuantity >=
- (purchaseOrderLine.quantityToReceive ??
- purchaseOrderLine.purchaseQuantity);
-
- let purchaseOrderLineUpdate = await client
- .from("purchaseOrderLine")
- .update({
- quantityReceived: newQuantityReceived,
- quantityToReceive: newQuantityToReceive,
- receivedComplete,
- })
- .eq("id", purchaseOrderLine.id);
-
- if (purchaseOrderLineUpdate.error) return purchaseOrderLineUpdate;
- });
-
- // Next, make the following entries for each line on the receipt:
- // - a value ledger entry for the value of the receipt
- // - a part ledger entry for the quantity received
- // - a G/L entry to debit interim inventory accrual
- // - a G/L entry to credit inventory received not invoiced
- receiptLines.data.forEach(async (receiptLine) => {
- // TODO:
- });
-
- break;
- default:
- break;
- }
-}
-
export async function upsertAccount(
client: SupabaseClient<Database>,
account:
diff --git a/apps/carbon/app/modules/accounting/ui/useAccountingSidebar.tsx b/apps/carbon/app/modules/accounting/ui/useAccountingSidebar.tsx
index 53fdfc981b..0d11a8f201 100644
--- a/apps/carbon/app/modules/accounting/ui/useAccountingSidebar.tsx
+++ b/apps/carbon/app/modules/accounting/ui/useAccountingSidebar.tsx
@@ -5,12 +5,27 @@ const accountingRoutes: AuthenticatedRouteGroup[] = [
{
name: "Manage",
routes: [
+ {
+ name: "Accounts Payable",
+ to: "/x/accounting/payable",
+ role: "employee",
+ },
+ // {
+ // name: "Accounts Receivable",
+ // to: "/x/accounting/receivable",
+ // role: "employee",
+ // },
{
name: "Chart of Accounts",
to: "/x/accounting/charts",
role: "employee",
},
// {
+ // name: "Payments",
+ // to: "/x/accounting/payments",
+ // role: "employee",
+ // },
+ // {
// name: "Journal Entries",
// to: "/x/accounting/journals",
// role: "employee",
@@ -20,6 +35,16 @@ const accountingRoutes: AuthenticatedRouteGroup[] = [
{
name: "Posting Groups",
routes: [
+ // {
+ // name: "Bank Account Groups",
+ // to: "/x/accounting/groups/bank",
+ // role: "employee",
+ // },
+ // {
+ // name: "Fixed Asset Groups",
+ // to: "/x/accounting/groups/fixed-asset",
+ // role: "employee",
+ // },
{
name: "Inventory Groups",
to: "/x/accounting/groups/inventory",
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx
index f31f191983..f32b4dcde7 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable/DocumentsTable.tsx
@@ -32,8 +32,8 @@ import { VscOpenPreview } from "react-icons/vsc";
import { Avatar, Table } from "~/components";
import { Confirm, ConfirmDelete } from "~/components/Modals";
import { useUrlParams } from "~/hooks";
-import { DocumentIcon } from "~/modules/documents";
import type { Document, DocumentLabel } from "~/modules/documents";
+import { DocumentIcon } from "~/modules/documents";
import { useDocument } from "../useDocument";
type DocumentsTableProps = {
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
index 10744d7ba5..0357dea00a 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
@@ -4,8 +4,8 @@ import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
import type { DocumentLabel } from "~/modules/documents/types";
import { mapRowsToOptions } from "~/utils/form";
-import DocumentCreateForm from "../DocumentCreateForm";
import { capitalize } from "~/utils/string";
+import DocumentCreateForm from "../DocumentCreateForm";
type DocumentTableFiltersProps = {
labels: DocumentLabel[];
diff --git a/apps/carbon/app/modules/inventory/services/inventory.form.ts b/apps/carbon/app/modules/inventory/services/inventory.form.ts
index 1e1c0aa1ba..9b65ef533d 100644
--- a/apps/carbon/app/modules/inventory/services/inventory.form.ts
+++ b/apps/carbon/app/modules/inventory/services/inventory.form.ts
@@ -22,6 +22,7 @@ export const receiptValidator = withZod(
sourceDocumentId: zfd.text(
z.string().min(1, { message: "Source Document ID is required" })
),
+ externalDocumentId: zfd.text(z.string().optional()),
sourceDocumentReadableId: zfd.text(z.string().optional()),
supplierId: zfd.text(z.string().optional()),
})
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
index 4ebd85783a..044f3b1642 100644
--- a/apps/carbon/app/modules/inventory/types.ts
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -1,7 +1,7 @@
import type { Database } from "@carbon/database";
import type {
- getReceipts,
getReceiptLines,
+ getReceipts,
getShippingMethods,
} from "./services";
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
index 2f7506ffc6..aa0e6218ec 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -11,10 +11,10 @@ import {
DrawerOverlay,
FormLabel,
Grid,
- Heading,
HStack,
VStack,
} from "@chakra-ui/react";
+import { Outlet } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
import {
Hidden,
@@ -38,6 +38,8 @@ type ReceiptFormProps = {
receiptLines?: ReceiptLine[];
};
+const formId = "receipt-form";
+
const ReceiptForm = ({
initialValues,
isPosted,
@@ -55,6 +57,7 @@ const ReceiptForm = ({
supplierId,
sourceDocuments,
onClose,
+ onPost,
setLocationId,
setSourceDocument,
setSourceDocumentId,
@@ -64,138 +67,154 @@ const ReceiptForm = ({
});
return (
- <Drawer onClose={onClose} isOpen={true} size="full">
- <ValidatedForm
- validator={receiptValidator}
- method="post"
- action={
- isEditing
- ? `/x/inventory/receipts/${initialValues.id}`
- : `/x/inventory/receipts/new`
- }
- defaultValues={initialValues}
- >
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{initialValues.receiptId}</DrawerHeader>
- <DrawerBody pb={8}>
- <VStack spacing={4} w="full" alignItems="start">
- <Menubar mb={2} mt={-2}>
- <MenubarItem
- onClick={() => alert("post")}
- isDisabled={internalReceiptItems.length === 0 || isPosted}
+ <>
+ <Drawer onClose={onClose} isOpen={true} size="full">
+ <ValidatedForm
+ id={formId}
+ validator={receiptValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/inventory/receipts/${initialValues.id}`
+ : `/x/inventory/receipts/new`
+ }
+ defaultValues={initialValues}
+ style={{ width: "100%" }}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{initialValues.receiptId}</DrawerHeader>
+ <DrawerBody pb={8}>
+ <VStack spacing={4} w="full" alignItems="start">
+ <Menubar mb={2} mt={-2}>
+ <MenubarItem
+ isDisabled={!isEditing || isPosted}
+ onClick={onPost}
+ >
+ Post Receipt
+ </MenubarItem>
+ </Menubar>
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
+ gridColumnGap={8}
+ w="full"
>
- Post Receipt
- </MenubarItem>
- </Menubar>
- <Grid
- gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
- gridColumnGap={8}
- w="full"
- >
- <Box w="full">
- <Hidden name="id" />
- <Hidden
- name="sourceDocumentReadableId"
- value={
- sourceDocuments.find((d) => d.id === sourceDocumentId)
- ?.name ?? ""
- }
- />
- <Hidden name="supplierId" value={supplierId ?? ""} />
- <VStack spacing={4} w="full" alignItems="start" minH="full">
- <Grid
- gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
- gridColumnGap={8}
- gridRowGap={4}
- w="full"
- >
- <Input name="receiptId" label="Receipt ID" isReadOnly />
- <SelectControlled
- name="locationId"
- label="Location"
- options={
- locations.map((l) => ({
- label: l.name,
- value: l.id,
- })) ?? []
- }
- value={locationId ?? undefined}
- onChange={(newValue) =>
- setLocationId(newValue as string)
- }
- isReadOnly={isPosted}
- />
- <Select
- name="sourceDocument"
- label="Source Document"
- options={receiptSourceDocumentType.map((v) => ({
- label: v,
- value: v,
- }))}
- onChange={(newValue) => {
- setSourceDocument(
- newValue.value as ReceiptSourceDocument
- );
- setSourceDocumentId(null);
- }}
- isReadOnly={isPosted}
- />
- <SelectControlled
- name="sourceDocumentId"
- label="Source Document ID"
- options={sourceDocuments.map((d) => ({
- label: d.name,
- value: d.id,
- }))}
- value={sourceDocumentId ?? undefined}
- onChange={(newValue) => {
- setSourceDocumentId(newValue as string);
- }}
- isReadOnly={isPosted}
- />
- </Grid>
- </VStack>
- </Box>
- <VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
- {/* TODO: notes component */}
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="flex-start">
- <Heading size="md">Notes</Heading>
- </HStack>
+ <Box w="full">
+ <Hidden name="id" />
+ <Hidden
+ name="sourceDocumentReadableId"
+ value={
+ sourceDocuments.find((d) => d.id === sourceDocumentId)
+ ?.name ?? ""
+ }
+ />
+ <Hidden name="supplierId" value={supplierId ?? ""} />
+ <VStack spacing={4} w="full" alignItems="start" minH="full">
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={4}
+ w="full"
+ >
+ <Input name="receiptId" label="Receipt ID" isReadOnly />
+ <SelectControlled
+ name="locationId"
+ label="Location"
+ options={
+ locations.map((l) => ({
+ label: l.name,
+ value: l.id,
+ })) ?? []
+ }
+ value={locationId ?? undefined}
+ onChange={(newValue) =>
+ setLocationId(newValue as string)
+ }
+ isReadOnly={isPosted}
+ />
+ <Select
+ name="sourceDocument"
+ label="Source Document"
+ options={receiptSourceDocumentType.map((v) => ({
+ label: v,
+ value: v,
+ }))}
+ onChange={(newValue) => {
+ setSourceDocument(
+ newValue.value as ReceiptSourceDocument
+ );
+ setSourceDocumentId(null);
+ }}
+ isReadOnly={isPosted}
+ />
+ <SelectControlled
+ name="sourceDocumentId"
+ label="Source Document ID"
+ options={sourceDocuments.map((d) => ({
+ label: d.name,
+ value: d.id,
+ }))}
+ value={sourceDocumentId ?? undefined}
+ onChange={(newValue) => {
+ setSourceDocumentId(newValue as string);
+ }}
+ isReadOnly={isPosted}
+ />
+ <Input
+ name="externalDocumentId"
+ label="External Reference"
+ />
+ </Grid>
+ </VStack>
+ </Box>
+ <VStack
+ spacing={8}
+ w="full"
+ alignItems="start"
+ py={[8, 8, 0]}
+ >
+ {/* TODO: notes component */}
+ <VStack alignItems="start" w="full" spacing={4} mb={4}>
+ <HStack w="full" justifyContent="flex-start">
+ <FormLabel>Notes</FormLabel>
+ </HStack>
+ </VStack>
+ {/* end notes component */}
</VStack>
- {/* end notes component */}
+ </Grid>
+ <VStack w="full" alignItems="start">
+ <FormLabel>Receipt Lines</FormLabel>
+ <DataGrid<ReceiptLine>
+ data={internalReceiptItems}
+ columns={receiptLineColumns}
+ canEdit={!isPosted}
+ contained={false}
+ editableComponents={editableComponents}
+ />
</VStack>
- </Grid>
- <VStack w="full" alignItems="start">
- <FormLabel>Receipt Lines</FormLabel>
- <DataGrid<ReceiptLine>
- data={internalReceiptItems}
- columns={receiptLineColumns}
- canEdit={!isPosted}
- contained={false}
- editableComponents={editableComponents}
- />
</VStack>
- </VStack>
- </DrawerBody>
- <DrawerFooter>
- <HStack spacing={2}>
- <Submit isDisabled={isDisabled}>Save</Submit>
- <Button
- size="md"
- colorScheme="gray"
- variant="solid"
- onClick={onClose}
- >
- Cancel
- </Button>
- </HStack>
- </DrawerFooter>
- </DrawerContent>
- </ValidatedForm>
- </Drawer>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit formId={formId} isDisabled={isDisabled}>
+ Save
+ </Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ <Outlet />
+ </>
);
};
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
index 5074939a0f..c28158e32d 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -10,6 +10,7 @@ import type {
ReceiptLineItem,
ReceiptSourceDocument,
} from "~/modules/inventory/types";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
import type { ListItem } from "~/types";
import type { TypeOfValidator } from "~/types/validators";
@@ -56,11 +57,23 @@ export default function useReceiptForm({
receipt.sourceDocumentId ?? null
);
- const onClose = () => {
- if (!sourceDocumentId && receipt.id) {
- deleteReceipt(receipt.id);
+ const onClose = async () => {
+ if (
+ !isEditing &&
+ (!sourceDocumentId || !locationId || receiptLines.length === 0)
+ ) {
+ await deleteReceipt();
}
- navigate(-1);
+
+ if (isEditing) {
+ navigate(`/x/inventory/receipts`);
+ } else {
+ navigate(-1);
+ }
+ };
+
+ const onPost = () => {
+ navigate(`/x/inventory/receipts/${receipt.id}/post`);
};
const sourceDocumentIdFromParams = params.get("sourceDocumentId");
@@ -78,24 +91,28 @@ export default function useReceiptForm({
sourceDocumentIdFromParams,
]);
- // TODO: this should call an API method that uses the service role to delete the receipt after
- // checking that it is not posted or received
- const deleteReceipt = useCallback(
- (id: string) => {
- if (!supabase) return;
+ // TODO: verify that it is not posted or received
+ const deleteReceipt = useCallback(async () => {
+ if (!supabase) return;
+
+ try {
+ await fetch(
+ `/api/settings/sequence/rollback?table=receipt&currentSequence=${receipt.receiptId}`,
+ {
+ method: "DELETE",
+ }
+ )
+ .then(console.log)
+ .catch(console.error);
- return supabase
+ await supabase
.from("receipt")
.delete()
- .eq("id", id)
- .then((response) => {
- if (response.error) {
- setError(response.error.message);
- }
- });
- },
- [supabase]
- );
+ .eq("receiptId", receipt.receiptId);
+ } catch {
+ setError("Failed to delete receipt");
+ }
+ }, [receipt.receiptId, supabase]);
const deleteReceiptItems = useCallback(async () => {
if (!supabase) throw new Error("supabase client is not defined");
@@ -140,21 +157,16 @@ export default function useReceiptForm({
case "Purchase Order":
const [
purchaseOrder,
- purchaseOrderLines,
receiptLines,
previouslyReceivedLines,
+ purchaseOrderLines,
] = await Promise.all([
supabase
.from("purchase_order_view")
.select("*")
.eq("id", sourceDocumentId)
.single(),
- supabase
- .from("purchaseOrderLine")
- .select("*")
- .eq("purchaseOrderId", sourceDocumentId)
- .eq("purchaseOrderLineType", "Part")
- .eq("locationId", locationId),
+
supabase
.from("receiptLine")
.select("*")
@@ -163,6 +175,14 @@ export default function useReceiptForm({
.from("receipt_quantity_received_by_line")
.select("*")
.eq("sourceDocumentId", sourceDocumentId),
+ locationId
+ ? supabase
+ .from("purchaseOrderLine")
+ .select("*")
+ .eq("purchaseOrderId", sourceDocumentId)
+ .eq("purchaseOrderLineType", "Part")
+ .eq("locationId", locationId)
+ : Promise.resolve({ data: [] as PurchaseOrderLine[], error: null }),
]);
if (purchaseOrder.error) {
@@ -218,15 +238,17 @@ export default function useReceiptForm({
return acc;
}
+ const outstandingQuantity =
+ d.purchaseQuantity -
+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0);
+
acc.push({
receiptId: receipt.receiptId,
lineId: d.id,
partId: d.partId,
orderQuantity: d.purchaseQuantity,
- outstandingQuantity:
- d.purchaseQuantity -
- (previouslyReceivedQuantitiesByLine[d.id] ?? 0),
- receivedQuantity: 0,
+ outstandingQuantity,
+ receivedQuantity: outstandingQuantity,
unitPrice: d.unitPrice,
unitOfMeasure: d.unitOfMeasureCode ?? "EA",
locationId: d.locationId,
@@ -368,6 +390,7 @@ export default function useReceiptForm({
supplierId,
sourceDocuments,
onClose,
+ onPost,
setLocationId,
setSourceDocument,
setSourceDocumentId,
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx
new file mode 100644
index 0000000000..3c68b5c538
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx
@@ -0,0 +1,49 @@
+import {
+ Button,
+ HStack,
+ Modal,
+ ModalBody,
+ ModalCloseButton,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+} from "@chakra-ui/react";
+import { Form, useNavigate } from "@remix-run/react";
+
+type ReceiptPostModalProps = {};
+
+const ReceiptPostModal = (props: ReceiptPostModalProps) => {
+ const navigate = useNavigate();
+
+ const onCancel = () => navigate(-1);
+
+ return (
+ <Modal isOpen={true} onClose={onCancel}>
+ <ModalOverlay />
+ <ModalContent>
+ <ModalHeader>Post Receipt</ModalHeader>
+ <ModalCloseButton />
+ <ModalBody>
+ Are you sure you want to post this receipt? This cannot be undone.
+ </ModalBody>
+
+ <ModalFooter>
+ <HStack spacing={2}>
+ <Button colorScheme="gray" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Form method="post">
+ <input type="hidden" name="intent" value="receive" />
+ <Button colorScheme="brand" type="submit">
+ Receive
+ </Button>
+ </Form>
+ </HStack>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ );
+};
+
+export default ReceiptPostModal;
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/index.ts b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/index.ts
new file mode 100644
index 0000000000..ea8571e190
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/index.ts
@@ -0,0 +1,3 @@
+import ReceiptPostModal from "./ReceiptPostModal";
+
+export default ReceiptPostModal;
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable/ReceiptsTable.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable/ReceiptsTable.tsx
index 7c1f7f7906..9e7210fd99 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable/ReceiptsTable.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTable/ReceiptsTable.tsx
@@ -1,12 +1,12 @@
import { formatDate } from "@carbon/utils";
-import { Link, MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem, Tag } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import { BsPencilSquare } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { Table } from "~/components";
-import { usePermissions, useUrlParams } from "~/hooks";
+import { usePermissions, useRealtime, useUrlParams } from "~/hooks";
import type { Receipt } from "~/modules/inventory";
type ReceiptsTableProps = {
@@ -15,6 +15,8 @@ type ReceiptsTableProps = {
};
const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
+ useRealtime("receipt");
+
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -40,7 +42,24 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
{
accessorKey: "sourceDocumentReadableId",
header: "Source Document ID",
- cell: (item) => item.getValue() ?? null,
+ cell: ({ row }) => {
+ switch (row.original.sourceDocument) {
+ case "Purchase Order":
+ return (
+ <Link
+ onClick={() =>
+ navigate(
+ `/x/purchase-order/${row.original.sourceDocumentId}`
+ )
+ }
+ >
+ {row.original.sourceDocumentReadableId}
+ </Link>
+ );
+ default:
+ return null;
+ }
+ },
},
{
accessorKey: "location.name",
@@ -52,6 +71,23 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
header: "Supplier",
cell: (item) => item.getValue() ?? null,
},
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: (item) => {
+ const status = item.getValue<"Draft" | "Pending" | "Posted">();
+ switch (status) {
+ case "Draft":
+ return <Tag>Draft</Tag>;
+ case "Pending":
+ return <Tag colorScheme="orange">Pending</Tag>;
+ case "Posted":
+ return <Tag colorScheme="green">Posted</Tag>;
+ default:
+ return null;
+ }
+ },
+ },
{
accessorKey: "postingDate",
header: "Posting Date",
@@ -77,7 +113,9 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
</MenuItem>
<MenuItem
isDisabled={
- !permissions.can("delete", "inventory") || !!row.postingDate
+ !permissions.can("delete", "inventory") ||
+ !!row.postingDate ||
+ row.status === "Pending"
}
icon={<IoMdTrash />}
onClick={() => {
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx
index 00dc6efb50..e0ff29b0cb 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx
@@ -3,7 +3,7 @@ import { Button, HStack } from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
-import { usePermissions, useUrlParams } from "~/hooks";
+import { usePermissions, useUrlParams, useUser } from "~/hooks";
import { receiptSourceDocumentType } from "~/modules/inventory";
import type { ListItem } from "~/types";
@@ -15,6 +15,9 @@ const ReceiptsTableFilters = ({ locations }: ReceiptsTableFiltersProps) => {
const [params, setParams] = useUrlParams();
const permissions = usePermissions();
const borderColor = useColor("gray.200");
+ const {
+ defaults: { locationId },
+ } = useUser();
const sourceDocumentOptions = receiptSourceDocumentType.map((type) => ({
label: type,
@@ -61,10 +64,15 @@ const ReceiptsTableFilters = ({ locations }: ReceiptsTableFiltersProps) => {
<Select
// @ts-ignore
size="sm"
- value={locationOptions.find(
- (location) => location.value === params.get("location")
- )}
- isClearable
+ value={
+ params.get("location")
+ ? locationOptions.find(
+ (location) => location.value === params.get("location")
+ )
+ : locationOptions.find(
+ (location) => location.value === locationId
+ )
+ }
options={locationOptions}
onChange={(selected) => {
setParams({ location: selected?.value });
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/index.ts b/apps/carbon/app/modules/inventory/ui/Receipts/index.ts
index a2e9f367d9..0bc482cc12 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/index.ts
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/index.ts
@@ -1,5 +1,6 @@
import ReceiptForm from "./ReceiptForm";
+import ReceiptPostModal from "./ReceiptPostModal";
import ReceiptsTable from "./ReceiptsTable";
import ReceiptsTableFilters from "./ReceiptsTableFilters";
-export { ReceiptForm, ReceiptsTable, ReceiptsTableFilters };
+export { ReceiptForm, ReceiptPostModal, ReceiptsTable, ReceiptsTableFilters };
diff --git a/apps/carbon/app/modules/parts/services/parts.server.ts b/apps/carbon/app/modules/parts/services/parts.server.ts
index 1a5c26ca75..3d1c78bedd 100644
--- a/apps/carbon/app/modules/parts/services/parts.server.ts
+++ b/apps/carbon/app/modules/parts/services/parts.server.ts
@@ -160,7 +160,11 @@ export async function getPartsList(
client: SupabaseClient<Database>,
replenishmentSystem: PartReplenishmentSystem | null
) {
- let query = client.from("part").select("id, name");
+ let query = client
+ .from("part")
+ .select("id, name")
+ .eq("blocked", false)
+ .eq("active", true);
if (replenishmentSystem) {
query = query.or(
`replenishmentSystem.eq.${replenishmentSystem},replenishmentSystem.eq.Buy and Make`
@@ -169,6 +173,19 @@ export async function getPartsList(
return query;
}
+export async function getPartQuantities(
+ client: SupabaseClient<Database>,
+ partId: string,
+ locationId: string
+) {
+ return client
+ .from("part_quantities_view")
+ .select("*")
+ .eq("partId", partId)
+ .eq("locationId", locationId)
+ .maybeSingle();
+}
+
export async function getPartSummary(
client: SupabaseClient<Database>,
id: string
diff --git a/apps/carbon/app/modules/parts/types.ts b/apps/carbon/app/modules/parts/types.ts
index e37e13d599..14d179ae79 100644
--- a/apps/carbon/app/modules/parts/types.ts
+++ b/apps/carbon/app/modules/parts/types.ts
@@ -3,6 +3,7 @@ import type {
getPartCost,
getPartGroups,
getPartGroupsList,
+ getPartQuantities,
getParts,
getPartSummary,
getPartSuppliers,
@@ -25,6 +26,10 @@ export type PartGroupListItem = NonNullable<
Awaited<ReturnType<typeof getPartGroupsList>>["data"]
>[number];
+export type PartQuantities = NonNullable<
+ Awaited<ReturnType<typeof getPartQuantities>>["data"]
+>;
+
export type PartReorderingPolicy =
Database["public"]["Enums"]["partReorderingPolicy"];
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartInventoryForm/PartInventoryForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartInventoryForm/PartInventoryForm.tsx
index a49f7570c8..d6bdf96eba 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartInventoryForm/PartInventoryForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartInventoryForm/PartInventoryForm.tsx
@@ -14,6 +14,7 @@ import { useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import { CreatableSelect, Hidden, Number, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
+import type { PartQuantities } from "~/modules/parts";
import { partInventoryValidator } from "~/modules/parts";
import type { ListItem } from "~/types";
import type { TypeOfValidator } from "~/types/validators";
@@ -23,6 +24,7 @@ type PartInventoryFormProps = {
TypeOfValidator<typeof partInventoryValidator>,
"hasNewShelf"
>;
+ quantities: PartQuantities;
locations: ListItem[];
shelves: string[];
};
@@ -30,6 +32,7 @@ type PartInventoryFormProps = {
const PartInventoryForm = ({
initialValues,
locations,
+ quantities,
shelves,
}: PartInventoryFormProps) => {
const permissions = usePermissions();
@@ -44,16 +47,7 @@ const PartInventoryForm = ({
<ValidatedForm
method="post"
validator={partInventoryValidator}
- defaultValues={{
- ...initialValues,
- // TODO: Remove these defaults once the API is ready
- // @ts-expect-error
- quantityOnHand: 0,
- quantityAvailable: 0,
- quantityOnPurchaseOrder: 0,
- quantityOnProdOrder: 0,
- quantityOnSalesOrder: 0,
- }}
+ defaultValues={{ ...quantities, ...initialValues }}
>
<Card w="full">
<CardHeader>
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
index 49b2dab6a6..fe298e154a 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartSidebar/PartSidebar.tsx
@@ -1,5 +1,5 @@
import { useColor } from "@carbon/react";
-import { Button, Box, VStack } from "@chakra-ui/react";
+import { Box, Button, VStack } from "@chakra-ui/react";
import { Link, useMatches, useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type { PartSummary } from "~/modules/parts/types";
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
index c37677ae74..49286c0d14 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
@@ -10,10 +10,10 @@ export const purchaseOrderLineType = [
"Comment",
] as const;
-export const purchaseOrderTypeType = ["Draft", "Purchase", "Return"] as const;
+export const purchaseOrderTypeType = ["Purchase", "Return"] as const;
export const purchaseOrderStatusType = [
- "Open",
+ "Draft",
"In Review",
"In External Review",
"Approved",
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index 8046695da2..8eae156354 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -1,4 +1,5 @@
import type { Database } from "@carbon/database";
+import { getLocalTimeZone, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRole } from "~/lib/supabase";
import { getEmployeeJob } from "~/modules/resources";
@@ -24,7 +25,7 @@ export async function closePurchaseOrder(
.from("purchaseOrder")
.update({
closed: true,
- closedAt: new Date().toISOString(),
+ closedAt: today(getLocalTimeZone()).toString(),
closedBy: userId,
})
.eq("id", purchaseOrderId)
@@ -333,6 +334,26 @@ export async function insertSupplier(
return client.from("supplier").insert([supplier]).select("id").single();
}
+export async function getUninvoicedReceipts(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & {
+ supplier: string | null;
+ }
+) {
+ let query = client.from("receipts_posted_not_invoiced").select("*");
+
+ if (args?.supplier) {
+ query = query.eq("supplierId", args.supplier);
+ }
+
+ if (args)
+ if (args) {
+ query = setGenericQueryFilters(query, args, "name");
+ }
+
+ return query;
+}
+
export async function insertSupplierContact(
client: SupabaseClient<Database>,
supplierContact: {
@@ -616,26 +637,14 @@ export async function upsertPurchaseOrderLine(
if ("id" in purchaseOrderLine) {
return client
.from("purchaseOrderLine")
- .update(
- sanitize({
- ...purchaseOrderLine,
- quantityToReceive: purchaseOrderLine.purchaseQuantity,
- quantityToInvoice: purchaseOrderLine.purchaseQuantity,
- })
- )
+ .update(sanitize(purchaseOrderLine))
.eq("id", purchaseOrderLine.id)
.select("id")
.single();
}
return client
.from("purchaseOrderLine")
- .insert([
- {
- ...purchaseOrderLine,
- quantityToReceive: purchaseOrderLine.purchaseQuantity,
- quantityToInvoice: purchaseOrderLine.purchaseQuantity,
- },
- ])
+ .insert([purchaseOrderLine])
.select("id")
.single();
}
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
index 32a12f05eb..92f14652c4 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
@@ -35,7 +35,7 @@ const PartPreview = () => {
if (routeData?.purchaseOrder) release(routeData.purchaseOrder);
}}
isDisabled={
- !["Open", "Approved"].includes(
+ !["Draft", "Approved"].includes(
routeData?.purchaseOrder?.status ?? ""
)
}
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
index 6d4d18617e..81676e0911 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
@@ -68,7 +68,7 @@ const PurchaseOrderLineForm = ({
value: location.id,
}));
- const isEditable = ["Open", "In Review", "In External Review"].includes(
+ const isEditable = ["Draft", "In Review", "In External Review"].includes(
routeData?.purchaseOrder?.status ?? ""
);
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index 5a9eb235f3..72a36cf9fa 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -4,6 +4,7 @@ import {
Card,
CardBody,
CardHeader,
+ Checkbox,
Heading,
HStack,
IconButton,
@@ -55,7 +56,7 @@ const PurchaseOrderLines = ({
handleCellEdit,
} = usePurchaseOrderLines();
- const isEditable = ["Open", "In Review", "In External Review"].includes(
+ const isEditable = ["Draft", "In Review", "In External Review"].includes(
routeData?.purchaseOrder?.status ?? ""
);
@@ -200,6 +201,42 @@ const PurchaseOrderLines = ({
}
},
},
+ {
+ id: "quantityReceived",
+ header: "Quantity Received",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <span>{row.original.quantityReceived}</span>;
+ }
+ },
+ },
+ {
+ id: "quantityInvoiced",
+ header: "Quantity Invoiced",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <span>{row.original.quantityInvoiced}</span>;
+ }
+ },
+ },
+ {
+ id: "receivedComplete",
+ header: "Received Complete",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <Checkbox isChecked={row.original.receivedComplete} />;
+ }
+ },
+ },
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [navigate]);
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
index da3e8f9c79..18fad05a39 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
@@ -1,5 +1,5 @@
import { Count, useColor } from "@carbon/react";
-import { Button, Box, VStack } from "@chakra-ui/react";
+import { Box, Button, VStack } from "@chakra-ui/react";
import { Link, useMatches, useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
import type {
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
index cc811d8c5f..57ab1bb360 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
@@ -132,18 +132,6 @@ const PurchaseOrdersTable = memo(
];
}, [edit, onFavorite]);
- const actions = useMemo(() => {
- return [
- {
- label: "Add to Favorites",
- icon: <BsStar />,
- onClick: (selected: PurchaseOrder[]) => {
- console.log("move to favorites", selected);
- },
- },
- ];
- }, []);
-
const defaultColumnVisibility = {
createdAt: false,
updatedAt: false,
@@ -171,7 +159,8 @@ const PurchaseOrdersTable = memo(
<MenuItem
icon={<MdCallReceived />}
isDisabled={
- !row.released || !permissions.can("update", "inventory")
+ !["Draft", "Approved"].includes(row.status ?? "") ||
+ !permissions.can("update", "inventory")
}
onClick={() => {
receive(row);
@@ -196,7 +185,6 @@ const PurchaseOrdersTable = memo(
return (
<>
<Table<PurchaseOrder>
- actions={actions}
count={count}
columns={columns}
data={rows}
@@ -205,7 +193,6 @@ const PurchaseOrdersTable = memo(
withFilters
withPagination
withSimpleSorting
- withSelectableRows
renderContextMenu={renderContextMenu}
/>
diff --git a/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx b/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx
index 93bd009ada..f515c0518d 100644
--- a/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx
+++ b/apps/carbon/app/modules/resources/ui/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx
@@ -20,8 +20,8 @@ import { useState } from "react";
import { BsPencilSquare } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { ConfirmDelete } from "~/components/Modals";
-import type { EquipmentTypeDetailType } from "~/modules/resources";
import { useUrlParams } from "~/hooks";
+import type { EquipmentTypeDetailType } from "~/modules/resources";
type Equipment = {
id: string;
diff --git a/apps/carbon/app/modules/resources/ui/Locations/LocationForm/LocationForm.tsx b/apps/carbon/app/modules/resources/ui/Locations/LocationForm/LocationForm.tsx
index 02dc2c6507..d57aaa41a7 100644
--- a/apps/carbon/app/modules/resources/ui/Locations/LocationForm/LocationForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/Locations/LocationForm/LocationForm.tsx
@@ -12,7 +12,7 @@ import {
} from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
-import { Hidden, Input, Number, Submit, Timezone } from "~/components/Form";
+import { Hidden, Input, Submit, Timezone } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { locationValidator } from "~/modules/resources";
import type { TypeOfValidator } from "~/types/validators";
@@ -58,8 +58,8 @@ const LocationForm = ({ initialValues }: LocationFormProps) => {
<Input name="postalCode" label="Postal Code" />
{/* <Country name="country" label="Country" /> */}
<Timezone name="timezone" label="Timezone" />
- <Number name="latitude" label="Latitude" min={-90} max={90} />
- <Number name="longitude" label="Longitude" min={-180} max={180} />
+ {/* <Number name="latitude" label="Latitude" min={-90} max={90} />
+ <Number name="longitude" label="Longitude" min={-180} max={180} /> */}
</VStack>
</DrawerBody>
<DrawerFooter>
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonAbilities/PersonAbilities.tsx b/apps/carbon/app/modules/resources/ui/Person/PersonAbilities/PersonAbilities.tsx
index b6dbc11dfd..13dca74c91 100644
--- a/apps/carbon/app/modules/resources/ui/Person/PersonAbilities/PersonAbilities.tsx
+++ b/apps/carbon/app/modules/resources/ui/Person/PersonAbilities/PersonAbilities.tsx
@@ -5,22 +5,21 @@ import {
CardBody,
CardHeader,
Center,
- Heading,
+ Flex,
Grid,
+ Heading,
Icon,
- Text,
- Flex,
List,
ListItem,
+ Text,
} from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import type { IconType } from "react-icons";
-import { BsCheckLg, BsBarChartFill } from "react-icons/bs";
+import { BsBarChartFill, BsCheckLg } from "react-icons/bs";
import { FaThumbsUp } from "react-icons/fa";
import type { EmployeeAbility } from "~/modules/resources";
-import { getTrainingStatus } from "~/modules/resources";
-import { AbilityEmployeeStatus } from "~/modules/resources";
+import { AbilityEmployeeStatus, getTrainingStatus } from "~/modules/resources";
type PersonAbilitiesProps = {
abilities: EmployeeAbility[];
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx b/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
index 7480f1a0c6..3de96c60e0 100644
--- a/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
+++ b/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
@@ -18,8 +18,7 @@ import {
Submit,
} from "~/components/Form";
import { SectionTitle } from "~/components/Layout";
-import type { EmployeeJob } from "~/modules/resources";
-import type { getShiftsList } from "~/modules/resources";
+import type { EmployeeJob, getShiftsList } from "~/modules/resources";
import { employeeJobValidator } from "~/modules/resources";
import { mapRowsToOptions } from "~/utils/form";
diff --git a/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypeDetail/WorkCellTypeDetail.tsx b/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypeDetail/WorkCellTypeDetail.tsx
index 915b0e98e7..c7e9b9a7a7 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypeDetail/WorkCellTypeDetail.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypeDetail/WorkCellTypeDetail.tsx
@@ -20,8 +20,8 @@ import { useState } from "react";
import { BsPencilSquare } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { ConfirmDelete } from "~/components/Modals";
-import type { WorkCellTypeDetailType } from "~/modules/resources";
import { useUrlParams } from "~/hooks";
+import type { WorkCellTypeDetailType } from "~/modules/resources";
type WorkCell = NonNullable<WorkCellTypeDetailType["workCell"]>;
diff --git a/apps/carbon/app/modules/settings/services/settings.server.ts b/apps/carbon/app/modules/settings/services/settings.server.ts
index f482de045d..5443c4a6e1 100644
--- a/apps/carbon/app/modules/settings/services/settings.server.ts
+++ b/apps/carbon/app/modules/settings/services/settings.server.ts
@@ -7,12 +7,32 @@ import { interpolateDate } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import type { sequenceValidator } from "./settings.form";
+export async function getCurrentSequence(
+ client: SupabaseClient<Database>,
+ table: string
+) {
+ const sequence = await getSequence(client, table);
+ if (sequence.error) {
+ return sequence;
+ }
+
+ const { prefix, suffix, next, size } = sequence.data;
+
+ const currentSequence = next.toString().padStart(size, "0");
+ const derivedPrefix = interpolateDate(prefix);
+ const derivedSuffix = interpolateDate(suffix);
+
+ return {
+ data: `${derivedPrefix}${currentSequence}${derivedSuffix}`,
+ error: null,
+ };
+}
+
export async function getNextSequence(
client: SupabaseClient<Database>,
table: string,
userId: string
) {
- // TODO: add transaction through stored procedure: https://www.postgresql.org/docs/current/plpgsql-transactions.html
const sequence = await getSequence(client, table);
if (sequence.error) {
return sequence;
@@ -68,7 +88,6 @@ export async function rollbackNextSequence(
table: string,
userId: string
) {
- // TODO: add transaction through stored procedure: https://www.postgresql.org/docs/current/plpgsql-transactions.html
const sequence = await getSequence(client, table);
if (sequence.error) {
return sequence;
diff --git a/apps/carbon/app/modules/users/services/users.server.ts b/apps/carbon/app/modules/users/services/users.server.ts
index 3f36b6c910..280abcdc88 100644
--- a/apps/carbon/app/modules/users/services/users.server.ts
+++ b/apps/carbon/app/modules/users/services/users.server.ts
@@ -3,6 +3,8 @@ import { redis } from "@carbon/redis";
import { redirect } from "@remix-run/node";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRole } from "~/lib/supabase";
+import { getSupplierContact } from "~/modules/purchasing";
+import { getCustomerContact } from "~/modules/sales";
import type {
EmployeeRow,
EmployeeTypePermission,
@@ -10,14 +12,12 @@ import type {
Permission,
User,
} from "~/modules/users";
-import { getSupplierContact } from "~/modules/purchasing";
import {
deleteAuthAccount,
sendInviteByEmail,
sendMagicLink,
} from "~/services/auth";
-import { getCustomerContact } from "~/modules/sales";
-import { requireAuthSession, flash } from "~/services/session";
+import { flash, requireAuthSession } from "~/services/session";
import type { Result } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
diff --git a/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm/BulkEditPermissionsForm.tsx b/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm/BulkEditPermissionsForm.tsx
index adbe490643..4078a2d674 100644
--- a/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm/BulkEditPermissionsForm.tsx
+++ b/apps/carbon/app/modules/users/ui/Employees/BulkEditPermissionsForm/BulkEditPermissionsForm.tsx
@@ -17,8 +17,8 @@ import { useEffect, useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import { Employees, Hidden, Radios, Submit } from "~/components/Form";
import { bulkPermissionsValidator } from "~/modules/users";
-import PermissionCheckboxes from "../../components/Permission";
import type { Permission } from "../../../types";
+import PermissionCheckboxes from "../../components/Permission";
type BulkEditPermissionsProps = {
userIds: string[];
diff --git a/apps/carbon/app/queues/accounting-posting.queue.server.ts b/apps/carbon/app/queues/accounting-posting.queue.server.ts
new file mode 100644
index 0000000000..647f764757
--- /dev/null
+++ b/apps/carbon/app/queues/accounting-posting.queue.server.ts
@@ -0,0 +1,30 @@
+import { Queue } from "~/lib/bullmq";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+
+export enum PostingQueueType {
+ Receipt = "receipt",
+}
+
+export type PostingQueueData = {
+ documentId: string;
+ type: PostingQueueType;
+};
+
+const client = getSupabaseServiceRole();
+
+export const postingQueue = Queue<PostingQueueData>(
+ "posting:v1",
+ async (job) => {
+ switch (job.data.type) {
+ case "receipt":
+ await client.functions.invoke("post-receipt", {
+ body: {
+ receiptId: job.data.documentId,
+ },
+ });
+ break;
+ default:
+ break;
+ }
+ }
+);
diff --git a/apps/carbon/app/queues/deactivate-users.queue.server.ts b/apps/carbon/app/queues/deactivate-users.queue.server.ts
deleted file mode 100644
index 2be90f4c45..0000000000
--- a/apps/carbon/app/queues/deactivate-users.queue.server.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Queue } from "~/lib/bullmq";
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { deactivateUser } from "~/modules/users";
-
-export type DeactivateUserQueueData = {
- id: string;
-};
-
-const client = getSupabaseServiceRole();
-
-export const deactivateUsersQueue = Queue<DeactivateUserQueueData>(
- "deactivateUsers:v1",
- async (job) => {
- await deactivateUser(client, job.data.id);
- }
-);
diff --git a/apps/carbon/app/queues/index.ts b/apps/carbon/app/queues/index.ts
index 031ec05cb7..00adab44d6 100644
--- a/apps/carbon/app/queues/index.ts
+++ b/apps/carbon/app/queues/index.ts
@@ -1,9 +1,16 @@
-import { bulkPermissionsQueue } from "./bulk-permissions.queue.server";
-import { deactivateUsersQueue } from "./deactivate-users.queue.server";
-import { resendInvitesQueue } from "./resend-invites.queue.server";
+import {
+ postingQueue,
+ PostingQueueType,
+} from "./accounting-posting.queue.server";
+import { userAdminQueue, UserAdminQueueType } from "./user-admin.queue.server";
+import { userPermissionsQueue } from "./user-permissions.queue.server";
-export { bulkPermissionsQueue, deactivateUsersQueue, resendInvitesQueue };
-
-export type { BulkPermissionsQueueData } from "./bulk-permissions.queue.server";
-export type { DeactivateUserQueueData } from "./deactivate-users.queue.server";
-export type { ResendInvitesQueueData } from "./resend-invites.queue.server";
+export type { UserAdminQueueData } from "./user-admin.queue.server";
+export type { UserPermissionsQueueData } from "./user-permissions.queue.server";
+export {
+ PostingQueueType,
+ UserAdminQueueType,
+ postingQueue,
+ userPermissionsQueue,
+ userAdminQueue,
+};
diff --git a/apps/carbon/app/queues/resend-invites.queue.server.ts b/apps/carbon/app/queues/resend-invites.queue.server.ts
deleted file mode 100644
index 2bb8b0dbfc..0000000000
--- a/apps/carbon/app/queues/resend-invites.queue.server.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Queue } from "~/lib/bullmq";
-import { getSupabaseServiceRole } from "~/lib/supabase";
-import { resendInvite } from "~/modules/users";
-
-export type ResendInvitesQueueData = {
- id: string;
-};
-
-const client = getSupabaseServiceRole();
-
-export const resendInvitesQueue = Queue<ResendInvitesQueueData>(
- "resendInvites:v1",
- async (job) => {
- await resendInvite(client, job.data.id);
- }
-);
diff --git a/apps/carbon/app/queues/user-admin.queue.server.ts b/apps/carbon/app/queues/user-admin.queue.server.ts
new file mode 100644
index 0000000000..4466a73529
--- /dev/null
+++ b/apps/carbon/app/queues/user-admin.queue.server.ts
@@ -0,0 +1,31 @@
+import { Queue } from "~/lib/bullmq";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { deactivateUser, resendInvite } from "~/modules/users";
+
+export enum UserAdminQueueType {
+ Resend = "resend",
+ Deactivate = "deactivate",
+}
+
+export type UserAdminQueueData = {
+ id: string;
+ type: UserAdminQueueType;
+};
+
+const client = getSupabaseServiceRole();
+
+export const userAdminQueue = Queue<UserAdminQueueData>(
+ "userAdmin:v1",
+ async (job) => {
+ switch (job.data.type) {
+ case "resend":
+ await resendInvite(client, job.data.id);
+ break;
+ case "deactivate":
+ await deactivateUser(client, job.data.id);
+ break;
+ default:
+ break;
+ }
+ }
+);
diff --git a/apps/carbon/app/queues/bulk-permissions.queue.server.ts b/apps/carbon/app/queues/user-permissions.queue.server.ts
similarity index 75%
rename from apps/carbon/app/queues/bulk-permissions.queue.server.ts
rename to apps/carbon/app/queues/user-permissions.queue.server.ts
index 16bd002f62..49909078c7 100644
--- a/apps/carbon/app/queues/bulk-permissions.queue.server.ts
+++ b/apps/carbon/app/queues/user-permissions.queue.server.ts
@@ -3,7 +3,7 @@ import { getSupabaseServiceRole } from "~/lib/supabase";
import type { Permission } from "~/modules/users";
import { updatePermissions } from "~/modules/users";
-export type BulkPermissionsQueueData = {
+export type UserPermissionsQueueData = {
id: string;
permissions: Record<string, Permission>;
addOnly: boolean;
@@ -11,8 +11,8 @@ export type BulkPermissionsQueueData = {
const client = getSupabaseServiceRole();
-export const bulkPermissionsQueue = Queue<BulkPermissionsQueueData>(
- "editBulkPermissions:v1",
+export const userPermissionsQueue = Queue<UserPermissionsQueueData>(
+ "userPermissions:v1",
async (job) => {
await updatePermissions(client, job.data);
}
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index 0e365bc5bc..f3adb51f9e 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -1,8 +1,11 @@
// root.tsx
import { ThemeProvider } from "@carbon/react";
+import { Heading, VStack } from "@chakra-ui/react";
import { SkipNavLink } from "@chakra-ui/skip-nav";
-import { VStack, Heading } from "@chakra-ui/react";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
+import { json } from "@remix-run/node";
import {
+ isRouteErrorResponse,
Links,
LiveReload,
Meta,
@@ -10,9 +13,8 @@ import {
Scripts,
ScrollRestoration,
useLoaderData,
+ useRouteError,
} from "@remix-run/react";
-import { json } from "@remix-run/node";
-import type { MetaFunction } from "@remix-run/node";
import React from "react";
import { getBrowserEnv } from "~/config/env";
import Background from "~/styles/background.css";
@@ -25,11 +27,19 @@ export function links() {
];
}
-export const meta: MetaFunction = () => ({
- charset: "utf-8",
- title: "Carbon ERP",
- viewport: "width=device-width",
-});
+export const meta: MetaFunction = () => {
+ return [
+ {
+ charset: "utf-8",
+ },
+ {
+ title: "Carbon ERP",
+ },
+ {
+ viewport: "width=device-width",
+ },
+ ];
+};
export async function loader() {
const { SUPABASE_API_URL, SUPABASE_ANON_PUBLIC } = getBrowserEnv();
@@ -84,7 +94,15 @@ export default function App() {
);
}
-export function ErrorBoundary({ error }: { error: Error }) {
+export function ErrorBoundary() {
+ const error = useRouteError();
+
+ const message = isRouteErrorResponse(error)
+ ? error.data.message ?? error.data
+ : error instanceof Error
+ ? error.message
+ : String(error);
+
return (
<Document title="Error!">
<ThemeProvider>
@@ -98,7 +116,7 @@ export function ErrorBoundary({ error }: { error: Error }) {
color="white"
>
<Heading as="h1">Something went wrong</Heading>
- <p>{error.message}</p>
+ <p>{message}</p>
</VStack>
</ThemeProvider>
</Document>
diff --git a/apps/carbon/app/routes/_public+/forgot-password.tsx b/apps/carbon/app/routes/_public+/forgot-password.tsx
index 6c20fca721..5f0837b7a3 100644
--- a/apps/carbon/app/routes/_public+/forgot-password.tsx
+++ b/apps/carbon/app/routes/_public+/forgot-password.tsx
@@ -10,22 +10,30 @@ import {
useColorModeValue,
VStack,
} from "@chakra-ui/react";
+import type {
+ ActionArgs,
+ LoaderArgs,
+ V2_MetaFunction as MetaFunction,
+} from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import type { ActionArgs, LoaderArgs, MetaFunction } from "@remix-run/node";
import { useActionData } from "@remix-run/react";
import { ValidatedForm, validationError } from "remix-validated-form";
import { Input, Submit } from "~/components/Form";
-import { getAuthSession } from "~/services/session";
-import { forgotPasswordValidator, sendMagicLink } from "~/services/auth";
import { getUserByEmail } from "~/modules/users";
-import { assertIsPost } from "~/utils/http";
+import { forgotPasswordValidator, sendMagicLink } from "~/services/auth";
+import { getAuthSession } from "~/services/session";
import type { FormActionData, Result } from "~/types";
+import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Forgot Password",
-});
+export const meta: MetaFunction = () => {
+ return [
+ {
+ title: "Carbon | Forgot Password",
+ },
+ ];
+};
export async function loader({ request }: LoaderArgs) {
const authSession = await getAuthSession(request);
diff --git a/apps/carbon/app/routes/_public+/login.tsx b/apps/carbon/app/routes/_public+/login.tsx
index 81bb7a5654..be661c5138 100644
--- a/apps/carbon/app/routes/_public+/login.tsx
+++ b/apps/carbon/app/routes/_public+/login.tsx
@@ -5,28 +5,32 @@ import {
AlertTitle,
Box,
Image,
- VStack,
useColorModeValue,
+ VStack,
} from "@chakra-ui/react";
+import type {
+ ActionArgs,
+ LoaderArgs,
+ V2_MetaFunction as MetaFunction,
+} from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import type { ActionArgs, LoaderArgs, MetaFunction } from "@remix-run/node";
import { Link, useActionData, useSearchParams } from "@remix-run/react";
import { ValidatedForm, validationError } from "remix-validated-form";
import { Input, Password, Submit } from "~/components/Form";
-import { createAuthSession, getAuthSession } from "~/services/session";
import {
- signInWithEmail,
loginValidator,
+ signInWithEmail,
verifyAuthSession,
} from "~/services/auth";
+import { createAuthSession, getAuthSession } from "~/services/session";
import type { FormActionData, Result } from "~/types";
import { assertIsPost } from "~/utils/http";
import { error } from "~/utils/result";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Login",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Login" }];
+};
export async function loader({ request }: LoaderArgs) {
const authSession = await getAuthSession(request);
diff --git a/apps/carbon/app/routes/_public+/reset-password.tsx b/apps/carbon/app/routes/_public+/reset-password.tsx
index f7c310ad2a..a396b9b403 100644
--- a/apps/carbon/app/routes/_public+/reset-password.tsx
+++ b/apps/carbon/app/routes/_public+/reset-password.tsx
@@ -1,24 +1,23 @@
import { useColor } from "@carbon/react";
import {
Box,
+ Button,
+ HStack,
Image,
Text,
- VStack,
useColorModeValue,
- Button,
- HStack,
+ VStack,
} from "@chakra-ui/react";
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
-import { json } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
import { useNavigate } from "@remix-run/react";
import { ValidatedForm, validationError } from "remix-validated-form";
import { Password, Submit } from "~/components/Form";
-import { resetPasswordValidator } from "~/services/auth";
import { resetPassword } from "~/modules/users";
-import { requireAuthSession, flash } from "~/services/session";
-import { error, success } from "~/utils/result";
+import { resetPasswordValidator } from "~/services/auth";
+import { flash, requireAuthSession } from "~/services/session";
import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
export async function loader({ request }: LoaderArgs) {
await requireAuthSession(request);
diff --git a/apps/carbon/app/routes/api+/settings.sequence.next.tsx b/apps/carbon/app/routes/api+/settings.sequence.next.tsx
new file mode 100644
index 0000000000..24044ce145
--- /dev/null
+++ b/apps/carbon/app/routes/api+/settings.sequence.next.tsx
@@ -0,0 +1,33 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client, userId } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const table = searchParams.get("table") as string;
+
+ if (!table || table === "undefined")
+ return json(
+ { data: null },
+ await flash(request, error(request, "Bad request for next sequence"))
+ );
+
+ const nextSequence = await getNextSequence(client, table, userId);
+ if (nextSequence.error) {
+ return json(
+ nextSequence,
+ await flash(
+ request,
+ error(nextSequence.error, `Failed to get next sequence for ${table}`)
+ )
+ );
+ }
+
+ return json(nextSequence);
+}
diff --git a/apps/carbon/app/routes/api+/settings.sequence.rollback.tsx b/apps/carbon/app/routes/api+/settings.sequence.rollback.tsx
new file mode 100644
index 0000000000..3a1e6dbca1
--- /dev/null
+++ b/apps/carbon/app/routes/api+/settings.sequence.rollback.tsx
@@ -0,0 +1,68 @@
+import type { ActionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getCurrentSequence, rollbackNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsDelete } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsDelete(request);
+ const { client, userId } = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const table = searchParams.get("table") as string;
+ const currentSequence = searchParams.get("currentSequence") as string;
+
+ if (
+ !table ||
+ table === "undefined" ||
+ !currentSequence ||
+ currentSequence === "undefined"
+ )
+ return json(
+ { data: null },
+ await flash(
+ request,
+ error(request, "Bad request for rolling back sequence")
+ )
+ );
+
+ const verifyCurrent = await getCurrentSequence(client, table);
+ if (verifyCurrent.error) {
+ return json(
+ verifyCurrent,
+ await flash(
+ request,
+ error(
+ verifyCurrent.error,
+ `Failed to get current sequence for ${table}`
+ )
+ )
+ );
+ }
+
+ if (verifyCurrent.data !== currentSequence) {
+ return json({
+ data: null,
+ error: "Sequence has changed since last request",
+ });
+ }
+
+ const rollback = await rollbackNextSequence(client, table, userId);
+ if (rollback.error) {
+ return json(
+ rollback,
+ await flash(
+ request,
+ error(rollback.error, `Failed to rollback sequence for ${table}`)
+ )
+ );
+ }
+
+ return json({
+ data: currentSequence,
+ error: null,
+ });
+}
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index a98a2adcb8..e288de05b6 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -1,4 +1,4 @@
-import { useNotification, useColor } from "@carbon/react";
+import { useColor, useNotification } from "@carbon/react";
import { Flex, Grid, GridItem, VStack } from "@chakra-ui/react";
import { SkipNavContent } from "@chakra-ui/skip-nav";
import type { LoaderArgs } from "@remix-run/node";
@@ -9,8 +9,8 @@ import { useEffect } from "react";
import { IconSidebar, Topbar } from "~/components/Layout";
import { getSupabase, SupabaseProvider } from "~/lib/supabase";
import {
- getUserClaims,
getUser,
+ getUserClaims,
getUserDefaults,
getUserGroups,
} from "~/modules/users";
diff --git a/apps/carbon/app/routes/x+/account+/_layout.tsx b/apps/carbon/app/routes/x+/account+/_layout.tsx
index 14fcdde6a3..bcec8cc6c1 100644
--- a/apps/carbon/app/routes/x+/account+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/account+/_layout.tsx
@@ -1,13 +1,13 @@
import { useColor } from "@carbon/react";
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { ContentSidebar } from "~/components/Layout/Sidebar";
import { useAccountSidebar } from "~/modules/account";
-export const meta: MetaFunction = () => ({
- title: "Carbon | My Account",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | My Account" }];
+};
export default function AccountRoute() {
const { links } = useAccountSidebar();
diff --git a/apps/carbon/app/routes/x+/accounting+/_layout.tsx b/apps/carbon/app/routes/x+/accounting+/_layout.tsx
index 988f14d8cf..df5a3a1a41 100644
--- a/apps/carbon/app/routes/x+/accounting+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/_layout.tsx
@@ -1,5 +1,8 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { LoaderArgs, MetaFunction } from "@remix-run/node";
+import type {
+ LoaderArgs,
+ V2_MetaFunction as MetaFunction,
+} from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
@@ -12,10 +15,9 @@ import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { error } from "~/utils/result";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Accounting",
-});
-
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Accounting" }];
+};
export async function loader({ request }: LoaderArgs) {
const { client } = await requirePermissions(request, {
view: "accounting",
diff --git a/apps/carbon/app/routes/x+/documents+/_layout.tsx b/apps/carbon/app/routes/x+/documents+/_layout.tsx
index ea37e33c43..695c431e82 100644
--- a/apps/carbon/app/routes/x+/documents+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/documents+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { ContentSidebar } from "~/components/Layout/Sidebar";
import { useDocumentsSidebar } from "~/modules/documents";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Documents",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Documents" }];
+};
export default function DocumentsRoute() {
const { links } = useDocumentsSidebar();
diff --git a/apps/carbon/app/routes/x+/inventory+/_layout.tsx b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
index 4c2be69135..dcea3241b2 100644
--- a/apps/carbon/app/routes/x+/inventory+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useInventorySidebar } from "~/modules/inventory";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Inventory",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Inventory" }];
+};
export default function UsersRoute() {
const { groups } = useInventorySidebar();
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx
new file mode 100644
index 0000000000..d2a80716a3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx
@@ -0,0 +1,53 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { ReceiptPostModal } from "~/modules/inventory";
+import { postingQueue, PostingQueueType } from "~/queues";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const { receiptId } = params;
+ if (!receiptId) throw new Error("receiptId not found");
+
+ const formData = await request.formData();
+
+ switch (formData.get("intent")) {
+ case "receive":
+ const setPendingState = await client
+ .from("receipt")
+ .update({
+ status: "Pending",
+ })
+ .eq("id", receiptId);
+
+ if (setPendingState.error) {
+ return redirect(
+ `/x/inventory/receipts`,
+ await flash(
+ request,
+ error(setPendingState.error, "Failed to post receipt")
+ )
+ );
+ }
+
+ postingQueue.add(`posting receipt ${receiptId}`, {
+ type: PostingQueueType.Receipt,
+ documentId: receiptId,
+ });
+
+ return redirect(`/x/inventory/receipts`);
+ default:
+ break;
+ }
+
+ return redirect(`/x/inventory/receipts`);
+}
+
+export default function ReceiptPostRoute() {
+ return <ReceiptPostModal />;
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
index 8085afbc36..d4cf2a23fc 100644
--- a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
@@ -2,7 +2,6 @@ import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import type { ReceiptSourceDocument } from "~/modules/inventory";
import {
getReceipt,
getReceiptLines,
@@ -67,7 +66,7 @@ export async function action({ request }: ActionArgs) {
}
return redirect(
- "/x/inventory/receipts",
+ `/x/inventory/receipts/${id}`,
await flash(request, success("Updated receipt"))
);
}
@@ -81,13 +80,15 @@ export default function EditReceiptsRoute() {
...receipt,
receiptId: receipt.receiptId ?? undefined,
sourceDocument: (receipt.sourceDocument ??
- "Purchase Order") as ReceiptSourceDocument,
+ "Purchase Order") as "Purchase Order",
sourceDocumentId: receipt.sourceDocumentId ?? undefined,
+ sourceDocumentReadbleId: receipt.sourceDocumentReadableId ?? undefined,
locationId: receipt.locationId ?? undefined,
};
return (
<ReceiptForm
+ // @ts-ignore
initialValues={initialValues}
isPosted={!!receipt?.postingDate ?? false}
receiptLines={receiptLines}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
index d60b3eca16..3043ca38c4 100644
--- a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
@@ -15,6 +15,11 @@ import { flash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
+// shouldRevalidate function
+export function shouldRevalidate() {
+ return false;
+}
+
export async function loader({ request }: LoaderArgs) {
const { client, userId } = await requirePermissions(request, {
create: "inventory",
@@ -86,7 +91,7 @@ export async function action({ request }: ActionArgs) {
}
return redirect(
- "/x/inventory/receipts",
+ `/x/inventory/receipts/${id}`,
await flash(request, success("Receipt created"))
);
}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
index 872a8db09d..49e7d04ba2 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
@@ -4,10 +4,11 @@ import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import { useRouteData } from "~/hooks";
import {
- PartInventoryForm,
getPartInventory,
+ getPartQuantities,
getShelvesList,
insertShelf,
+ PartInventoryForm,
partInventoryValidator,
upsertPartInventory,
} from "~/modules/parts";
@@ -101,8 +102,17 @@ export async function loader({ request, params }: LoaderArgs) {
);
}
+ const quantities = await getPartQuantities(client, partId, locationId);
+ if (quantities.error || !quantities.data) {
+ return redirect(
+ "/x/parts",
+ await flash(request, error(quantities, "Failed to load part quantities"))
+ );
+ }
+
return json({
partInventory: partInventory.data,
+ quantities: quantities.data,
shelves: shelves.data.map((s) => s.id),
});
}
@@ -168,7 +178,7 @@ export async function action({ request, params }: ActionArgs) {
export default function PartInventoryRoute() {
const sharedPartsData = useRouteData<{ locations: ListItem[] }>("/x/part");
- const { partInventory, shelves } = useLoaderData<typeof loader>();
+ const { partInventory, quantities, shelves } = useLoaderData<typeof loader>();
const initialValues = {
...partInventory,
@@ -177,6 +187,7 @@ export default function PartInventoryRoute() {
return (
<PartInventoryForm
initialValues={initialValues}
+ quantities={quantities}
locations={sharedPartsData?.locations ?? []}
shelves={shelves}
/>
diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsx
index 98b2d1796f..08874941ce 100644
--- a/apps/carbon/app/routes/x+/part+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx
@@ -1,21 +1,24 @@
import { VStack } from "@chakra-ui/react";
-import type { LoaderArgs, MetaFunction } from "@remix-run/node";
+import type {
+ LoaderArgs,
+ V2_MetaFunction as MetaFunction,
+} from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import {
getPartCostingMethods,
getPartGroupsList,
getPartManufacturingPolicies,
- getPartRorderdingPolicies,
getPartReplenishmentSystems,
+ getPartRorderdingPolicies,
getPartTypes,
getUnitOfMeasuresList,
} from "~/modules/parts";
import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Parts",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Login" }];
+};
export async function loader({ request }: LoaderArgs) {
const { client } = await requirePermissions(request, {
diff --git a/apps/carbon/app/routes/x+/part+/flow.tsx b/apps/carbon/app/routes/x+/part+/flow.tsx
index c62786eef2..a9501730b4 100644
--- a/apps/carbon/app/routes/x+/part+/flow.tsx
+++ b/apps/carbon/app/routes/x+/part+/flow.tsx
@@ -1,22 +1,25 @@
-import type { LoaderArgs, MetaFunction } from "@remix-run/node";
+import type {
+ LoaderArgs,
+ V2_MetaFunction as MetaFunction,
+} from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { useCallback } from "react";
-import type { Connection, Node, Edge } from "reactflow";
+import type { Connection, Edge, Node } from "reactflow";
import ReactFlow, {
- Controls,
+ addEdge,
Background,
BackgroundVariant,
- addEdge,
- useNodesState,
+ Controls,
useEdgesState,
+ useNodesState,
} from "reactflow";
import reactFlowStyles from "reactflow/dist/style.css";
import { requirePermissions } from "~/services/auth";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Parts",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Parts" }];
+};
export function links() {
return [{ rel: "stylesheet", href: reactFlowStyles }];
diff --git a/apps/carbon/app/routes/x+/parts+/_layout.tsx b/apps/carbon/app/routes/x+/parts+/_layout.tsx
index 599b310f65..6a06c7ecbc 100644
--- a/apps/carbon/app/routes/x+/parts+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/parts+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { usePartsSidebar } from "~/modules/parts";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Parts",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Parts" }];
+};
export default function PartsRoute() {
const { groups } = usePartsSidebar();
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
index 99a07cd697..1a152e0c42 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
@@ -72,7 +72,7 @@ export default function PurchaseOrderBasicRoute() {
supplierReference: orderData?.purchaseOrder?.supplierReference ?? "",
orderDate: orderData?.purchaseOrder?.orderDate ?? "",
type: orderData?.purchaseOrder?.type ?? "Draft",
- status: orderData?.purchaseOrder?.status ?? "Open",
+ status: orderData?.purchaseOrder?.status ?? "Draft",
receiptRequestedDate: orderData?.purchaseOrder?.receiptRequestedDate ?? "",
receiptPromisedDate: orderData?.purchaseOrder?.receiptPromisedDate ?? "",
notes: orderData?.purchaseOrder?.notes ?? "",
diff --git a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
index 11542d7845..af2e2dfcac 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
@@ -1,10 +1,10 @@
import { VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Purchasing",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Purchasing" }];
+};
export default function PurchaseOrderRoute() {
return (
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
index e059482c4a..4097eece2f 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -81,7 +81,7 @@ export default function PurchaseOrderNewRoute() {
purchaseOrderId: undefined,
supplierId: supplierId ?? undefined,
orderDate: today(getLocalTimeZone()).toString(),
- status: "Open" as PurchaseOrderStatus,
+ status: "Draft" as PurchaseOrderStatus,
type: "Purchase" as PurchaseOrderType,
};
diff --git a/apps/carbon/app/routes/x+/purchasing+/_layout.tsx b/apps/carbon/app/routes/x+/purchasing+/_layout.tsx
index 7dd97bcb25..cc06f5a441 100644
--- a/apps/carbon/app/routes/x+/purchasing+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { usePurchasingSidebar } from "~/modules/purchasing";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Purchasing",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Purchasing" }];
+};
export default function UsersRoute() {
const { groups } = usePurchasingSidebar();
diff --git a/apps/carbon/app/routes/x+/resources+/_layout.tsx b/apps/carbon/app/routes/x+/resources+/_layout.tsx
index 243ed5b12b..778675b5dd 100644
--- a/apps/carbon/app/routes/x+/resources+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/resources+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useResourcesSidebar } from "~/modules/resources";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Resources",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Resources" }];
+};
export default function ResourcesRoute() {
const { groups } = useResourcesSidebar();
diff --git a/apps/carbon/app/routes/x+/resources+/ability.$abilityId.tsx b/apps/carbon/app/routes/x+/resources+/ability.$abilityId.tsx
index 77ebc73fd5..abdfd34ffb 100644
--- a/apps/carbon/app/routes/x+/resources+/ability.$abilityId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/ability.$abilityId.tsx
@@ -14,8 +14,7 @@ import {
useDisclosure,
} from "@chakra-ui/react";
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { json } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
import { Link, Outlet, useLoaderData, useNavigate } from "@remix-run/react";
import { ParentSize } from "@visx/responsive";
import { useState } from "react";
@@ -23,15 +22,15 @@ import { IoMdAdd, IoMdClose } from "react-icons/io";
import { MdEdit, MdOutlineArrowBackIos } from "react-icons/md";
import { ValidatedForm, validationError } from "remix-validated-form";
import { Hidden, Input, Submit } from "~/components/Form";
+import type { AbilityDatum } from "~/modules/resources";
import {
AbilityChart,
- AbilityEmployeesTable,
abilityCurveValidator,
+ AbilityEmployeesTable,
abilityNameValidator,
getAbility,
updateAbility,
} from "~/modules/resources";
-import type { AbilityDatum } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { error, success } from "~/utils/result";
diff --git a/apps/carbon/app/routes/x+/sales+/_layout.tsx b/apps/carbon/app/routes/x+/sales+/_layout.tsx
index 91a86cc3a6..b19b2d3eb1 100644
--- a/apps/carbon/app/routes/x+/sales+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/sales+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useSalesSidebar } from "~/modules/sales";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Sales",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Sales" }];
+};
export default function UsersRoute() {
const { groups } = useSalesSidebar();
diff --git a/apps/carbon/app/routes/x+/settings+/_layout.tsx b/apps/carbon/app/routes/x+/settings+/_layout.tsx
index 514711e6c0..21172ce7b3 100644
--- a/apps/carbon/app/routes/x+/settings+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/settings+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useSettingsSidebar } from "~/modules/settings";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Settings",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Settings" }];
+};
export default function SettingsRoute() {
const { groups } = useSettingsSidebar();
diff --git a/apps/carbon/app/routes/x+/users+/_layout.tsx b/apps/carbon/app/routes/x+/users+/_layout.tsx
index b6612bcda7..59a66a241f 100644
--- a/apps/carbon/app/routes/x+/users+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/users+/_layout.tsx
@@ -1,12 +1,12 @@
import { Grid, VStack } from "@chakra-ui/react";
-import type { MetaFunction } from "@remix-run/node";
+import type { V2_MetaFunction as MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import { GroupedContentSidebar } from "~/components/Layout/Sidebar";
import { useUsersSidebar } from "~/modules/users";
-export const meta: MetaFunction = () => ({
- title: "Carbon | Users",
-});
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Users" }];
+};
export default function UsersRoute() {
const { groups } = useUsersSidebar();
diff --git a/apps/carbon/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/carbon/app/routes/x+/users+/bulk-edit-permissions.tsx
index ab1f0a8914..c913788e3e 100644
--- a/apps/carbon/app/routes/x+/users+/bulk-edit-permissions.tsx
+++ b/apps/carbon/app/routes/x+/users+/bulk-edit-permissions.tsx
@@ -2,14 +2,14 @@ import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import type { Permission } from "~/modules/users";
-import type { BulkPermissionsQueueData } from "~/queues";
-import { bulkPermissionsQueue } from "~/queues";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
import {
bulkPermissionsValidator,
userPermissionsValidator,
} from "~/modules/users";
+import type { UserPermissionsQueueData } from "~/queues";
+import { userPermissionsQueue } from "~/queues";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
@@ -42,7 +42,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const jobs = userIds.map<{ name: string; data: BulkPermissionsQueueData }>(
+ const jobs = userIds.map<{ name: string; data: UserPermissionsQueueData }>(
(id) => ({
name: `permission update for ${id}`,
data: {
@@ -53,7 +53,7 @@ export async function action({ request }: ActionArgs) {
})
);
- await bulkPermissionsQueue.addBulk(jobs);
+ await userPermissionsQueue.addBulk(jobs);
return redirect(
"/x/users/employees",
diff --git a/apps/carbon/app/routes/x+/users+/deactivate.tsx b/apps/carbon/app/routes/x+/users+/deactivate.tsx
index 4e3f1cf19c..490f654fae 100644
--- a/apps/carbon/app/routes/x+/users+/deactivate.tsx
+++ b/apps/carbon/app/routes/x+/users+/deactivate.tsx
@@ -1,9 +1,9 @@
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import type { DeactivateUserQueueData } from "~/queues";
import { deactivateUser, deactivateUsersValidator } from "~/modules/users";
-import { deactivateUsersQueue } from "~/queues";
+import type { UserAdminQueueData } from "~/queues";
+import { userAdminQueue, UserAdminQueueType } from "~/queues";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { safeRedirect } from "~/utils/http";
@@ -30,17 +30,18 @@ export async function action({ request }: ActionArgs) {
return redirect(safeRedirect(redirectTo), await flash(request, result));
} else {
- const jobs = users.map<{ name: string; data: DeactivateUserQueueData }>(
+ const jobs = users.map<{ name: string; data: UserAdminQueueData }>(
(id) => ({
name: `deactivate user ${id}`,
data: {
id,
+ type: UserAdminQueueType.Deactivate,
},
})
);
try {
- await deactivateUsersQueue.addBulk(jobs);
+ await userAdminQueue.addBulk(jobs);
return redirect(
safeRedirect(redirectTo),
await flash(
diff --git a/apps/carbon/app/routes/x+/users+/resend-invite.tsx b/apps/carbon/app/routes/x+/users+/resend-invite.tsx
index 6c1e290dc6..bbd04f57d7 100644
--- a/apps/carbon/app/routes/x+/users+/resend-invite.tsx
+++ b/apps/carbon/app/routes/x+/users+/resend-invite.tsx
@@ -2,8 +2,8 @@ import type { ActionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import { resendInvite, resendInviteValidator } from "~/modules/users";
-import type { ResendInvitesQueueData } from "~/queues";
-import { resendInvitesQueue } from "~/queues";
+import type { UserAdminQueueData } from "~/queues";
+import { userAdminQueue, UserAdminQueueType } from "~/queues";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { error, success } from "~/utils/result";
@@ -29,17 +29,18 @@ export async function action({ request }: ActionArgs) {
return json({}, await flash(request, result));
} else {
- const jobs = users.map<{ name: string; data: ResendInvitesQueueData }>(
+ const jobs = users.map<{ name: string; data: UserAdminQueueData }>(
(id) => ({
name: `reinvite user ${id}`,
data: {
id,
+ type: UserAdminQueueType.Resend,
},
})
);
try {
- await resendInvitesQueue.addBulk(jobs);
+ await userAdminQueue.addBulk(jobs);
return json(
{},
await flash(request, success("Successfully added invites to queue."))
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index cadf75eb93..cd97a264b9 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -4,11 +4,10 @@ import type {
AuthSession as SupabaseAuthSession,
SupabaseClient,
} from "@supabase/supabase-js";
-import { VERCEL_URL } from "~/config/env";
-import { REFRESH_ACCESS_TOKEN_THRESHOLD } from "~/config/env";
+import { REFRESH_ACCESS_TOKEN_THRESHOLD, VERCEL_URL } from "~/config/env";
import { getSupabase, getSupabaseServiceRole } from "~/lib/supabase";
-import { requireAuthSession, flash } from "~/services/session";
import { getUserClaims } from "~/modules/users";
+import { flash, requireAuthSession } from "~/services/session";
import { error } from "~/utils/result";
import type { AuthSession } from "./types";
diff --git a/apps/carbon/app/utils/http.ts b/apps/carbon/app/utils/http.ts
index 98bbf0b3df..468656716c 100644
--- a/apps/carbon/app/utils/http.ts
+++ b/apps/carbon/app/utils/http.ts
@@ -21,6 +21,7 @@ export function isPost(request: Request) {
}
export function isDelete(request: Request) {
+ console.log("METHOD", request.method.toLowerCase());
return request.method.toLowerCase() === "delete";
}
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 3a62e06f14..1478500490 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -8,7 +8,7 @@
"dev": "run-p dev:*",
"dev:remix": "remix dev",
"start": "remix-serve build",
- "clean": "rimraf .cache .turbo node_modules dist public build",
+ "clean": "rimraf .cache .turbo node_modules dist build",
"lint": "TIMING=1 eslint \"app/**/*.ts*\"",
"types": "tsc"
},
@@ -31,7 +31,7 @@
"@remix-run/serve": "1.18.1",
"@vercel/remix": "1.18.1",
"@remix-validated-form/with-zod": "^2.0.6",
- "@supabase/supabase-js": "^2.31.0",
+ "@supabase/supabase-js": "^2.33.1",
"@tanstack/react-table": "^8.9.3",
"@visx/axis": "3.3.0",
"@visx/curve": "3.3.0",
diff --git a/apps/carbon/remix.config.js b/apps/carbon/remix.config.js
index 8ae29cfbd2..8e676dca3a 100644
--- a/apps/carbon/remix.config.js
+++ b/apps/carbon/remix.config.js
@@ -6,10 +6,10 @@ const { flatRoutes } = require("remix-flat-routes");
module.exports = {
future: {
v2_dev: false,
- v2_errorBoundary: false,
+ v2_errorBoundary: true,
v2_headers: false,
- v2_meta: false,
- v2_normalizeFormMethod: false,
+ v2_meta: true,
+ v2_normalizeFormMethod: true,
v2_routeConvention: true,
},
ignoredRouteFiles: ["**/.*"],
@@ -33,10 +33,10 @@ module.exports = {
],
watchPaths: async () => {
return [
- "../../packages/carbon-react/src/**/*",
- "../../packages/carbon-database/src/**/*",
- "../../packages/carbon-logger/src/**/*",
- "../../packages/carbon-utils/src/**/*",
+ "../../packages/react/src/**/*",
+ "../../packages/database/src/**/*",
+ "../../packages/logger/src/**/*",
+ "../../packages/utils/src/**/*",
];
},
};
diff --git a/package.json b/package.json
index 5263e177ad..d0f92191b4 100755
--- a/package.json
+++ b/package.json
@@ -12,7 +12,6 @@
"predb:build": "tsx scripts/generate-schema-md.ts",
"db:build": "run-s db:kill db:start setup",
"postdb:build": "tsx scripts/generate-db-types.ts",
- "db:init": "turbo run db:init",
"db:restart": "run-s db:stop db:start",
"db:start": "run-p db:start:database db:start:redis",
"db:start:database": "yarn workspace @carbon/database supabase start",
@@ -23,6 +22,7 @@
"db:kill:supabase": "yarn workspace @carbon/database supabase stop --no-backup",
"db:kill:redis": "yarn workspace @carbon/redis db:kill",
"db:types": "yarn workspace @carbon/database db:types",
+ "db:function:new": "yarn workspace @carbon/database supabase functions new",
"db:migrate": "yarn workspace @carbon/database db:migrate",
"db:migrate:new": "yarn workspace @carbon/database supabase migration new",
"db:push": "turbo run db:push",
@@ -35,7 +35,6 @@
"dev:www": "turbo run dev --filter=./www",
"dev:packages": "turbo run dev --filter=./packages/*",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
- "init": "run-s db:init db:start",
"lint": "turbo run lint",
"prepare": "husky install",
"setup": "turbo run setup",
@@ -47,13 +46,13 @@
"npm-run-all": "^4.1.5",
"prettier": "^2.8.0",
"rimraf": "^5.0.0",
- "supabase": "1.77.9",
+ "supabase": "1.93.0",
"tsx": "^3.12.1",
"turbo": "^1.8.3"
},
"packageManager": "[email protected]",
"engines": {
- "node": ">=16"
+ "node": ">=18"
},
"lint-staged": {
"(apps|packages|www)/**/*.{js,ts,jsx,tsx}": [
diff --git a/packages/carbon-database/supabase/.branches/_current_branch b/packages/carbon-database/supabase/.branches/_current_branch
deleted file mode 100644
index 88d050b190..0000000000
--- a/packages/carbon-database/supabase/.branches/_current_branch
+++ /dev/null
@@ -1 +0,0 @@
-main
\ No newline at end of file
diff --git a/packages/carbon-database/.env b/packages/database/.env
similarity index 100%
rename from packages/carbon-database/.env
rename to packages/database/.env
diff --git a/packages/database/.eslintrc.js b/packages/database/.eslintrc.js
new file mode 100644
index 0000000000..54b8d7daac
--- /dev/null
+++ b/packages/database/.eslintrc.js
@@ -0,0 +1,5 @@
+module.exports = {
+ root: true,
+ extends: ["carbon"],
+ ignorePatterns: ["**/supabase/functions/**/*"],
+};
diff --git a/packages/carbon-database/package.json b/packages/database/package.json
similarity index 94%
rename from packages/carbon-database/package.json
rename to packages/database/package.json
index 28f989ee1e..f5a4995bb7 100644
--- a/packages/carbon-database/package.json
+++ b/packages/database/package.json
@@ -27,7 +27,7 @@
},
"devDependencies": {
"@carbon/tsconfig": "*",
- "@supabase/supabase-js": "^2.31.0",
+ "@supabase/supabase-js": "^2.33.1",
"@types/node": "^18.15.0",
"@types/uuid": "^8.3.4",
"dotenv": "16.3.1",
@@ -35,7 +35,7 @@
"eslint-config-carbon": "*",
"npm-run-all": "^4.1.5",
"rimraf": "^4.4.0",
- "supabase": "1.77.9",
+ "supabase": "1.93.0",
"tsup": "^6.5.0",
"tsx": "^3.12.1",
"typescript": "^4.9.3",
diff --git a/packages/carbon-database/src/index.ts b/packages/database/src/index.ts
similarity index 100%
rename from packages/carbon-database/src/index.ts
rename to packages/database/src/index.ts
diff --git a/packages/carbon-database/src/seed.ts b/packages/database/src/seed.ts
similarity index 100%
rename from packages/carbon-database/src/seed.ts
rename to packages/database/src/seed.ts
diff --git a/packages/carbon-database/src/seed/admin.ts b/packages/database/src/seed/admin.ts
similarity index 100%
rename from packages/carbon-database/src/seed/admin.ts
rename to packages/database/src/seed/admin.ts
diff --git a/packages/carbon-database/src/seed/employee-types.ts b/packages/database/src/seed/employee-types.ts
similarity index 100%
rename from packages/carbon-database/src/seed/employee-types.ts
rename to packages/database/src/seed/employee-types.ts
diff --git a/packages/carbon-database/src/seed/features.ts b/packages/database/src/seed/features.ts
similarity index 100%
rename from packages/carbon-database/src/seed/features.ts
rename to packages/database/src/seed/features.ts
diff --git a/packages/carbon-database/src/seed/index.ts b/packages/database/src/seed/index.ts
similarity index 100%
rename from packages/carbon-database/src/seed/index.ts
rename to packages/database/src/seed/index.ts
diff --git a/packages/carbon-database/src/types.ts b/packages/database/src/types.ts
similarity index 95%
rename from packages/carbon-database/src/types.ts
rename to packages/database/src/types.ts
index 5d62898775..be6328d567 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2019,6 +2019,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeJob_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "employeeJob_locationId_fkey";
columns: ["locationId"];
@@ -2235,6 +2241,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "equipment_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "equipment_locationId_fkey";
columns: ["locationId"];
@@ -2358,12 +2370,12 @@ export interface Database {
amount: number;
createdAt: string;
description: string | null;
- documentNumber: string | null;
+ documentId: string | null;
documentType:
- | Database["public"]["Enums"]["accountDocumentLedgerType"]
+ | Database["public"]["Enums"]["generalLedgerDocumentType"]
| null;
entryNumber: number;
- externalDocumentNumber: string | null;
+ externalDocumentId: string | null;
id: string;
postingDate: string;
};
@@ -2372,26 +2384,26 @@ export interface Database {
amount: number;
createdAt?: string;
description?: string | null;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
- | Database["public"]["Enums"]["accountDocumentLedgerType"]
+ | Database["public"]["Enums"]["generalLedgerDocumentType"]
| null;
entryNumber?: number;
- externalDocumentNumber?: string | null;
+ externalDocumentId?: string | null;
id?: string;
- postingDate: string;
+ postingDate?: string;
};
Update: {
accountNumber?: string;
amount?: number;
createdAt?: string;
description?: string | null;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
- | Database["public"]["Enums"]["accountDocumentLedgerType"]
+ | Database["public"]["Enums"]["generalLedgerDocumentType"]
| null;
entryNumber?: number;
- externalDocumentNumber?: string | null;
+ externalDocumentId?: string | null;
id?: string;
postingDate?: string;
};
@@ -2760,6 +2772,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partCost_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partCost_partId_fkey";
columns: ["partId"];
@@ -2897,6 +2915,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partInventory_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partInventory_locationId_fkey";
columns: ["locationId"];
@@ -2909,6 +2933,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partInventory_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partInventory_partId_fkey";
columns: ["partId"];
@@ -2937,63 +2967,51 @@ export interface Database {
};
partLedger: {
Row: {
- costAmount: number;
createdAt: string;
- documentNumber: string | null;
+ documentId: string | null;
documentType:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber: number;
entryType: Database["public"]["Enums"]["partLedgerType"];
+ externalDocumentId: string | null;
id: string;
- invoicedQuantity: number;
locationId: string | null;
- open: boolean;
partId: string;
postingDate: string;
quantity: number;
- remainingQuantity: number;
- salesAmount: number;
shelfId: string | null;
};
Insert: {
- costAmount: number;
createdAt?: string;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber?: number;
entryType: Database["public"]["Enums"]["partLedgerType"];
+ externalDocumentId?: string | null;
id?: string;
- invoicedQuantity: number;
locationId?: string | null;
- open?: boolean;
partId: string;
- postingDate: string;
+ postingDate?: string;
quantity: number;
- remainingQuantity: number;
- salesAmount: number;
shelfId?: string | null;
};
Update: {
- costAmount?: number;
createdAt?: string;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber?: number;
entryType?: Database["public"]["Enums"]["partLedgerType"];
+ externalDocumentId?: string | null;
id?: string;
- invoicedQuantity?: number;
locationId?: string | null;
- open?: boolean;
partId?: string;
postingDate?: string;
quantity?: number;
- remainingQuantity?: number;
- salesAmount?: number;
shelfId?: string | null;
};
Relationships: [
@@ -3003,6 +3021,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partLedger_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partLedger_locationId_fkey";
columns: ["locationId"];
@@ -3015,6 +3039,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partLedger_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partLedger_partId_fkey";
columns: ["partId"];
@@ -3029,6 +3059,34 @@ export interface Database {
}
];
};
+ partLedgerValueLedgerRelation: {
+ Row: {
+ partLedgerId: string;
+ valueLedgerId: string;
+ };
+ Insert: {
+ partLedgerId: string;
+ valueLedgerId: string;
+ };
+ Update: {
+ partLedgerId?: string;
+ valueLedgerId?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "partLedgerValueLedgerRelation_partLedgerId_fkey";
+ columns: ["partLedgerId"];
+ referencedRelation: "partLedger";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partLedgerValueLedgerRelation_valueLedgerId_fkey";
+ columns: ["valueLedgerId"];
+ referencedRelation: "valueLedger";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
partner: {
Row: {
active: boolean;
@@ -3225,6 +3283,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partPlanning_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partPlanning_locationId_fkey";
columns: ["locationId"];
@@ -3237,6 +3301,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partPlanning_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partPlanning_partId_fkey";
columns: ["partId"];
@@ -3331,6 +3401,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partReplenishment_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partReplenishment_partId_fkey";
columns: ["partId"];
@@ -3449,6 +3525,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partSupplier_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partSupplier_partId_fkey";
columns: ["partId"];
@@ -3564,6 +3646,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partUnitSalePrice_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "partUnitSalePrice_partId_fkey";
columns: ["partId"];
@@ -3818,6 +3906,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "postingGroupInventory_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "postingGroupInventory_locationId_fkey";
columns: ["locationId"];
@@ -4353,6 +4447,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrderDelivery_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "purchaseOrderDelivery_locationId_fkey";
columns: ["locationId"];
@@ -4535,6 +4635,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrderLine_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "purchaseOrderLine_partId_fkey";
columns: ["partId"];
@@ -4735,7 +4841,9 @@ export interface Database {
Row: {
createdAt: string;
createdBy: string;
+ externalDocumentId: string | null;
id: string;
+ invoiced: boolean | null;
locationId: string | null;
postingDate: string | null;
receiptId: string;
@@ -4744,6 +4852,7 @@ export interface Database {
| null;
sourceDocumentId: string | null;
sourceDocumentReadableId: string | null;
+ status: Database["public"]["Enums"]["receiptStatus"];
supplierId: string | null;
updatedAt: string | null;
updatedBy: string | null;
@@ -4751,7 +4860,9 @@ export interface Database {
Insert: {
createdAt?: string;
createdBy: string;
+ externalDocumentId?: string | null;
id?: string;
+ invoiced?: boolean | null;
locationId?: string | null;
postingDate?: string | null;
receiptId: string;
@@ -4760,6 +4871,7 @@ export interface Database {
| null;
sourceDocumentId?: string | null;
sourceDocumentReadableId?: string | null;
+ status?: Database["public"]["Enums"]["receiptStatus"];
supplierId?: string | null;
updatedAt?: string | null;
updatedBy?: string | null;
@@ -4767,7 +4879,9 @@ export interface Database {
Update: {
createdAt?: string;
createdBy?: string;
+ externalDocumentId?: string | null;
id?: string;
+ invoiced?: boolean | null;
locationId?: string | null;
postingDate?: string | null;
receiptId?: string;
@@ -4776,6 +4890,7 @@ export interface Database {
| null;
sourceDocumentId?: string | null;
sourceDocumentReadableId?: string | null;
+ status?: Database["public"]["Enums"]["receiptStatus"];
supplierId?: string | null;
updatedAt?: string | null;
updatedBy?: string | null;
@@ -4799,6 +4914,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "receipt_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "receipt_locationId_fkey";
columns: ["locationId"];
@@ -4920,6 +5041,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "receiptLine_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "receiptLine_locationId_fkey";
columns: ["locationId"];
@@ -4932,6 +5059,12 @@ export interface Database {
referencedRelation: "part";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "receiptLine_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["partId"];
+ },
{
foreignKeyName: "receiptLine_partId_fkey";
columns: ["partId"];
@@ -4944,6 +5077,12 @@ export interface Database {
referencedRelation: "receipt";
referencedColumns: ["receiptId"];
},
+ {
+ foreignKeyName: "receiptLine_receiptId_fkey";
+ columns: ["receiptId"];
+ referencedRelation: "receipts_posted_not_invoiced";
+ referencedColumns: ["receiptId"];
+ },
{
foreignKeyName: "receiptLine_shelfId_fkey";
columns: ["shelfId", "locationId"];
@@ -5093,6 +5232,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shelf_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "shelf_locationId_fkey";
columns: ["locationId"];
@@ -5172,6 +5317,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shifts_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "shifts_locationId_fkey";
columns: ["locationId"];
@@ -5569,6 +5720,79 @@ export interface Database {
}
];
};
+ supplierLedger: {
+ Row: {
+ amount: number;
+ createdAt: string;
+ documentId: string | null;
+ documentType:
+ | Database["public"]["Enums"]["supplierLedgerDocumentType"]
+ | null;
+ entryNumber: number;
+ externalDocumentId: string | null;
+ id: string;
+ postingDate: string;
+ supplierId: string;
+ };
+ Insert: {
+ amount: number;
+ createdAt?: string;
+ documentId?: string | null;
+ documentType?:
+ | Database["public"]["Enums"]["supplierLedgerDocumentType"]
+ | null;
+ entryNumber?: number;
+ externalDocumentId?: string | null;
+ id?: string;
+ postingDate?: string;
+ supplierId: string;
+ };
+ Update: {
+ amount?: number;
+ createdAt?: string;
+ documentId?: string | null;
+ documentType?:
+ | Database["public"]["Enums"]["supplierLedgerDocumentType"]
+ | null;
+ entryNumber?: number;
+ externalDocumentId?: string | null;
+ id?: string;
+ postingDate?: string;
+ supplierId?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "supplierLedger_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "supplier";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierLedger_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "contractors_view";
+ referencedColumns: ["supplierId"];
+ },
+ {
+ foreignKeyName: "supplierLedger_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "partners_view";
+ referencedColumns: ["supplierId"];
+ },
+ {
+ foreignKeyName: "supplierLedger_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "purchase_order_suppliers_view";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierLedger_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "suppliers_view";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
supplierLocation: {
Row: {
addressId: string;
@@ -6112,12 +6336,13 @@ export interface Database {
costAmountExpected: number;
costLedgerType: Database["public"]["Enums"]["costLedgerType"];
createdAt: string;
- documentNumber: string | null;
+ documentId: string | null;
documentType:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber: number;
expectedCostPostedToGl: number;
+ externalDocumentId: string | null;
id: string;
partLedgerType: Database["public"]["Enums"]["partLedgerType"];
postingDate: string;
@@ -6129,15 +6354,16 @@ export interface Database {
costAmountExpected?: number;
costLedgerType: Database["public"]["Enums"]["costLedgerType"];
createdAt?: string;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber?: number;
expectedCostPostedToGl?: number;
+ externalDocumentId?: string | null;
id?: string;
partLedgerType: Database["public"]["Enums"]["partLedgerType"];
- postingDate: string;
+ postingDate?: string;
};
Update: {
actualCostPostedToGl?: number;
@@ -6146,19 +6372,20 @@ export interface Database {
costAmountExpected?: number;
costLedgerType?: Database["public"]["Enums"]["costLedgerType"];
createdAt?: string;
- documentNumber?: string | null;
+ documentId?: string | null;
documentType?:
| Database["public"]["Enums"]["partLedgerDocumentType"]
| null;
entryNumber?: number;
expectedCostPostedToGl?: number;
+ externalDocumentId?: string | null;
id?: string;
partLedgerType?: Database["public"]["Enums"]["partLedgerType"];
postingDate?: string;
};
Relationships: [];
};
- valueLedgerAccountLedgerRelation: {
+ valueLedgerGeneralLedgerRelation: {
Row: {
generalLedgerId: string;
valueLedgerId: string;
@@ -6173,13 +6400,13 @@ export interface Database {
};
Relationships: [
{
- foreignKeyName: "valueLedgerAccountLedgerRelation_generalLedgerId_fkey";
+ foreignKeyName: "valueLedgerGeneralLedgerRelation_generalLedgerId_fkey";
columns: ["generalLedgerId"];
referencedRelation: "generalLedger";
referencedColumns: ["id"];
},
{
- foreignKeyName: "valueLedgerAccountLedgerRelation_valueLedgerId_fkey";
+ foreignKeyName: "valueLedgerGeneralLedgerRelation_valueLedgerId_fkey";
columns: ["valueLedgerId"];
referencedRelation: "valueLedger";
referencedColumns: ["id"];
@@ -6251,6 +6478,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "warehouse_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "warehouse_locationId_fkey";
columns: ["locationId"];
@@ -6330,6 +6563,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "workCell_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "workCell_locationId_fkey";
columns: ["locationId"];
@@ -6748,6 +6987,18 @@ export interface Database {
};
Relationships: [];
};
+ part_quantities_view: {
+ Row: {
+ locationId: string | null;
+ partId: string | null;
+ quantityAvailable: number | null;
+ quantityOnHand: number | null;
+ quantityOnProdOrder: number | null;
+ quantityOnPurchaseOrder: number | null;
+ quantityOnSalesOrder: number | null;
+ };
+ Relationships: [];
+ };
partners_view: {
Row: {
abilityIds: string[] | null;
@@ -6900,6 +7151,53 @@ export interface Database {
};
Relationships: [];
};
+ receipts_posted_not_invoiced: {
+ Row: {
+ estimatedCost: number | null;
+ id: string | null;
+ postingDate: string | null;
+ receiptId: string | null;
+ sourceDocument:
+ | Database["public"]["Enums"]["receiptSourceDocument"]
+ | null;
+ sourceDocumentId: string | null;
+ sourceDocumentReadableId: string | null;
+ supplierId: string | null;
+ supplierName: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "receipt_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "supplier";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receipt_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "contractors_view";
+ referencedColumns: ["supplierId"];
+ },
+ {
+ foreignKeyName: "receipt_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "partners_view";
+ referencedColumns: ["supplierId"];
+ },
+ {
+ foreignKeyName: "receipt_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "purchase_order_suppliers_view";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receipt_supplierId_fkey";
+ columns: ["supplierId"];
+ referencedRelation: "suppliers_view";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
suppliers_view: {
Row: {
id: string | null;
@@ -6926,6 +7224,12 @@ export interface Database {
}
];
};
+ total_receipts_posted_not_invoiced: {
+ Row: {
+ total: number | null;
+ };
+ Relationships: [];
+ };
user_default_view: {
Row: {
locationId: string | null;
@@ -6938,6 +7242,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeJob_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "part_quantities_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "employeeJob_locationId_fkey";
columns: ["locationId"];
@@ -7079,13 +7389,6 @@ export interface Database {
};
};
Enums: {
- accountDocumentLedgerType:
- | "Quote"
- | "Order"
- | "Invoice"
- | "Credit Memo"
- | "Blanket Order"
- | "Return Order";
costLedgerType:
| "Direct Cost"
| "Revaluation"
@@ -7112,6 +7415,13 @@ export interface Database {
| "Seconds/Piece"
| "Total Hours"
| "Total Minutes";
+ generalLedgerDocumentType:
+ | "Quote"
+ | "Order"
+ | "Invoice"
+ | "Credit Memo"
+ | "Blanket Order"
+ | "Return Order";
glAccountCategory:
| "Bank"
| "Accounts Receivable"
@@ -7175,7 +7485,7 @@ export interface Database {
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month";
purchaseOrderLineType: "Comment" | "G/L Account" | "Part" | "Fixed Asset";
purchaseOrderStatus:
- | "Open"
+ | "Draft"
| "In Review"
| "In External Review"
| "Approved"
@@ -7199,6 +7509,7 @@ export interface Database {
| "Outbound Transfer"
| "Manufacturing Consumption"
| "Manufacturing Output";
+ receiptStatus: "Draft" | "Pending" | "Posted";
searchEntity:
| "Resource"
| "Person"
@@ -7210,6 +7521,13 @@ export interface Database {
| "Sales Order"
| "Document";
shippingCarrier: "UPS" | "FedEx" | "USPS" | "DHL" | "Other";
+ supplierLedgerDocumentType:
+ | "Payment"
+ | "Invoice"
+ | "Credit Memo"
+ | "Finance Charge Memo"
+ | "Reminder"
+ | "Refund";
};
CompositeTypes: {
[_ in never]: never;
diff --git a/packages/carbon-database/supabase/.gitignore b/packages/database/supabase/.gitignore
similarity index 100%
rename from packages/carbon-database/supabase/.gitignore
rename to packages/database/supabase/.gitignore
diff --git a/packages/carbon-database/supabase/config.toml b/packages/database/supabase/config.toml
similarity index 100%
rename from packages/carbon-database/supabase/config.toml
rename to packages/database/supabase/config.toml
diff --git a/packages/database/supabase/functions/lib/database.ts b/packages/database/supabase/functions/lib/database.ts
new file mode 100644
index 0000000000..4e55408516
--- /dev/null
+++ b/packages/database/supabase/functions/lib/database.ts
@@ -0,0 +1,43 @@
+import { Pool } from "https://deno.land/x/[email protected]/mod.ts";
+import {
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler,
+} from "https://esm.sh/[email protected]";
+import { PostgresDriver } from "../lib/driver.ts";
+
+export function getConnectionPool(connections: number) {
+ return new Pool(Deno.env.get("SUPABASE_DB_URL")!, connections);
+ // TODO: if we're deploying to a remote environment, use this:
+ // return new Pool(
+ // {
+ // tls: { caCertificates: [Deno.env.get("DB_SSL_CERT")!] },
+ // database: "postgres",
+ // hostname: Deno.env.get("DB_HOSTNAME"),
+ // user: "postgres",
+ // port: 5432,
+ // password: Deno.env.get("DB_PASSWORD"),
+ // },
+ // connections
+ // );
+}
+
+export function getDatabaseClient<T>(pool: Pool): Kysely<T> {
+ return new Kysely<T>({
+ dialect: {
+ createAdapter() {
+ return new PostgresAdapter();
+ },
+ createDriver() {
+ return new PostgresDriver({ pool });
+ },
+ createIntrospector(db: Kysely<unknown>) {
+ return new PostgresIntrospector(db);
+ },
+ createQueryCompiler() {
+ return new PostgresQueryCompiler();
+ },
+ },
+ });
+}
diff --git a/packages/database/supabase/functions/lib/driver.ts b/packages/database/supabase/functions/lib/driver.ts
new file mode 100644
index 0000000000..cd398f9dca
--- /dev/null
+++ b/packages/database/supabase/functions/lib/driver.ts
@@ -0,0 +1,162 @@
+import type {
+ Pool,
+ PoolClient,
+} from "https://deno.land/x/[email protected]/mod.ts";
+import type {
+ DatabaseConnection,
+ Driver,
+ PostgresCursorConstructor,
+ QueryResult,
+ TransactionSettings,
+} from "https://esm.sh/[email protected]";
+import { CompiledQuery } from "https://esm.sh/[email protected]";
+import {
+ freeze,
+ isFunction,
+} from "https://esm.sh/[email protected]/dist/esm/util/object-utils.js";
+import { extendStackTrace } from "https://esm.sh/[email protected]/dist/esm/util/stack-trace-utils.js";
+
+export interface PostgresDialectConfig {
+ pool: Pool | (() => Promise<Pool>);
+ cursor?: PostgresCursorConstructor;
+ onCreateConnection?: (connection: DatabaseConnection) => Promise<void>;
+}
+
+const PRIVATE_RELEASE_METHOD = Symbol();
+
+export class PostgresDriver implements Driver {
+ readonly #config: PostgresDialectConfig;
+ readonly #connections = new WeakMap<PoolClient, DatabaseConnection>();
+ #pool?: Pool;
+
+ constructor(config: PostgresDialectConfig) {
+ this.#config = freeze({ ...config });
+ }
+
+ async init(): Promise<void> {
+ this.#pool = isFunction(this.#config.pool)
+ ? await this.#config.pool()
+ : this.#config.pool;
+ }
+
+ async acquireConnection(): Promise<DatabaseConnection> {
+ const client = await this.#pool!.connect();
+ let connection = this.#connections.get(client);
+
+ if (!connection) {
+ connection = new PostgresConnection(client, {
+ cursor: this.#config.cursor ?? null,
+ });
+ this.#connections.set(client, connection);
+
+ // The driver must take care of calling `onCreateConnection` when a new
+ // connection is created. The `pg` module doesn't provide an async hook
+ // for the connection creation. We need to call the method explicitly.
+ if (this.#config?.onCreateConnection) {
+ await this.#config.onCreateConnection(connection);
+ }
+ }
+
+ return connection;
+ }
+
+ async beginTransaction(
+ connection: DatabaseConnection,
+ settings: TransactionSettings
+ ): Promise<void> {
+ if (settings.isolationLevel) {
+ await connection.executeQuery(
+ CompiledQuery.raw(
+ `start transaction isolation level ${settings.isolationLevel}`
+ )
+ );
+ } else {
+ await connection.executeQuery(CompiledQuery.raw("begin"));
+ }
+ }
+
+ async commitTransaction(connection: DatabaseConnection): Promise<void> {
+ await connection.executeQuery(CompiledQuery.raw("commit"));
+ }
+
+ async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
+ await connection.executeQuery(CompiledQuery.raw("rollback"));
+ }
+
+ async releaseConnection(connection: PostgresConnection): Promise<void> {
+ connection[PRIVATE_RELEASE_METHOD]();
+ }
+
+ async destroy(): Promise<void> {
+ if (this.#pool) {
+ const pool = this.#pool;
+ this.#pool = undefined;
+ await pool.end();
+ }
+ }
+}
+
+interface PostgresConnectionOptions {
+ cursor: PostgresCursorConstructor | null;
+}
+
+class PostgresConnection implements DatabaseConnection {
+ #client: PoolClient;
+ #options: PostgresConnectionOptions;
+
+ constructor(client: PoolClient, options: PostgresConnectionOptions) {
+ this.#client = client;
+ this.#options = options;
+ }
+
+ async executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
+ try {
+ const result = await this.#client.queryObject<O>(compiledQuery.sql, [
+ ...compiledQuery.parameters,
+ ]);
+
+ if (
+ result.command === "INSERT" ||
+ result.command === "UPDATE" ||
+ result.command === "DELETE"
+ ) {
+ const numAffectedRows = BigInt(result.rowCount || 0);
+
+ return {
+ numUpdatedOrDeletedRows: numAffectedRows,
+ numAffectedRows,
+ rows: result.rows ?? [],
+ } as any;
+ }
+
+ return {
+ rows: result.rows ?? [],
+ };
+ } catch (err) {
+ throw extendStackTrace(err, new Error());
+ }
+ }
+
+ // deno-lint-ignore require-yield
+ async *streamQuery<O>(
+ _compiledQuery: CompiledQuery,
+ chunkSize: number
+ ): AsyncIterableIterator<QueryResult<O>> {
+ if (!this.#options.cursor) {
+ throw new Error(
+ "'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."
+ );
+ }
+
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
+ throw new Error("chunkSize must be a positive integer");
+ }
+
+ // stream not available
+ return null;
+ }
+
+ [PRIVATE_RELEASE_METHOD](): void {
+ this.#client.release();
+ }
+}
diff --git a/packages/database/supabase/functions/lib/headers.ts b/packages/database/supabase/functions/lib/headers.ts
new file mode 100644
index 0000000000..02b087a135
--- /dev/null
+++ b/packages/database/supabase/functions/lib/headers.ts
@@ -0,0 +1,5 @@
+export const corsHeaders = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Headers":
+ "authorization, x-client-info, apikey, content-type",
+};
diff --git a/packages/database/supabase/functions/lib/supabase.ts b/packages/database/supabase/functions/lib/supabase.ts
new file mode 100644
index 0000000000..29f4fb6aec
--- /dev/null
+++ b/packages/database/supabase/functions/lib/supabase.ts
@@ -0,0 +1,47 @@
+import { createClient } from "https://esm.sh/@supabase/[email protected]";
+import type { Database } from "../../../src/types.ts";
+
+export const getSupabase = (authorizationHeader: string | null) => {
+ if (!authorizationHeader) throw new Error("Authorization header is required");
+
+ return createClient<Database>(
+ Deno.env.get("SUPABASE_URL") ?? "",
+ Deno.env.get("SUPABASE_ANON_PUBLIC") ?? "",
+ {
+ global: {
+ headers: { authorizationHeader },
+ },
+ auth: {
+ autoRefreshToken: false,
+ persistSession: false,
+ },
+ }
+ );
+};
+
+export const getSupabaseServiceRole = (authorizationHeader: string | null) => {
+ if (!authorizationHeader) throw new Error("Authorization header is required");
+
+ // Verify that the request is coming from a service role
+ const claims = JSON.parse(
+ atob(authorizationHeader.split(" ")[1].split(".")[1])
+ );
+ if (claims.role !== "service_role") {
+ throw new Error("Service role is required");
+ }
+
+ // Create a Supabase client with the service role key
+ return createClient<Database>(
+ Deno.env.get("SUPABASE_URL") ?? "",
+ Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "",
+ {
+ global: {
+ headers: { authorizationHeader },
+ },
+ auth: {
+ autoRefreshToken: false,
+ persistSession: false,
+ },
+ }
+ );
+};
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
new file mode 100644
index 0000000000..966e0bc769
--- /dev/null
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -0,0 +1,370 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import type { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";
+
+import { client } from "https://esm.sh/v132/[email protected]/denonext/websocket.mjs";
+import type { Database } from "../../../src/types.ts";
+import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+// Use the supabase types to define a subset of the database we'll transact with
+interface DB {
+ generalLedger: Database["public"]["Tables"]["generalLedger"]["Insert"];
+ purchaseOrderDelivery: Database["public"]["Tables"]["purchaseOrderDelivery"]["Update"];
+ purchaseOrderLine: Database["public"]["Tables"]["purchaseOrderLine"]["Update"];
+ partLedger: Database["public"]["Tables"]["partLedger"]["Insert"];
+ partLedgerValueLedgerRelation: Database["public"]["Tables"]["partLedgerValueLedgerRelation"]["Insert"];
+ receipt: Database["public"]["Tables"]["receipt"]["Update"];
+ valueLedger: Database["public"]["Tables"]["valueLedger"]["Insert"];
+ valueLedgerGeneralLedgerRelation: Database["public"]["Tables"]["valueLedgerGeneralLedgerRelation"]["Insert"];
+}
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const { receiptId } = await req.json();
+
+ try {
+ if (!receiptId) throw new Error("No receiptId provided");
+
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+
+ const receipt = await client
+ .from("receipt")
+ .select("*")
+ .eq("id", receiptId)
+ .single();
+ if (receipt.error) throw new Error("Failed to fetch receipt");
+
+ const receiptLines = await client
+ .from("receiptLine")
+ .select("*")
+ .eq("receiptId", receipt.data.receiptId);
+ if (receiptLines.error) throw new Error("Failed to fetch receipt lines");
+
+ const partGroups = await client
+ .from("part")
+ .select("id, partGroupId")
+ .in(
+ "id",
+ receiptLines.data.reduce<string[]>((acc, receiptLine) => {
+ if (receiptLine.partId && !acc.includes(receiptLine.partId)) {
+ acc.push(receiptLine.partId);
+ }
+ return acc;
+ }, [])
+ );
+ if (partGroups.error) throw new Error("Failed to fetch part groups");
+
+ switch (receipt.data?.sourceDocument) {
+ case "Purchase Order": {
+ let purchaseOrderLineUpdates: Record<
+ string,
+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]
+ > = {};
+
+ const valueLedgerInserts: Database["public"]["Tables"]["valueLedger"]["Insert"][] =
+ [];
+ const partLedgerInserts: Database["public"]["Tables"]["partLedger"]["Insert"][] =
+ [];
+ const generalLedgerInserts: Database["public"]["Tables"]["generalLedger"]["Insert"][] =
+ [];
+
+ if (!receipt.data.sourceDocumentId)
+ throw new Error("Receipt has no sourceDocumentId");
+
+ const [purchaseOrder, purchaseOrderLines] = await Promise.all([
+ client
+ .from("purchaseOrder")
+ .select("*")
+ .eq("id", receipt.data.sourceDocumentId)
+ .single(),
+ client
+ .from("purchaseOrderLine")
+ .select("*")
+ .eq("purchaseOrderId", receipt.data.sourceDocumentId),
+ ]);
+ if (purchaseOrder.error)
+ throw new Error("Failed to fetch purchase order");
+ if (purchaseOrderLines.error)
+ throw new Error("Failed to fetch purchase order lines");
+
+ const receiptLinesByLineId = receiptLines.data.reduce<
+ Record<string, Database["public"]["Tables"]["receiptLine"]["Row"]>
+ >((acc, receiptLine) => {
+ if (receiptLine.lineId) {
+ acc[receiptLine.lineId] = receiptLine;
+ }
+ return acc;
+ }, {});
+
+ purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<
+ Record<
+ string,
+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]
+ >
+ >((acc, purchaseOrderLine) => {
+ const receiptLine = receiptLinesByLineId[purchaseOrderLine.id];
+ if (
+ receiptLine &&
+ receiptLine.receivedQuantity &&
+ purchaseOrderLine.purchaseQuantity &&
+ purchaseOrderLine.purchaseQuantity > 0
+ ) {
+ const newQuantityReceived =
+ (purchaseOrderLine.quantityReceived ?? 0) +
+ receiptLine.receivedQuantity;
+
+ const receivedComplete =
+ purchaseOrderLine.receivedComplete ||
+ receiptLine.receivedQuantity >=
+ (purchaseOrderLine.quantityToReceive ??
+ purchaseOrderLine.purchaseQuantity);
+
+ return {
+ ...acc,
+ [purchaseOrderLine.id]: {
+ quantityReceived: newQuantityReceived,
+ receivedComplete,
+ },
+ };
+ }
+
+ return acc;
+ }, {});
+
+ const cachedInventoryPostingGroups: Record<
+ string,
+ Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
+ > = {};
+
+ for await (const receiptLine of receiptLines.data) {
+ const expectedValue =
+ receiptLine.receivedQuantity * receiptLine.unitPrice;
+
+ // value ledger entry
+ valueLedgerInserts.push({
+ partLedgerType: "Purchase",
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: "Purchase Receipt",
+ documentId: receipt.data?.receiptId ?? undefined,
+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,
+ costAmountActual: 0,
+ costAmountExpected: expectedValue,
+ actualCostPostedToGl: 0,
+ expectedCostPostedToGl: expectedValue,
+ });
+
+ // part ledger entry
+ partLedgerInserts.push({
+ entryType: "Positive Adjmt.",
+ documentType: "Purchase Receipt",
+ documentId: receipt.data?.receiptId ?? undefined,
+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,
+ partId: receiptLine.partId,
+ locationId: receiptLine.locationId ?? undefined,
+ shelfId: receiptLine.shelfId ?? undefined,
+ quantity: receiptLine.receivedQuantity,
+ });
+
+ // general ledger entries
+ let postingGroup:
+ | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
+ | null = null;
+ const partGroupId: string | null =
+ partGroups.data.find(
+ (partGroup) => partGroup.id === receiptLine.partId
+ )?.partGroupId ?? null;
+ const locationId = receiptLine.locationId ?? null;
+
+ if (`${partGroupId}-${locationId}` in cachedInventoryPostingGroups) {
+ postingGroup =
+ cachedInventoryPostingGroups[`${partGroupId}-${locationId}`];
+ } else {
+ const inventoryPostingGroup = await getInventoryPostingGroup(
+ client,
+ {
+ partGroupId,
+ locationId,
+ }
+ );
+
+ if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
+ throw new Error("Error getting inventory posting group");
+ }
+
+ postingGroup = inventoryPostingGroup.data ?? null;
+ cachedInventoryPostingGroups[`${partGroupId}-${locationId}`] =
+ postingGroup;
+ }
+
+ if (!postingGroup) {
+ throw new Error("No inventory posting group found");
+ }
+
+ generalLedgerInserts.push({
+ accountNumber: postingGroup.inventoryInterimAccrualAccount,
+ description: "Interim Inventory Accrual",
+ amount: -expectedValue,
+ documentType: "Order",
+ documentId: receipt.data?.sourceDocumentReadableId ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ });
+ generalLedgerInserts.push({
+ accountNumber: postingGroup.inventoryReceivedNotInvoicedAccount,
+ description: "Inventory Received Not Invoiced",
+ amount: expectedValue,
+ documentType: "Order",
+ documentId: receipt.data?.sourceDocumentReadableId ?? undefined,
+ externalDocumentId:
+ purchaseOrder.data?.supplierReference ?? undefined,
+ });
+ }
+
+ await db.transaction().execute(async (trx) => {
+ for await (const [purchaseOrderLineId, update] of Object.entries(
+ purchaseOrderLineUpdates
+ )) {
+ await trx
+ .updateTable("purchaseOrderLine")
+ .set(update)
+ .where("id", "=", purchaseOrderLineId)
+ .execute();
+ }
+
+ await trx
+ .updateTable("purchaseOrderDelivery")
+ .set({
+ deliveryDate: format(new Date(), "yyyy-MM-dd"),
+ locationId: receipt.data.locationId,
+ })
+ .where("id", "=", receipt.data.sourceDocumentId)
+ .execute();
+
+ const partLedgerIds = await trx
+ .insertInto("partLedger")
+ .values(partLedgerInserts)
+ .returning(["id"])
+ .execute();
+
+ const generalLedgerIds = await trx
+ .insertInto("generalLedger")
+ .values(generalLedgerInserts)
+ .returning(["id"])
+ .execute();
+
+ const valueLedgerIds = await trx
+ .insertInto("valueLedger")
+ .values(valueLedgerInserts)
+ .returning(["id"])
+ .execute();
+
+ const glEntriesPerValueEntry =
+ generalLedgerIds.length / valueLedgerIds.length;
+ if (
+ glEntriesPerValueEntry !== 2 ||
+ partLedgerIds.length !== valueLedgerIds.length
+ ) {
+ throw new Error("Failed to insert ledger entries");
+ }
+
+ for (let i = 0; i < valueLedgerIds.length; i++) {
+ const valueLedgerId = valueLedgerIds[i].id;
+ const partLedgerId = partLedgerIds[i].id;
+
+ if (!valueLedgerId || !partLedgerId) {
+ throw new Error("Failed to insert ledger entries");
+ }
+
+ await trx
+ .insertInto("partLedgerValueLedgerRelation")
+ .values({
+ partLedgerId,
+ valueLedgerId,
+ })
+ .execute();
+
+ for (let j = 0; j < glEntriesPerValueEntry; j++) {
+ const generalLedgerId =
+ generalLedgerIds[i * glEntriesPerValueEntry + j].id;
+ if (!generalLedgerId) {
+ throw new Error("Failed to insert ledger entries");
+ }
+
+ await trx
+ .insertInto("valueLedgerGeneralLedgerRelation")
+ .values({
+ valueLedgerId,
+ generalLedgerId,
+ })
+ .execute();
+ }
+ }
+
+ await trx
+ .updateTable("receipt")
+ .set({
+ status: "Posted",
+ postingDate: format(new Date(), "yyyy-MM-dd"),
+ })
+ .where("id", "=", receiptId)
+ .execute();
+ });
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+
+ return new Response(
+ JSON.stringify({
+ data: null,
+ error: null,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ if (receiptId) {
+ client.from("receipt").update({ status: "Draft" }).eq("id", receiptId);
+ }
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
+
+async function getInventoryPostingGroup(
+ client: SupabaseClient<Database>,
+ args: {
+ partGroupId: string | null;
+ locationId: string | null;
+ }
+) {
+ let query = client.from("postingGroupInventory").select("*");
+
+ if (args.partGroupId === null) {
+ query = query.is("partGroupId", null);
+ } else {
+ query = query.eq("partGroupId", args.partGroupId);
+ }
+
+ if (args.locationId === null) {
+ query = query.is("locationId", null);
+ } else {
+ query = query.eq("locationId", args.locationId);
+ }
+
+ return await query.single();
+}
diff --git a/packages/carbon-database/supabase/migrations/20230123003711_xid.sql b/packages/database/supabase/migrations/20230123003711_xid.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123003711_xid.sql
rename to packages/database/supabase/migrations/20230123003711_xid.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004206_claims.sql
rename to packages/database/supabase/migrations/20230123004206_claims.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004316_users.sql b/packages/database/supabase/migrations/20230123004316_users.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004316_users.sql
rename to packages/database/supabase/migrations/20230123004316_users.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004339_employee-types.sql b/packages/database/supabase/migrations/20230123004339_employee-types.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004339_employee-types.sql
rename to packages/database/supabase/migrations/20230123004339_employee-types.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004409_permissions.sql b/packages/database/supabase/migrations/20230123004409_permissions.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004409_permissions.sql
rename to packages/database/supabase/migrations/20230123004409_permissions.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004436_employee.sql
rename to packages/database/supabase/migrations/20230123004436_employee.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004514_buckets.sql
rename to packages/database/supabase/migrations/20230123004514_buckets.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004536_attributes.sql b/packages/database/supabase/migrations/20230123004536_attributes.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004536_attributes.sql
rename to packages/database/supabase/migrations/20230123004536_attributes.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql
rename to packages/database/supabase/migrations/20230123004612_suppliers-and-customers.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123004632_groups.sql b/packages/database/supabase/migrations/20230123004632_groups.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123004632_groups.sql
rename to packages/database/supabase/migrations/20230123004632_groups.sql
diff --git a/packages/carbon-database/supabase/migrations/20230123212853_search.sql b/packages/database/supabase/migrations/20230123212853_search.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230123212853_search.sql
rename to packages/database/supabase/migrations/20230123212853_search.sql
diff --git a/packages/carbon-database/supabase/migrations/20230126050441_rbac.sql b/packages/database/supabase/migrations/20230126050441_rbac.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230126050441_rbac.sql
rename to packages/database/supabase/migrations/20230126050441_rbac.sql
diff --git a/packages/carbon-database/supabase/migrations/20230209041302_notes.sql b/packages/database/supabase/migrations/20230209041302_notes.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230209041302_notes.sql
rename to packages/database/supabase/migrations/20230209041302_notes.sql
diff --git a/packages/carbon-database/supabase/migrations/20230215023746_abilities.sql b/packages/database/supabase/migrations/20230215023746_abilities.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230215023746_abilities.sql
rename to packages/database/supabase/migrations/20230215023746_abilities.sql
diff --git a/packages/carbon-database/supabase/migrations/20230224035103_shifts.sql b/packages/database/supabase/migrations/20230224035103_shifts.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230224035103_shifts.sql
rename to packages/database/supabase/migrations/20230224035103_shifts.sql
diff --git a/packages/carbon-database/supabase/migrations/20230302030217_equipment.sql b/packages/database/supabase/migrations/20230302030217_equipment.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230302030217_equipment.sql
rename to packages/database/supabase/migrations/20230302030217_equipment.sql
diff --git a/packages/carbon-database/supabase/migrations/20230303041316_realtime-users.sql b/packages/database/supabase/migrations/20230303041316_realtime.sql
similarity index 70%
rename from packages/carbon-database/supabase/migrations/20230303041316_realtime-users.sql
rename to packages/database/supabase/migrations/20230303041316_realtime.sql
index 1cf481e859..9894dd25ce 100644
--- a/packages/carbon-database/supabase/migrations/20230303041316_realtime-users.sql
+++ b/packages/database/supabase/migrations/20230303041316_realtime.sql
@@ -5,6 +5,3 @@ BEGIN;
-- re-create the supabase_realtime publication with no tables
CREATE publication supabase_realtime;
COMMIT;
-
--- add a table to the publication
-ALTER publication supabase_realtime ADD TABLE "user";
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql b/packages/database/supabase/migrations/20230315222231_holidays.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230315222231_holidays.sql
rename to packages/database/supabase/migrations/20230315222231_holidays.sql
diff --git a/packages/carbon-database/supabase/migrations/20230319224154_partners.sql b/packages/database/supabase/migrations/20230319224154_partners.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230319224154_partners.sql
rename to packages/database/supabase/migrations/20230319224154_partners.sql
diff --git a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql b/packages/database/supabase/migrations/20230329021751_contractors.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
rename to packages/database/supabase/migrations/20230329021751_contractors.sql
diff --git a/packages/carbon-database/supabase/migrations/20230330024715_accounts.sql b/packages/database/supabase/migrations/20230330024715_accounts.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230330024715_accounts.sql
rename to packages/database/supabase/migrations/20230330024715_accounts.sql
diff --git a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
similarity index 96%
rename from packages/carbon-database/supabase/migrations/20230330024716_parts.sql
rename to packages/database/supabase/migrations/20230330024716_parts.sql
index 4b63714d5d..da9770a548 100644
--- a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -160,6 +160,7 @@ CREATE INDEX "part_description_index" ON "part"("description");
CREATE INDEX "part_partType_index" ON "part"("partType");
CREATE INDEX "part_partGroupId_index" ON "part"("partGroupId");
CREATE INDEX "part_replenishmentSystem_index" ON "part"("replenishmentSystem");
+CREATE INDEX "part_active_blocked_index" ON "part"("active", "blocked");
ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;
@@ -727,30 +728,6 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partInv
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
--- CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
--- FOR SELECT
--- USING (
--- coalesce(get_my_claim('parts_view')::boolean, false) = true
--- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
--- AND (
--- "partId" IN (
--- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
--- );
-
--- CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
--- FOR UPDATE
--- USING (
--- coalesce(get_my_claim('parts_update')::boolean, false) = true
--- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
--- AND (
--- "partId" IN (
--- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
--- );
\ No newline at end of file
+
+
+
diff --git a/packages/carbon-database/supabase/migrations/20230423023136_documents.sql b/packages/database/supabase/migrations/20230423023136_documents.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230423023136_documents.sql
rename to packages/database/supabase/migrations/20230423023136_documents.sql
diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/database/supabase/migrations/20230510035345_purchasing.sql
similarity index 97%
rename from packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
rename to packages/database/supabase/migrations/20230510035345_purchasing.sql
index b04b1bfdef..1fba4dc979 100644
--- a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/database/supabase/migrations/20230510035345_purchasing.sql
@@ -149,7 +149,7 @@ CREATE TYPE "purchaseOrderType" AS ENUM (
);
CREATE TYPE "purchaseOrderStatus" AS ENUM (
- 'Open',
+ 'Draft',
'In Review',
'In External Review',
'Approved',
@@ -162,7 +162,7 @@ CREATE TABLE "purchaseOrder" (
"id" TEXT NOT NULL DEFAULT xid(),
"purchaseOrderId" TEXT NOT NULL,
"type" "purchaseOrderType" NOT NULL,
- "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Open',
+ "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Draft',
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
@@ -205,9 +205,9 @@ CREATE TABLE "purchaseOrderLine" (
"assetId" TEXT,
"description" TEXT,
"purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
- "quantityToReceive" NUMERIC(9,2) DEFAULT 0,
+ "quantityToReceive" NUMERIC(9,2) GENERATED ALWAYS AS (CASE WHEN "purchaseOrderLineType" = 'Comment' THEN 0 ELSE GREATEST(("purchaseQuantity" - "quantityReceived"), 0) END) STORED,
"quantityReceived" NUMERIC(9,2) DEFAULT 0,
- "quantityToInvoice" NUMERIC(9,2) DEFAULT 0,
+ "quantityToInvoice" NUMERIC(9,2) GENERATED ALWAYS AS (CASE WHEN "purchaseOrderLineType" = 'Comment' THEN 0 ELSE GREATEST(("purchaseQuantity" - "quantityInvoiced"), 0) END) STORED,
"quantityInvoiced" NUMERIC(9,2) DEFAULT 0,
"unitPrice" NUMERIC(9,2),
"unitOfMeasureCode" TEXT,
diff --git a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql b/packages/database/supabase/migrations/20230525025310_sequences.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
rename to packages/database/supabase/migrations/20230525025310_sequences.sql
diff --git a/packages/carbon-database/supabase/migrations/20230629113514_purchasing-files.sql b/packages/database/supabase/migrations/20230629113514_purchasing-files.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230629113514_purchasing-files.sql
rename to packages/database/supabase/migrations/20230629113514_purchasing-files.sql
diff --git a/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
rename to packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
diff --git a/packages/carbon-database/supabase/migrations/20230704160029_supplier-view.sql b/packages/database/supabase/migrations/20230704160029_supplier-view.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230704160029_supplier-view.sql
rename to packages/database/supabase/migrations/20230704160029_supplier-view.sql
diff --git a/packages/carbon-database/supabase/migrations/20230704161623_parts-view.sql b/packages/database/supabase/migrations/20230704161623_parts-view.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230704161623_parts-view.sql
rename to packages/database/supabase/migrations/20230704161623_parts-view.sql
diff --git a/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql b/packages/database/supabase/migrations/20230704175831_view-rls.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql
rename to packages/database/supabase/migrations/20230704175831_view-rls.sql
diff --git a/packages/carbon-database/supabase/migrations/20230705033431_warehouses.sql b/packages/database/supabase/migrations/20230705033431_warehouses.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230705033431_warehouses.sql
rename to packages/database/supabase/migrations/20230705033431_warehouses.sql
diff --git a/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql b/packages/database/supabase/migrations/20230705033432_ledgers.sql
similarity index 70%
rename from packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql
rename to packages/database/supabase/migrations/20230705033432_ledgers.sql
index d37df15238..06a033b8e7 100644
--- a/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql
+++ b/packages/database/supabase/migrations/20230705033432_ledgers.sql
@@ -1,4 +1,4 @@
-CREATE TYPE "accountDocumentLedgerType" AS ENUM (
+CREATE TYPE "generalLedgerDocumentType" AS ENUM (
'Quote',
'Order',
'Invoice',
@@ -10,13 +10,13 @@ CREATE TYPE "accountDocumentLedgerType" AS ENUM (
CREATE TABLE "generalLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"accountNumber" TEXT NOT NULL,
"description" TEXT,
"amount" NUMERIC(19, 4) NOT NULL,
- "documentType" "accountDocumentLedgerType",
- "documentNumber" TEXT,
- "externalDocumentNumber" TEXT,
+ "documentType" "generalLedgerDocumentType",
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "generalLedger_pkey" PRIMARY KEY ("id"),
@@ -89,12 +89,13 @@ CREATE TYPE "partLedgerDocumentType" AS ENUM (
CREATE TABLE "valueLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"partLedgerType" "partLedgerType" NOT NULL,
"costLedgerType" "costLedgerType" NOT NULL,
"adjustment" BOOLEAN NOT NULL DEFAULT false,
"documentType" "partLedgerDocumentType",
- "documentNumber" TEXT,
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,
"costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,
"actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,
@@ -113,40 +114,37 @@ CREATE POLICY "Employees with accounting_view can view the value ledger" ON "val
(get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE TABLE "valueLedgerAccountLedgerRelation" (
+CREATE TABLE "valueLedgerGeneralLedgerRelation" (
"valueLedgerId" TEXT NOT NULL,
"generalLedgerId" TEXT NOT NULL,
- CONSTRAINT "valueLedgerAccountLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),
- CONSTRAINT "valueLedgerAccountLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),
- CONSTRAINT "valueLedgerAccountLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),
+ CONSTRAINT "valueLedgerGeneralLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")
);
-ALTER TABLE "valueLedgerAccountLedgerRelation" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "valueLedgerGeneralLedgerRelation" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees with accounting_view can view the value ledger account relations" ON "valueLedgerAccountLedgerRelation"
+CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "valueLedgerGeneralLedgerRelation"
FOR SELECT
USING (
coalesce(get_my_claim('accounting_view')::boolean, false) = true AND
(get_my_claim('role'::text)) = '"employee"'::jsonb
);
+
CREATE TABLE "partLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
"entryNumber" SERIAL,
- "postingDate" DATE NOT NULL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"entryType" "partLedgerType" NOT NULL,
"documentType" "partLedgerDocumentType",
- "documentNumber" TEXT,
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
"partId" TEXT NOT NULL,
"locationId" TEXT,
"shelfId" TEXT,
"quantity" NUMERIC(12, 4) NOT NULL,
- "invoicedQuantity" NUMERIC(12, 4) NOT NULL,
- "remainingQuantity" NUMERIC(12, 4) NOT NULL,
- "salesAmount" NUMERIC(12, 4) NOT NULL,
- "costAmount" NUMERIC(12, 4) NOT NULL,
- "open" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),
@@ -167,7 +165,47 @@ CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger"
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+CREATE TABLE "partLedgerValueLedgerRelation" (
+ "partLedgerId" TEXT NOT NULL,
+ "valueLedgerId" TEXT NOT NULL,
+
+ CONSTRAINT "partLedgerValueLedgerRelation_pkey" PRIMARY KEY ("partLedgerId", "valueLedgerId"),
+ CONSTRAINT "partLedgerValueLedgerRelation_partLedgerId_fkey" FOREIGN KEY ("partLedgerId") REFERENCES "partLedger"("id"),
+ CONSTRAINT "partLedgerValueLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id")
+);
+ALTER TABLE "partLedgerValueLedgerRelation" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with accounting_view can view the part ledger/value ledger relations" ON "partLedgerValueLedgerRelation"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE TYPE "supplierLedgerDocumentType" AS ENUM (
+ 'Payment',
+ 'Invoice',
+ 'Credit Memo',
+ 'Finance Charge Memo',
+ 'Reminder',
+ 'Refund'
+);
+
+CREATE TABLE "supplierLedger" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "entryNumber" SERIAL,
+ "postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,
+ "documentType" "supplierLedgerDocumentType",
+ "documentId" TEXT,
+ "externalDocumentId" TEXT,
+ "supplierId" TEXT NOT NULL,
+ "amount" NUMERIC(19, 4) NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+
+ CONSTRAINT "supplierLedger_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierLedger_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON UPDATE CASCADE ON DELETE CASCADE
+);
CREATE OR REPLACE FUNCTION gl_transactions_by_account_number(
@@ -195,3 +233,5 @@ AS $$
$$;
+
+
diff --git a/packages/carbon-database/supabase/migrations/20230728025201_receipts.sql b/packages/database/supabase/migrations/20230728025201_receipts.sql
similarity index 89%
rename from packages/carbon-database/supabase/migrations/20230728025201_receipts.sql
rename to packages/database/supabase/migrations/20230728025201_receipts.sql
index 5c1511cd88..0c7e8426db 100644
--- a/packages/carbon-database/supabase/migrations/20230728025201_receipts.sql
+++ b/packages/database/supabase/migrations/20230728025201_receipts.sql
@@ -9,6 +9,12 @@ CREATE TYPE "receiptSourceDocument" AS ENUM (
'Manufacturing Output'
);
+CREATE TYPE "receiptStatus" AS ENUM (
+ 'Draft',
+ 'Pending',
+ 'Posted'
+);
+
CREATE TABLE "receipt" (
"id" TEXT NOT NULL DEFAULT xid(),
"receiptId" TEXT NOT NULL,
@@ -16,8 +22,11 @@ CREATE TABLE "receipt" (
"sourceDocument" "receiptSourceDocument",
"sourceDocumentId" TEXT,
"sourceDocumentReadableId" TEXT,
+ "externalDocumentId" TEXT,
"supplierId" TEXT,
+ "status" "receiptStatus" NOT NULL DEFAULT 'Draft',
"postingDate" DATE,
+ "invoiced" BOOLEAN DEFAULT FALSE,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -38,12 +47,12 @@ CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId");
ALTER TABLE "receipt" ENABLE ROW LEVEL SECURITY;
+-- TODO: this is a workaround to get around a bug with realtime subscriptions not working with the standard RLS
+-- it seems the client is not sending the right JWT token when it subscribes to the realtime channel
CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"
FOR SELECT
- USING (
- coalesce(get_my_claim('inventory_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
+ USING (coalesce(get_my_claim('inventory_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
CREATE POLICY "Employees with inventory_create can insert receipts" ON "receipt"
@@ -67,6 +76,8 @@ CREATE POLICY "Employees with inventory_delete can delete receipts" ON "receipt"
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+ALTER publication supabase_realtime ADD TABLE "receipt";
+
CREATE TABLE "receiptLine" (
"id" TEXT NOT NULL DEFAULT xid(),
"receiptId" TEXT NOT NULL,
@@ -137,3 +148,5 @@ CREATE VIEW "receipt_quantity_received_by_line" AS
INNER JOIN "receiptLine" l
ON l."receiptId" = r."receiptId"
GROUP BY r."sourceDocumentId", l."lineId";
+
+
diff --git a/packages/carbon-database/supabase/migrations/20230810035313_defaults.sql b/packages/database/supabase/migrations/20230810035313_defaults.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230810035313_defaults.sql
rename to packages/database/supabase/migrations/20230810035313_defaults.sql
diff --git a/packages/carbon-database/supabase/migrations/20230820020844_posting-groups.sql b/packages/database/supabase/migrations/20230820020844_posting-groups.sql
similarity index 100%
rename from packages/carbon-database/supabase/migrations/20230820020844_posting-groups.sql
rename to packages/database/supabase/migrations/20230820020844_posting-groups.sql
diff --git a/packages/database/supabase/migrations/20230912210957_accounts-payable.sql b/packages/database/supabase/migrations/20230912210957_accounts-payable.sql
new file mode 100644
index 0000000000..85ab2e27ba
--- /dev/null
+++ b/packages/database/supabase/migrations/20230912210957_accounts-payable.sql
@@ -0,0 +1,45 @@
+CREATE VIEW "receipts_posted_not_invoiced" AS
+ SELECT
+ r."id",
+ r."receiptId",
+ r."sourceDocument",
+ r."sourceDocumentId",
+ r."sourceDocumentReadableId",
+ r."postingDate",
+ r."supplierId",
+ s."name" AS "supplierName",
+ SUM(l."receivedQuantity" * l."unitPrice") AS "estimatedCost"
+ FROM "receipt" r
+ INNER JOIN "receiptLine" l
+ ON l."receiptId" = r."receiptId"
+ INNER JOIN "supplier" s
+ ON s."id" = r."supplierId"
+ WHERE r."status" = 'Posted'
+ AND r."invoiced" = FALSE
+ AND r."sourceDocument" != 'Manufacturing Consumption'
+ AND r."sourceDocument" != 'Manufacturing Output'
+ AND r."sourceDocument" != 'Inbound Transfer'
+ AND r."sourceDocument" != 'Outbound Transfer'
+
+ GROUP BY
+ r."id",
+ r."receiptId",
+ r."sourceDocument",
+ r."sourceDocumentId",
+ r."sourceDocumentReadableId",
+ r."postingDate",
+ r."supplierId",
+ s."name";
+;
+
+CREATE VIEW "total_receipts_posted_not_invoiced" AS
+ SELECT SUM(l."receivedQuantity" * l."unitPrice") AS "total"
+ FROM "receipt" r
+ INNER JOIN "receiptLine" l
+ ON l."receiptId" = r."receiptId"
+ WHERE r."status" = 'Posted'
+ AND r."invoiced" = FALSE
+ AND r."sourceDocument" != 'Manufacturing Consumption'
+ AND r."sourceDocument" != 'Manufacturing Output'
+ AND r."sourceDocument" != 'Inbound Transfer'
+ AND r."sourceDocument" != 'Outbound Transfer';
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230915193213_quantity-on-hand.sql b/packages/database/supabase/migrations/20230915193213_quantity-on-hand.sql
new file mode 100644
index 0000000000..103f671252
--- /dev/null
+++ b/packages/database/supabase/migrations/20230915193213_quantity-on-hand.sql
@@ -0,0 +1,32 @@
+CREATE VIEW "part_quantities_view" AS
+ SELECT
+ p."id" AS "partId",
+ loc."id" AS "locationId",
+ COALESCE(SUM(pl."quantity"), 0) AS "quantityOnHand",
+ COALESCE(pol."quantityToReceive", 0) AS "quantityOnPurchaseOrder",
+ 0 AS "quantityOnSalesOrder",
+ 0 AS "quantityOnProdOrder",
+ 0 AS "quantityAvailable"
+ FROM "part" p
+ CROSS JOIN "location" loc
+ LEFT JOIN "partLedger" pl
+ ON pl."partId" = p."id" AND pl."locationId" = loc."id"
+ LEFT JOIN (
+ SELECT
+ pol."partId",
+ pol."locationId",
+ COALESCE(SUM(GREATEST(pol."quantityToReceive", 0)), 0) AS "quantityToReceive"
+ FROM "purchaseOrderLine" pol
+ INNER JOIN "purchaseOrder" po
+ ON pol."purchaseOrderId" = po."id"
+ WHERE po."status" != 'Draft'
+ AND po."status" != 'Rejected'
+ AND po."status" != 'Closed'
+ GROUP BY
+ pol."partId",
+ pol."locationId"
+ ) pol ON pol."partId" = p."id" AND pol."locationId" = loc."id"
+ GROUP BY
+ p."id",
+ loc."id",
+ pol."quantityToReceive"
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/seed.sql b/packages/database/supabase/seed.sql
similarity index 100%
rename from packages/carbon-database/supabase/seed.sql
rename to packages/database/supabase/seed.sql
diff --git a/packages/carbon-database/tsconfig.json b/packages/database/tsconfig.json
similarity index 100%
rename from packages/carbon-database/tsconfig.json
rename to packages/database/tsconfig.json
diff --git a/packages/carbon-database/tsup.config.bundled_o7g8q4dn64b.mjs b/packages/database/tsup.config.bundled_o7g8q4dn64b.mjs
similarity index 100%
rename from packages/carbon-database/tsup.config.bundled_o7g8q4dn64b.mjs
rename to packages/database/tsup.config.bundled_o7g8q4dn64b.mjs
diff --git a/packages/carbon-database/tsup.config.ts b/packages/database/tsup.config.ts
similarity index 100%
rename from packages/carbon-database/tsup.config.ts
rename to packages/database/tsup.config.ts
diff --git a/packages/carbon-database/.eslintrc.js b/packages/jest/.eslintrc.js
similarity index 100%
rename from packages/carbon-database/.eslintrc.js
rename to packages/jest/.eslintrc.js
diff --git a/packages/carbon-jest/node/jest-preset.js b/packages/jest/node/jest-preset.js
similarity index 100%
rename from packages/carbon-jest/node/jest-preset.js
rename to packages/jest/node/jest-preset.js
diff --git a/packages/carbon-jest/package.json b/packages/jest/package.json
similarity index 76%
rename from packages/carbon-jest/package.json
rename to packages/jest/package.json
index 738d63b184..85ed85be49 100644
--- a/packages/carbon-jest/package.json
+++ b/packages/jest/package.json
@@ -8,5 +8,8 @@
},
"dependencies": {
"ts-jest": "^26.5.0"
+ },
+ "devDependencies": {
+ "eslint-config-carbon": "*"
}
}
diff --git a/packages/carbon-logger/.eslintrc.js b/packages/logger/.eslintrc.js
similarity index 100%
rename from packages/carbon-logger/.eslintrc.js
rename to packages/logger/.eslintrc.js
diff --git a/packages/carbon-logger/package.json b/packages/logger/package.json
similarity index 100%
rename from packages/carbon-logger/package.json
rename to packages/logger/package.json
diff --git a/packages/carbon-logger/src/__tests__/log.test.ts b/packages/logger/src/__tests__/log.test.ts
similarity index 100%
rename from packages/carbon-logger/src/__tests__/log.test.ts
rename to packages/logger/src/__tests__/log.test.ts
diff --git a/packages/carbon-logger/src/__tests__/tsconfig.json b/packages/logger/src/__tests__/tsconfig.json
similarity index 100%
rename from packages/carbon-logger/src/__tests__/tsconfig.json
rename to packages/logger/src/__tests__/tsconfig.json
diff --git a/packages/carbon-logger/src/index.ts b/packages/logger/src/index.ts
similarity index 100%
rename from packages/carbon-logger/src/index.ts
rename to packages/logger/src/index.ts
diff --git a/packages/carbon-logger/tsconfig.json b/packages/logger/tsconfig.json
similarity index 100%
rename from packages/carbon-logger/tsconfig.json
rename to packages/logger/tsconfig.json
diff --git a/packages/carbon-react/.eslintrc.js b/packages/react/.eslintrc.js
similarity index 100%
rename from packages/carbon-react/.eslintrc.js
rename to packages/react/.eslintrc.js
diff --git a/packages/carbon-react/package.json b/packages/react/package.json
similarity index 100%
rename from packages/carbon-react/package.json
rename to packages/react/package.json
diff --git a/packages/carbon-react/src/Button/BorderFollower.tsx b/packages/react/src/Button/BorderFollower.tsx
similarity index 100%
rename from packages/carbon-react/src/Button/BorderFollower.tsx
rename to packages/react/src/Button/BorderFollower.tsx
diff --git a/packages/carbon-react/src/Button/BorderMask.tsx b/packages/react/src/Button/BorderMask.tsx
similarity index 100%
rename from packages/carbon-react/src/Button/BorderMask.tsx
rename to packages/react/src/Button/BorderMask.tsx
diff --git a/packages/carbon-react/src/Button/Button.tsx b/packages/react/src/Button/Button.tsx
similarity index 100%
rename from packages/carbon-react/src/Button/Button.tsx
rename to packages/react/src/Button/Button.tsx
diff --git a/packages/carbon-react/src/Button/index.ts b/packages/react/src/Button/index.ts
similarity index 100%
rename from packages/carbon-react/src/Button/index.ts
rename to packages/react/src/Button/index.ts
diff --git a/packages/carbon-react/src/Count/Count.tsx b/packages/react/src/Count/Count.tsx
similarity index 100%
rename from packages/carbon-react/src/Count/Count.tsx
rename to packages/react/src/Count/Count.tsx
diff --git a/packages/carbon-react/src/Count/index.ts b/packages/react/src/Count/index.ts
similarity index 100%
rename from packages/carbon-react/src/Count/index.ts
rename to packages/react/src/Count/index.ts
diff --git a/packages/carbon-react/src/DataTable/DataTable.tsx b/packages/react/src/DataTable/DataTable.tsx
similarity index 100%
rename from packages/carbon-react/src/DataTable/DataTable.tsx
rename to packages/react/src/DataTable/DataTable.tsx
diff --git a/packages/carbon-react/src/DataTable/DataTableColumnHeader.tsx b/packages/react/src/DataTable/DataTableColumnHeader.tsx
similarity index 100%
rename from packages/carbon-react/src/DataTable/DataTableColumnHeader.tsx
rename to packages/react/src/DataTable/DataTableColumnHeader.tsx
diff --git a/packages/carbon-react/src/DataTable/DataTablePagination.tsx b/packages/react/src/DataTable/DataTablePagination.tsx
similarity index 100%
rename from packages/carbon-react/src/DataTable/DataTablePagination.tsx
rename to packages/react/src/DataTable/DataTablePagination.tsx
diff --git a/packages/carbon-react/src/DataTable/index.ts b/packages/react/src/DataTable/index.ts
similarity index 100%
rename from packages/carbon-react/src/DataTable/index.ts
rename to packages/react/src/DataTable/index.ts
diff --git a/packages/carbon-react/src/Dot/Dot.tsx b/packages/react/src/Dot/Dot.tsx
similarity index 100%
rename from packages/carbon-react/src/Dot/Dot.tsx
rename to packages/react/src/Dot/Dot.tsx
diff --git a/packages/carbon-react/src/Dot/index.ts b/packages/react/src/Dot/index.ts
similarity index 100%
rename from packages/carbon-react/src/Dot/index.ts
rename to packages/react/src/Dot/index.ts
diff --git a/packages/carbon-react/src/HTML/HTML.tsx b/packages/react/src/HTML/HTML.tsx
similarity index 100%
rename from packages/carbon-react/src/HTML/HTML.tsx
rename to packages/react/src/HTML/HTML.tsx
diff --git a/packages/carbon-react/src/HTML/index.ts b/packages/react/src/HTML/index.ts
similarity index 100%
rename from packages/carbon-react/src/HTML/index.ts
rename to packages/react/src/HTML/index.ts
diff --git a/packages/carbon-react/src/Inputs/Date/DatePicker.tsx b/packages/react/src/Inputs/Date/DatePicker.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/DatePicker.tsx
rename to packages/react/src/Inputs/Date/DatePicker.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/DateRangePicker.tsx b/packages/react/src/Inputs/Date/DateRangePicker.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/DateRangePicker.tsx
rename to packages/react/src/Inputs/Date/DateRangePicker.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/DateTimePicker.tsx b/packages/react/src/Inputs/Date/DateTimePicker.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/DateTimePicker.tsx
rename to packages/react/src/Inputs/Date/DateTimePicker.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/TimePicker.tsx b/packages/react/src/Inputs/Date/TimePicker.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/TimePicker.tsx
rename to packages/react/src/Inputs/Date/TimePicker.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/Button.tsx b/packages/react/src/Inputs/Date/components/Button.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/Button.tsx
rename to packages/react/src/Inputs/Date/components/Button.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/Calendar.tsx b/packages/react/src/Inputs/Date/components/Calendar.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/Calendar.tsx
rename to packages/react/src/Inputs/Date/components/Calendar.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx b/packages/react/src/Inputs/Date/components/CalendarCell.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/CalendarCell.tsx
rename to packages/react/src/Inputs/Date/components/CalendarCell.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/CalendarGrid.tsx b/packages/react/src/Inputs/Date/components/CalendarGrid.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/CalendarGrid.tsx
rename to packages/react/src/Inputs/Date/components/CalendarGrid.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/DateField.tsx b/packages/react/src/Inputs/Date/components/DateField.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/DateField.tsx
rename to packages/react/src/Inputs/Date/components/DateField.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/DateSegment.tsx b/packages/react/src/Inputs/Date/components/DateSegment.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/DateSegment.tsx
rename to packages/react/src/Inputs/Date/components/DateSegment.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/Popover.tsx b/packages/react/src/Inputs/Date/components/Popover.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/Popover.tsx
rename to packages/react/src/Inputs/Date/components/Popover.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/RangeCalendar.tsx b/packages/react/src/Inputs/Date/components/RangeCalendar.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/RangeCalendar.tsx
rename to packages/react/src/Inputs/Date/components/RangeCalendar.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/components/StyledField.tsx b/packages/react/src/Inputs/Date/components/StyledField.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/components/StyledField.tsx
rename to packages/react/src/Inputs/Date/components/StyledField.tsx
diff --git a/packages/carbon-react/src/Inputs/Date/index.ts b/packages/react/src/Inputs/Date/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Date/index.ts
rename to packages/react/src/Inputs/Date/index.ts
diff --git a/packages/carbon-react/src/Inputs/Editor/Editor.tsx b/packages/react/src/Inputs/Editor/Editor.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Editor.tsx
rename to packages/react/src/Inputs/Editor/Editor.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/BlockQuote.tsx b/packages/react/src/Inputs/Editor/Toolbar/BlockQuote.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/BlockQuote.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/BlockQuote.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Bold.tsx b/packages/react/src/Inputs/Editor/Toolbar/Bold.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Bold.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Bold.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Code.tsx b/packages/react/src/Inputs/Editor/Toolbar/Code.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Code.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Code.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/CodeBlock.tsx b/packages/react/src/Inputs/Editor/Toolbar/CodeBlock.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/CodeBlock.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/CodeBlock.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Heading.tsx b/packages/react/src/Inputs/Editor/Toolbar/Heading.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Heading.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Heading.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/HorizontalRule.tsx b/packages/react/src/Inputs/Editor/Toolbar/HorizontalRule.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/HorizontalRule.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/HorizontalRule.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Italic.tsx b/packages/react/src/Inputs/Editor/Toolbar/Italic.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Italic.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Italic.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/OrderedList.tsx b/packages/react/src/Inputs/Editor/Toolbar/OrderedList.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/OrderedList.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/OrderedList.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Paragraph.tsx b/packages/react/src/Inputs/Editor/Toolbar/Paragraph.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Paragraph.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Paragraph.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Strike.tsx b/packages/react/src/Inputs/Editor/Toolbar/Strike.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Strike.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Strike.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/Toolbar.tsx b/packages/react/src/Inputs/Editor/Toolbar/Toolbar.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/Toolbar.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/Toolbar.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/ToolbarButton.tsx b/packages/react/src/Inputs/Editor/Toolbar/ToolbarButton.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/ToolbarButton.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/ToolbarButton.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/UnorderedList.tsx b/packages/react/src/Inputs/Editor/Toolbar/UnorderedList.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/UnorderedList.tsx
rename to packages/react/src/Inputs/Editor/Toolbar/UnorderedList.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/Toolbar/index.ts b/packages/react/src/Inputs/Editor/Toolbar/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/Toolbar/index.ts
rename to packages/react/src/Inputs/Editor/Toolbar/index.ts
diff --git a/packages/carbon-react/src/Inputs/Editor/ToolbarButton.tsx b/packages/react/src/Inputs/Editor/ToolbarButton.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/ToolbarButton.tsx
rename to packages/react/src/Inputs/Editor/ToolbarButton.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/index.tsx b/packages/react/src/Inputs/Editor/index.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/index.tsx
rename to packages/react/src/Inputs/Editor/index.tsx
diff --git a/packages/carbon-react/src/Inputs/Editor/types.ts b/packages/react/src/Inputs/Editor/types.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Editor/types.ts
rename to packages/react/src/Inputs/Editor/types.ts
diff --git a/packages/carbon-react/src/Inputs/File/File.tsx b/packages/react/src/Inputs/File/File.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/File/File.tsx
rename to packages/react/src/Inputs/File/File.tsx
diff --git a/packages/carbon-react/src/Inputs/File/index.ts b/packages/react/src/Inputs/File/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/File/index.ts
rename to packages/react/src/Inputs/File/index.ts
diff --git a/packages/carbon-react/src/Inputs/Phone/countries.json b/packages/react/src/Inputs/Phone/countries.json
similarity index 100%
rename from packages/carbon-react/src/Inputs/Phone/countries.json
rename to packages/react/src/Inputs/Phone/countries.json
diff --git a/packages/carbon-react/src/Inputs/Select/CreatableSelect.tsx b/packages/react/src/Inputs/Select/CreatableSelect.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/CreatableSelect.tsx
rename to packages/react/src/Inputs/Select/CreatableSelect.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/Select.tsx b/packages/react/src/Inputs/Select/Select.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/Select.tsx
rename to packages/react/src/Inputs/Select/Select.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/containers.tsx b/packages/react/src/Inputs/Select/components/containers.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/containers.tsx
rename to packages/react/src/Inputs/Select/components/containers.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/control.tsx b/packages/react/src/Inputs/Select/components/control.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/control.tsx
rename to packages/react/src/Inputs/Select/components/control.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/index.ts b/packages/react/src/Inputs/Select/components/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/index.ts
rename to packages/react/src/Inputs/Select/components/index.ts
diff --git a/packages/carbon-react/src/Inputs/Select/components/input.tsx b/packages/react/src/Inputs/Select/components/input.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/input.tsx
rename to packages/react/src/Inputs/Select/components/input.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/menu.tsx b/packages/react/src/Inputs/Select/components/menu.tsx
similarity index 99%
rename from packages/carbon-react/src/Inputs/Select/components/menu.tsx
rename to packages/react/src/Inputs/Select/components/menu.tsx
index 0194c920bd..d691636171 100644
--- a/packages/carbon-react/src/Inputs/Select/components/menu.tsx
+++ b/packages/react/src/Inputs/Select/components/menu.tsx
@@ -361,7 +361,6 @@ export const Option = <
isMulti,
hideSelectedOptions,
selectedOptionStyle,
- // selectedOptionColor,
chakraStyles,
},
} = props;
@@ -374,7 +373,7 @@ export const Option = <
lg: "0.5rem 1rem",
};
- const selectedBg = useColor("gray.500");
+ const selectedBg = useColor("gray.900");
const selectedColor = useColor("white");
const showCheckIcon: boolean =
diff --git a/packages/carbon-react/src/Inputs/Select/components/multi-value.tsx b/packages/react/src/Inputs/Select/components/multi-value.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/multi-value.tsx
rename to packages/react/src/Inputs/Select/components/multi-value.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/placeholder.tsx b/packages/react/src/Inputs/Select/components/placeholder.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/placeholder.tsx
rename to packages/react/src/Inputs/Select/components/placeholder.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/components/single-value.tsx b/packages/react/src/Inputs/Select/components/single-value.tsx
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/components/single-value.tsx
rename to packages/react/src/Inputs/Select/components/single-value.tsx
diff --git a/packages/carbon-react/src/Inputs/Select/index.ts b/packages/react/src/Inputs/Select/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/index.ts
rename to packages/react/src/Inputs/Select/index.ts
diff --git a/packages/carbon-react/src/Inputs/Select/react.select.d.ts b/packages/react/src/Inputs/Select/react.select.d.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/react.select.d.ts
rename to packages/react/src/Inputs/Select/react.select.d.ts
diff --git a/packages/carbon-react/src/Inputs/Select/types.ts b/packages/react/src/Inputs/Select/types.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/types.ts
rename to packages/react/src/Inputs/Select/types.ts
diff --git a/packages/carbon-react/src/Inputs/Select/useSelect.ts b/packages/react/src/Inputs/Select/useSelect.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/useSelect.ts
rename to packages/react/src/Inputs/Select/useSelect.ts
diff --git a/packages/carbon-react/src/Inputs/Select/utils.ts b/packages/react/src/Inputs/Select/utils.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/Select/utils.ts
rename to packages/react/src/Inputs/Select/utils.ts
diff --git a/packages/carbon-react/src/Inputs/index.ts b/packages/react/src/Inputs/index.ts
similarity index 100%
rename from packages/carbon-react/src/Inputs/index.ts
rename to packages/react/src/Inputs/index.ts
diff --git a/packages/carbon-react/src/Loading/Loading.tsx b/packages/react/src/Loading/Loading.tsx
similarity index 100%
rename from packages/carbon-react/src/Loading/Loading.tsx
rename to packages/react/src/Loading/Loading.tsx
diff --git a/packages/carbon-react/src/Loading/index.ts b/packages/react/src/Loading/index.ts
similarity index 100%
rename from packages/carbon-react/src/Loading/index.ts
rename to packages/react/src/Loading/index.ts
diff --git a/packages/carbon-react/src/Menu/Menubar.tsx b/packages/react/src/Menu/Menubar.tsx
similarity index 100%
rename from packages/carbon-react/src/Menu/Menubar.tsx
rename to packages/react/src/Menu/Menubar.tsx
diff --git a/packages/carbon-react/src/Menu/index.ts b/packages/react/src/Menu/index.ts
similarity index 100%
rename from packages/carbon-react/src/Menu/index.ts
rename to packages/react/src/Menu/index.ts
diff --git a/packages/carbon-react/src/Message/index.ts b/packages/react/src/Message/index.ts
similarity index 100%
rename from packages/carbon-react/src/Message/index.ts
rename to packages/react/src/Message/index.ts
diff --git a/packages/carbon-react/src/Message/useNotification.tsx b/packages/react/src/Message/useNotification.tsx
similarity index 100%
rename from packages/carbon-react/src/Message/useNotification.tsx
rename to packages/react/src/Message/useNotification.tsx
diff --git a/packages/carbon-react/src/Overlay/ActionMenu/ActionMenu.tsx b/packages/react/src/Overlay/ActionMenu/ActionMenu.tsx
similarity index 100%
rename from packages/carbon-react/src/Overlay/ActionMenu/ActionMenu.tsx
rename to packages/react/src/Overlay/ActionMenu/ActionMenu.tsx
diff --git a/packages/carbon-react/src/Overlay/ActionMenu/index.ts b/packages/react/src/Overlay/ActionMenu/index.ts
similarity index 100%
rename from packages/carbon-react/src/Overlay/ActionMenu/index.ts
rename to packages/react/src/Overlay/ActionMenu/index.ts
diff --git a/packages/carbon-react/src/Overlay/ContextMenu/ContextMenu.tsx b/packages/react/src/Overlay/ContextMenu/ContextMenu.tsx
similarity index 100%
rename from packages/carbon-react/src/Overlay/ContextMenu/ContextMenu.tsx
rename to packages/react/src/Overlay/ContextMenu/ContextMenu.tsx
diff --git a/packages/carbon-react/src/Overlay/ContextMenu/index.ts b/packages/react/src/Overlay/ContextMenu/index.ts
similarity index 100%
rename from packages/carbon-react/src/Overlay/ContextMenu/index.ts
rename to packages/react/src/Overlay/ContextMenu/index.ts
diff --git a/packages/carbon-react/src/Overlay/index.ts b/packages/react/src/Overlay/index.ts
similarity index 100%
rename from packages/carbon-react/src/Overlay/index.ts
rename to packages/react/src/Overlay/index.ts
diff --git a/packages/carbon-react/src/SSR/ClientOnly.tsx b/packages/react/src/SSR/ClientOnly.tsx
similarity index 100%
rename from packages/carbon-react/src/SSR/ClientOnly.tsx
rename to packages/react/src/SSR/ClientOnly.tsx
diff --git a/packages/carbon-react/src/SSR/index.ts b/packages/react/src/SSR/index.ts
similarity index 100%
rename from packages/carbon-react/src/SSR/index.ts
rename to packages/react/src/SSR/index.ts
diff --git a/packages/carbon-react/src/Theme/ThemeProvider.tsx b/packages/react/src/Theme/ThemeProvider.tsx
similarity index 100%
rename from packages/carbon-react/src/Theme/ThemeProvider.tsx
rename to packages/react/src/Theme/ThemeProvider.tsx
diff --git a/packages/carbon-react/src/Theme/focusRing.ts b/packages/react/src/Theme/focusRing.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/focusRing.ts
rename to packages/react/src/Theme/focusRing.ts
diff --git a/packages/carbon-react/src/Theme/fonts.ts b/packages/react/src/Theme/fonts.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/fonts.ts
rename to packages/react/src/Theme/fonts.ts
diff --git a/packages/carbon-react/src/Theme/index.ts b/packages/react/src/Theme/index.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/index.ts
rename to packages/react/src/Theme/index.ts
diff --git a/packages/carbon-react/src/Theme/palette.ts b/packages/react/src/Theme/palette.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/palette.ts
rename to packages/react/src/Theme/palette.ts
diff --git a/packages/carbon-react/src/Theme/reset.ts b/packages/react/src/Theme/reset.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/reset.ts
rename to packages/react/src/Theme/reset.ts
diff --git a/packages/carbon-react/src/Theme/theme.ts b/packages/react/src/Theme/theme.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/theme.ts
rename to packages/react/src/Theme/theme.ts
diff --git a/packages/carbon-react/src/Theme/tokens.ts b/packages/react/src/Theme/tokens.ts
similarity index 100%
rename from packages/carbon-react/src/Theme/tokens.ts
rename to packages/react/src/Theme/tokens.ts
diff --git a/packages/carbon-react/src/__tests__/tsconfig.json b/packages/react/src/__tests__/tsconfig.json
similarity index 100%
rename from packages/carbon-react/src/__tests__/tsconfig.json
rename to packages/react/src/__tests__/tsconfig.json
diff --git a/packages/carbon-react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/index.ts
rename to packages/react/src/hooks/index.ts
diff --git a/packages/carbon-react/src/hooks/useColor.tsx b/packages/react/src/hooks/useColor.tsx
similarity index 100%
rename from packages/carbon-react/src/hooks/useColor.tsx
rename to packages/react/src/hooks/useColor.tsx
diff --git a/packages/carbon-react/src/hooks/useDebounce.ts b/packages/react/src/hooks/useDebounce.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/useDebounce.ts
rename to packages/react/src/hooks/useDebounce.ts
diff --git a/packages/carbon-react/src/hooks/useEscape.tsx b/packages/react/src/hooks/useEscape.tsx
similarity index 100%
rename from packages/carbon-react/src/hooks/useEscape.tsx
rename to packages/react/src/hooks/useEscape.tsx
diff --git a/packages/carbon-react/src/hooks/useHydrated.ts b/packages/react/src/hooks/useHydrated.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/useHydrated.ts
rename to packages/react/src/hooks/useHydrated.ts
diff --git a/packages/carbon-react/src/hooks/useInterval.ts b/packages/react/src/hooks/useInterval.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/useInterval.ts
rename to packages/react/src/hooks/useInterval.ts
diff --git a/packages/carbon-react/src/hooks/useKeyboardShortcuts.ts b/packages/react/src/hooks/useKeyboardShortcuts.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/useKeyboardShortcuts.ts
rename to packages/react/src/hooks/useKeyboardShortcuts.ts
diff --git a/packages/carbon-react/src/hooks/useLocalStorage.ts b/packages/react/src/hooks/useLocalStorage.ts
similarity index 100%
rename from packages/carbon-react/src/hooks/useLocalStorage.ts
rename to packages/react/src/hooks/useLocalStorage.ts
diff --git a/packages/carbon-react/src/index.tsx b/packages/react/src/index.tsx
similarity index 100%
rename from packages/carbon-react/src/index.tsx
rename to packages/react/src/index.tsx
diff --git a/packages/carbon-react/tsconfig.json b/packages/react/tsconfig.json
similarity index 100%
rename from packages/carbon-react/tsconfig.json
rename to packages/react/tsconfig.json
diff --git a/packages/carbon-redis/.eslintrc.js b/packages/redis/.eslintrc.js
similarity index 100%
rename from packages/carbon-redis/.eslintrc.js
rename to packages/redis/.eslintrc.js
diff --git a/packages/carbon-redis/docker-compose.yml b/packages/redis/docker-compose.yml
similarity index 88%
rename from packages/carbon-redis/docker-compose.yml
rename to packages/redis/docker-compose.yml
index dd92c3f9de..5d9cc08a2a 100644
--- a/packages/carbon-redis/docker-compose.yml
+++ b/packages/redis/docker-compose.yml
@@ -1,6 +1,7 @@
version: "3.8"
+name: "carbon-redis"
services:
- carbon-redis:
+ redis:
image: redis:7.0-alpine
restart: always
ports:
diff --git a/packages/carbon-redis/package.json b/packages/redis/package.json
similarity index 100%
rename from packages/carbon-redis/package.json
rename to packages/redis/package.json
diff --git a/packages/carbon-redis/src/client.ts b/packages/redis/src/client.ts
similarity index 100%
rename from packages/carbon-redis/src/client.ts
rename to packages/redis/src/client.ts
diff --git a/packages/carbon-redis/src/index.ts b/packages/redis/src/index.ts
similarity index 100%
rename from packages/carbon-redis/src/index.ts
rename to packages/redis/src/index.ts
diff --git a/packages/carbon-redis/tsconfig.json b/packages/redis/tsconfig.json
similarity index 100%
rename from packages/carbon-redis/tsconfig.json
rename to packages/redis/tsconfig.json
diff --git a/packages/carbon-redis/tsup.config.bundled_r5u3e79sewr.mjs b/packages/redis/tsup.config.bundled_r5u3e79sewr.mjs
similarity index 100%
rename from packages/carbon-redis/tsup.config.bundled_r5u3e79sewr.mjs
rename to packages/redis/tsup.config.bundled_r5u3e79sewr.mjs
diff --git a/packages/carbon-redis/tsup.config.ts b/packages/redis/tsup.config.ts
similarity index 100%
rename from packages/carbon-redis/tsup.config.ts
rename to packages/redis/tsup.config.ts
diff --git a/packages/carbon-tsconfig/base.json b/packages/tsconfig/base.json
similarity index 100%
rename from packages/carbon-tsconfig/base.json
rename to packages/tsconfig/base.json
diff --git a/packages/carbon-tsconfig/nextjs.json b/packages/tsconfig/nextjs.json
similarity index 100%
rename from packages/carbon-tsconfig/nextjs.json
rename to packages/tsconfig/nextjs.json
diff --git a/packages/carbon-tsconfig/package.json b/packages/tsconfig/package.json
similarity index 100%
rename from packages/carbon-tsconfig/package.json
rename to packages/tsconfig/package.json
diff --git a/packages/carbon-tsconfig/react-library.json b/packages/tsconfig/react-library.json
similarity index 100%
rename from packages/carbon-tsconfig/react-library.json
rename to packages/tsconfig/react-library.json
diff --git a/packages/carbon-tsconfig/vite.json b/packages/tsconfig/vite.json
similarity index 100%
rename from packages/carbon-tsconfig/vite.json
rename to packages/tsconfig/vite.json
diff --git a/packages/carbon-utils/.eslintrc.js b/packages/utils/.eslintrc.js
similarity index 100%
rename from packages/carbon-utils/.eslintrc.js
rename to packages/utils/.eslintrc.js
diff --git a/packages/carbon-utils/package.json b/packages/utils/package.json
similarity index 100%
rename from packages/carbon-utils/package.json
rename to packages/utils/package.json
diff --git a/packages/carbon-utils/src/arrays.ts b/packages/utils/src/arrays.ts
similarity index 100%
rename from packages/carbon-utils/src/arrays.ts
rename to packages/utils/src/arrays.ts
diff --git a/packages/carbon-utils/src/date.ts b/packages/utils/src/date.ts
similarity index 100%
rename from packages/carbon-utils/src/date.ts
rename to packages/utils/src/date.ts
diff --git a/packages/carbon-utils/src/file.ts b/packages/utils/src/file.ts
similarity index 100%
rename from packages/carbon-utils/src/file.ts
rename to packages/utils/src/file.ts
diff --git a/packages/carbon-utils/src/index.ts b/packages/utils/src/index.ts
similarity index 100%
rename from packages/carbon-utils/src/index.ts
rename to packages/utils/src/index.ts
diff --git a/packages/carbon-utils/src/math.ts b/packages/utils/src/math.ts
similarity index 100%
rename from packages/carbon-utils/src/math.ts
rename to packages/utils/src/math.ts
diff --git a/packages/carbon-utils/src/ssr.ts b/packages/utils/src/ssr.ts
similarity index 100%
rename from packages/carbon-utils/src/ssr.ts
rename to packages/utils/src/ssr.ts
diff --git a/packages/carbon-utils/src/types.ts b/packages/utils/src/types.ts
similarity index 100%
rename from packages/carbon-utils/src/types.ts
rename to packages/utils/src/types.ts
diff --git a/packages/carbon-utils/src/url.ts b/packages/utils/src/url.ts
similarity index 100%
rename from packages/carbon-utils/src/url.ts
rename to packages/utils/src/url.ts
diff --git a/packages/carbon-utils/tsconfig.json b/packages/utils/tsconfig.json
similarity index 100%
rename from packages/carbon-utils/tsconfig.json
rename to packages/utils/tsconfig.json
diff --git a/scripts/generate-schema-md.ts b/scripts/generate-schema-md.ts
index 7bcf92c5cc..70809ccfbc 100644
--- a/scripts/generate-schema-md.ts
+++ b/scripts/generate-schema-md.ts
@@ -2,7 +2,7 @@ import fs from "fs";
import path from "path";
readFiles(
- path.resolve(__dirname, "../packages/carbon-database/supabase/migrations"),
+ path.resolve(__dirname, "../packages/database/supabase/migrations"),
writeMarkDown,
(err) => {
throw new Error(err.message);
@@ -46,7 +46,7 @@ function readFiles(
const stream = fs.createWriteStream("SCHEMA.md", { flags: "a" });
stream.write(`
-This file is generated by \`scripts/generate-schema-md.ts\` using the migrations in \`packages/carbon-database/supabase/migrations\`.
+This file is generated by \`scripts/generate-schema-md.ts\` using the migrations in \`packages/database/supabase/migrations\`.
`);
fs.readdir(dirName, function (err, fileNames) {
diff --git a/scripts/generate-seed-sql.sh b/scripts/generate-seed-sql.sh
index c63736c35c..2cf1d14b53 100755
--- a/scripts/generate-seed-sql.sh
+++ b/scripts/generate-seed-sql.sh
@@ -1,2 +1,2 @@
#!/bin/bash
-pg_dump -d postgresql://postgres:postgres@localhost:54322/postgres --no-comments --data-only --column-inserts -n public > packages/carbon-database/supabase/seed.sql
\ No newline at end of file
+pg_dump -d postgresql://postgres:postgres@localhost:54322/postgres --no-comments --data-only --column-inserts -n public > packages/database/supabase/seed.sql
\ No newline at end of file
diff --git a/www/pages/docs/core-concepts/writing.mdx b/www/pages/docs/core-concepts/writing.mdx
index 5c73c8ac1b..25760d53f0 100644
--- a/www/pages/docs/core-concepts/writing.mdx
+++ b/www/pages/docs/core-concepts/writing.mdx
@@ -133,3 +133,78 @@ export async function createPerson(
For more information on the service layer, see the [Supabase
documentation](https://supabase.io/docs/reference/javascript/insert)
</Callout>
+
+## Transactions
+
+When a database transaction is needed, use a deno-based edge function. The reason for this is that the supabase client currently does not support transactions.
+
+To create a new edge function run `yarn db:function:new <name-of-function>`
+
+This will create a new edge function in `packages/database/supabase/functions/<name-of-function>`.
+
+The pattern for the transaction looks like this:
+
+```ts
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
+import type { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";
+
+import type { Database } from "../../../src/types.ts";
+import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+// Use the supabase types to define a subset of the database we'll transact with
+interface DB {
+ generalLedger: Database["public"]["Tables"]["generalLedger"]["Update"];
+ partLedger: Database["public"]["Tables"]["partLedger"]["Insert"];
+ valueLedger: Database["public"]["Tables"]["valueLedger"]["Insert"];
+}
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+serve(async (req: Request) => {
+ try {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .updateTable("partLedger")
+ .set({
+ expectedCost: 0,
+ })
+ .where("id", "=", partLedgerId)
+ .execute();
+
+ const generalLedgerIds = await trx
+ .insertInto("generalLedger")
+ .values(generalLedgerInserts)
+ .execute();
+
+ const valueLedgerIds = await trx
+ .insertInto("valueLedger")
+ .values(valueLedgerInserts)
+ .execute();
+ });
+
+ return new Response(
+ JSON.stringify({
+ data: null,
+ error: null,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
+```
diff --git a/www/pages/docs/getting-started.mdx b/www/pages/docs/getting-started.mdx
index 8298b94d5a..0c0b9b04b4 100644
--- a/www/pages/docs/getting-started.mdx
+++ b/www/pages/docs/getting-started.mdx
@@ -25,7 +25,7 @@ First download and initialize the repository dependencies.
```bash
$ git clone https://github.com/barbinbrad/carbon
$ yarn # install dependencies
-$ yarn init # pull and start the containers
+$ yarn db:start # pull and start the containers
```
Copy the environment variables from the initialization script to an `.env` file:
@@ -34,7 +34,7 @@ Copy the environment variables from the initialization script to an `.env` file:
$ cp ./.env.example ./.env
```
-After you've set the enviroment variables to the output of `yarn init` you can run
+After you've set the enviroment variables to the output of `yarn db:start` you can run
```bash
$ nvm use # use node v18
diff --git a/www/pages/docs/tech-stack.mdx b/www/pages/docs/tech-stack.mdx
index dce92dd212..dbb310ef6c 100644
--- a/www/pages/docs/tech-stack.mdx
+++ b/www/pages/docs/tech-stack.mdx
@@ -27,7 +27,7 @@ We chose TypeScript because it allows us to use a single, strongly-typed languag
[React](https://reactjs.org) is a JavaScript library for building user interfaces. It's the most popular frontend framework in the world, and it's used by many of the biggest companies in the world, including Facebook, Netflix, and Airbnb.
-We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tree/main/packages/carbon-react/src) that has a bunch of React pre-built components that you can use to build your UI. You can also draw from a rich ecosystem of existing React component libraries.
+We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tree/main/packages/react/src) that has a bunch of React pre-built components that you can use to build your UI. You can also draw from a rich ecosystem of existing React component libraries.
## Chakra UI
diff --git a/yarn.lock b/yarn.lock
index c596a9170d..7909ee2960 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3685,17 +3685,24 @@
dependencies:
cross-fetch "^3.1.5"
-"@supabase/postgrest-js@^1.7.0":
- version "1.7.2"
- resolved "https://registry.yarnpkg.com/@supabase/postgrest-js/-/postgrest-js-1.7.2.tgz#800814b98bb8cec840b65f0c545a3474f23c343a"
- integrity sha512-GK80JpRq8l6Qll85erICypAfQCied8tdlXfsDN14W844HqXCSOisk8AaE01DAwGJanieaoN5fuqhzA2yKxDvEQ==
+"@supabase/node-fetch@^2.6.14":
+ version "2.6.14"
+ resolved "https://registry.yarnpkg.com/@supabase/node-fetch/-/node-fetch-2.6.14.tgz#6a3e2924e3de8aeeb82c193c786ffb25da9af23f"
+ integrity sha512-w/Tsd22e/5fAeoxqQ4P2MX6EyF+iM6rc9kmlMVFkHuG0rAltt2TLhFbDJfemnHbtvnazWaRfy5KnFU/SYT37dQ==
dependencies:
- cross-fetch "^3.1.5"
+ whatwg-url "^5.0.0"
-"@supabase/realtime-js@^2.7.3":
- version "2.7.3"
- resolved "https://registry.yarnpkg.com/@supabase/realtime-js/-/realtime-js-2.7.3.tgz#cbcb84181add681ab99c87032bfe88101c6863b3"
- integrity sha512-c7TzL81sx2kqyxsxcDduJcHL9KJdCOoKimGP6lQSqiZKX42ATlBZpWbyy9KFGFBjAP4nyopMf5JhPi2ZH9jyNw==
+"@supabase/postgrest-js@^1.8.0":
+ version "1.8.4"
+ resolved "https://registry.yarnpkg.com/@supabase/postgrest-js/-/postgrest-js-1.8.4.tgz#89e8355503979ad25e7340b910d17704507ab325"
+ integrity sha512-ELjpvhb04wILUiJz9zIsTSwaz9LQNlX+Ig5/LgXQ7k68qQI6NqHVn+ISRNt53DngUIyOnLHjeqqIRHBZ7zpgGA==
+ dependencies:
+ "@supabase/node-fetch" "^2.6.14"
+
+"@supabase/realtime-js@^2.7.4":
+ version "2.7.4"
+ resolved "https://registry.yarnpkg.com/@supabase/realtime-js/-/realtime-js-2.7.4.tgz#de41195bd3f2cdd6db82d9f93c4c5b8fae9f809b"
+ integrity sha512-FzSzs1k9ruh/uds5AJ95Nc3beiMCCIhougExJ3O98CX1LMLAKUKFy5FivKLvcNhXnNfUEL0XUfGMb4UH2J7alg==
dependencies:
"@types/phoenix" "^1.5.4"
"@types/websocket" "^1.0.3"
@@ -3708,15 +3715,15 @@
dependencies:
cross-fetch "^3.1.5"
-"@supabase/supabase-js@^2.31.0":
- version "2.31.0"
- resolved "https://registry.yarnpkg.com/@supabase/supabase-js/-/supabase-js-2.31.0.tgz#49fe09652fa72b1173efe4ac086592e31c662cef"
- integrity sha512-W9/4s+KnSUX67wJKBn/3yLq+ieycnMzVjK3nNTLX5Wko3ypNT/081l2iFYrf+nsLQ1CiT4mA92I3dxCy6CmxTg==
+"@supabase/supabase-js@^2.33.1":
+ version "2.33.1"
+ resolved "https://registry.yarnpkg.com/@supabase/supabase-js/-/supabase-js-2.33.1.tgz#2407861afe63c2817d030514c87a745f78dfe68a"
+ integrity sha512-jA00rquPTppPOHpBB6KABW98lfg0gYXcuGqP3TB1iiduznRVsi3GGk2qBKXPDLMYSe0kRlQp5xCwWWthaJr8eA==
dependencies:
"@supabase/functions-js" "^2.1.0"
"@supabase/gotrue-js" "^2.46.1"
- "@supabase/postgrest-js" "^1.7.0"
- "@supabase/realtime-js" "^2.7.3"
+ "@supabase/postgrest-js" "^1.8.0"
+ "@supabase/realtime-js" "^2.7.4"
"@supabase/storage-js" "^2.5.1"
cross-fetch "^3.1.5"
@@ -14098,10 +14105,10 @@ sucrase@^3.20.3:
pirates "^4.0.1"
ts-interface-checker "^0.1.9"
- version "1.77.9"
- resolved "https://registry.yarnpkg.com/supabase/-/supabase-1.77.9.tgz#d946ffdf32889b276488cf42017bd267b024667a"
- integrity sha512-AyMaMsb+QpUMTE1XfV8Vhl/9G+Hkzk61RXf/JP5uyxc256hcb3N3FQoW2bi+A/BodJ/rfZOPE7vv+xtfVf6vyQ==
+ version "1.93.0"
+ resolved "https://registry.yarnpkg.com/supabase/-/supabase-1.93.0.tgz#35bd2706120379c7151622c548bdf95663b05e2f"
+ integrity sha512-7VKWPVy1QSnBcx/ubKIGFOWw9LjL6C1sMTh0d+ox0TP69+KhzphlA4Z/iFPvC6x9gUwhe9UTI0AdqJYsIwrPEA==
dependencies:
bin-links "^4.0.1"
node-fetch "^3.2.10"