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.

Receipts (#36)

Brad Barbin2a1e232a8702
diff --git a/.github/workflows/supabase-prod.yml b/.github/workflows/supabase-prod.yml
deleted file mode 100644
index fb7b0f162d..0000000000
--- a/.github/workflows/supabase-prod.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-# name: Deploy
-
-# on:
-# workflow_dispatch:
-# push:
-# branches:
-# - main
-# paths:
-# - "packages/carbon-database/**"
-# - "package-lock.json"
-
-# concurrency:
-# group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
-# cancel-in-progress: true
-
-# jobs:
-# deploy:
-# name: supabase
-# runs-on: ubuntu-latest
-
-# env:
-# SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
-# SUPABASE_DB_PASSWORD: ${{ secrets.PRODUCTION_DB_PASSWORD }}
-# SUPABASE_PROJECT_ID: ${{ secrets.SUPABASE_PROJECT_ID }}
-
-# steps:
-# - name: Checkout code
-# uses: actions/checkout@v3
-
-# - name: 📦 Install dependencies
-# uses: ./.github/actions/dependencies
-
-# - name: 🚀 Sync local database with supabase remote
-# run: yarn deploy
diff --git a/README.md b/README.md
index 287fe66231..1b84b23f53 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ It includes:
## Project Status
- [x] Pre-Alpha: Developing foundation
-- [ ] Alpha: Heavy feature development
+- [ ] Alpha: Heavy feature development and refinement
- [ ] Public Alpha: Ready for use. But go easy on us, there'll be bugs.
- [ ] Public Beta: Stable enough for most non-enterprise use-cases.
- [ ] Public: Production-ready
diff --git a/SCHEMA.md b/SCHEMA.md
index 56abd7f17b..5826fa6bf6 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -2922,7 +2922,7 @@ CREATE VIEW "contractors_view" AS
ON s.id = sc."supplierId"
INNER JOIN "contact" c
ON c.id = sc."contactId"
- INNER JOIN "contractorAbility" pa
+ LEFT JOIN "contractorAbility" pa
ON pa."contractorId" = p.id
WHERE p."active" = true
GROUP BY p.id, p.active, p."hoursPerWeek", s.id, c.id, s.name, c."firstName", c."lastName", c."email"
@@ -3433,7 +3433,7 @@ CREATE TABLE "part" (
CONSTRAINT "part_pkey" PRIMARY KEY ("id"),
CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL,
+ CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id"),
CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
CONSTRAINT "part_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
@@ -3496,12 +3496,6 @@ BEGIN
INSERT INTO public."partReplenishment"("partId", "createdBy")
VALUES (new.id, new."createdBy");
- INSERT INTO public."partPlanning"("partId", "createdBy")
- VALUES (new.id, new."createdBy");
-
- INSERT INTO public."partInventory"("partId", "createdBy")
- VALUES (new.id, new."createdBy");
-
INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")
-- TODO: get default currency
VALUES (new.id, 'USD', new."createdBy");
@@ -3875,7 +3869,7 @@ CREATE TABLE "warehouse" (
CREATE TABLE "shelf" (
"id" TEXT NOT NULL,
- "locationId" TEXT,
+ "locationId" TEXT NOT NULL,
"warehouseId" TEXT,
"active" BOOLEAN NOT NULL DEFAULT true,
"createdBy" TEXT NOT NULL,
@@ -3883,14 +3877,14 @@ CREATE TABLE "shelf" (
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "shelf_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shelf_pkey" PRIMARY KEY ("id", "locationId"),
CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,
CONSTRAINT "shelf_warehouseId_fkey" FOREIGN KEY ("warehouseId") REFERENCES "warehouse"("id") ON DELETE CASCADE,
CONSTRAINT "shelf_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "shelf_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "shelf_locationId_index" ON "shelf" ("locationId");
+CREATE INDEX "shelf_id_locationId_index" ON "shelf" ("id", "locationId");
CREATE INDEX "shelf_warehouseId_index" ON "shelf" ("warehouseId");
ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;
@@ -3926,6 +3920,7 @@ CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"
CREATE TABLE "partPlanning" (
"partId" TEXT NOT NULL,
+ "locationId" TEXT NOT NULL,
"reorderingPolicy" "partReorderingPolicy" NOT NULL DEFAULT 'Demand-Based Reorder',
"critical" BOOLEAN NOT NULL DEFAULT false,
"safetyStockQuantity" INTEGER NOT NULL DEFAULT 0,
@@ -3936,8 +3931,6 @@ CREATE TABLE "partPlanning" (
"reorderPoint" INTEGER NOT NULL DEFAULT 0,
"reorderQuantity" INTEGER NOT NULL DEFAULT 0,
"reorderMaximumInventory" INTEGER NOT NULL DEFAULT 0,
- "reorderOverflowLevel" INTEGER NOT NULL DEFAULT 0,
- "reorderTimeBucket" INTEGER NOT NULL DEFAULT 5,
"minimumOrderQuantity" INTEGER NOT NULL DEFAULT 0,
"maximumOrderQuantity" INTEGER NOT NULL DEFAULT 0,
"orderMultiple" INTEGER NOT NULL DEFAULT 1,
@@ -3946,12 +3939,15 @@ CREATE TABLE "partPlanning" (
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "partPlanning_partId_locationId_key" UNIQUE ("partId", "locationId"),
CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "partPlanning_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "partPlanning_partId_index" ON "partPlanning" ("partId");
+CREATE INDEX "partPlanning_partId_locationId_index" ON "partPlanning" ("partId", "locationId");
ALTER TABLE "partPlanning" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning"
@@ -3961,6 +3957,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+-- these are records are created lazily when a user attempts to view them
+CREATE POLICY "Employees with part_view can insert part planning" ON "partPlanning"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with parts_update can update part planning" ON "partPlanning"
FOR UPDATE
USING (
@@ -3971,24 +3975,23 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partPla
CREATE TABLE "partInventory" (
"partId" TEXT NOT NULL,
- "shelfId" TEXT,
- "stockoutWarning" BOOLEAN NOT NULL DEFAULT true,
- "unitVolume" NUMERIC(15,5) NOT NULL DEFAULT 0,
- "unitWeight" NUMERIC(15,5) NOT NULL DEFAULT 0,
+ "locationId" TEXT NOT NULL,
+ "defaultShelfId" TEXT,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),
+ CONSTRAINT "partInventory_partId_locationId_key" UNIQUE ("partId", "locationId"),
CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,
+ CONSTRAINT "partInventory_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("defaultShelfId", "locationId") REFERENCES "shelf"("id", "locationId") ON DELETE SET NULL,
CONSTRAINT "partInventory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partInventory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "partInventory_partId_index" ON "partInventory" ("partId");
-CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("shelfId");
+CREATE INDEX "partInventory_partId_locationId_index" ON "partInventory" ("partId", "locationId");
+CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("defaultShelfId");
ALTER TABLE "partInventory" ENABLE ROW LEVEL SECURITY;
@@ -3999,6 +4002,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "partInventor
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+-- these are records are created lazily when a user attempts to view them
+CREATE POLICY "Employees with part_view can insert part planning" ON "partInventory"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with parts_update can update part planning" ON "partInventory"
FOR UPDATE
USING (
@@ -4454,26 +4465,26 @@ CREATE TYPE "purchaseOrderType" AS ENUM (
'Return'
);
-CREATE TYPE "purchaseOrderApprovalStatus" AS ENUM (
- 'Draft',
+CREATE TYPE "purchaseOrderStatus" AS ENUM (
+ 'Open',
'In Review',
'In External Review',
'Approved',
'Rejected',
- 'Confirmed'
+ 'Released',
+ 'Closed'
);
CREATE TABLE "purchaseOrder" (
"id" TEXT NOT NULL DEFAULT xid(),
"purchaseOrderId" TEXT NOT NULL,
"type" "purchaseOrderType" NOT NULL,
- "status" "purchaseOrderApprovalStatus" NOT NULL,
+ "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Open',
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
"supplierContactId" TEXT,
"supplierReference" TEXT,
- "closed" BOOLEAN NOT NULL DEFAULT FALSE,
"closedAt" DATE,
"closedBy" TEXT,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
@@ -4493,6 +4504,7 @@ CREATE TABLE "purchaseOrder" (
CREATE INDEX "purchaseOrder_purchaseOrderId_idx" ON "purchaseOrder" ("purchaseOrderId");
CREATE INDEX "purchaseOrder_supplierId_idx" ON "purchaseOrder" ("supplierId");
CREATE INDEX "purchaseOrder_supplierContactId_idx" ON "purchaseOrder" ("supplierContactId");
+CREATE INDEX "purchaseOrder_status_idx" ON "purchaseOrder" ("status");
CREATE TYPE "purchaseOrderLineType" AS ENUM (
'Comment',
@@ -4510,8 +4522,13 @@ CREATE TABLE "purchaseOrderLine" (
"assetId" TEXT,
"description" TEXT,
"purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
+ "quantityToReceive" NUMERIC(9,2) DEFAULT 0,
+ "quantityReceived" NUMERIC(9,2) DEFAULT 0,
+ "quantityToInvoice" NUMERIC(9,2) DEFAULT 0,
+ "quantityInvoiced" NUMERIC(9,2) DEFAULT 0,
"unitPrice" NUMERIC(9,2),
"unitOfMeasureCode" TEXT,
+ "locationId" TEXT,
"shelfId" TEXT,
"setupPrice" NUMERIC(9,2),
"receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
@@ -4556,7 +4573,7 @@ CREATE TABLE "purchaseOrderLine" (
CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,
-- TODO: Add assetId foreign key
- CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "purchaseOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
@@ -4681,6 +4698,7 @@ CREATE VIEW "purchase_order_view" AS
pd."receiptPromisedDate",
pd."dropShipment",
pol."lineCount",
+ l."id" AS "locationId",
l."name" AS "locationName",
s."name" AS "supplierName",
u."avatarUrl" AS "createdByAvatar",
@@ -4690,7 +4708,6 @@ CREATE VIEW "purchase_order_view" AS
u2."avatarUrl" AS "updatedByAvatar",
u2."fullName" AS "updatedByFullName",
p."updatedAt",
- p."closed",
p."closedAt",
u3."avatarUrl" AS "closedByAvatar",
u3."fullName" AS "closedByFullName",
@@ -4753,7 +4770,7 @@ CREATE TABLE "sequence" (
);
INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
-VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 5, 1);
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 6, 1);
```
@@ -5410,7 +5427,7 @@ CREATE TABLE "partLedger" (
CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),
CONSTRAINT "partLedger_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT "partLedger_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,
- CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON UPDATE CASCADE ON DELETE SET NULL
+ CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf"("id", "locationId") ON UPDATE CASCADE ON DELETE SET NULL
);
ALTER TABLE "partLedger" ENABLE ROW LEVEL SECURITY;
@@ -5456,3 +5473,104 @@ $$;
```
+
+
+## `receipts`
+
+```sql
+CREATE TYPE "receiptSourceDocument" AS ENUM (
+ 'Sales Order',
+ 'Sales Return Order',
+ 'Purchase Order',
+ 'Purchase Return Order',
+ 'Inbound Transfer',
+ 'Outbound Transfer',
+ 'Manufacturing Consumption',
+ 'Manufacturing Output'
+);
+
+CREATE TABLE "receipt" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "receiptId" TEXT NOT NULL,
+ "locationId" TEXT,
+ "sourceDocument" "receiptSourceDocument",
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "supplierId" TEXT,
+ "postingDate" DATE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "receipt_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "receipt_receiptId_key" UNIQUE ("receiptId"),
+ CONSTRAINT "receipt_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receipt_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receipt_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receipt_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX "receipt_receiptId_idx" ON "receipt" ("receiptId");
+CREATE INDEX "receipt_locationId_idx" ON "receipt" ("locationId");
+CREATE INDEX "receipt_sourceDocumentId_idx" ON "receipt" ("sourceDocumentId");
+CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId");
+
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
+VALUES ('receipt', 'Receipt', 'RE', NULL, 0, 6, 1);
+
+CREATE TABLE "receiptLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "receiptId" TEXT NOT NULL,
+ "lineId" TEXT,
+ "partId" TEXT NOT NULL,
+ "orderQuantity" NUMERIC(18, 4) NOT NULL,
+ "outstandingQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,
+ "receivedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,
+ "locationId" TEXT,
+ "shelfId" TEXT,
+ "unitOfMeasure" TEXT NOT NULL,
+ "unitPrice" NUMERIC(18, 4) NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "receiptLine_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("receiptId") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX "receiptLine_receiptId_idx" ON "receiptLine" ("receiptId");
+CREATE INDEX "receiptLine_lineId_idx" ON "receiptLine" ("lineId");
+CREATE INDEX "receiptLine_receiptId_lineId_idx" ON "receiptLine" ("receiptId", "lineId");
+
+CREATE VIEW "receipt_quantity_received_by_line" AS
+ SELECT
+ r."sourceDocumentId",
+ l."lineId",
+ SUM(l."receivedQuantity") AS "receivedQuantity"
+ FROM "receipt" r
+ INNER JOIN "receiptLine" l
+ ON l."receiptId" = r."receiptId"
+ GROUP BY r."sourceDocumentId", l."lineId";
+
+```
+
+
+
+## `defaults`
+
+```sql
+CREATE VIEW "user_default_view" AS
+ SELECT
+ u.id as "userId",
+ ej."locationId"
+ FROM "user" u
+ LEFT JOIN "employeeJob" ej ON ej.id = u.id;
+```
+
diff --git a/apps/carbon/app/components/Editable/EditableList.tsx b/apps/carbon/app/components/Editable/EditableList.tsx
index fe247c167b..d4b301c983 100644
--- a/apps/carbon/app/components/Editable/EditableList.tsx
+++ b/apps/carbon/app/components/Editable/EditableList.tsx
@@ -40,6 +40,7 @@ const EditableList =
return (
<Select
autoFocus
+ borderRadius="none"
options={options}
// @ts-ignore
onChange={onChange}
diff --git a/apps/carbon/app/components/Editable/EditableNumber.tsx b/apps/carbon/app/components/Editable/EditableNumber.tsx
index c30d0f44f4..fe8a2b4ac4 100644
--- a/apps/carbon/app/components/Editable/EditableNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableNumber.tsx
@@ -57,7 +57,12 @@ const EditableNumber =
// eslint-disable-next-line jsx-a11y/no-autofocus
return (
- <NumberInput defaultValue={value as number} size="sm" w="full">
+ <NumberInput
+ defaultValue={value as number}
+ size="sm"
+ w="full"
+ borderRadius="none"
+ >
<NumberInputField autoFocus onKeyDown={onKeyDown} onBlur={onBlur} />
</NumberInput>
);
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
index c321a6f21c..dfa9ae0cc9 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -5,8 +5,8 @@ import type {
PostgrestSingleResponse,
SupabaseClient,
} from "@supabase/supabase-js";
-import type { PurchaseOrderLine } from "~/modules/purchasing";
import type { EditableTableCellComponentProps } from "~/components/Editable";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
const EditablePurchaseOrderLineNumber =
(
@@ -19,6 +19,7 @@ const EditablePurchaseOrderLineNumber =
client?: SupabaseClient<Database>;
parts: { label: string; value: string }[];
accounts: { label: string; value: string }[];
+ defaultLocationId: string | null;
}
) =>
({
@@ -93,8 +94,9 @@ const EditablePurchaseOrderLineNumber =
.single(),
client
.from("partInventory")
- .select("shelfId")
+ .select("defaultShelfId")
.eq("partId", partId)
+ .eq("locationId", options.defaultLocationId)
.single(),
client
.from("partCost")
@@ -108,12 +110,19 @@ const EditablePurchaseOrderLineNumber =
return;
}
+ console.log({
+ partId,
+ locationId: options.defaultLocationId,
+ shelfId: shelf.data?.defaultShelfId,
+ });
+
onUpdate("partId", partId);
onUpdate("description", part.data?.name);
onUpdate("assetId", null);
onUpdate("accountNumber", null);
onUpdate("unitOfMeasureCode", part.data?.unitOfMeasureCode ?? null);
- onUpdate("shelfId", shelf.data?.shelfId ?? null);
+ onUpdate("locationId", options.defaultLocationId);
+ onUpdate("shelfId", shelf.data?.defaultShelfId ?? null);
onUpdate("unitPrice", cost.data?.unitCost ?? null);
try {
@@ -125,7 +134,8 @@ const EditablePurchaseOrderLineNumber =
accountNumber: null,
description: part.data?.name,
unitOfMeasureCode: part.data?.unitOfMeasureCode ?? null,
- shelfId: shelf.data?.shelfId ?? null,
+ locationId: options.defaultLocationId,
+ shelfId: shelf.data?.defaultShelfId ?? null,
unitPrice: cost.data?.unitCost ?? null,
})
.eq("id", row.id);
@@ -158,6 +168,7 @@ const EditablePurchaseOrderLineNumber =
options={selectOptions}
onChange={onChange}
// @ts-ignore
+ borderRadius="none"
size="sm"
/>
);
diff --git a/apps/carbon/app/components/Editable/EditableText.tsx b/apps/carbon/app/components/Editable/EditableText.tsx
index b7b547700e..9d57bec4a9 100644
--- a/apps/carbon/app/components/Editable/EditableText.tsx
+++ b/apps/carbon/app/components/Editable/EditableText.tsx
@@ -58,6 +58,7 @@ const EditableText =
<Input
autoFocus
defaultValue={value as string}
+ borderRadius="none"
size="sm"
w="full"
onBlur={onBlur}
diff --git a/apps/carbon/app/components/Form/Part.tsx b/apps/carbon/app/components/Form/Part.tsx
index 8f20af6361..e627a67247 100644
--- a/apps/carbon/app/components/Form/Part.tsx
+++ b/apps/carbon/app/components/Form/Part.tsx
@@ -27,7 +27,7 @@ const Part = ({
onChange,
...props
}: PartSelectProps) => {
- const { getInputProps, error, defaultValue } = useField(name);
+ const { getInputProps, error } = useField(name);
const [value, setValue] = useControlField<string | undefined>(name);
const partFetcher = useFetcher<Awaited<ReturnType<typeof getPartsList>>>();
@@ -70,14 +70,6 @@ const Part = ({
[value, options]
);
- // so that we can call onChange on load
- useEffect(() => {
- if (controlledValue && controlledValue.value === defaultValue) {
- handleChange(controlledValue);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [controlledValue?.value]);
-
return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
diff --git a/apps/carbon/app/components/Form/SelectControlled.tsx b/apps/carbon/app/components/Form/SelectControlled.tsx
index 835611d0d4..eacba275c9 100644
--- a/apps/carbon/app/components/Form/SelectControlled.tsx
+++ b/apps/carbon/app/components/Form/SelectControlled.tsx
@@ -17,7 +17,7 @@ export type SelectControlledProps = {
isLoading?: boolean;
placeholder?: string;
value: string | undefined;
- onChange: (newValue: string | number | undefined) => void;
+ onChange?: (newValue: string | number | undefined) => void;
};
const SelectControlled = ({
diff --git a/apps/carbon/app/components/Grid/Grid.tsx b/apps/carbon/app/components/Grid/Grid.tsx
index fc5aa36a0c..fdd012c033 100644
--- a/apps/carbon/app/components/Grid/Grid.tsx
+++ b/apps/carbon/app/components/Grid/Grid.tsx
@@ -7,10 +7,10 @@ import {
Icon,
Table,
Tbody,
- Text,
- Thead,
Td,
+ Text,
Th,
+ Thead,
Tr,
VStack,
} from "@chakra-ui/react";
@@ -22,16 +22,17 @@ import {
} from "@tanstack/react-table";
import { useCallback, useEffect, useRef, useState } from "react";
import { BsPlus } from "react-icons/bs";
-import { Row } from "./components";
import type {
EditableTableCellComponent,
Position,
} from "~/components/Editable";
+import { Row } from "./components";
import { getAccessorKey, updateNestedProperty } from "./utils";
interface GridProps<T extends object> {
canEdit?: boolean;
columns: ColumnDef<T>[];
+ contained?: boolean;
data: T[];
defaultColumnOrder?: string[];
defaultColumnVisibility?: Record<string, boolean>;
@@ -46,6 +47,7 @@ interface GridProps<T extends object> {
const Grid = <T extends object>({
canEdit = true,
columns,
+ contained = true,
data,
editableComponents,
defaultColumnOrder,
@@ -351,8 +353,10 @@ const Grid = <T extends object>({
w="full"
h="full"
bg={useColor("white")}
- overflow="scroll"
- style={{ contain: "strict" }}
+ overflowX="auto"
+ style={{
+ contain: contained ? "strict" : undefined,
+ }}
ref={tableContainerRef}
onKeyDown={onKeyDown}
>
@@ -439,6 +443,20 @@ const Grid = <T extends object>({
/>
);
})}
+ {rows.length === 0 && !onNewRow && (
+ <Tr
+ h={10}
+ _hover={{
+ backgroundColor: "gray.100",
+ }}
+ >
+ <Td colSpan={24}>
+ <Text color="gray.500" w="full" textAlign="center">
+ No Data
+ </Text>
+ </Td>
+ </Tr>
+ )}
{onNewRow && (
<Tr
onClick={onNewRow}
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index 5f6aa30ab5..401ce9cdcd 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -77,6 +77,11 @@ export default function useBreadcrumbs(): Route[] {
name: "Inventory",
to: match.pathname,
});
+ case "routes/x+/inventory+/receipts":
+ return acc.concat({
+ name: "Receipts",
+ to: match.pathname,
+ });
case "routes/x+/inventory+/shipping-methods":
return acc.concat({
name: "Shipping Methods",
diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
index b5b13d4faa..244757de73 100644
--- a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
+++ b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx
@@ -1,6 +1,6 @@
import { Loading } from "@carbon/react";
import type { IconProps } from "@chakra-ui/react";
-import { Box, Icon, List, ListItem, MenuIcon, Text } 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";
@@ -146,7 +146,7 @@ const Option = ({
onClick={onClick}
sx={sx}
>
- <MenuIcon>
+ <HStack spacing={1} w="full" alignItems="center">
<CheckIcon
display="block"
marginEnd="0.75rem"
@@ -155,8 +155,8 @@ const Option = ({
h={4}
opacity={isSelected ? 1 : 0}
/>
- </MenuIcon>
- <Text noOfLines={1}>{name}</Text>
+ <Text noOfLines={1}>{name}</Text>
+ </HStack>
</ListItem>
);
};
diff --git a/apps/carbon/app/entry.client.tsx b/apps/carbon/app/entry.client.tsx
index 0f4cc739db..b3284edbf8 100644
--- a/apps/carbon/app/entry.client.tsx
+++ b/apps/carbon/app/entry.client.tsx
@@ -25,10 +25,3 @@ if (typeof requestIdleCallback === "function") {
// https://caniuse.com/requestidlecallback
setTimeout(hydrate, 1);
}
-
-if ("serviceWorker" in navigator) {
- window.addEventListener("load", () => {
- // we will register it after the page complete the load
- navigator.serviceWorker.register("/serviceWorker.js");
- });
-}
diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsx
index 3b7dadd6c9..e062d526b2 100644
--- a/apps/carbon/app/hooks/useUser.tsx
+++ b/apps/carbon/app/hooks/useUser.tsx
@@ -1,6 +1,6 @@
import { useRouteData } from "./useRouteData";
-type User = {
+type PersonalData = {
id: string;
email: string;
firstName: string;
@@ -10,19 +10,33 @@ type User = {
type Groups = string[];
-type UserWithGroups = User & { groups: Groups };
+type Defaults = {
+ locationId: string | null;
+};
+
+type User = PersonalData & {
+ groups: Groups;
+ defaults: Defaults;
+};
-export function useUser(): UserWithGroups {
- const data = useRouteData<{ user: unknown; groups: unknown }>("/x");
+export function useUser(): User {
+ const data = useRouteData<{
+ user: unknown;
+ groups: unknown;
+ defaults: unknown;
+ }>("/x");
if (
data?.user &&
isUser(data.user) &&
data?.groups &&
- isGroups(data.groups)
+ isGroups(data.groups) &&
+ data?.defaults &&
+ isDefaults(data.defaults)
) {
return {
...data.user,
groups: data.groups,
+ defaults: data.defaults,
};
}
// TODO: force logout -- the likely cause is development changes
@@ -31,7 +45,11 @@ export function useUser(): UserWithGroups {
);
}
-function isGroups(value: any): value is Groups {
+function isDefaults(value: any): value is Defaults {
+ return typeof value.locationId === "string" || value.locationId === null;
+}
+
+function isGroups(value: any): value is string[] {
return Array.isArray(value) && value.every((v) => typeof v === "string");
}
diff --git a/apps/carbon/app/modules/account/interfaces/UserAttributes/UserAttributesForm.tsx b/apps/carbon/app/modules/account/interfaces/UserAttributes/UserAttributesForm.tsx
index d9cbe46cdc..159b74edbd 100644
--- a/apps/carbon/app/modules/account/interfaces/UserAttributes/UserAttributesForm.tsx
+++ b/apps/carbon/app/modules/account/interfaces/UserAttributes/UserAttributesForm.tsx
@@ -17,14 +17,15 @@ import {
Boolean as BooleanInput,
DatePicker,
Employee,
- Input,
Hidden,
+ Input,
Number as NumberInput,
- Submit,
Select,
+ Submit,
} from "~/components/Form";
import { UserSelect } from "~/components/Selectors";
import { usePermissions, useUser } from "~/hooks";
+import type { PublicAttributes } from "~/modules/account";
import {
attributeBooleanValidator,
attributeNumericValidator,
@@ -32,7 +33,6 @@ import {
attributeUserValidator,
deleteUserAttributeValueValidator,
} from "~/modules/account";
-import type { PublicAttributes } from "~/modules/account";
import { DataType } from "~/modules/users";
type UserAttributesFormProps = {
@@ -183,7 +183,7 @@ function renderTypedForm({
<Submit size="sm" type="submit">
Save
</Submit>
- <Button variant="ghost" onClick={onClose}>
+ <Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
</HStack>
diff --git a/apps/carbon/app/modules/account/services/account.server.ts b/apps/carbon/app/modules/account/services/account.server.ts
index c2108d59e1..eec5f744c8 100644
--- a/apps/carbon/app/modules/account/services/account.server.ts
+++ b/apps/carbon/app/modules/account/services/account.server.ts
@@ -150,7 +150,8 @@ export async function upsertUserAttributeValue(
updatedBy,
})
.eq("id", userAttributeValueId)
- .select("id");
+ .select("id")
+ .single();
} else {
return client
.from("userAttributeValue")
@@ -160,6 +161,7 @@ export async function upsertUserAttributeValue(
userId,
createdBy: updatedBy,
})
- .select("id");
+ .select("id")
+ .single();
}
}
diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
index 67ef0e3008..ea6c0195fe 100644
--- a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
@@ -3,6 +3,7 @@ import {
Button,
ButtonGroup,
IconButton,
+ Link,
MenuItem,
useDisclosure,
} from "@chakra-ui/react";
@@ -42,12 +43,16 @@ const AccountCategoriesTable = memo(
deleteModal.onClose();
};
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "category",
header: "Category",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id as string)}>
+ {row.original.category}
+ </Link>
+ ),
},
{
header: "Income/Balance",
@@ -105,7 +110,7 @@ const AccountCategoriesTable = memo(
}, [navigate, params]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
index 4ac1f8467f..9c47aba6c2 100644
--- a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
@@ -26,7 +26,7 @@ const AttributeCategoriesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx
index 11b9ceac87..4ee6c7ffcb 100644
--- a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx
@@ -1,6 +1,13 @@
import { DataTable, DataTableColumnHeader } from "@carbon/react";
-import { Box, Checkbox, HStack, IconButton, Text } from "@chakra-ui/react";
-import { Link } from "@remix-run/react";
+import {
+ Box,
+ Checkbox,
+ HStack,
+ IconButton,
+ Link,
+ Text,
+} from "@chakra-ui/react";
+import { Link as RemixLink, useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { MdMoreHoriz } from "react-icons/md";
@@ -11,6 +18,7 @@ type ChartOfAccountsTableProps = {
};
const ChartOfAccountsTable = memo(({ data }: ChartOfAccountsTableProps) => {
+ const navigate = useNavigate();
const columns = useMemo<ColumnDef<Chart>[]>(() => {
return [
{
@@ -23,13 +31,17 @@ const ChartOfAccountsTable = memo(({ data }: ChartOfAccountsTableProps) => {
return (
<HStack>
- <Text fontWeight={isPosting ? "normal" : "bold"}>
+ <Link
+ onClick={() => navigate(row.original.id)}
+ fontWeight={isPosting ? "normal" : "bold"}
+ >
{row.original.number}
- </Text>
+ </Link>
+
<Box position="relative" w={6} h={6}>
<IconButton
aria-label="Edit account"
- as={Link}
+ as={RemixLink}
icon={<MdMoreHoriz />}
size="sm"
position="absolute"
@@ -105,7 +117,7 @@ const ChartOfAccountsTable = memo(({ data }: ChartOfAccountsTableProps) => {
cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
},
];
- }, []);
+ }, [navigate]);
return <DataTable data={data} columns={columns} />;
});
diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx
index 642fb16fe9..2e9392d196 100644
--- a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx
@@ -1,4 +1,4 @@
-import { Checkbox, MenuItem } from "@chakra-ui/react";
+import { Checkbox, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -18,12 +18,16 @@ const CurrenciesTable = memo(({ data, count }: CurrenciesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "code",
@@ -48,10 +52,10 @@ const CurrenciesTable = memo(({ data, count }: CurrenciesTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -83,7 +87,7 @@ const CurrenciesTable = memo(({ data, count }: CurrenciesTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx
index 30a28df5a6..b50b4577e6 100644
--- a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx
@@ -24,7 +24,7 @@ const CurrenciesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx
index 625d405ea4..7ac592de09 100644
--- a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTable/PaymentTermsTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -18,12 +18,16 @@ const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "daysDue",
@@ -46,10 +50,10 @@ const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {
cell: (item) => item.getValue(),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -83,7 +87,7 @@ const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx
index a82b9fa2ef..a708dcd35f 100644
--- a/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx
+++ b/apps/carbon/app/modules/accounting/interfaces/PaymentTerms/PaymentTermsTableFilters/PaymentTermsTableFilters.tsx
@@ -24,7 +24,7 @@ const PaymentTermsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.ts
index 48e3b4043d..53f9cc8ade 100644
--- a/apps/carbon/app/modules/accounting/services/accounting.server.ts
+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts
@@ -136,17 +136,14 @@ export async function getAccounts(
export async function getAccountsList(
client: SupabaseClient<Database>,
- type: string | null
+ type = "Posting"
) {
- let query = client.from("account").select("number, name").eq("active", true);
-
- if (type) {
- query = query.eq("type", type);
- }
-
- query = query.order("name", { ascending: true });
-
- return query;
+ return client
+ .from("account")
+ .select("number, name")
+ .eq("active", true)
+ .eq("type", type)
+ .order("name", { ascending: true });
}
export async function getAccountCategories(
@@ -420,42 +417,50 @@ export async function insertAccountEntries(
client: SupabaseClient<Database>,
accountEntries: TypeOfValidator<typeof accountLedgerValidator>[]
) {
- return client.from("accountLedger").insert(accountEntries).select("id");
+ return client
+ .from("accountLedger")
+ .insert(accountEntries)
+ .select("id")
+ .single();
}
export async function insertAccountLedger(
client: SupabaseClient<Database>,
accountEntry: TypeOfValidator<typeof accountLedgerValidator>
) {
- return client.from("accountLedger").insert([accountEntry]).select("id");
+ return client
+ .from("accountLedger")
+ .insert([accountEntry])
+ .select("id")
+ .single();
}
export async function insertPartEntries(
client: SupabaseClient<Database>,
partEntries: TypeOfValidator<typeof partLedgerValidator>[]
) {
- return client.from("partLedger").insert(partEntries).select("id");
+ return client.from("partLedger").insert(partEntries).select("id").single();
}
export async function insertPartLedger(
client: SupabaseClient<Database>,
partEntry: TypeOfValidator<typeof partLedgerValidator>
) {
- return client.from("partLedger").insert([partEntry]).select("id");
+ return client.from("partLedger").insert([partEntry]).select("id").single();
}
export async function insertValueEntries(
client: SupabaseClient<Database>,
valueEntries: TypeOfValidator<typeof valueLedgerValidator>[]
) {
- return client.from("valueLedger").insert(valueEntries).select("id");
+ return client.from("valueLedger").insert(valueEntries).select("id").single();
}
export async function insertValueLedger(
client: SupabaseClient<Database>,
valueEntry: TypeOfValidator<typeof valueLedgerValidator>
) {
- return client.from("valueLedger").insert([valueEntry]).select("id");
+ return client.from("valueLedger").insert([valueEntry]).select("id").single();
}
export async function upsertAccount(
@@ -470,13 +475,14 @@ export async function upsertAccount(
})
) {
if ("createdBy" in account) {
- return client.from("account").insert([account]).select("id");
+ return client.from("account").insert([account]).select("id").single();
}
return client
.from("account")
.update(sanitize(account))
.eq("id", account.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertAccountCategory(
@@ -494,13 +500,15 @@ export async function upsertAccountCategory(
return client
.from("accountCategory")
.insert([accountCategory])
- .select("id");
+ .select("id")
+ .single();
}
return client
.from("accountCategory")
.update(sanitize(accountCategory))
.eq("id", accountCategory.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertAccountSubcategory(
@@ -518,13 +526,15 @@ export async function upsertAccountSubcategory(
return client
.from("accountSubcategory")
.insert([accountSubcategory])
- .select("id");
+ .select("id")
+ .single();
}
return client
.from("accountSubcategory")
.update(sanitize(accountSubcategory))
.eq("id", accountSubcategory.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertCurrency(
@@ -543,13 +553,14 @@ export async function upsertCurrency(
}
if ("createdBy" in currency) {
- return client.from("currency").insert([currency]).select("id");
+ return client.from("currency").insert([currency]).select("id").single();
}
return client
.from("currency")
.update(sanitize(currency))
.eq("id", currency.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPaymentTerm(
@@ -564,11 +575,16 @@ export async function upsertPaymentTerm(
})
) {
if ("createdBy" in paymentTerm) {
- return client.from("paymentTerm").insert([paymentTerm]).select("id");
+ return client
+ .from("paymentTerm")
+ .insert([paymentTerm])
+ .select("id")
+ .single();
}
return client
.from("paymentTerm")
.update(sanitize(paymentTerm))
.eq("id", paymentTerm.id)
- .select("id");
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
index 288a275652..10744d7ba5 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTableFilters/DocumentsTableFilters.tsx
@@ -56,7 +56,7 @@ const DocumentsTableFilters = ({ labels }: DocumentTableFiltersProps) => {
<Select
// @ts-ignore
size="sm"
- value={documentTypeOptions.filter(
+ value={documentTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
@@ -72,7 +72,7 @@ const DocumentsTableFilters = ({ labels }: DocumentTableFiltersProps) => {
<Select
// @ts-ignore
size="sm"
- value={labelOptions.filter(
+ value={labelOptions.find(
(label) =>
params.getAll("labels").includes(label.value as string) ||
label.value === params.get("label")
diff --git a/apps/carbon/app/modules/documents/services/documents.server.ts b/apps/carbon/app/modules/documents/services/documents.server.ts
index acaa544729..d5366de278 100644
--- a/apps/carbon/app/modules/documents/services/documents.server.ts
+++ b/apps/carbon/app/modules/documents/services/documents.server.ts
@@ -203,7 +203,7 @@ export async function upsertDocument(
})
) {
if ("createdBy" in document) {
- return client.from("document").insert(document).select("id");
+ return client.from("document").insert(document).select("id").single();
}
return client
.from("document")
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/ReceiptForm.tsx
new file mode 100644
index 0000000000..2f7506ffc6
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -0,0 +1,202 @@
+import { Menubar, MenubarItem } from "@carbon/react";
+import {
+ Box,
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ FormLabel,
+ Grid,
+ Heading,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Hidden,
+ Input,
+ Select,
+ SelectControlled,
+ Submit,
+} from "~/components/Form";
+import DataGrid from "~/components/Grid";
+import type { ReceiptLine, ReceiptSourceDocument } from "~/modules/inventory";
+import {
+ receiptSourceDocumentType,
+ receiptValidator,
+} from "~/modules/inventory";
+import type { TypeOfValidator } from "~/types/validators";
+import useReceiptForm from "./useReceiptForm";
+
+type ReceiptFormProps = {
+ initialValues: TypeOfValidator<typeof receiptValidator>;
+ isPosted: boolean;
+ receiptLines?: ReceiptLine[];
+};
+
+const ReceiptForm = ({
+ initialValues,
+ isPosted,
+ receiptLines,
+}: ReceiptFormProps) => {
+ const {
+ editableComponents,
+ locationId,
+ locations,
+ internalReceiptItems,
+ isEditing,
+ isDisabled,
+ receiptLineColumns,
+ sourceDocumentId,
+ supplierId,
+ sourceDocuments,
+ onClose,
+ setLocationId,
+ setSourceDocument,
+ setSourceDocumentId,
+ } = useReceiptForm({
+ receipt: initialValues,
+ receiptLines: receiptLines ?? [],
+ });
+
+ 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}
+ >
+ 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>
+ </VStack>
+ {/* end notes component */}
+ </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>
+ );
+};
+
+export default ReceiptForm;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/index.ts b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/index.ts
new file mode 100644
index 0000000000..000433f10d
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/index.ts
@@ -0,0 +1,3 @@
+import ReceiptForm from "./ReceiptForm";
+
+export default ReceiptForm;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/useReceiptForm.tsx
new file mode 100644
index 0000000000..77927b8f61
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -0,0 +1,376 @@
+import { useMatches, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { EditableNumber } from "~/components/Editable";
+import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { receiptValidator } from "~/modules/inventory";
+import type {
+ ReceiptLine,
+ ReceiptLineItem,
+ ReceiptSourceDocument,
+} from "~/modules/inventory/types";
+import type { ListItem } from "~/types";
+import type { TypeOfValidator } from "~/types/validators";
+
+export default function useReceiptForm({
+ receipt,
+ receiptLines,
+}: {
+ receipt: TypeOfValidator<typeof receiptValidator>;
+ receiptLines: ReceiptLine[];
+}) {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const user = useUser();
+ const [params] = useUrlParams();
+ const [error, setError] = useState<string | null>(null);
+ const { supabase } = useSupabase();
+
+ const isDisabled = !permissions.can("update", "inventory");
+ const isEditing = !useMatches().some(({ pathname }) =>
+ pathname.includes("new")
+ );
+
+ const routeData = useRouteData<{
+ locations: ListItem[];
+ }>("/x/inventory/receipts");
+
+ const [internalReceiptItems, setReceiptItems] = useState<ReceiptLine[]>(
+ receiptLines ?? []
+ );
+
+ const [locationId, setLocationId] = useState<string | null>(
+ receipt.locationId ?? user.defaults.locationId ?? null
+ );
+ const [supplierId, setSupplierId] = useState<string | null>(
+ receipt.supplierId ?? null
+ );
+
+ const [sourceDocuments, setSourceDocuments] = useState<ListItem[]>([]);
+ const [sourceDocument, setSourceDocument] = useState<ReceiptSourceDocument>(
+ receipt.sourceDocument ?? "Purchase Order"
+ );
+
+ const [sourceDocumentId, setSourceDocumentId] = useState<string | null>(
+ receipt.sourceDocumentId ?? null
+ );
+
+ const onClose = () => {
+ if (!sourceDocumentId && receipt.id) {
+ deleteReceipt(receipt.id);
+ }
+ navigate(-1);
+ };
+
+ const sourceDocumentIdFromParams = params.get("sourceDocumentId");
+ const sourceDocumentFromParams = params.get("sourceDocument");
+
+ useEffect(() => {
+ if (sourceDocumentIdFromParams && sourceDocumentFromParams) {
+ setSourceDocument(sourceDocumentFromParams as ReceiptSourceDocument);
+ setSourceDocumentId(sourceDocumentIdFromParams);
+ }
+ }, [
+ setSourceDocument,
+ setSourceDocumentId,
+ sourceDocumentFromParams,
+ 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;
+
+ return supabase
+ .from("receipt")
+ .delete()
+ .eq("id", id)
+ .then((response) => {
+ if (response.error) {
+ setError(response.error.message);
+ }
+ });
+ },
+ [supabase]
+ );
+
+ const deleteReceiptItems = useCallback(async () => {
+ if (!supabase) throw new Error("supabase client is not defined");
+
+ return supabase
+ .from("receiptLine")
+ .delete()
+ .eq("receiptId", receipt.receiptId);
+ }, [receipt.receiptId, supabase]);
+
+ const fetchSourceDocuments = useCallback(() => {
+ if (!supabase) return;
+
+ switch (sourceDocument) {
+ case "Purchase Order":
+ supabase
+ ?.from("purchaseOrder")
+ .select("id, purchaseOrderId")
+ .eq("status", "Released")
+ .then((response) => {
+ if (response.error) {
+ setError(response.error.message);
+ } else {
+ setSourceDocuments(
+ response.data.map((d) => ({
+ name: d.purchaseOrderId,
+ id: d.id,
+ }))
+ );
+ }
+ });
+
+ default:
+ setSourceDocuments([]);
+ }
+ }, [sourceDocument, supabase]);
+
+ const fetchSourceDocument = useCallback(async () => {
+ if (!supabase || !sourceDocumentId) return;
+
+ switch (sourceDocument) {
+ case "Purchase Order":
+ const [
+ purchaseOrder,
+ purchaseOrderLines,
+ receiptLines,
+ previouslyReceivedLines,
+ ] = 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("*")
+ .eq("receiptId", receipt.receiptId),
+ supabase
+ .from("receipt_quantity_received_by_line")
+ .select("*")
+ .eq("sourceDocumentId", sourceDocumentId),
+ ]);
+
+ if (purchaseOrder.error) {
+ setError(purchaseOrder.error.message);
+ setReceiptItems([]);
+ break;
+ } else {
+ setSupplierId(purchaseOrder.data.supplierId);
+ }
+
+ if (receiptLines.error) {
+ setError(receiptLines.error.message);
+ setReceiptItems([]);
+ break;
+ }
+
+ if (
+ receipt.sourceDocumentId === sourceDocumentId &&
+ receiptLines.data.length > 0
+ ) {
+ // no need to insert and fetch lines if they already exist
+ setReceiptItems(receiptLines.data);
+ break;
+ }
+
+ const deleteExistingLines = await deleteReceiptItems();
+ if (deleteExistingLines.error) {
+ setError(deleteExistingLines.error.message);
+ break;
+ }
+
+ if (purchaseOrderLines.error) {
+ setError(purchaseOrderLines.error.message);
+ break;
+ }
+
+ const previouslyReceivedQuantitiesByLine = (
+ previouslyReceivedLines.data ?? []
+ ).reduce<Record<string, number>>((acc, d) => {
+ if (d.lineId) acc[d.lineId] = d.receivedQuantity ?? 0;
+ return acc;
+ }, {});
+
+ const receiptLineItems = purchaseOrderLines.data.reduce<
+ ReceiptLineItem[]
+ >((acc, d) => {
+ if (
+ !d.partId ||
+ !d.purchaseQuantity ||
+ d.unitPrice === null ||
+ isNaN(d.unitPrice)
+ ) {
+ return acc;
+ }
+
+ acc.push({
+ receiptId: receipt.receiptId,
+ lineId: d.id,
+ partId: d.partId,
+ orderQuantity: d.purchaseQuantity,
+ outstandingQuantity:
+ d.purchaseQuantity -
+ (previouslyReceivedQuantitiesByLine[d.id] ?? 0),
+ receivedQuantity: 0,
+ unitPrice: d.unitPrice,
+ unitOfMeasure: d.unitOfMeasureCode ?? "EA",
+ locationId: d.locationId,
+ shelfId: d.shelfId,
+ createdBy: user?.id ?? "",
+ });
+
+ return acc;
+ }, []);
+
+ const { error: insertError } = await supabase
+ .from("receiptLine")
+ .insert(receiptLineItems);
+
+ if (insertError) {
+ setError(insertError.message);
+ setReceiptItems([]);
+ break;
+ }
+
+ const { data: receiptLinesData, error: selectError } = await supabase
+ .from("receiptLine")
+ .select("*")
+ .eq("receiptId", receipt.receiptId);
+
+ if (selectError) {
+ setError(selectError.message);
+ setReceiptItems([]);
+ break;
+ }
+
+ setReceiptItems(receiptLinesData ?? []);
+ break;
+ default:
+ return;
+ }
+ }, [
+ deleteReceiptItems,
+ locationId,
+ receipt.receiptId,
+ receipt.sourceDocumentId,
+ sourceDocument,
+ sourceDocumentId,
+ supabase,
+ user?.id,
+ ]);
+
+ useEffect(() => {
+ fetchSourceDocuments();
+ }, [fetchSourceDocuments, sourceDocument]);
+
+ useEffect(() => {
+ if (sourceDocumentId) {
+ fetchSourceDocument();
+ } else {
+ setSupplierId(null);
+ }
+ }, [fetchSourceDocument, setLocationId, setSupplierId, sourceDocumentId]);
+
+ const receiptLineColumns = useMemo<ColumnDef<ReceiptLine>[]>(() => {
+ return [
+ {
+ accessorKey: "partId",
+ header: "Part",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "orderQuantity",
+ header: "Order Quantity",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "outstandingQuantity",
+ header: "Outstanding Quantity",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "receivedQuantity",
+ header: "Received Quantity",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "unitPrice",
+ header: "Unit Cost",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "locationId",
+ header: "Location",
+ cell: ({ row }) =>
+ (routeData?.locations ?? []).find(
+ (l) => l.id === row.original.locationId
+ )?.name ?? null,
+ },
+ {
+ accessorKey: "shelfId",
+ header: "Shelf",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "unitOfMeasure",
+ header: "Unit of Measure",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, [routeData?.locations]);
+
+ const handleCellEdit = useCallback(
+ async (id: string, value: unknown, row: ReceiptLine) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("receiptLine")
+ .update({
+ [id]: value,
+ })
+ .eq("id", row.id);
+ },
+ [supabase]
+ );
+
+ const receiptLineEditableComponents = useMemo(
+ () => ({
+ receivedQuantity: EditableNumber(handleCellEdit),
+ unitPrice: EditableNumber(handleCellEdit),
+ }),
+ [handleCellEdit]
+ );
+
+ return {
+ editableComponents: receiptLineEditableComponents,
+ error,
+ locationId,
+ locations: routeData?.locations ?? [],
+ internalReceiptItems,
+ isEditing,
+ isDisabled,
+ receiptLineColumns,
+ sourceDocument,
+ sourceDocumentId,
+ supplierId,
+ sourceDocuments,
+ onClose,
+ setLocationId,
+ setSourceDocument,
+ setSourceDocumentId,
+ };
+}
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/ReceiptsTable.tsx b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/ReceiptsTable.tsx
new file mode 100644
index 0000000000..7c1f7f7906
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/ReceiptsTable.tsx
@@ -0,0 +1,108 @@
+import { formatDate } from "@carbon/utils";
+import { Link, MenuItem } 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 type { Receipt } from "~/modules/inventory";
+
+type ReceiptsTableProps = {
+ data: Receipt[];
+ count: number;
+};
+
+const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {
+ const [params] = useUrlParams();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const rows = useMemo(() => data, [data]);
+
+ const columns = useMemo<ColumnDef<Receipt>[]>(() => {
+ const result: ColumnDef<(typeof rows)[number]>[] = [
+ {
+ accessorKey: "receiptId",
+ header: "Receipt ID",
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.receiptId}
+ </Link>
+ ),
+ },
+ {
+ accessorKey: "sourceDocument",
+ header: "Source Document",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "sourceDocumentReadableId",
+ header: "Source Document ID",
+ cell: (item) => item.getValue() ?? null,
+ },
+ {
+ accessorKey: "location.name",
+ header: "Location",
+ cell: (item) => item.getValue() ?? null,
+ },
+ {
+ accessorKey: "supplier.name",
+ header: "Supplier",
+ cell: (item) => item.getValue() ?? null,
+ },
+ {
+ accessorKey: "postingDate",
+ header: "Posting Date",
+ cell: (item) => formatDate(item.getValue<string>()),
+ },
+ ];
+
+ return result;
+ }, [navigate]);
+
+ const renderContextMenu = useCallback(
+ (row: Receipt) => {
+ return (
+ <>
+ <MenuItem
+ isDisabled={!permissions.can("update", "inventory")}
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(`/x/inventory/receipts/${row.id}?${params.toString()}`);
+ }}
+ >
+ Edit Receipt
+ </MenuItem>
+ <MenuItem
+ isDisabled={
+ !permissions.can("delete", "inventory") || !!row.postingDate
+ }
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/x/inventory/receipts/delete/${row.id}?${params.toString()}`
+ );
+ }}
+ >
+ Delete Receipt
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<(typeof data)[number]>
+ data={data}
+ columns={columns}
+ count={count}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+ReceiptsTable.displayName = "ReceiptsTable";
+export default ReceiptsTable;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/index.ts b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/index.ts
new file mode 100644
index 0000000000..4aa53880d5
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTable/index.ts
@@ -0,0 +1,3 @@
+import ReceiptsTable from "./ReceiptsTable";
+
+export default ReceiptsTable;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx
new file mode 100644
index 0000000000..00dc6efb50
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/ReceiptsTableFilters.tsx
@@ -0,0 +1,93 @@
+import { Select, useColor } from "@carbon/react";
+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 { receiptSourceDocumentType } from "~/modules/inventory";
+import type { ListItem } from "~/types";
+
+type ReceiptsTableFiltersProps = {
+ locations: ListItem[];
+};
+
+const ReceiptsTableFilters = ({ locations }: ReceiptsTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+
+ const sourceDocumentOptions = receiptSourceDocumentType.map((type) => ({
+ label: type,
+ value: type,
+ }));
+
+ const locationOptions = locations.map(({ id, name }) => ({
+ label: name,
+ value: id,
+ }));
+
+ return (
+ <HStack
+ px={4}
+ py={3}
+ justifyContent="space-between"
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="search"
+ size="sm"
+ minW={180}
+ placeholder="Search"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={sourceDocumentOptions.find(
+ (document) => document.value === params.get("document")
+ )}
+ isClearable
+ options={sourceDocumentOptions}
+ onChange={(selected) => {
+ setParams({ document: selected?.value });
+ }}
+ aria-label="Source Document"
+ placeholder="Source Document"
+ minW={180}
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={locationOptions.find(
+ (location) => location.value === params.get("location")
+ )}
+ isClearable
+ options={locationOptions}
+ onChange={(selected) => {
+ setParams({ location: selected?.value });
+ }}
+ aria-label="Location"
+ placeholder="Location"
+ minW={180}
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "inventory") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Receipt
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default ReceiptsTableFilters;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/index.ts b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/index.ts
new file mode 100644
index 0000000000..420ba9beba
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/ReceiptsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import ReceiptsTableFilters from "./ReceiptsTableFilters";
+
+export default ReceiptsTableFilters;
diff --git a/apps/carbon/app/modules/inventory/interfaces/Receipts/index.ts b/apps/carbon/app/modules/inventory/interfaces/Receipts/index.ts
new file mode 100644
index 0000000000..a2e9f367d9
--- /dev/null
+++ b/apps/carbon/app/modules/inventory/interfaces/Receipts/index.ts
@@ -0,0 +1,5 @@
+import ReceiptForm from "./ReceiptForm";
+import ReceiptsTable from "./ReceiptsTable";
+import ReceiptsTableFilters from "./ReceiptsTableFilters";
+
+export { ReceiptForm, ReceiptsTable, ReceiptsTableFilters };
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx
index 80089d10d9..0447d1a41b 100644
--- a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodForm/ShippingMethodForm.tsx
@@ -12,24 +12,16 @@ import {
} from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
-import { Hidden, Input, Select, Submit } from "~/components/Form";
+import { Account, Hidden, Input, Select, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { shippingMethodValidator } from "~/modules/inventory";
import type { TypeOfValidator } from "~/types/validators";
-import { mapRowsToOptions } from "~/utils/form";
type ShippingMethodFormProps = {
initialValues: TypeOfValidator<typeof shippingMethodValidator>;
- accounts: {
- number: string;
- name: string;
- }[];
};
-const ShippingMethodForm = ({
- initialValues,
- accounts,
-}: ShippingMethodFormProps) => {
+const ShippingMethodForm = ({ initialValues }: ShippingMethodFormProps) => {
const permissions = usePermissions();
const navigate = useNavigate();
const onClose = () => navigate(-1);
@@ -46,12 +38,6 @@ const ShippingMethodForm = ({
})
);
- const accountOptions = mapRowsToOptions({
- data: accounts,
- value: "number",
- label: "name",
- });
-
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
<ValidatedForm
@@ -79,11 +65,7 @@ const ShippingMethodForm = ({
label="Carrier"
options={shippingCarrierOptions}
/>
- <Select
- name="carrierAccountId"
- label="Carrier Account"
- options={accountOptions}
- />
+ <Account name="carrierAccountId" label="Carrier Account" />
<Input
name="trackingUrl"
label="Tracking URL"
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx
index 8da8f2d730..f891c6f69f 100644
--- a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTable/ShippingMethodsTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -23,12 +23,16 @@ const ShippingMethodsTable = memo(
const rows = useMemo(() => data, [data]);
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
- const result: ColumnDef<typeof rows[number]>[] = [
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
+ const result: ColumnDef<(typeof rows)[number]>[] = [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "carrier",
@@ -55,7 +59,7 @@ const ShippingMethodsTable = memo(
}, [permissions]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -89,7 +93,7 @@ const ShippingMethodsTable = memo(
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx
index 1b2e82afa1..8fef928478 100644
--- a/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx
+++ b/apps/carbon/app/modules/inventory/interfaces/ShippingMethods/ShippingMethodsTableFilters/ShippingMethodsTableFilters.tsx
@@ -24,7 +24,7 @@ const ShippingMethodsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/inventory/interfaces/index.ts b/apps/carbon/app/modules/inventory/interfaces/index.ts
index 1edad05971..967c0af24b 100644
--- a/apps/carbon/app/modules/inventory/interfaces/index.ts
+++ b/apps/carbon/app/modules/inventory/interfaces/index.ts
@@ -1,4 +1,5 @@
import useInventorySidebar from "./useInventorySidebar";
export { useInventorySidebar };
+export * from "./Receipts";
export * from "./ShippingMethods";
diff --git a/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx b/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx
index fdc626a56c..9920d04d7a 100644
--- a/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx
+++ b/apps/carbon/app/modules/inventory/interfaces/useInventorySidebar.tsx
@@ -2,6 +2,19 @@ import { usePermissions } from "~/hooks";
import type { AuthenticatedRouteGroup } from "~/types";
const inventoryRoutes: AuthenticatedRouteGroup[] = [
+ {
+ name: "Manage",
+ routes: [
+ {
+ name: "Receipts",
+ to: "/x/inventory/receipts",
+ },
+ {
+ name: "Shipments",
+ to: "/x/inventory/shipments",
+ },
+ ],
+ },
{
name: "Configure",
routes: [
diff --git a/apps/carbon/app/modules/inventory/services/inventory.form.ts b/apps/carbon/app/modules/inventory/services/inventory.form.ts
index c8499553f5..1e1c0aa1ba 100644
--- a/apps/carbon/app/modules/inventory/services/inventory.form.ts
+++ b/apps/carbon/app/modules/inventory/services/inventory.form.ts
@@ -2,6 +2,31 @@ import { withZod } from "@remix-validated-form/with-zod";
import { z } from "zod";
import { zfd } from "zod-form-data";
+export const receiptSourceDocumentType = [
+ // "Sales Order",
+ // "Sales Return Order",
+ "Purchase Order",
+ // "Purchase Return Order",
+ // "Inbound Transfer",
+ // "Outbound Transfer",
+ // "Manufacturing Consumption",
+ // "Manufacturing Output",
+] as const;
+
+export const receiptValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ receiptId: z.string().min(1, { message: "Receipt ID is required" }),
+ locationId: zfd.text(z.string().optional()),
+ sourceDocument: z.enum(receiptSourceDocumentType).optional(),
+ sourceDocumentId: zfd.text(
+ z.string().min(1, { message: "Source Document ID is required" })
+ ),
+ sourceDocumentReadableId: zfd.text(z.string().optional()),
+ supplierId: zfd.text(z.string().optional()),
+ })
+);
+
export const shippingMethodValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/inventory/services/inventory.server.ts b/apps/carbon/app/modules/inventory/services/inventory.server.ts
index 8348f32514..493132ad8a 100644
--- a/apps/carbon/app/modules/inventory/services/inventory.server.ts
+++ b/apps/carbon/app/modules/inventory/services/inventory.server.ts
@@ -4,7 +4,17 @@ import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
-import type { shippingMethodValidator } from "./inventory.form";
+import type {
+ receiptValidator,
+ shippingMethodValidator,
+} from "./inventory.form";
+
+export async function deleteReceipt(
+ client: SupabaseClient<Database>,
+ receiptId: string
+) {
+ return client.from("receipt").delete().eq("id", receiptId);
+}
export async function deleteShippingMethod(
client: SupabaseClient<Database>,
@@ -16,6 +26,53 @@ export async function deleteShippingMethod(
.eq("id", shippingMethodId);
}
+export async function getReceipts(
+ client: SupabaseClient<Database>,
+ args: GenericQueryFilters & {
+ search: string | null;
+ document: string | null;
+ location: string | null;
+ }
+) {
+ let query = client
+ .from("receipt")
+ .select("*, location(name), supplier(name)", {
+ count: "exact",
+ })
+ .neq("sourceDocumentId", "");
+
+ if (args.search) {
+ query = query.or(
+ `receiptId.ilike.%${args.search}%,sourceDocumentReadableId.ilike.%${args.search}%`
+ );
+ }
+
+ if (args.document) {
+ query = query.eq("sourceDocument", args.document);
+ }
+
+ if (args.location) {
+ query = query.eq("locationId", args.location);
+ }
+
+ query = setGenericQueryFilters(query, args, "receiptId", false);
+ return query;
+}
+
+export async function getReceipt(
+ client: SupabaseClient<Database>,
+ receiptId: string
+) {
+ return client.from("receipt").select("*").eq("id", receiptId).single();
+}
+
+export async function getReceiptLines(
+ client: SupabaseClient<Database>,
+ receiptId: string
+) {
+ return client.from("receiptLine").select("*").eq("receiptId", receiptId);
+}
+
export async function getShippingMethod(
client: SupabaseClient<Database>,
shippingMethodId: string
@@ -64,6 +121,30 @@ export async function getShippingTermsList(client: SupabaseClient<Database>) {
.order("name", { ascending: true });
}
+export async function upsertReceipt(
+ client: SupabaseClient<Database>,
+ receipt:
+ | (Omit<TypeOfValidator<typeof receiptValidator>, "id" | "receiptId"> & {
+ receiptId: string;
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof receiptValidator>, "id" | "receiptId"> & {
+ id: string;
+ receiptId: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in receipt) {
+ return client.from("receipt").insert([receipt]).select("id").single();
+ }
+ return client
+ .from("receipt")
+ .update(sanitize(receipt))
+ .eq("id", receipt.id)
+ .select("id")
+ .single();
+}
+
export async function upsertShippingMethod(
client: SupabaseClient<Database>,
shippingMethod:
@@ -76,11 +157,16 @@ export async function upsertShippingMethod(
})
) {
if ("createdBy" in shippingMethod) {
- return client.from("shippingMethod").insert([shippingMethod]).select("id");
+ return client
+ .from("shippingMethod")
+ .insert([shippingMethod])
+ .select("id")
+ .single();
}
return client
.from("shippingMethod")
.update(sanitize(shippingMethod))
.eq("id", shippingMethod.id)
- .select("id");
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
index a120fd18a3..4ebd85783a 100644
--- a/apps/carbon/app/modules/inventory/types.ts
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -1,5 +1,25 @@
import type { Database } from "@carbon/database";
-import type { getShippingMethods } from "./services";
+import type {
+ getReceipts,
+ getReceiptLines,
+ getShippingMethods,
+} from "./services";
+
+export type Receipt = NonNullable<
+ Awaited<ReturnType<typeof getReceipts>>["data"]
+>[number];
+
+export type ReceiptSourceDocument =
+ Database["public"]["Enums"]["receiptSourceDocument"];
+
+export type ReceiptLine = NonNullable<
+ Awaited<ReturnType<typeof getReceiptLines>>["data"]
+>[number];
+
+export type ReceiptLineItem = Omit<
+ ReceiptLine,
+ "id" | "updatedBy" | "createdAt" | "updatedAt"
+>;
export type ShippingCarrier = Database["public"]["Enums"]["shippingCarrier"];
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx
index 9118b570d1..a49f7570c8 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx
@@ -1,23 +1,21 @@
+import { Select } from "@carbon/react";
import {
+ Box,
Card,
CardBody,
CardFooter,
CardHeader,
Grid,
Heading,
+ HStack,
VStack,
} from "@chakra-ui/react";
import { useState } from "react";
import { ValidatedForm } from "remix-validated-form";
-import {
- Boolean,
- CreatableSelect,
- Hidden,
- Number,
- Submit,
-} from "~/components/Form";
+import { CreatableSelect, Hidden, Number, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { partInventoryValidator } from "~/modules/parts";
+import type { ListItem } from "~/types";
import type { TypeOfValidator } from "~/types/validators";
type PartInventoryFormProps = {
@@ -25,16 +23,22 @@ type PartInventoryFormProps = {
TypeOfValidator<typeof partInventoryValidator>,
"hasNewShelf"
>;
+ locations: ListItem[];
shelves: string[];
};
const PartInventoryForm = ({
initialValues,
+ locations,
shelves,
}: PartInventoryFormProps) => {
const permissions = usePermissions();
const [hasNewShelf, setHasNewShelf] = useState(false);
const shelfOptions = shelves.map((shelf) => ({ value: shelf, label: shelf }));
+ const locationOptions = locations.map((location) => ({
+ label: location.name,
+ value: location.id,
+ }));
return (
<ValidatedForm
@@ -53,10 +57,27 @@ const PartInventoryForm = ({
>
<Card w="full">
<CardHeader>
- <Heading size="md">Inventory</Heading>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Inventory</Heading>
+ <Box w={180}>
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={locationOptions.find(
+ (location) => location.value === initialValues.locationId
+ )}
+ options={locationOptions}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = `/x/part/${initialValues.partId}/inventory?location=${selected?.value}`;
+ }}
+ />
+ </Box>
+ </HStack>
</CardHeader>
<CardBody>
<Hidden name="partId" />
+ <Hidden name="locationId" />
<Hidden name="hasNewShelf" value={hasNewShelf.toString()} />
<Grid
gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}
@@ -67,8 +88,8 @@ const PartInventoryForm = ({
<VStack alignItems="start" spacing={2} w="full">
<CreatableSelect
options={shelfOptions}
- name="shelfId"
- label="Shelf"
+ name="defaultShelfId"
+ label="Default Shelf"
onUsingCreatedChanged={setHasNewShelf}
// @ts-ignore
w="full"
@@ -78,18 +99,20 @@ const PartInventoryForm = ({
label="Quantity On Hand"
isReadOnly
/>
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
<Number
name="quantityAvailable"
label="Quantity Available"
isReadOnly
/>
- </VStack>
- <VStack alignItems="start" spacing={2} w="full">
<Number
name="quantityOnPurchaseOrder"
label="Quantity On Purchase Order"
isReadOnly
/>
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
<Number
name="quantityOnProdOrder"
label="Quantity On Prod Order"
@@ -101,11 +124,6 @@ const PartInventoryForm = ({
isReadOnly
/>
</VStack>
- <VStack alignItems="start" spacing={2} w="full">
- <Number name="unitVolume" label="Unit Volume" />
- <Number name="unitWeight" label="Unit Weight" />
- <Boolean name="stockoutWarning" label="Stockout Warning" />
- </VStack>
</Grid>
</CardBody>
<CardFooter>
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx
index ee806dc830..fb4cc4acfc 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx
@@ -1,33 +1,45 @@
+import { Select } from "@carbon/react";
import {
+ Box,
Card,
CardBody,
CardFooter,
CardHeader,
Grid,
Heading,
+ HStack,
VStack,
} from "@chakra-ui/react";
import { ValidatedForm } from "remix-validated-form";
-import { Boolean, Hidden, Number, Select, Submit } from "~/components/Form";
+import {
+ Boolean,
+ Hidden,
+ Number,
+ Select as SelectForm,
+ Submit,
+} from "~/components/Form";
import { usePermissions } from "~/hooks";
import type { PartReorderingPolicy } from "~/modules/parts";
import { partPlanningValidator } from "~/modules/parts";
+import type { ListItem } from "~/types";
import type { TypeOfValidator } from "~/types/validators";
type PartPlanningFormProps = {
initialValues: TypeOfValidator<typeof partPlanningValidator>;
+ locations: ListItem[];
partReorderingPolicies: PartReorderingPolicy[];
};
const PartPlanningForm = ({
initialValues,
+ locations,
partReorderingPolicies,
}: PartPlanningFormProps) => {
const permissions = usePermissions();
- const partReorderingOptions = partReorderingPolicies.map((policy) => ({
- label: policy,
- value: policy,
+ const locationOptions = locations.map((location) => ({
+ label: location.name,
+ value: location.id,
}));
return (
@@ -38,10 +50,27 @@ const PartPlanningForm = ({
>
<Card w="full">
<CardHeader>
- <Heading size="md">Planning</Heading>
+ <HStack w="full" justifyContent="space-between">
+ <Heading size="md">Planning</Heading>
+ <Box w={180}>
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={locationOptions.find(
+ (location) => location.value === initialValues.locationId
+ )}
+ options={locationOptions}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = `/x/part/${initialValues.partId}/planning?location=${selected?.value}`;
+ }}
+ />
+ </Box>
+ </HStack>
</CardHeader>
<CardBody>
<Hidden name="partId" />
+ <Hidden name="locationId" />
<Grid
gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}
gridColumnGap={8}
@@ -49,10 +78,13 @@ const PartPlanningForm = ({
w="full"
>
<VStack alignItems="start" spacing={2} w="full">
- <Select
+ <SelectForm
name="reorderingPolicy"
label="Reordering Policy"
- options={partReorderingOptions}
+ options={partReorderingPolicies.map((policy) => ({
+ label: policy,
+ value: policy,
+ }))}
/>
<Boolean name="critical" label="Critical" />
<Number
@@ -94,14 +126,6 @@ const PartPlanningForm = ({
name="reorderMaximumInventory"
label="Reorder Maximum Inventory"
/>
- <Number
- name="reorderOverflowLevel"
- label="Reorder Overflow Level"
- />
- <Number
- name="reorderTimeBucket"
- label="Reorder Time Bucket (Days)"
- />
</VStack>
</Grid>
</CardBody>
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx
index d889a8c54c..a423eef12f 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx
@@ -16,15 +16,17 @@ import type { PartSummary } from "~/modules/parts";
const PartPreview = () => {
const { partId } = useParams();
if (!partId) throw new Error("Could not find partId");
- const routeData = useRouteData<PartSummary>(`/x/part/${partId}`);
+ const routeData = useRouteData<{ partSummary: PartSummary }>(
+ `/x/part/${partId}`
+ );
return (
<Card w="full">
<CardHeader>
<HStack justifyContent="space-between" alignItems="start">
<Stack direction={["column", "column", "row"]} spacing={2}>
- <Heading size="md">{routeData?.id}</Heading>
- <Text color="gray.500">{routeData?.name}</Text>
+ <Heading size="md">{routeData?.partSummary?.id}</Heading>
+ <Text color="gray.500">{routeData?.partSummary?.name}</Text>
</Stack>
<Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
View History
@@ -39,7 +41,9 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Replenishment System</Text>
- <Text fontWeight="bold">{routeData?.replenishmentSystem}</Text>
+ <Text fontWeight="bold">
+ {routeData?.partSummary?.replenishmentSystem}
+ </Text>
</Stack>
<Stack
direction={["row", "row", "column"]}
@@ -47,7 +51,7 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Part Type</Text>
- <Text fontWeight="bold">{routeData?.partType}</Text>
+ <Text fontWeight="bold">{routeData?.partSummary?.partType}</Text>
</Stack>
<Stack
direction={["row", "row", "column"]}
@@ -55,15 +59,9 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Unit of Measure</Text>
- <Text fontWeight="bold">{routeData?.unitOfMeasureCode}</Text>
- </Stack>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
- >
- <Text color="gray.500">Location</Text>
- <Text fontWeight="bold">--</Text>
+ <Text fontWeight="bold">
+ {routeData?.partSummary?.unitOfMeasureCode}
+ </Text>
</Stack>
</Stack>
</CardBody>
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx
index f962c1b5b1..49b2dab6a6 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx
@@ -13,11 +13,13 @@ const PartSidebar = () => {
"PartSidebar requires a partId and could not find partId in params"
);
- const routeData = useRouteData<PartSummary>(`/x/part/${partId}`);
- if (!routeData?.replenishmentSystem)
+ const routeData = useRouteData<{ partSummary: PartSummary }>(
+ `/x/part/${partId}`
+ );
+ if (!routeData?.partSummary?.replenishmentSystem)
throw new Error("Could not find replenishmentSystem in routeData");
- const links = usePartSidebar(routeData.replenishmentSystem);
+ const links = usePartSidebar(routeData.partSummary.replenishmentSystem);
const matches = useMatches();
return (
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx
index 0ebb5470fc..92a94efe54 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx
@@ -95,7 +95,7 @@ const PartSupplierForm = ({ initialValues }: PartSupplierFormProps) => {
<DrawerFooter>
<HStack>
<Submit isDisabled={isDisabled}>Save</Submit>
- <Button variant="ghost" onClick={onClose}>
+ <Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
</HStack>
diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx
index a17b3734f1..13cf1508cd 100644
--- a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -22,12 +22,16 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
const rows = useMemo(() => data, [data]);
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
- const result: ColumnDef<typeof rows[number]>[] = [
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
+ const result: ColumnDef<(typeof rows)[number]>[] = [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "description",
@@ -55,10 +59,10 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
},
])
: result;
- }, [hasAccounting]);
+ }, [hasAccounting, navigate]);
const renderContextMenu = useCallback(
- (row: typeof rows[number]) => {
+ (row: (typeof rows)[number]) => {
return (
<>
<MenuItem
@@ -86,7 +90,7 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsx
index a21c88d918..9487cdf44d 100644
--- a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsx
@@ -24,7 +24,7 @@ const PartGroupsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
index db333f8160..3ecf513791 100644
--- a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
@@ -21,7 +21,11 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
{
accessorKey: "id",
header: "Part ID",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(`/x/part/${row.original.id}`)}>
+ {row.original.id}
+ </Link>
+ ),
},
{
accessorKey: "name",
diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx
index 61ff3729a9..e33c627ac8 100644
--- a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx
@@ -53,7 +53,7 @@ const PartsTableFilters = ({
// @ts-ignore
size="sm"
isClearable
- value={partGroupsOptions.filter(
+ value={partGroupsOptions.find(
(type) => type.value === params.get("group")
)}
options={partGroupsOptions}
@@ -69,7 +69,7 @@ const PartsTableFilters = ({
<Select
// @ts-ignore
size="sm"
- value={partTypeOptions.filter(
+ value={partTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
index 041d8e0480..c2a41a00d6 100644
--- a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -19,12 +19,16 @@ const UnitOfMeasuresTable = memo(
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "code",
@@ -32,10 +36,10 @@ const UnitOfMeasuresTable = memo(
cell: (item) => item.getValue(),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -63,7 +67,7 @@ const UnitOfMeasuresTable = memo(
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsx
index 55ddada23b..2e6296f9c1 100644
--- a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsx
@@ -24,7 +24,7 @@ const UnitOfMeasuresTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/parts/services/parts.form.ts b/apps/carbon/app/modules/parts/services/parts.form.ts
index a4fc99e78d..0fd26148d6 100644
--- a/apps/carbon/app/modules/parts/services/parts.form.ts
+++ b/apps/carbon/app/modules/parts/services/parts.form.ts
@@ -58,11 +58,9 @@ export const partGroupValidator = withZod(
export const partInventoryValidator = withZod(
z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
- shelfId: zfd.text(z.string().optional()),
+ locationId: z.string().min(20, { message: "Location is required" }),
+ defaultShelfId: zfd.text(z.string().optional()),
hasNewShelf: z.enum(["true", "false"]),
- stockoutWarning: zfd.checkbox(),
- unitVolume: zfd.numeric(z.number().min(0)),
- unitWeight: zfd.numeric(z.number().min(0)),
})
);
@@ -85,6 +83,7 @@ export const partManufacturingValidator = withZod(
export const partPlanningValidator = withZod(
z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
+ locationId: z.string().min(20, { message: "Location is required" }),
reorderingPolicy: z.enum(
[
"Manual Reorder",
@@ -107,8 +106,6 @@ export const partPlanningValidator = withZod(
reorderPoint: zfd.numeric(z.number().min(0)),
reorderQuantity: zfd.numeric(z.number().min(0)),
reorderMaximumInventory: zfd.numeric(z.number().min(0)),
- reorderOverflowLevel: zfd.numeric(z.number().min(0)),
- reorderTimeBucket: zfd.numeric(z.number().min(0)),
minimumOrderQuantity: zfd.numeric(z.number().min(0)),
maximumOrderQuantity: zfd.numeric(z.number().min(0)),
orderMultiple: zfd.numeric(z.number().min(1)),
diff --git a/apps/carbon/app/modules/parts/services/parts.server.ts b/apps/carbon/app/modules/parts/services/parts.server.ts
index 9b26feab1b..283b002dd3 100644
--- a/apps/carbon/app/modules/parts/services/parts.server.ts
+++ b/apps/carbon/app/modules/parts/services/parts.server.ts
@@ -99,9 +99,15 @@ export async function getPartGroupsList(
export async function getPartInventory(
client: SupabaseClient<Database>,
- id: string
+ partId: string,
+ locationId: string
) {
- return client.from("partInventory").select("*").eq("partId", id).single();
+ return client
+ .from("partInventory")
+ .select("*")
+ .eq("partId", partId)
+ .eq("locationId", locationId)
+ .maybeSingle();
}
export async function getPartManufacturing(
@@ -113,9 +119,15 @@ export async function getPartManufacturing(
export async function getPartPlanning(
client: SupabaseClient<Database>,
- id: string
+ partId: string,
+ locationId: string
) {
- return client.from("partPlanning").select("*").eq("partId", id).single();
+ return client
+ .from("partPlanning")
+ .select("*")
+ .eq("partId", partId)
+ .eq("locationId", locationId)
+ .maybeSingle();
}
export async function getPartPurchasing(
@@ -235,8 +247,15 @@ export function getPartCostingMethods(): Database["public"]["Enums"]["partCostin
return ["Standard", "Average", "FIFO", "LIFO"];
}
-export async function getShelvesList(client: SupabaseClient<Database>) {
- return client.from("shelf").select("id").eq("active", true);
+export async function getShelvesList(
+ client: SupabaseClient<Database>,
+ locationId: string
+) {
+ return client
+ .from("shelf")
+ .select("id")
+ .eq("active", true)
+ .eq("locationId", locationId);
}
export async function getUnitOfMeasure(
@@ -273,13 +292,19 @@ export async function getUnitOfMeasuresList(client: SupabaseClient<Database>) {
export async function insertShelf(
client: SupabaseClient<Database>,
shelfId: string,
+ locationId: string,
userId: string
) {
- const shelfLookup = await client.from("shelf").select("id").eq("id", shelfId);
+ const shelfLookup = await client
+ .from("shelf")
+ .select("id")
+ .eq("id", shelfId)
+ .eq("locationId", locationId)
+ .maybeSingle();
if (shelfLookup.error) return shelfLookup;
// the shelf is inactive, so we can just reactivate it
- if (shelfLookup.data?.length) {
+ if (shelfLookup.data) {
return client.from("shelf").update({ active: true }).eq("id", shelfId);
}
@@ -289,10 +314,12 @@ export async function insertShelf(
.insert([
{
id: shelfId,
+ locationId,
createdBy: userId,
},
])
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPart(
@@ -302,7 +329,7 @@ export async function upsertPart(
| (TypeOfValidator<typeof partValidator> & { updatedBy: string })
) {
if ("createdBy" in part) {
- return client.from("part").insert(part).select("id");
+ return client.from("part").insert(part).select("id").single();
}
return client.from("part").update(sanitize(part)).eq("id", part.id);
}
@@ -319,17 +346,25 @@ export async function upsertPartCost(
export async function upsertPartInventory(
client: SupabaseClient<Database>,
- partInventory: Omit<
- TypeOfValidator<typeof partInventoryValidator>,
- "hasNewShelf"
- > & {
- updatedBy: string;
- }
+ partInventory:
+ | {
+ partId: string;
+ locationId: string;
+ createdBy: string;
+ }
+ | (Omit<TypeOfValidator<typeof partInventoryValidator>, "hasNewShelf"> & {
+ updatedBy: string;
+ })
) {
+ if ("createdBy" in partInventory) {
+ return client.from("partInventory").insert(partInventory);
+ }
+
return client
.from("partInventory")
.update(sanitize(partInventory))
- .eq("partId", partInventory.partId);
+ .eq("partId", partInventory.partId)
+ .eq("locationId", partInventory.locationId);
}
export async function upsertPartManufacturing(
@@ -346,14 +381,24 @@ export async function upsertPartManufacturing(
export async function upsertPartPlanning(
client: SupabaseClient<Database>,
- partPlanning: TypeOfValidator<typeof partPlanningValidator> & {
- updatedBy: string;
- }
+ partPlanning:
+ | {
+ partId: string;
+ locationId: string;
+ createdBy: string;
+ }
+ | (TypeOfValidator<typeof partPlanningValidator> & {
+ updatedBy: string;
+ })
) {
+ if ("createdBy" in partPlanning) {
+ return client.from("partPlanning").insert(partPlanning);
+ }
return client
.from("partPlanning")
.update(sanitize(partPlanning))
- .eq("partId", partPlanning.partId);
+ .eq("partId", partPlanning.partId)
+ .eq("locationId", partPlanning.locationId);
}
export async function upsertPartPurchasing(
@@ -390,7 +435,7 @@ export async function upsertPartGroup(
}
) {
if ("createdBy" in partGroup) {
- return client.from("partGroup").insert([partGroup]).select("id");
+ return client.from("partGroup").insert([partGroup]).select("id").single();
}
return (
client
@@ -399,6 +444,7 @@ export async function upsertPartGroup(
// @ts-ignore
.eq("id", partGroup.id)
.select("id")
+ .single()
);
}
@@ -414,13 +460,18 @@ export async function upsertPartSupplier(
})
) {
if ("createdBy" in partSupplier) {
- return client.from("partSupplier").insert([partSupplier]).select("id");
+ return client
+ .from("partSupplier")
+ .insert([partSupplier])
+ .select("id")
+ .single();
}
return client
.from("partSupplier")
.update(sanitize(partSupplier))
.eq("id", partSupplier.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPartUnitSalePrice(
@@ -446,8 +497,13 @@ export async function upsertUnitOfMeasure(
.from("unitOfMeasure")
.update(sanitize(unitOfMeasure))
.eq("id", unitOfMeasure.id)
- .select("id");
+ .select("id")
+ .single();
}
- return client.from("unitOfMeasure").insert([unitOfMeasure]).select("id");
+ return client
+ .from("unitOfMeasure")
+ .insert([unitOfMeasure])
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
index 114241255a..0a1dece707 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
@@ -11,37 +11,31 @@ import {
import { useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import {
- Boolean,
DatePicker,
Hidden,
Input,
Select,
+ SelectControlled,
Submit,
Supplier,
SupplierContact,
TextArea,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type {
- PurchaseOrderApprovalStatus,
- PurchaseOrderType,
+import {
+ purchaseOrderStatusType,
+ purchaseOrderTypeType,
+ purchaseOrderValidator,
} from "~/modules/purchasing";
-import { purchaseOrderValidator } from "~/modules/purchasing";
import type { TypeOfValidator } from "~/types/validators";
type PurchaseOrderFormValues = TypeOfValidator<typeof purchaseOrderValidator>;
type PurchaseOrderFormProps = {
initialValues: PurchaseOrderFormValues;
- purchaseOrderApprovalStatuses: PurchaseOrderApprovalStatus[];
- purchaseOrderTypes: PurchaseOrderType[];
};
-const PurchaseOrderForm = ({
- initialValues,
- purchaseOrderApprovalStatuses,
- purchaseOrderTypes,
-}: PurchaseOrderFormProps) => {
+const PurchaseOrderForm = ({ initialValues }: PurchaseOrderFormProps) => {
const permissions = usePermissions();
const [supplier, setSupplier] = useState<string | undefined>(
initialValues.supplierId
@@ -49,12 +43,12 @@ const PurchaseOrderForm = ({
const isEditing = initialValues.id !== undefined;
const isSupplier = permissions.is("supplier");
- const approvalOptions = purchaseOrderApprovalStatuses.map((approval) => ({
- label: approval,
- value: approval,
+ const statusOptions = purchaseOrderStatusType.map((status) => ({
+ label: status,
+ value: status,
}));
- const typeOptions = purchaseOrderTypes.map((type) => ({
+ const typeOptions = purchaseOrderTypeType.map((type) => ({
label: type,
value: type,
}));
@@ -110,23 +104,25 @@ const PurchaseOrderForm = ({
label="Order Date"
isDisabled={isSupplier}
/>
- <Select name="type" label="Type" options={typeOptions} />
<Select
- name="status"
- label="Approval Status"
+ name="type"
+ label="Type"
+ options={typeOptions}
isReadOnly={isSupplier}
- options={approvalOptions}
/>
+ {isEditing && (
+ <SelectControlled
+ name="status"
+ label="Status"
+ value={initialValues.status}
+ options={statusOptions}
+ isReadOnly={isSupplier}
+ />
+ )}
</VStack>
<VStack alignItems="start" spacing={2} w="full">
{isEditing && (
<>
- <Boolean
- name="closed"
- label="Closed"
- isReadOnly={isSupplier}
- isDisabled={isSupplier}
- />
<TextArea
name="notes"
label="Notes"
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
index 02f03fa3dd..32a12f05eb 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
@@ -1,3 +1,4 @@
+import { Menubar, MenubarItem } from "@carbon/react";
import {
Button,
Card,
@@ -7,87 +8,110 @@ import {
HStack,
Stack,
Text,
+ VStack,
} from "@chakra-ui/react";
import { useParams } from "@remix-run/react";
import { FaHistory } from "react-icons/fa";
-import { useRouteData } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
import type { PurchaseOrder } from "~/modules/purchasing";
+import { usePurchaseOrder } from "../../PurchaseOrders/usePurchaseOrder";
const PartPreview = () => {
+ const permissions = usePermissions();
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
const routeData = useRouteData<{ purchaseOrder: PurchaseOrder }>(
`/x/purchase-order/${orderId}`
);
+ const { receive, release } = usePurchaseOrder();
+
return (
- <Card w="full">
- <CardHeader>
- <HStack justifyContent="space-between" alignItems="start">
- <Stack direction="column" spacing={2}>
- <Heading size="md">
- {routeData?.purchaseOrder?.purchaseOrderId}
- </Heading>
- <Text color="gray.500">
- {routeData?.purchaseOrder?.supplierName}
- </Text>
- </Stack>
- <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
- Supplier Details
- </Button>
- </HStack>
- </CardHeader>
- <CardBody>
- <Stack direction={["column", "column", "row"]} spacing={8}>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
- >
- <Text color="gray.500">Order Date</Text>
- <Text fontWeight="bold">{routeData?.purchaseOrder?.orderDate}</Text>
- </Stack>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
+ <VStack w="full" alignItems="start" spacing={2}>
+ {permissions.is("employee") && (
+ <Menubar>
+ <MenubarItem
+ onClick={() => {
+ if (routeData?.purchaseOrder) release(routeData.purchaseOrder);
+ }}
+ isDisabled={
+ !["Open", "Approved"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ )
+ }
>
- <Text color="gray.500">Delivery Location</Text>
- <Text fontWeight="bold">
- {routeData?.purchaseOrder?.dropShipment
- ? "Drop Ship"
- : routeData?.purchaseOrder?.locationName}
- </Text>
- </Stack>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
+ Release
+ </MenubarItem>
+ <MenubarItem
+ onClick={() => {
+ if (routeData?.purchaseOrder) receive(routeData.purchaseOrder);
+ }}
+ isDisabled={routeData?.purchaseOrder?.status !== "Released"}
>
- <Text color="gray.500">Promised Date</Text>
- <Text fontWeight="bold">
- {routeData?.purchaseOrder?.receiptPromisedDate}
- </Text>
- </Stack>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
- >
- <Text color="gray.500">Order Type</Text>
- <Text fontWeight="bold">{routeData?.purchaseOrder?.type}</Text>
- </Stack>
- <Stack
- direction={["row", "row", "column"]}
- alignItems="start"
- justifyContent="space-between"
- >
- <Text color="gray.500">Order Status</Text>
- <Text fontWeight="bold">{routeData?.purchaseOrder?.status}</Text>
+ Receive
+ </MenubarItem>
+ </Menubar>
+ )}
+
+ <Card w="full">
+ <CardHeader>
+ <HStack justifyContent="space-between" alignItems="start">
+ <Stack direction="column" spacing={2}>
+ <Heading size="md">
+ {routeData?.purchaseOrder?.purchaseOrderId}
+ </Heading>
+ <Text color="gray.500">
+ {routeData?.purchaseOrder?.supplierName}
+ </Text>
+ </Stack>
+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
+ Supplier Details
+ </Button>
+ </HStack>
+ </CardHeader>
+ <CardBody>
+ <Stack direction={["column", "column", "row"]} spacing={8}>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Order Date</Text>
+ <Text fontWeight="bold">
+ {routeData?.purchaseOrder?.orderDate}
+ </Text>
+ </Stack>
+
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Promised Date</Text>
+ <Text fontWeight="bold">
+ {routeData?.purchaseOrder?.receiptPromisedDate}
+ </Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Type</Text>
+ <Text fontWeight="bold">{routeData?.purchaseOrder?.type}</Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Status</Text>
+ <Text fontWeight="bold">{routeData?.purchaseOrder?.status}</Text>
+ </Stack>
</Stack>
- </Stack>
- </CardBody>
- </Card>
+ </CardBody>
+ </Card>
+ </VStack>
);
};
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
index a6e6065b4c..6d4d18617e 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
@@ -18,8 +18,8 @@ import {
NumberInputStepper,
VStack,
} from "@chakra-ui/react";
-import { useNavigate, useParams } from "@remix-run/react";
-import { useState } from "react";
+import { useFetcher, useNavigate, useParams } from "@remix-run/react";
+import { useEffect, useMemo, useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import {
Account,
@@ -27,47 +27,93 @@ import {
Number,
Part,
Select,
+ SelectControlled,
Submit,
} from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
-import type { PurchaseOrderLineType } from "~/modules/purchasing";
-import { purchaseOrderLineValidator } from "~/modules/purchasing";
+import type { getShelvesList } from "~/modules/parts";
+import type {
+ PurchaseOrder,
+ PurchaseOrderLineType,
+} from "~/modules/purchasing";
+import {
+ purchaseOrderLineType,
+ purchaseOrderLineValidator,
+} from "~/modules/purchasing";
+import type { ListItem } from "~/types";
import type { TypeOfValidator } from "~/types/validators";
type PurchaseOrderLineFormProps = {
initialValues: TypeOfValidator<typeof purchaseOrderLineValidator>;
- purchaseOrderLineTypes: PurchaseOrderLineType[];
};
const PurchaseOrderLineForm = ({
initialValues,
- purchaseOrderLineTypes,
}: PurchaseOrderLineFormProps) => {
const permissions = usePermissions();
const { supabase } = useSupabase();
const navigate = useNavigate();
+ const { defaults } = useUser();
const { orderId } = useParams();
+ const routeData = useRouteData<{
+ locations: ListItem[];
+ purchaseOrder: PurchaseOrder;
+ }>(`/x/purchase-order/${orderId}`);
+
+ const locations = routeData?.locations ?? [];
+ const locationOptions = locations.map((location) => ({
+ label: location.name,
+ value: location.id,
+ }));
+
+ const isEditable = ["Open", "In Review", "In External Review"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ );
+
const [type, setType] = useState(initialValues.purchaseOrderLineType);
+ const [locationId, setLocationId] = useState(defaults.locationId ?? "");
const [partData, setPartData] = useState<{
+ partId: string;
description: string;
unitPrice: string;
uom: string;
shelfId: string;
}>({
+ partId: initialValues.partId ?? "",
description: initialValues.description ?? "",
unitPrice: initialValues.unitPrice?.toString() ?? "0",
uom: initialValues.unitOfMeasureCode ?? "",
shelfId: initialValues.shelfId ?? "",
});
+ const shelfFetcher = useFetcher<Awaited<ReturnType<typeof getShelvesList>>>();
+
+ useEffect(() => {
+ if (locationId) {
+ shelfFetcher.load(`/api/parts/shelf?locationId=${locationId}`);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [locationId]);
+
+ const shelfOptions = useMemo(
+ () =>
+ shelfFetcher.data?.data?.map((shelf) => ({
+ label: shelf.id,
+ value: shelf.id,
+ })) ?? [],
+ [shelfFetcher.data]
+ );
+
const isEditing = initialValues.id !== undefined;
- const isDisabled = isEditing
+ const isDisabled = !isEditable
+ ? true
+ : isEditing
? !permissions.can("update", "purchasing")
: !permissions.can("create", "purchasing");
- const purchaseOrderLineTypeOptions = purchaseOrderLineTypes.map((type) => ({
+ const purchaseOrderLineTypeOptions = purchaseOrderLineType.map((type) => ({
label: type,
value: type,
}));
@@ -77,6 +123,7 @@ const PurchaseOrderLineForm = ({
const onTypeChange = (type: PurchaseOrderLineType) => {
setType(type);
setPartData({
+ partId: "",
description: "",
unitPrice: "0",
uom: "EA",
@@ -94,9 +141,10 @@ const PurchaseOrderLineForm = ({
.single(),
supabase
.from("partInventory")
- .select("shelfId")
+ .select("defaultShelfId")
.eq("partId", partId)
- .single(),
+ .eq("locationId", locationId)
+ .maybeSingle(),
supabase
.from("partCost")
.select("unitCost")
@@ -105,13 +153,36 @@ const PurchaseOrderLineForm = ({
]);
setPartData({
+ partId,
description: part.data?.name ?? "",
unitPrice: cost.data?.unitCost?.toString() ?? "0",
uom: part.data?.unitOfMeasureCode ?? "EA",
- shelfId: shelf.data?.shelfId ?? "",
+ shelfId: shelf.data?.defaultShelfId ?? "",
});
};
+ const onLocationChange = async (
+ newLocationId: string | number | undefined
+ ) => {
+ if (!supabase) throw new Error("supabase is not defined");
+ if (typeof newLocationId !== "string")
+ throw new Error("locationId is not a string");
+
+ setLocationId(newLocationId);
+ if (!partData.partId) return;
+ const shelf = await supabase
+ .from("partInventory")
+ .select("defaultShelfId")
+ .eq("partId", partData.partId)
+ .eq("locationId", newLocationId)
+ .maybeSingle();
+
+ setPartData((d) => ({
+ ...d,
+ shelfId: shelf?.data?.defaultShelfId ?? "",
+ }));
+ };
+
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
<ValidatedForm
@@ -160,6 +231,7 @@ const PurchaseOrderLineForm = ({
label="Account"
onChange={({ label }) => {
setPartData({
+ partId: "",
description: label,
unitPrice: "0",
uom: "EA",
@@ -204,15 +276,28 @@ const PurchaseOrderLineForm = ({
</NumberInputStepper>
</NumberInput>
</FormControl>
- {/*
- // TODO:
- <Shelf name="shelfId" label="Shelf" value={shelf}/> */}
+ <SelectControlled
+ name="locationId"
+ label="Location"
+ options={locationOptions}
+ value={locationId}
+ onChange={onLocationChange}
+ />
+ <SelectControlled
+ name="shelfId"
+ label="Shelf"
+ options={shelfOptions}
+ value={partData.shelfId}
+ onChange={(newValue) =>
+ setPartData((d) => ({ ...d, shelfId: newValue as string }))
+ }
+ />
</VStack>
</DrawerBody>
<DrawerFooter>
<HStack>
<Submit isDisabled={isDisabled}>Save</Submit>
- <Button variant="ghost" onClick={onClose}>
+ <Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
</HStack>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index 96d440cfb7..5a9eb235f3 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -1,25 +1,33 @@
import {
- Button,
Box,
+ Button,
Card,
CardBody,
CardHeader,
Heading,
HStack,
IconButton,
+ Menu,
+ MenuButton,
+ MenuItem,
+ MenuList,
} from "@chakra-ui/react";
-import { Link, Outlet, useNavigate } from "@remix-run/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { useMemo } from "react";
-import Grid from "~/components/Grid";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { MdMoreHoriz } from "react-icons/md";
import {
- EditablePurchaseOrderLineNumber,
EditableNumber,
+ EditablePurchaseOrderLineNumber,
EditableText,
} from "~/components/Editable";
-import type { PurchaseOrderLine } from "~/modules/purchasing";
+import Grid from "~/components/Grid";
+import { useRouteData, useUser } from "~/hooks";
+import type { PurchaseOrder, PurchaseOrderLine } from "~/modules/purchasing";
+import type { ListItem } from "~/types";
import usePurchaseOrderLines from "./usePurchaseOrderLines";
-import { MdMoreHoriz } from "react-icons/md";
type PurchaseOrderLinesProps = {
purchaseOrderLines: PurchaseOrderLine[];
@@ -28,9 +36,28 @@ type PurchaseOrderLinesProps = {
const PurchaseOrderLines = ({
purchaseOrderLines,
}: PurchaseOrderLinesProps) => {
+ const { orderId } = useParams();
+ if (!orderId) throw new Error("orderId not found");
+
const navigate = useNavigate();
- const { canEdit, supabase, partOptions, accountOptions, handleCellEdit } =
- usePurchaseOrderLines();
+ const routeData = useRouteData<{
+ locations: ListItem[];
+ purchaseOrder: PurchaseOrder;
+ }>(`/x/purchase-order/${orderId}`);
+ const locations = routeData?.locations ?? [];
+ const { defaults } = useUser();
+ const {
+ canEdit,
+ canDelete,
+ supabase,
+ partOptions,
+ accountOptions,
+ handleCellEdit,
+ } = usePurchaseOrderLines();
+
+ const isEditable = ["Open", "In Review", "In External Review"].includes(
+ routeData?.purchaseOrder?.status ?? ""
+ );
const columns = useMemo<ColumnDef<PurchaseOrderLine>[]>(() => {
return [
@@ -42,21 +69,38 @@ const PurchaseOrderLines = ({
accessorKey: "purchaseOrderLineType",
header: "Type",
cell: ({ row }) => (
- <HStack justify="space-between">
+ <HStack justify="space-between" minW={100}>
<span>{row.original.purchaseOrderLineType}</span>
<Box position="relative" w={6} h={5}>
- <IconButton
- aria-label="Edit purchase order line type"
- as={Link}
- icon={<MdMoreHoriz />}
- size="sm"
- position="absolute"
- right={-1}
- top={-1}
- to={`${row.original.id}`}
- onClick={(e) => e.stopPropagation()}
- variant="ghost"
- />
+ <Menu>
+ <MenuButton
+ as={IconButton}
+ aria-label="Edit purchase order line type"
+ icon={<MdMoreHoriz />}
+ size="sm"
+ position="absolute"
+ right={-1}
+ top="-6px"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ <MenuList>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ onClick={() => navigate(row.original.id)}
+ isDisabled={!isEditable || !canEdit}
+ >
+ Edit Line
+ </MenuItem>
+ <MenuItem
+ icon={<IoMdTrash />}
+ onClick={() => navigate(`delete/${row.original.id}`)}
+ isDisabled={!isEditable || !canDelete}
+ >
+ Delete Line
+ </MenuItem>
+ </MenuList>
+ </Menu>
</Box>
</HStack>
),
@@ -114,6 +158,20 @@ const PurchaseOrderLines = ({
}
},
},
+ {
+ accessorKey: "locationId",
+ header: "Location",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Part":
+ return (
+ <span>
+ {locations.find((l) => l.id == row.original.locationId)?.name}
+ </span>
+ );
+ }
+ },
+ },
{
accessorKey: "shelfId",
header: "Shelf",
@@ -143,7 +201,8 @@ const PurchaseOrderLines = ({
},
},
];
- }, []);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [navigate]);
const editableComponents = useMemo(
() => ({
@@ -154,9 +213,10 @@ const PurchaseOrderLines = ({
client: supabase,
parts: partOptions,
accounts: accountOptions,
+ defaultLocationId: defaults.locationId,
}),
}),
- [handleCellEdit, supabase, partOptions, accountOptions]
+ [handleCellEdit, supabase, partOptions, accountOptions, defaults.locationId]
);
return (
@@ -166,7 +226,7 @@ const PurchaseOrderLines = ({
<Heading size="md" display="inline-flex">
Purchase Order Lines
</Heading>
- {canEdit && (
+ {canEdit && isEditable && (
<Button colorScheme="brand" as={Link} to="new">
New
</Button>
@@ -176,9 +236,9 @@ const PurchaseOrderLines = ({
<Grid<PurchaseOrderLine>
data={purchaseOrderLines}
columns={columns}
- canEdit={canEdit}
+ canEdit={canEdit && isEditable}
editableComponents={editableComponents}
- onNewRow={canEdit ? () => navigate("new") : undefined}
+ onNewRow={canEdit && isEditable ? () => navigate("new") : undefined}
/>
</CardBody>
</Card>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
index aa929c5f52..cc811d8c5f 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
@@ -1,8 +1,16 @@
-import { HStack, Icon, MenuItem, Text, useDisclosure } from "@chakra-ui/react";
+import {
+ HStack,
+ Icon,
+ Link,
+ MenuItem,
+ Text,
+ useDisclosure,
+} from "@chakra-ui/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { BsPencilSquare, BsStar, BsStarFill } from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
+import { MdCallReceived } from "react-icons/md";
import { Avatar, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
@@ -26,7 +34,7 @@ const PurchaseOrdersTable = memo(
setRows(data);
}, [data]);
- const { edit, favorite } = usePurchaseOrder();
+ const { edit, favorite, receive } = usePurchaseOrder();
const [selectedPurchaseOrder, setSelectedPurchaseOrder] =
useState<PurchaseOrder | null>(null);
@@ -65,7 +73,10 @@ const PurchaseOrdersTable = memo(
as={row.original.favorite ? BsStarFill : BsStar}
onClick={() => onFavorite(row.original)}
/>
- <span>{row.original.purchaseOrderId}</span>
+
+ <Link onClick={() => edit(row.original)}>
+ {row.original.purchaseOrderId}
+ </Link>
</HStack>
),
},
@@ -119,7 +130,7 @@ const PurchaseOrdersTable = memo(
cell: (item) => item.getValue(),
},
];
- }, [onFavorite]);
+ }, [edit, onFavorite]);
const actions = useMemo(() => {
return [
@@ -147,7 +158,7 @@ const PurchaseOrdersTable = memo(
isDisabled={!permissions.can("view", "purchasing")}
onClick={() => edit(row)}
>
- View
+ Edit
</MenuItem>
<MenuItem
icon={<BsStar />}
@@ -157,6 +168,17 @@ const PurchaseOrdersTable = memo(
>
Favorite
</MenuItem>
+ <MenuItem
+ icon={<MdCallReceived />}
+ isDisabled={
+ !row.released || !permissions.can("update", "inventory")
+ }
+ onClick={() => {
+ receive(row);
+ }}
+ >
+ Receive
+ </MenuItem>
<MenuItem
icon={<IoMdTrash />}
isDisabled={!permissions.can("delete", "purchasing")}
@@ -169,7 +191,7 @@ const PurchaseOrdersTable = memo(
</MenuItem>
</>
);
- }, [closePurchaseOrderModal, edit, onFavorite, permissions]);
+ }, [closePurchaseOrderModal, edit, onFavorite, permissions, receive]);
return (
<>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
index 6a6b94bffc..88569d2612 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
@@ -4,18 +4,7 @@ import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
-
-const purchaseOrderStatusOptions = [
- "Draft",
- "In Review",
- "In External Review",
- "Approved",
- "Rejected",
- "Confirmed",
-].map((type) => ({
- label: type,
- value: type,
-}));
+import { purchaseOrderStatusType } from "~/modules/purchasing";
type PurchaseOrdersTableFiltersProps = {
suppliers: { id: string | null; name: string | null }[];
@@ -36,6 +25,11 @@ const PurchaseOrdersTableFilters = ({
value: supplier.id,
}));
+ const purchaseOrderStatusOptions = purchaseOrderStatusType.map((status) => ({
+ label: status,
+ value: status,
+ }));
+
return (
<HStack
px={4}
@@ -56,7 +50,7 @@ const PurchaseOrdersTableFilters = ({
<Select
// @ts-ignore
size="sm"
- value={purchaseOrderStatusOptions.filter(
+ value={purchaseOrderStatusOptions.find(
(type) => type.value === params.get("status")
)}
isClearable
@@ -71,7 +65,7 @@ const PurchaseOrdersTableFilters = ({
<Select
// @ts-ignore
size="sm"
- value={supplierOptions.filter(
+ value={supplierOptions.find(
(supplier) => supplier.value === params.get("supplierId")
)}
isClearable
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts
index c7f5ae5dc1..eecdcaf696 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/usePurchaseOrder.ts
@@ -1,4 +1,4 @@
-import { useNavigate } from "@remix-run/react";
+import { useNavigate, useSubmit } from "@remix-run/react";
import { useCallback } from "react";
import { useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
@@ -8,6 +8,7 @@ import type {
} from "~/modules/purchasing";
export const usePurchaseOrder = () => {
+ const submit = useSubmit();
const navigate = useNavigate();
const { supabase } = useSupabase();
const user = useUser();
@@ -51,8 +52,38 @@ export const usePurchaseOrder = () => {
[insertTransaction, supabase, user?.id]
);
+ const receive = useCallback(
+ (purchaseOrder: PurchaseOrder) =>
+ navigate(
+ `/x/inventory/receipts/new?sourceDocument=Purchase Order&sourceDocumentId=${purchaseOrder.id}`
+ ),
+ [navigate]
+ );
+
+ const release = useCallback(
+ async (purchaseOrder: PurchaseOrder) => {
+ if (!supabase) throw new Error("Supabase is undefined");
+
+ const { error } = await supabase
+ .from("purchaseOrder")
+ .update({
+ status: "Released",
+ })
+ .eq("id", purchaseOrder.id);
+
+ if (!error) {
+ submit(`/x/purchase-order/${purchaseOrder.id}`, {
+ method: "post",
+ });
+ }
+ },
+ [submit, supabase]
+ );
+
return {
edit,
favorite,
+ receive,
+ release,
};
};
diff --git a/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx
index 4ace8b0d0a..15bad5eae4 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTable/SupplierTypesTable.tsx
@@ -1,4 +1,4 @@
-import { Box, MenuItem } from "@chakra-ui/react";
+import { Box, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -18,12 +18,16 @@ const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Supplier Type",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id as string)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "color",
@@ -40,10 +44,10 @@ const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -89,7 +93,7 @@ const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx b/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx
index e1c5e8108c..6764dd83d7 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/SupplierTypes/SupplierTypesTableFilters/SupplierTypesTableFilters.tsx
@@ -24,7 +24,7 @@ const SupplierTypesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
index b8c2d2b97d..9341c399d5 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
@@ -1,4 +1,10 @@
-import { Button, ButtonGroup, IconButton, MenuItem } from "@chakra-ui/react";
+import {
+ Button,
+ ButtonGroup,
+ IconButton,
+ Link,
+ MenuItem,
+} from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
@@ -21,7 +27,11 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id as string)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "type",
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
index 52c936183b..50ab01ccba 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
@@ -47,13 +47,13 @@ const SuppliersTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
{supplierTypeOptions.length > 0 && (
<Select
// @ts-ignore
size="sm"
- value={supplierTypeOptions.filter(
+ value={supplierTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
@@ -71,7 +71,7 @@ const SuppliersTableFilters = ({
// @ts-ignore
size="sm"
isClearable
- value={supplierStatusOptions.filter(
+ value={supplierStatusOptions.find(
(type) => type.value === params.get("status")
)}
options={supplierStatusOptions}
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
index d4b85cde3c..c37677ae74 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
@@ -3,36 +3,40 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
+export const purchaseOrderLineType = [
+ "Part",
+ "G/L Account",
+ "Fixed Asset",
+ "Comment",
+] as const;
+
+export const purchaseOrderTypeType = ["Draft", "Purchase", "Return"] as const;
+
+export const purchaseOrderStatusType = [
+ "Open",
+ "In Review",
+ "In External Review",
+ "Approved",
+ "Rejected",
+ "Released",
+ "Closed",
+] as const;
+
export const purchaseOrderValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
purchaseOrderId: zfd.text(z.string().optional()),
orderDate: z.string().min(1, { message: "Order Date is required" }),
- type: z.enum(["Draft", "Purchase", "Return"], {
+ type: z.enum(purchaseOrderTypeType, {
errorMap: (issue, ctx) => ({
message: "Type is required",
}),
}),
- status: z.enum(
- [
- "Draft",
- "In Review",
- "In External Review",
- "Approved",
- "Rejected",
- "Confirmed",
- ],
- {
- errorMap: (issue, ctx) => ({
- message: "Status is required",
- }),
- }
- ),
+ status: z.enum(purchaseOrderStatusType).optional(),
notes: zfd.text(z.string().optional()),
supplierId: z.string().min(36, { message: "Supplier is required" }),
supplierContactId: zfd.text(z.string().optional()),
supplierReference: zfd.text(z.string().optional()),
- closed: zfd.checkbox(),
})
);
@@ -83,14 +87,11 @@ export const purchaseOrderLineValidator = withZod(
.object({
id: zfd.text(z.string().optional()),
purchaseOrderId: z.string().min(20, { message: "Order is required" }),
- purchaseOrderLineType: z.enum(
- ["Comment", "Part", "G/L Account", "Fixed Asset"],
- {
- errorMap: (issue, ctx) => ({
- message: "Type is required",
- }),
- }
- ),
+ purchaseOrderLineType: z.enum(purchaseOrderLineType, {
+ errorMap: (issue, ctx) => ({
+ message: "Type is required",
+ }),
+ }),
partId: zfd.text(z.string().optional()),
accountNumber: zfd.text(z.string().optional()),
assetId: zfd.text(z.string().optional()),
@@ -99,6 +100,7 @@ export const purchaseOrderLineValidator = withZod(
unitOfMeasureCode: zfd.text(z.string().optional()),
unitPrice: zfd.numeric(z.number().optional()),
setupPrice: zfd.numeric(z.number().optional()),
+ locationId: zfd.text(z.string().optional()),
shelfId: zfd.text(z.string().optional()),
})
.refine(
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index 90c4e91b80..d95e648f67 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -3,9 +3,9 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRole } from "~/lib/supabase";
import { getEmployeeJob } from "~/modules/resources";
import type { TypeOfValidator } from "~/types/validators";
-import { sanitize } from "~/utils/supabase";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
import type {
purchaseOrderDeliveryValidator,
purchaseOrderLineValidator,
@@ -27,7 +27,8 @@ export async function closePurchaseOrder(
closedBy: userId,
})
.eq("id", purchaseOrderId)
- .select("id");
+ .select("id")
+ .single();
}
export async function deletePurchaseOrder(
@@ -41,6 +42,16 @@ export async function deletePurchaseOrder(
]);
}
+export async function deletePurchaseOrderLine(
+ client: SupabaseClient<Database>,
+ purchaseOrderLineId: string
+) {
+ return client
+ .from("purchaseOrderLine")
+ .delete()
+ .eq("id", purchaseOrderLineId);
+}
+
export async function deleteSupplierContact(
client: SupabaseClient<Database>,
supplierId: string,
@@ -125,7 +136,7 @@ export async function getPurchaseOrders(
query = query.eq("supplierId", args.supplierId);
}
- query = setGenericQueryFilters(query, args, "purchaseOrderId");
+ query = setGenericQueryFilters(query, args, "purchaseOrderId", false);
return query;
}
@@ -151,17 +162,6 @@ export async function getPurchaseOrderPayment(
.single();
}
-export function getPurchaseOrderApprovalStatuses(): Database["public"]["Enums"]["purchaseOrderApprovalStatus"][] {
- return [
- "Draft",
- "In Review",
- "In External Review",
- "Approved",
- "Rejected",
- "Confirmed",
- ];
-}
-
export async function getPurchaseOrderLines(
client: SupabaseClient<Database>,
purchaseOrderId: string
@@ -183,20 +183,12 @@ export async function getPurchaseOrderLine(
.single();
}
-export function getPurchaseOrderLineTypes(): Database["public"]["Enums"]["purchaseOrderLineType"][] {
- return ["Part", "G/L Account", "Fixed Asset", "Comment"];
-}
-
export async function getPurchaseOrderSuppliers(
client: SupabaseClient<Database>
) {
return client.from("purchase_order_suppliers_view").select("id, name");
}
-export function getPurchaseOrderTypes(): Database["public"]["Enums"]["purchaseOrderType"][] {
- return ["Draft", "Purchase", "Return"];
-}
-
export async function getSupplier(
client: SupabaseClient<Database>,
supplierId: string
@@ -324,9 +316,16 @@ export async function getSupplierTypes(
export async function insertSupplier(
client: SupabaseClient<Database>,
- supplier: TypeOfValidator<typeof supplierValidator> & {}
+ supplier:
+ | (Omit<TypeOfValidator<typeof supplierValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof supplierValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
) {
- return client.from("supplier").insert([supplier]).select("id");
+ return client.from("supplier").insert([supplier]).select("id").single();
}
export async function insertSupplierContact(
@@ -357,12 +356,13 @@ export async function insertSupplierContact(
const insertContact = await getSupabaseServiceRole()
.from("contact")
.insert([supplierContact.contact])
- .select("id");
+ .select("id")
+ .single();
if (insertContact.error) {
return insertContact;
}
- const contactId = insertContact.data[0].id;
+ const contactId = insertContact.data?.id;
if (!contactId) {
return { data: null, error: new Error("Contact ID not found") };
}
@@ -375,7 +375,8 @@ export async function insertSupplierContact(
contactId,
},
])
- .select("id");
+ .select("id")
+ .single();
}
export async function insertSupplierLocation(
@@ -395,12 +396,13 @@ export async function insertSupplierLocation(
const insertAddress = await client
.from("address")
.insert([supplierLocation.address])
- .select("id");
+ .select("id")
+ .single();
if (insertAddress.error) {
return insertAddress;
}
- const addressId = insertAddress.data[0].id;
+ const addressId = insertAddress.data?.id;
if (!addressId) {
return { data: null, error: new Error("Address ID not found") };
}
@@ -413,7 +415,8 @@ export async function insertSupplierLocation(
addressId,
},
])
- .select("id");
+ .select("id")
+ .single();
}
export async function updateSupplier(
@@ -427,7 +430,8 @@ export async function updateSupplier(
.from("supplier")
.update(sanitize(supplier))
.eq("id", supplier.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function updateSupplierContact(
@@ -458,7 +462,8 @@ export async function updateSupplierContact(
.from("contact")
.update(sanitize(supplierContact.contact))
.eq("id", supplierContact.contactId)
- .select("id");
+ .select("id")
+ .single();
}
export async function updateSupplierLocation(
@@ -479,7 +484,8 @@ export async function updateSupplierLocation(
.from("address")
.update(sanitize(supplierLocation.address))
.eq("id", supplierLocation.addressId)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPurchaseOrder(
@@ -581,12 +587,14 @@ export async function upsertPurchaseOrderDelivery(
.from("purchaseOrderDelivery")
.update(sanitize(purchaseOrderDelivery))
.eq("id", purchaseOrderDelivery.id)
- .select("id");
+ .select("id")
+ .single();
}
return client
.from("purchaseOrderDelivery")
.insert([purchaseOrderDelivery])
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPurchaseOrderLine(
@@ -605,12 +613,14 @@ export async function upsertPurchaseOrderLine(
.from("purchaseOrderLine")
.update(sanitize(purchaseOrderLine))
.eq("id", purchaseOrderLine.id)
- .select("id");
+ .select("id")
+ .single();
}
return client
.from("purchaseOrderLine")
.insert([purchaseOrderLine])
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertPurchaseOrderPayment(
@@ -629,17 +639,23 @@ export async function upsertPurchaseOrderPayment(
.from("purchaseOrderPayment")
.update(sanitize(purchaseOrderPayment))
.eq("id", purchaseOrderPayment.id)
- .select("id");
+ .select("id")
+ .single();
}
return client
.from("purchaseOrderPayment")
.insert([purchaseOrderPayment])
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertSupplierType(
client: SupabaseClient<Database>,
supplierType: { id?: string; name: string; color: string | null }
) {
- return client.from("supplierType").upsert([supplierType]).select("id");
+ return client
+ .from("supplierType")
+ .upsert([supplierType])
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index ba99fa0a6d..b674503b16 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -26,8 +26,8 @@ export type PurchaseOrderLine = NonNullable<
export type PurchaseOrderLineType =
Database["public"]["Enums"]["purchaseOrderLineType"];
-export type PurchaseOrderApprovalStatus =
- Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+export type PurchaseOrderStatus =
+ Database["public"]["Enums"]["purchaseOrderStatus"];
export type PurchaseOrderType =
Database["public"]["Enums"]["purchaseOrderType"];
diff --git a/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTable/AbilitiesTable.tsx b/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTable/AbilitiesTable.tsx
index ef1eae292b..dfd00bebe0 100644
--- a/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTable/AbilitiesTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTable/AbilitiesTable.tsx
@@ -1,4 +1,4 @@
-import { AvatarGroup, MenuItem } from "@chakra-ui/react";
+import { AvatarGroup, MenuItem, Link } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -55,12 +55,18 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {
: [],
}));
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Ability",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link
+ onClick={() => navigate(`/x/resources/ability/${row.original.id}`)}
+ >
+ {row.original.name}
+ </Link>
+ ),
},
{
header: "Employees",
@@ -96,10 +102,10 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof rows[number]) => {
+ (row: (typeof rows)[number]) => {
return (
<>
<MenuItem
@@ -126,7 +132,7 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={rows}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTableFilters/AbilitiesTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTableFilters/AbilitiesTableFilters.tsx
index e0d9d84e76..3cffe68de8 100644
--- a/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTableFilters/AbilitiesTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Abilities/AbilitiesTableFilters/AbilitiesTableFilters.tsx
@@ -24,7 +24,7 @@ const AbilitiesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx b/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
index d79bf8d75d..3a69ff585c 100644
--- a/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTable/AttributesCategoriesTable.tsx
@@ -3,6 +3,7 @@ import {
Button,
ButtonGroup,
IconButton,
+ Link,
MenuItem,
useDisclosure,
} from "@chakra-ui/react";
@@ -42,12 +43,16 @@ const AttributeCategoriesTable = memo(
deleteModal.onClose();
};
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Category",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
header: "Attributes",
@@ -101,7 +106,7 @@ const AttributeCategoriesTable = memo(
}, [navigate, params]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -150,7 +155,7 @@ const AttributeCategoriesTable = memo(
return (
<>
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count ?? 0}
diff --git a/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
index 517bd8b7d7..f68a000cde 100644
--- a/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Attributes/AttributeCategoriesTableFilters/AttributeCategoriesTableFilters.tsx
@@ -24,7 +24,7 @@ const AttributeCategoriesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx
index 999d9d64a9..60c932c8f3 100644
--- a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx
@@ -38,12 +38,12 @@ const ContractorsTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={abilitiesOptions.filter(
+ value={abilitiesOptions.find(
(type) => type.value === params.get("ability")
)}
isClearable
diff --git a/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTable/DepartmentsTable.tsx b/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTable/DepartmentsTable.tsx
index 73a0e5e282..93602c463b 100644
--- a/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTable/DepartmentsTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTable/DepartmentsTable.tsx
@@ -1,4 +1,4 @@
-import { Box, MenuItem } from "@chakra-ui/react";
+import { Box, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -26,12 +26,16 @@ const DepartmentsTable = memo(({ data, count }: DepartmentsTableProps) => {
: row.department?.name) ?? "",
}));
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Department",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "color",
@@ -52,10 +56,10 @@ const DepartmentsTable = memo(({ data, count }: DepartmentsTableProps) => {
cell: ({ row }) => row.original.parentDepartment,
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -86,7 +90,7 @@ const DepartmentsTable = memo(({ data, count }: DepartmentsTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={rows}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTableFilters/DepartmentsTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTableFilters/DepartmentsTableFilters.tsx
index d5896328d2..d3cc3fb051 100644
--- a/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTableFilters/DepartmentsTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Departments/DepartmentsTableFilters/DepartmentsTableFilters.tsx
@@ -25,7 +25,7 @@ const DepartmentsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTable/EquipmentTypesTable.tsx b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTable/EquipmentTypesTable.tsx
index e7a49c3bb4..ba8c325af4 100644
--- a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTable/EquipmentTypesTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTable/EquipmentTypesTable.tsx
@@ -5,6 +5,7 @@ import {
HStack,
Icon,
IconButton,
+ Link,
MenuItem,
Text,
useDisclosure,
@@ -50,14 +51,16 @@ const EquipmentTypesTable = memo(
deleteModal.onClose();
};
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Equipment Type",
cell: ({ row }) => (
<HStack>
- <span>{row.original.name}</span>
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
{row.original.requiredAbility && (
<Icon
as={BsFillCheckCircleFill}
@@ -128,7 +131,7 @@ const EquipmentTypesTable = memo(
}, [params]);
const renderContextMenu = useCallback<
- (row: typeof data[number]) => JSX.Element
+ (row: (typeof data)[number]) => JSX.Element
>(
(row) => (
<>
@@ -177,7 +180,7 @@ const EquipmentTypesTable = memo(
return (
<>
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count ?? 0}
diff --git a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTableFilters/EquipmentTypesTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTableFilters/EquipmentTypesTableFilters.tsx
index 15dd588a40..94fdb3946d 100644
--- a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTableFilters/EquipmentTypesTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypesTableFilters/EquipmentTypesTableFilters.tsx
@@ -24,7 +24,7 @@ const EquipmentTypesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTable/HolidaysTable.tsx b/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTable/HolidaysTable.tsx
index dbe53ec2de..14471570df 100644
--- a/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTable/HolidaysTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTable/HolidaysTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -20,12 +20,16 @@ const HolidaysTable = memo(({ data, count }: HolidaysTableProps) => {
const rows = data;
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Holiday",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {`${row.original.name} (${row.original.year})`}
+ </Link>
+ ),
},
{
accessorKey: "date",
@@ -33,10 +37,10 @@ const HolidaysTable = memo(({ data, count }: HolidaysTableProps) => {
cell: (item) => item.getValue(),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -65,7 +69,7 @@ const HolidaysTable = memo(({ data, count }: HolidaysTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={rows}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx
index 322ccfad39..28d9dfc723 100644
--- a/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx
@@ -34,14 +34,14 @@ const HolidaysTableFilters = ({ years }: HolidaysTableFiltersProps) => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
value={
params.get("year")
- ? yearsOptions.filter(
+ ? yearsOptions.find(
(year) => year.value.toString() === params.get("year")
)
: {
diff --git a/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx b/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx
index 67e4afb45d..bff00ecc6f 100644
--- a/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -22,12 +22,16 @@ const LocationsTable = memo(({ data, count }: LocationsTableProps) => {
...row,
}));
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Location",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "addressLine1",
@@ -51,10 +55,10 @@ const LocationsTable = memo(({ data, count }: LocationsTableProps) => {
cell: (item) => item.getValue(),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -83,7 +87,7 @@ const LocationsTable = memo(({ data, count }: LocationsTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={rows}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTableFilters/LocationsTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTableFilters/LocationsTableFilters.tsx
index 9d75eca64c..4968fea6cb 100644
--- a/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTableFilters/LocationsTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTableFilters/LocationsTableFilters.tsx
@@ -25,7 +25,7 @@ const LocationsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
index 00c5638261..34f84c089b 100644
--- a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
@@ -36,12 +36,12 @@ const PartnersTableFilters = ({ abilities }: PartnersTableFiltersProps) => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={abilitiesOptions.filter(
+ value={abilitiesOptions.find(
(type) => type.value === params.get("ability")
)}
isClearable
diff --git a/apps/carbon/app/modules/resources/interfaces/People/PeopleTableFilters/PeopleTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/People/PeopleTableFilters/PeopleTableFilters.tsx
index 90612c592f..e841aaad27 100644
--- a/apps/carbon/app/modules/resources/interfaces/People/PeopleTableFilters/PeopleTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/People/PeopleTableFilters/PeopleTableFilters.tsx
@@ -37,12 +37,12 @@ const PeopleTableFilters = ({ employeeTypes }: PeopleTableFiltersProps) => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={employeeTypeOptions.filter(
+ value={employeeTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
diff --git a/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTable/ShiftsTable.tsx b/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTable/ShiftsTable.tsx
index 72f700dea2..7691c3c695 100644
--- a/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTable/ShiftsTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTable/ShiftsTable.tsx
@@ -1,4 +1,4 @@
-import { AvatarGroup, Badge, MenuItem } from "@chakra-ui/react";
+import { AvatarGroup, Badge, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -67,7 +67,7 @@ const ShiftsTable = memo(({ data, count }: ShiftsTableProps) => {
: [],
}));
- const renderDays = useCallback((row: typeof rows[number]) => {
+ const renderDays = useCallback((row: (typeof rows)[number]) => {
const days = [
row.monday && "M",
row.tuesday && "Tu",
@@ -85,12 +85,16 @@ const ShiftsTable = memo(({ data, count }: ShiftsTableProps) => {
));
}, []);
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Shift",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
header: "Employees",
@@ -128,10 +132,10 @@ const ShiftsTable = memo(({ data, count }: ShiftsTableProps) => {
cell: ({ row }) => renderDays(row.original),
},
];
- }, [renderDays]);
+ }, [navigate, renderDays]);
const renderContextMenu = useCallback(
- (row: typeof rows[number]) => {
+ (row: (typeof rows)[number]) => {
return (
<>
<MenuItem
@@ -160,7 +164,7 @@ const ShiftsTable = memo(({ data, count }: ShiftsTableProps) => {
);
return (
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
data={rows}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTableFilters/ShiftsTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTableFilters/ShiftsTableFilters.tsx
index 7197dff398..65b2e028f6 100644
--- a/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTableFilters/ShiftsTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Shifts/ShiftsTableFilters/ShiftsTableFilters.tsx
@@ -35,12 +35,12 @@ const ShiftsTableFilters = ({ locations }: ShiftsTableFiltersProps) => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={locationOptions.filter(
+ value={locationOptions.find(
(type) => type.value === params.get("location")
)}
isClearable
diff --git a/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx b/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
index 0113e44052..7b005eb9c5 100644
--- a/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
@@ -5,6 +5,7 @@ import {
HStack,
Icon,
IconButton,
+ Link,
MenuItem,
Text,
useDisclosure,
@@ -47,14 +48,16 @@ const WorkCellTypesTable = memo(({ data, count }: WorkCellTypesTableProps) => {
deleteModal.onClose();
};
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Work Cell Type",
cell: ({ row }) => (
<HStack>
- <span>{row.original.name}</span>
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
{row.original.requiredAbility && (
<Icon
as={BsFillCheckCircleFill}
@@ -125,7 +128,7 @@ const WorkCellTypesTable = memo(({ data, count }: WorkCellTypesTableProps) => {
}, [params]);
const renderContextMenu = useCallback<
- (row: typeof data[number]) => JSX.Element
+ (row: (typeof data)[number]) => JSX.Element
>(
(row) => (
<>
@@ -172,7 +175,7 @@ const WorkCellTypesTable = memo(({ data, count }: WorkCellTypesTableProps) => {
return (
<>
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count ?? 0}
diff --git a/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTableFilters/WorkCellTypesTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTableFilters/WorkCellTypesTableFilters.tsx
index 1b0039ee35..9a2c341fcb 100644
--- a/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTableFilters/WorkCellTypesTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/WorkCells/WorkCellTypesTableFilters/WorkCellTypesTableFilters.tsx
@@ -24,7 +24,7 @@ const WorkCellTypesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/resources/services/resources.server.ts b/apps/carbon/app/modules/resources/services/resources.server.ts
index 90e4adfb04..05f4022b40 100644
--- a/apps/carbon/app/modules/resources/services/resources.server.ts
+++ b/apps/carbon/app/modules/resources/services/resources.server.ts
@@ -785,7 +785,7 @@ export async function insertAbility(
createdBy: string;
}
) {
- return client.from("ability").insert([ability]).select("id");
+ return client.from("ability").insert([ability]).select("id").single();
}
export async function insertEmployeeAbilities(
@@ -799,7 +799,11 @@ export async function insertEmployeeAbilities(
trainingCompleted: true,
}));
- return client.from("employeeAbility").insert(employeeAbilities).select("id");
+ return client
+ .from("employeeAbility")
+ .insert(employeeAbilities)
+ .select("id")
+ .single();
}
export async function insertAttribute(
@@ -827,7 +831,8 @@ export async function insertAttribute(
return client
.from("userAttribute")
.upsert([{ ...attribute, sortOrder: maxSortOrder + 1 }])
- .select("id");
+ .select("id")
+ .single();
}
export async function insertAttributeCategory(
@@ -841,7 +846,8 @@ export async function insertAttributeCategory(
return client
.from("userAttributeCategory")
.upsert([attributeCategory])
- .select("id");
+ .select("id")
+ .single();
}
export async function insertNote(
@@ -852,7 +858,7 @@ export async function insertNote(
createdBy: string;
}
) {
- return client.from("userNote").insert([note]).select("id");
+ return client.from("userNote").insert([note]).select("id").single();
}
export async function updateAbility(
@@ -1002,7 +1008,7 @@ export async function upsertDepartment(
.update(sanitize(department))
.eq("id", department.id);
}
- return client.from("department").insert(department).select("id");
+ return client.from("department").insert(department).select("id").single();
}
export async function upsertEmployeeAbility(
@@ -1038,7 +1044,8 @@ export async function upsertEmployeeAbility(
return client
.from("employeeAbility")
.insert([{ ...update }])
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertEmployeeJob(
@@ -1085,7 +1092,7 @@ export async function upsertEquipment(
const { id, ...update } = equipment;
return client.from("equipment").update(sanitize(update)).eq("id", id);
}
- return client.from("equipment").insert([equipment]).select("id");
+ return client.from("equipment").insert([equipment]).select("id").single();
}
export async function upsertEquipmentType(
@@ -1111,7 +1118,11 @@ export async function upsertEquipmentType(
const { id, ...update } = equipmentType;
return client.from("equipmentType").update(sanitize(update)).eq("id", id);
}
- return client.from("equipmentType").insert([equipmentType]).select("id");
+ return client
+ .from("equipmentType")
+ .insert([equipmentType])
+ .select("id")
+ .single();
}
export async function upsertHoliday(
@@ -1135,7 +1146,7 @@ export async function upsertHoliday(
.update(sanitize(holiday))
.eq("id", holiday.id);
}
- return client.from("holiday").insert(holiday).select("id");
+ return client.from("holiday").insert(holiday).select("id").single();
}
export async function upsertLocation(
@@ -1155,7 +1166,7 @@ export async function upsertLocation(
.update(sanitize(location))
.eq("id", location.id);
}
- return client.from("location").insert([location]).select("id");
+ return client.from("location").insert([location]).select("id").single();
}
export async function upsertPartner(
@@ -1230,7 +1241,7 @@ export async function upsertShift(
return client.from("shift").update(sanitize(update)).eq("id", id);
}
- return client.from("shift").insert([update]).select("id");
+ return client.from("shift").insert([update]).select("id").single();
}
export async function upsertWorkCell(
@@ -1260,7 +1271,7 @@ export async function upsertWorkCell(
const { id, ...update } = workCell;
return client.from("workCell").update(sanitize(update)).eq("id", id);
}
- return client.from("workCell").insert([workCell]).select("id");
+ return client.from("workCell").insert([workCell]).select("id").single();
}
export async function upsertWorkCellType(
@@ -1286,5 +1297,9 @@ export async function upsertWorkCellType(
const { id, ...update } = workCellType;
return client.from("workCellType").update(sanitize(update)).eq("id", id);
}
- return client.from("workCellType").insert([workCellType]).select("id");
+ return client
+ .from("workCellType")
+ .insert([workCellType])
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx
index f73921ab08..b3f8989e3f 100644
--- a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTable/CustomerTypesTable.tsx
@@ -1,4 +1,4 @@
-import { Box, MenuItem } from "@chakra-ui/react";
+import { Box, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -18,12 +18,16 @@ const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Customer Type",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "color",
@@ -40,10 +44,10 @@ const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -83,7 +87,7 @@ const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx
index fd284e4536..2ec4aa9877 100644
--- a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypesTableFilters/CustomerTypesTableFilters.tsx
@@ -24,7 +24,7 @@ const CustomerTypesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
index 1354e80d07..7ecb2fd5d6 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
@@ -1,4 +1,10 @@
-import { Button, ButtonGroup, IconButton, MenuItem } from "@chakra-ui/react";
+import {
+ Button,
+ ButtonGroup,
+ IconButton,
+ Link,
+ MenuItem,
+} from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
@@ -21,7 +27,11 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
// @ts-ignore
@@ -74,7 +84,7 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useMemo(
// eslint-disable-next-line react/display-name
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTableFilters/CustomersTableFilters.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTableFilters/CustomersTableFilters.tsx
index 9f24c3adad..a2e435c487 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTableFilters/CustomersTableFilters.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTableFilters/CustomersTableFilters.tsx
@@ -47,13 +47,13 @@ const CustomersTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
{customerTypeOptions.length > 0 && (
<Select
// @ts-ignore
size="sm"
- value={customerTypeOptions.filter(
+ value={customerTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
@@ -71,7 +71,7 @@ const CustomersTableFilters = ({
// @ts-ignore
size="sm"
isClearable
- value={customerStatusOptions.filter(
+ value={customerStatusOptions.find(
(type) => type.value === params.get("status")
)}
options={customerStatusOptions}
diff --git a/apps/carbon/app/modules/sales/services/sales.server.ts b/apps/carbon/app/modules/sales/services/sales.server.ts
index 7885d94850..f34201930c 100644
--- a/apps/carbon/app/modules/sales/services/sales.server.ts
+++ b/apps/carbon/app/modules/sales/services/sales.server.ts
@@ -177,7 +177,7 @@ export async function insertCustomer(
createdBy: string;
}
) {
- return client.from("customer").insert([customer]).select("id");
+ return client.from("customer").insert([customer]).select("id").single();
}
export async function insertCustomerContact(
@@ -209,12 +209,13 @@ export async function insertCustomerContact(
const insertContact = await getSupabaseServiceRole()
.from("contact")
.insert([customerContact.contact])
- .select("id");
+ .select("id")
+ .single();
if (insertContact.error) {
return insertContact;
}
- const contactId = insertContact.data[0].id;
+ const contactId = insertContact.data?.id;
if (!contactId) {
return { data: null, error: new Error("Contact ID not found") };
}
@@ -227,7 +228,8 @@ export async function insertCustomerContact(
contactId,
},
])
- .select("id");
+ .select("id")
+ .single();
}
export async function insertCustomerLocation(
@@ -247,12 +249,13 @@ export async function insertCustomerLocation(
const insertAddress = await client
.from("address")
.insert([customerLocation.address])
- .select("id");
+ .select("id")
+ .single();
if (insertAddress.error) {
return insertAddress;
}
- const addressId = insertAddress.data[0].id;
+ const addressId = insertAddress.data?.id;
if (!addressId) {
return { data: null, error: new Error("Address ID not found") };
}
@@ -265,7 +268,8 @@ export async function insertCustomerLocation(
addressId,
},
])
- .select("id");
+ .select("id")
+ .single();
}
export async function updateCustomer(
@@ -279,7 +283,8 @@ export async function updateCustomer(
.from("customer")
.update(sanitize(customer))
.eq("id", customer.id)
- .select("id");
+ .select("id")
+ .single();
}
export async function updateCustomerContact(
@@ -310,7 +315,8 @@ export async function updateCustomerContact(
.from("contact")
.update(sanitize(customerContact.contact))
.eq("id", customerContact.contactId)
- .select("id");
+ .select("id")
+ .single();
}
export async function updateCustomerLocation(
@@ -331,12 +337,17 @@ export async function updateCustomerLocation(
.from("address")
.update(sanitize(customerLocation.address))
.eq("id", customerLocation.addressId)
- .select("id");
+ .select("id")
+ .single();
}
export async function upsertCustomerType(
client: SupabaseClient<Database>,
customerType: { id?: string; name: string; color: string | null }
) {
- return client.from("customerType").upsert([customerType]).select("id");
+ return client
+ .from("customerType")
+ .upsert([customerType])
+ .select("id")
+ .single();
}
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx
index 8391e3131b..a6002298fa 100644
--- a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTable/SequencesTable.tsx
@@ -1,4 +1,4 @@
-import { MenuItem } from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -17,12 +17,16 @@ const SequencesTable = memo(({ data, count }: SequencesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Name",
- cell: (item) => item.getValue(),
+ cell: ({ row }) => (
+ <Link onClick={() => navigate(row.original.table)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "prefix",
@@ -50,10 +54,10 @@ const SequencesTable = memo(({ data, count }: SequencesTableProps) => {
cell: (item) => item.getValue(),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -74,7 +78,7 @@ const SequencesTable = memo(({ data, count }: SequencesTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx
index 7a0a526ab0..cd6396ed4a 100644
--- a/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx
+++ b/apps/carbon/app/modules/settings/interfaces/Sequences/SequencesTableFilters/SequencesTableFilters.tsx
@@ -19,7 +19,7 @@ const SequencesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
</HStack>
diff --git a/apps/carbon/app/modules/settings/services/settings.form.ts b/apps/carbon/app/modules/settings/services/settings.form.ts
index 4599f70d7c..0b4bcc2e31 100644
--- a/apps/carbon/app/modules/settings/services/settings.form.ts
+++ b/apps/carbon/app/modules/settings/services/settings.form.ts
@@ -7,7 +7,7 @@ export const sequenceValidator = withZod(
table: z.string().min(1, { message: "Table is required" }),
prefix: zfd.text(z.string().optional()),
suffix: zfd.text(z.string().optional()),
- next: zfd.numeric(z.number().min(1)),
+ next: zfd.numeric(z.number().min(0)),
step: zfd.numeric(z.number().min(1)),
size: zfd.numeric(z.number().min(1).max(20)),
})
diff --git a/apps/carbon/app/modules/users/interfaces/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx b/apps/carbon/app/modules/users/interfaces/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx
index 899d19880a..f8a0440f7a 100644
--- a/apps/carbon/app/modules/users/interfaces/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Customers/CustomerAccountsTableFilters/CustomerAccountsTableFilters.tsx
@@ -39,12 +39,12 @@ const CustomerAccountsTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={customerTypeOptions.filter(
+ value={customerTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
diff --git a/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx b/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
index 0cb6817053..31e01346f7 100644
--- a/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
+++ b/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTable/EmployeeTypesTable.tsx
@@ -1,4 +1,4 @@
-import { Box, MenuItem } from "@chakra-ui/react";
+import { Box, Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -18,12 +18,19 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
const navigate = useNavigate();
const permissions = usePermissions();
- const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
return [
{
accessorKey: "name",
header: "Employee Type",
- cell: (item) => item.getValue(),
+ cell: ({ row, getValue }) =>
+ row.original.protected ? (
+ getValue()
+ ) : (
+ <Link onClick={() => navigate(row.original.id)}>
+ {row.original.name}
+ </Link>
+ ),
},
{
accessorKey: "color",
@@ -40,10 +47,10 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
),
},
];
- }, []);
+ }, [navigate]);
const renderContextMenu = useCallback(
- (row: typeof data[number]) => {
+ (row: (typeof data)[number]) => {
return (
<>
<MenuItem
@@ -83,7 +90,7 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {
);
return (
- <Table<typeof data[number]>
+ <Table<(typeof data)[number]>
data={data}
columns={columns}
count={count}
diff --git a/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx b/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
index 0fbf7d80bc..09b8d9e35b 100644
--- a/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
+++ b/apps/carbon/app/modules/users/interfaces/EmployeeTypes/EmployeeTypesTableFilters/EmployeeTypesTableFilters.tsx
@@ -24,7 +24,7 @@ const EmployeeTypesTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx
index e1628dd238..b0de5ecd32 100644
--- a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx
@@ -1,4 +1,4 @@
-import { HStack, MenuItem, useDisclosure } from "@chakra-ui/react";
+import { HStack, Link, MenuItem, useDisclosure } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
@@ -10,8 +10,8 @@ import { usePermissions, useUrlParams } from "~/hooks";
import type { Employee } from "~/modules/users";
import {
BulkEditPermissionsForm,
- ResendInviteModal,
DeactivateUsersModal,
+ ResendInviteModal,
} from "~/modules/users";
type EmployeesTableProps = {
@@ -55,7 +55,7 @@ const EmployeesTable = memo(
[data]
);
- const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
return [
{
header: "User",
@@ -68,13 +68,21 @@ const EmployeesTable = memo(
// @ts-ignore
path={row.original.user?.avatarUrl}
/>
-
- <span>
+ {/* // @ts-ignore */}
+ <Link
+ onClick={() =>
+ navigate(
+ `/x/users/employees/${
+ row.original.user?.id
+ }?${params.toString()}`
+ )
+ }
+ >
{
// @ts-ignore
`${row.original.user?.firstName} ${row.original.user?.lastName}`
}
- </span>
+ </Link>
</HStack>
),
},
@@ -158,7 +166,7 @@ const EmployeesTable = memo(
}, []);
const renderContextMenu = useCallback(
- ({ user }: typeof rows[number]) => {
+ ({ user }: (typeof rows)[number]) => {
if (Array.isArray(user) || user === null) return null;
return (
<>
@@ -198,7 +206,7 @@ const EmployeesTable = memo(
return (
<>
- <Table<typeof rows[number]>
+ <Table<(typeof rows)[number]>
actions={actions}
count={count}
columns={columns}
diff --git a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
index 0ad079bf8a..c095aa873d 100644
--- a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTableFilters/EmployeesTableFilters.tsx
@@ -39,12 +39,12 @@ const EmployeesTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={employeeTypeOptions.filter(
+ value={employeeTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
diff --git a/apps/carbon/app/modules/users/interfaces/Groups/GroupsTableFilters/GroupsTableFilters.tsx b/apps/carbon/app/modules/users/interfaces/Groups/GroupsTableFilters/GroupsTableFilters.tsx
index 0f73b90a36..83f541b3b0 100644
--- a/apps/carbon/app/modules/users/interfaces/Groups/GroupsTableFilters/GroupsTableFilters.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Groups/GroupsTableFilters/GroupsTableFilters.tsx
@@ -24,7 +24,7 @@ const GroupsTableFilters = () => {
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
</HStack>
<HStack spacing={2}>
diff --git a/apps/carbon/app/modules/users/interfaces/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx b/apps/carbon/app/modules/users/interfaces/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx
index 0d22db897e..f1ab01fc37 100644
--- a/apps/carbon/app/modules/users/interfaces/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Suppliers/SupplierAccountsTableFilters/SupplierAccountsTableFilters.tsx
@@ -39,12 +39,12 @@ const SupplierAccountsTableFilters = ({
param="name"
size="sm"
minW={180}
- placeholder="Filter by name"
+ placeholder="Search"
/>
<Select
// @ts-ignore
size="sm"
- value={supplierTypeOptions.filter(
+ value={supplierTypeOptions.find(
(type) => type.value === params.get("type")
)}
isClearable
diff --git a/apps/carbon/app/modules/users/services/users.server.ts b/apps/carbon/app/modules/users/services/users.server.ts
index 99c3af2983..3f36b6c910 100644
--- a/apps/carbon/app/modules/users/services/users.server.ts
+++ b/apps/carbon/app/modules/users/services/users.server.ts
@@ -86,8 +86,13 @@ export async function createCustomerAccount(
return error(updateContact.error, "Failed to update customer contact");
}
+ const generatedId = Array.isArray(insertUser.data)
+ ? insertUser.data[0].id
+ : // @ts-ignore
+ insertUser.data?.id!;
+
const createCustomerAccount = await insertCustomerAccount(client, {
- id: insertUser.data[0].id,
+ id: generatedId,
customerId,
});
@@ -538,7 +543,7 @@ export async function getUserClaims(
);
}
// convert rawClaims to permissions
- claims = makePermissionsFromClaims(rawClaims.data);
+ claims = makePermissionsFromClaims(rawClaims.data as Json[]);
// store claims in redis
await redis.set(getPermissionCacheKey(userId), JSON.stringify(claims));
@@ -562,6 +567,17 @@ export async function getUserGroups(
return client.rpc("groups_for_user", { uid: userId });
}
+export async function getUserDefaults(
+ client: SupabaseClient<Database>,
+ userId: string
+) {
+ return client
+ .from("user_default_view")
+ .select("*")
+ .eq("userId", userId)
+ .single();
+}
+
export async function getUsers(client: SupabaseClient<Database>) {
return client
.from("user")
@@ -577,28 +593,36 @@ async function insertCustomerAccount(
customerId: string;
}
) {
- return client.from("customerAccount").insert(customerAccount).select("id");
+ return client
+ .from("customerAccount")
+ .insert(customerAccount)
+ .select("id")
+ .single();
}
export async function insertEmployee(
client: SupabaseClient<Database>,
employee: EmployeeRow
) {
- return client.from("employee").insert([employee]);
+ return client.from("employee").insert([employee]).select("id").single();
}
export async function insertEmployeeType(
client: SupabaseClient<Database>,
employeeType: { id?: string; name: string; color?: string }
) {
- return client.from("employeeType").insert([employeeType]).select("id");
+ return client
+ .from("employeeType")
+ .insert([employeeType])
+ .select("id")
+ .single();
}
export async function insertGroup(
client: SupabaseClient<Database>,
group: { name: string }
) {
- return client.from("group").insert(group).select("id");
+ return client.from("group").insert(group).select("id").single();
}
async function insertSupplierAccount(
@@ -608,7 +632,11 @@ async function insertSupplierAccount(
supplierId: string;
}
) {
- return client.from("supplierAccount").insert(supplierAccount).select("id");
+ return client
+ .from("supplierAccount")
+ .insert(supplierAccount)
+ .select("id")
+ .single();
}
async function insertUser(
@@ -868,8 +896,8 @@ export async function updatePermissions(
});
const claimsUpdate = await setUserClaims(id, {
- ...currentClaims,
- ...newClaims,
+ ...(currentClaims as Record<string, boolean>),
+ ...(newClaims as Record<string, boolean>),
});
if (claimsUpdate.error)
return error(claimsUpdate.error, "Failed to update claims");
@@ -886,7 +914,11 @@ export async function upsertEmployeeType(
client: SupabaseClient<Database>,
employeeType: { id?: string; name: string; color?: string }
) {
- return client.from("employeeType").upsert([employeeType]).select("id");
+ return client
+ .from("employeeType")
+ .upsert([employeeType])
+ .select("id")
+ .single();
}
export async function upsertEmployeeTypePermissions(
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index ce71fdf867..0e365bc5bc 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -1,6 +1,7 @@
// root.tsx
import { ThemeProvider } from "@carbon/react";
import { SkipNavLink } from "@chakra-ui/skip-nav";
+import { VStack, Heading } from "@chakra-ui/react";
import {
Links,
LiveReload,
@@ -16,7 +17,6 @@ import React from "react";
import { getBrowserEnv } from "~/config/env";
import Background from "~/styles/background.css";
import NProgress from "~/styles/nprogress.css";
-import { Box, Heading } from "@chakra-ui/react";
export function links() {
return [
@@ -48,7 +48,8 @@ function Document({
children: React.ReactNode;
title?: string;
}) {
- const { env } = useLoaderData<typeof loader>();
+ const loaderData = useLoaderData<typeof loader>();
+ const env = loaderData?.env ?? {};
return (
<html lang="en">
@@ -87,17 +88,18 @@ export function ErrorBoundary({ error }: { error: Error }) {
return (
<Document title="Error!">
<ThemeProvider>
- <Box
+ <VStack
w="full"
h="100vh"
alignItems="center"
+ justifyContent="center"
gap={4}
bg="black"
color="white"
>
<Heading as="h1">Something went wrong</Heading>
<p>{error.message}</p>
- </Box>
+ </VStack>
</ThemeProvider>
</Document>
);
diff --git a/apps/carbon/app/routes/api+/parts.shelf.tsx b/apps/carbon/app/routes/api+/parts.shelf.tsx
new file mode 100644
index 0000000000..edadf82a87
--- /dev/null
+++ b/apps/carbon/app/routes/api+/parts.shelf.tsx
@@ -0,0 +1,21 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getShelvesList } from "~/modules/parts";
+import { requirePermissions } from "~/services/auth";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const url = new URL(request.url);
+ const locationId = url.searchParams.get("locationId");
+ if (!locationId) {
+ return json({
+ data: [],
+ error: null,
+ });
+ }
+
+ return json(await getShelvesList(authorized.client, locationId));
+}
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 0c95de418a..a98a2adcb8 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -8,7 +8,12 @@ import NProgress from "nprogress";
import { useEffect } from "react";
import { IconSidebar, Topbar } from "~/components/Layout";
import { getSupabase, SupabaseProvider } from "~/lib/supabase";
-import { getUserClaims, getUser, getUserGroups } from "~/modules/users";
+import {
+ getUserClaims,
+ getUser,
+ getUserDefaults,
+ getUserGroups,
+} from "~/modules/users";
import {
destroyAuthSession,
getSessionFlash,
@@ -23,11 +28,12 @@ export async function loader({ request }: LoaderArgs) {
const client = getSupabase(accessToken);
// parallelize the requests
- const [sessionFlash, user, claims, groups] = await Promise.all([
+ const [sessionFlash, user, claims, groups, defaults] = await Promise.all([
getSessionFlash(request),
getUser(client, userId),
getUserClaims(request, client),
getUserGroups(client, userId),
+ getUserDefaults(client, userId),
]);
if (!claims || user.error || !user.data || !groups.data) {
@@ -44,6 +50,7 @@ export async function loader({ request }: LoaderArgs) {
user: user.data,
groups: groups.data,
+ defaults: defaults.data,
permissions: claims?.permissions,
role: claims?.role,
result: sessionFlash?.result,
diff --git a/apps/carbon/app/routes/x+/accounting+/charts.new.tsx b/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
index 189da3ee9f..e0767ff536 100644
--- a/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
@@ -54,7 +54,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const accountNumber = insertAccount.data[0]?.id;
+ const accountNumber = insertAccount.data?.id;
if (!accountNumber) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx b/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx
index 9348fbddf3..e61f462561 100644
--- a/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx
@@ -48,7 +48,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const currencyId = insertCurrency.data[0]?.id;
+ const currencyId = insertCurrency.data?.id;
if (!currencyId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx
index 02163df660..8da68836d4 100644
--- a/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/payment-terms.new.tsx
@@ -56,7 +56,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const paymentTermId = insertPaymentTerm.data[0]?.id;
+ const paymentTermId = insertPaymentTerm.data?.id;
if (!paymentTermId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/inventory+/index.tsx b/apps/carbon/app/routes/x+/inventory+/index.tsx
index 061034bc98..d3a3364295 100644
--- a/apps/carbon/app/routes/x+/inventory+/index.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/index.tsx
@@ -1,5 +1,5 @@
import { redirect } from "@remix-run/node";
export async function loader() {
- return redirect("/x/inventory/shipping-methods");
+ return redirect("/x/inventory/receipts");
}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
new file mode 100644
index 0000000000..8085afbc36
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
@@ -0,0 +1,96 @@
+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,
+ ReceiptForm,
+ receiptValidator,
+ upsertReceipt,
+} from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ role: "employee",
+ });
+
+ const { receiptId } = params;
+ if (!receiptId) throw notFound("receiptId not found");
+
+ const [receipt, receiptLines] = await Promise.all([
+ getReceipt(client, receiptId),
+ getReceiptLines(client, receiptId),
+ ]);
+
+ return json({
+ receipt: receipt?.data ?? null,
+ receiptLines: receiptLines?.data ?? [],
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const validation = await receiptValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateReceipt = await upsertReceipt(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (updateReceipt.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateReceipt.error, "Failed to update receipt")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, success("Updated receipt"))
+ );
+}
+
+export default function EditReceiptsRoute() {
+ const { receipt, receiptLines } = useLoaderData<typeof loader>();
+ if (!receipt?.receiptId) throw notFound("receiptId not found");
+ if (!receipt?.sourceDocumentId) throw notFound("sourceDocumentId not found");
+
+ const initialValues = {
+ ...receipt,
+ receiptId: receipt.receiptId ?? undefined,
+ sourceDocument: (receipt.sourceDocument ??
+ "Purchase Order") as ReceiptSourceDocument,
+ sourceDocumentId: receipt.sourceDocumentId ?? undefined,
+ locationId: receipt.locationId ?? undefined,
+ };
+
+ return (
+ <ReceiptForm
+ initialValues={initialValues}
+ isPosted={!!receipt?.postingDate ?? false}
+ receiptLines={receiptLines}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.delete.$receiptId.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.delete.$receiptId.tsx
new file mode 100644
index 0000000000..82774e68a8
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.delete.$receiptId.tsx
@@ -0,0 +1,98 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteReceipt, getReceipt } from "~/modules/inventory";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "inventory",
+ });
+ const { receiptId } = params;
+ if (!receiptId) throw notFound("receiptId not found");
+
+ const receipt = await getReceipt(client, receiptId);
+ if (receipt.error) {
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, error(receipt.error, "Failed to get receipt"))
+ );
+ }
+
+ return json({ receipt: receipt.data });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "inventory",
+ });
+
+ const { receiptId } = params;
+ if (!receiptId) {
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, error(params, "Failed to get an receipt id"))
+ );
+ }
+
+ // make sure the receipt has not been posted
+ const { error: getReceiptError, data: receipt } = await getReceipt(
+ client,
+ receiptId
+ );
+ if (getReceiptError) {
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, error(getReceiptError, "Failed to get receipt"))
+ );
+ }
+
+ if (receipt?.postingDate) {
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(
+ request,
+ error(getReceiptError, "Cannot delete a posted receipt")
+ )
+ );
+ }
+
+ const { error: deleteReceiptError } = await deleteReceipt(client, receiptId);
+ if (deleteReceiptError) {
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(
+ request,
+ error(deleteReceiptError, "Failed to delete receipt")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, success("Successfully deleted receipt"))
+ );
+}
+
+export default function DeleteShippingMethodRoute() {
+ const { receiptId } = useParams();
+ const { receipt } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!receiptId || !receipt) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate("/x/inventory/receipts");
+
+ return (
+ <ConfirmDelete
+ action={`/x/inventory/receipts/delete/${receiptId}`}
+ name={receipt.receiptId}
+ text={`Are you sure you want to delete the receipt: ${receipt.receiptId}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
new file mode 100644
index 0000000000..d60b3eca16
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
@@ -0,0 +1,113 @@
+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 { useUser } from "~/hooks";
+import type { ReceiptSourceDocument } from "~/modules/inventory";
+import {
+ ReceiptForm,
+ receiptValidator,
+ upsertReceipt,
+} from "~/modules/inventory";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const nextSequence = await getNextSequence(client, "receipt", userId);
+ if (nextSequence.error) {
+ return redirect(
+ "/x/inventory/receipts/new",
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const insertReceipt = await upsertReceipt(client, {
+ receiptId: nextSequence.data,
+ sourceDocumentId: "",
+ createdBy: userId,
+ });
+ if (insertReceipt.error) {
+ await rollbackNextSequence(client, "receipt", userId);
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(
+ request,
+ error(insertReceipt.error, "Failed to generate receipt")
+ )
+ );
+ }
+
+ return json({
+ receipt: {
+ id: insertReceipt.data.id,
+ receiptId: nextSequence.data,
+ },
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "inventory",
+ });
+
+ const validation = await receiptValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("id not found");
+
+ const updateReceipt = await upsertReceipt(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+ if (updateReceipt.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateReceipt.error, "Failed to update receipt")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/inventory/receipts",
+ await flash(request, success("Receipt created"))
+ );
+}
+
+export default function NewReceiptsRoute() {
+ const { receipt } = useLoaderData<typeof loader>();
+ const { defaults } = useUser();
+
+ const initialValues = {
+ ...receipt,
+ sourceDocument: "Purchase Order" as ReceiptSourceDocument,
+ sourceDocumentId: "",
+ locationId: defaults.locationId ?? undefined,
+ };
+
+ return (
+ <ReceiptForm
+ // @ts-expect-error
+ initialValues={initialValues}
+ isPosted={false}
+ receiptLines={[]}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.tsx
new file mode 100644
index 0000000000..cfdb4ab18d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.tsx
@@ -0,0 +1,66 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ ReceiptsTable,
+ ReceiptsTableFilters,
+ getReceipts,
+} from "~/modules/inventory";
+import { getLocationsList } from "~/modules/resources";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const document = searchParams.get("document");
+ const location = searchParams.get("location");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ const [receipts, locations] = await Promise.all([
+ getReceipts(client, {
+ search,
+ document,
+ location,
+ limit,
+ offset,
+ sorts,
+ }),
+ getLocationsList(client),
+ ]);
+
+ if (receipts.error) {
+ return redirect(
+ "/x/inventory",
+ await flash(request, error(null, "Error loading receipts"))
+ );
+ }
+
+ return json({
+ receipts: receipts.data ?? [],
+ count: receipts.count ?? 0,
+ locations: locations.data ?? [],
+ });
+}
+
+export default function ReceiptsRoute() {
+ const { receipts, count, locations } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <ReceiptsTableFilters locations={locations ?? []} />
+ <ReceiptsTable data={receipts ?? []} count={count ?? 0} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
index b7e41be63f..711654b820 100644
--- a/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
@@ -3,7 +3,6 @@ import { redirect } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
import type { ShippingCarrier } from "~/modules/inventory";
import {
ShippingMethodForm,
@@ -73,9 +72,6 @@ export async function action({ request }: ActionArgs) {
export default function EditShippingMethodsRoute() {
const { shippingMethod } = useLoaderData<typeof loader>();
- const routeData = useRouteData<{
- accounts: { name: string; number: string }[];
- }>("/x/inventory/shipping-methods");
const initialValues = {
id: shippingMethod?.id ?? undefined,
@@ -85,10 +81,5 @@ export default function EditShippingMethodsRoute() {
trackingUrl: shippingMethod?.trackingUrl ?? "",
};
- return (
- <ShippingMethodForm
- initialValues={initialValues}
- accounts={routeData?.accounts ?? []}
- />
- );
+ return <ShippingMethodForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx
index cfce790209..e2de551bcd 100644
--- a/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.new.tsx
@@ -2,7 +2,6 @@ import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { json } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
import type { ShippingCarrier } from "~/modules/inventory";
import {
ShippingMethodForm,
@@ -55,7 +54,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const shippingMethodId = insertShippingMethod.data[0]?.id;
+ const shippingMethodId = insertShippingMethod.data?.id;
if (!shippingMethodId) {
return json(
{},
@@ -73,19 +72,10 @@ export async function action({ request }: ActionArgs) {
}
export default function NewShippingMethodsRoute() {
- const routeData = useRouteData<{
- accounts: { name: string; number: string }[];
- }>("/x/inventory/shipping-methods");
-
const initialValues = {
name: "",
carrier: "" as ShippingCarrier,
};
- return (
- <ShippingMethodForm
- initialValues={initialValues}
- accounts={routeData?.accounts ?? []}
- />
- );
+ return <ShippingMethodForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx b/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx
index 5e54c86298..15f9cec198 100644
--- a/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.tsx
@@ -25,7 +25,7 @@ export async function loader({ request }: LoaderArgs) {
const name = searchParams.get("name");
const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
- const [shippingMethods, accounts] = await Promise.all([
+ const [shippingMethods] = await Promise.all([
getShippingMethods(client, {
name,
limit,
@@ -38,21 +38,13 @@ export async function loader({ request }: LoaderArgs) {
if (shippingMethods.error) {
return redirect(
"/x/inventory",
- await flash(request, error(null, "Error loading part groups"))
- );
- }
-
- if (accounts.error) {
- return redirect(
- "/x/inventory",
- await flash(request, error(accounts.error, "Error loading accounts"))
+ await flash(request, error(null, "Error loading shipping methods"))
);
}
return json({
shippingMethods: shippingMethods.data ?? [],
count: shippingMethods.count ?? 0,
- accounts: accounts.data ?? [],
});
}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.index.tsx b/apps/carbon/app/routes/x+/part+/$partId.index.tsx
index 32a2de58de..3d9d9d5acc 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.index.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.index.tsx
@@ -59,19 +59,21 @@ export default function PartBasicRoute() {
}>("/x/part");
const { partId } = useParams();
- const partData = useRouteData<PartSummary>(`/x/part/${partId}`);
+ const partData = useRouteData<{ partSummary: PartSummary }>(
+ `/x/part/${partId}`
+ );
if (!partData) throw new Error("Could not find part data");
const initialValues = {
- id: partData.id,
- name: partData.name ?? "",
- description: partData.description ?? undefined,
- partType: partData.partType,
- partGroupId: partData.partGroupId,
- replenishmentSystem: partData.replenishmentSystem,
- unitOfMeasureCode: partData.unitOfMeasureCode,
- blocked: partData.blocked,
- active: partData.active,
+ id: partData.partSummary?.id,
+ name: partData.partSummary?.name ?? "",
+ description: partData.partSummary?.description ?? undefined,
+ partType: partData.partSummary?.partType,
+ partGroupId: partData.partSummary?.partGroupId ?? undefined,
+ replenishmentSystem: partData.partSummary?.replenishmentSystem,
+ unitOfMeasureCode: partData.partSummary?.unitOfMeasureCode,
+ blocked: partData.partSummary?.blocked,
+ active: partData.partSummary?.active,
};
return (
diff --git a/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
index a300773c02..872a8db09d 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx
@@ -2,6 +2,7 @@ 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 { useRouteData } from "~/hooks";
import {
PartInventoryForm,
getPartInventory,
@@ -10,33 +11,89 @@ import {
partInventoryValidator,
upsertPartInventory,
} from "~/modules/parts";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
+import type { ListItem } from "~/types";
import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
export async function loader({ request, params }: LoaderArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
view: "parts",
});
const { partId } = params;
if (!partId) throw new Error("Could not find partId");
- const [partInventory, shelves] = await Promise.all([
- getPartInventory(client, partId),
- getShelvesList(client),
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId);
+ if (userDefaults.error) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client);
+ if (locations.error || !locations.data?.length) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let [partInventory, shelves] = await Promise.all([
+ getPartInventory(client, partId, locationId),
+ getShelvesList(client, locationId),
]);
- if (partInventory.error) {
- return redirect(
- "/x/parts",
- await flash(
- request,
- error(partInventory.error, "Failed to load part inventory")
- )
- );
+ if (partInventory.error || !partInventory.data) {
+ const insertPartInventory = await upsertPartInventory(client, {
+ partId,
+ locationId,
+ createdBy: userId,
+ });
+
+ if (insertPartInventory.error) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(insertPartInventory.error, "Failed to insert part inventory")
+ )
+ );
+ }
+
+ partInventory = await getPartInventory(client, partId, locationId);
+ if (partInventory.error || !partInventory.data) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(partInventory.error, "Failed to load part inventory")
+ )
+ );
+ }
}
+
if (shelves.error) {
return redirect(
"/x/parts",
@@ -70,8 +127,13 @@ export async function action({ request, params }: ActionArgs) {
const { hasNewShelf, ...update } = validation.data;
- if (hasNewShelf === "true" && update.shelfId) {
- const createShelf = await insertShelf(client, update.shelfId, userId);
+ if (hasNewShelf === "true" && update.defaultShelfId) {
+ const createShelf = await insertShelf(
+ client,
+ update.defaultShelfId,
+ update.locationId,
+ userId
+ );
if (createShelf.error) {
return redirect(
`/x/part/${partId}/inventory`,
@@ -99,16 +161,24 @@ export async function action({ request, params }: ActionArgs) {
}
return redirect(
- `/x/part/${partId}/inventory`,
+ `/x/part/${partId}/inventory?location=${update.locationId}`,
await flash(request, success("Updated part inventory"))
);
}
export default function PartInventoryRoute() {
+ const sharedPartsData = useRouteData<{ locations: ListItem[] }>("/x/part");
const { partInventory, shelves } = useLoaderData<typeof loader>();
+
const initialValues = {
...partInventory,
- shelfId: partInventory.shelfId ?? undefined,
+ defaultShelfId: partInventory.defaultShelfId ?? undefined,
};
- return <PartInventoryForm initialValues={initialValues} shelves={shelves} />;
+ return (
+ <PartInventoryForm
+ initialValues={initialValues}
+ locations={sharedPartsData?.locations ?? []}
+ shelves={shelves}
+ />
+ );
}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.planning.tsx b/apps/carbon/app/routes/x+/part+/$partId.planning.tsx
index 9a4bc5d6b2..c5adc3ac9f 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.planning.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.planning.tsx
@@ -10,29 +10,84 @@ import {
partPlanningValidator,
upsertPartPlanning,
} from "~/modules/parts";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
+import type { ListItem } from "~/types";
import { assertIsPost } from "~/utils/http";
import { error, success } from "~/utils/result";
export async function loader({ request, params }: LoaderArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, userId } = await requirePermissions(request, {
view: "parts",
});
const { partId } = params;
if (!partId) throw new Error("Could not find partId");
- const partPlanning = await getPartPlanning(client, partId);
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ let locationId = searchParams.get("location");
- if (partPlanning.error) {
- return redirect(
- "/x/parts",
- await flash(
- request,
- error(partPlanning.error, "Failed to load part planning")
- )
- );
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId);
+ if (userDefaults.error) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client);
+ if (locations.error || !locations.data?.length) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ let partPlanning = await getPartPlanning(client, partId, locationId);
+
+ if (partPlanning.error || !partPlanning.data) {
+ const insertPartPlanning = await upsertPartPlanning(client, {
+ partId,
+ locationId,
+ createdBy: userId,
+ });
+
+ if (insertPartPlanning.error) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(insertPartPlanning.error, "Failed to insert part planning")
+ )
+ );
+ }
+
+ partPlanning = await getPartPlanning(client, partId, locationId);
+ if (partPlanning.error || !partPlanning.data) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(partPlanning.error, "Failed to load part planning")
+ )
+ );
+ }
}
return json({
@@ -74,7 +129,7 @@ export async function action({ request, params }: ActionArgs) {
}
return redirect(
- `/x/part/${partId}/planning`,
+ `/x/part/${partId}/planning?location=${validation.data.locationId}`,
await flash(request, success("Updated part planning"))
);
}
@@ -82,14 +137,17 @@ export async function action({ request, params }: ActionArgs) {
export default function PartPlanningRoute() {
const sharedPartsData = useRouteData<{
partReorderingPolicies: PartReorderingPolicy[];
+ locations: ListItem[];
}>("/x/part");
const { partPlanning } = useLoaderData<typeof loader>();
if (!sharedPartsData) throw new Error("Could not load shared parts data");
+
return (
<PartPlanningForm
initialValues={partPlanning}
+ locations={sharedPartsData.locations ?? []}
partReorderingPolicies={sharedPartsData.partReorderingPolicies}
/>
);
diff --git a/apps/carbon/app/routes/x+/part+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$partId.tsx
index 9d19bc6b51..5496226fc5 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.tsx
@@ -15,7 +15,8 @@ export async function loader({ request, params }: LoaderArgs) {
const { partId } = params;
if (!partId) throw new Error("Could not find partId");
- const partSummary = await getPartSummary(client, partId);
+ const [partSummary] = await Promise.all([getPartSummary(client, partId)]);
+
if (partSummary.error) {
return redirect(
"/x/parts",
@@ -26,7 +27,9 @@ export async function loader({ request, params }: LoaderArgs) {
);
}
- return json(partSummary.data);
+ return json({
+ partSummary: partSummary.data,
+ });
}
export default function PartRoute() {
diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsx
index ebbc4ae655..98b2d1796f 100644
--- a/apps/carbon/app/routes/x+/part+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx
@@ -10,6 +10,7 @@ import {
getPartTypes,
getUnitOfMeasuresList,
} from "~/modules/parts";
+import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
export const meta: MetaFunction = () => ({
@@ -21,12 +22,14 @@ export async function loader({ request }: LoaderArgs) {
view: "parts",
});
- const [partGroups, unitOfMeasures] = await Promise.all([
+ const [partGroups, unitOfMeasures, locations] = await Promise.all([
getPartGroupsList(client),
getUnitOfMeasuresList(client),
+ getLocationsList(client),
]);
return {
+ locations: locations?.data ?? [],
partCostingMethods: getPartCostingMethods(),
partGroups: partGroups?.data ?? [],
partManufacturingPolicies: getPartManufacturingPolicies(),
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index 07a0ab4900..07dcc490c7 100644
--- a/apps/carbon/app/routes/x+/part+/new.tsx
+++ b/apps/carbon/app/routes/x+/part+/new.tsx
@@ -39,7 +39,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const partId = createPart.data[0]?.id;
+ const partId = createPart.data?.id;
return redirect(
`/x/part/${partId}`,
@@ -58,6 +58,9 @@ export default function PartsNewRoute() {
const initialValues = {
name: "",
description: "",
+ partType: "Inventory" as "Inventory",
+ replenishmentSystem: "Buy" as "Buy",
+ unitOfMeasureCode: "EA",
};
return (
diff --git a/apps/carbon/app/routes/x+/parts+/groups.new.tsx b/apps/carbon/app/routes/x+/parts+/groups.new.tsx
index b0e9319d72..9430e7e3da 100644
--- a/apps/carbon/app/routes/x+/parts+/groups.new.tsx
+++ b/apps/carbon/app/routes/x+/parts+/groups.new.tsx
@@ -60,7 +60,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const partGroupId = insertPartGroup.data[0]?.id;
+ const partGroupId = insertPartGroup.data?.id;
if (!partGroupId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/parts+/groups.tsx b/apps/carbon/app/routes/x+/parts+/groups.tsx
index c80a66020a..34d27b8759 100644
--- a/apps/carbon/app/routes/x+/parts+/groups.tsx
+++ b/apps/carbon/app/routes/x+/parts+/groups.tsx
@@ -1,13 +1,12 @@
import { VStack } from "@chakra-ui/react";
import type { 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 { Outlet, useLoaderData } from "@remix-run/react";
import { getAccountsList } from "~/modules/accounting";
import {
+ getPartGroups,
PartGroupsTable,
PartGroupsTableFilters,
- getPartGroups,
} from "~/modules/parts";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -34,6 +33,7 @@ export async function loader({ request }: LoaderArgs) {
}),
getAccountsList(client),
]);
+
if (partGroups.error) {
return redirect(
"/x/parts",
diff --git a/apps/carbon/app/routes/x+/parts+/uom.new.tsx b/apps/carbon/app/routes/x+/parts+/uom.new.tsx
index 48d61576eb..dbc0cd0501 100644
--- a/apps/carbon/app/routes/x+/parts+/uom.new.tsx
+++ b/apps/carbon/app/routes/x+/parts+/uom.new.tsx
@@ -51,7 +51,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const unitOfMeasureId = insertUnitOfMeasure.data[0]?.id;
+ const unitOfMeasureId = insertUnitOfMeasure.data?.id;
if (!unitOfMeasureId) {
return json(
{},
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 75d1866b3e..99a07cd697 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
@@ -3,11 +3,7 @@ import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import { useRouteData } from "~/hooks";
-import type {
- PurchaseOrder,
- PurchaseOrderApprovalStatus,
- PurchaseOrderType,
-} from "~/modules/purchasing";
+import type { PurchaseOrder } from "~/modules/purchasing";
import {
PurchaseOrderForm,
purchaseOrderValidator,
@@ -62,11 +58,6 @@ export async function action({ request, params }: ActionArgs) {
}
export default function PurchaseOrderBasicRoute() {
- const sharedPurchaseOrdersData = useRouteData<{
- purchaseOrderApprovalStatuses: PurchaseOrderApprovalStatus[];
- purchaseOrderTypes: PurchaseOrderType[];
- }>("/x/purchase-order");
-
const { orderId } = useParams();
const orderData = useRouteData<{ purchaseOrder: PurchaseOrder }>(
`/x/purchase-order/${orderId}`
@@ -81,20 +72,11 @@ export default function PurchaseOrderBasicRoute() {
supplierReference: orderData?.purchaseOrder?.supplierReference ?? "",
orderDate: orderData?.purchaseOrder?.orderDate ?? "",
type: orderData?.purchaseOrder?.type ?? "Draft",
- status: orderData?.purchaseOrder?.status ?? "Draft",
+ status: orderData?.purchaseOrder?.status ?? "Open",
receiptRequestedDate: orderData?.purchaseOrder?.receiptRequestedDate ?? "",
receiptPromisedDate: orderData?.purchaseOrder?.receiptPromisedDate ?? "",
notes: orderData?.purchaseOrder?.notes ?? "",
- closed: orderData?.purchaseOrder?.closed ?? false,
};
- return (
- <PurchaseOrderForm
- initialValues={initialValues}
- purchaseOrderApprovalStatuses={
- sharedPurchaseOrdersData?.purchaseOrderApprovalStatuses ?? []
- }
- purchaseOrderTypes={sharedPurchaseOrdersData?.purchaseOrderTypes ?? []}
- />
- );
+ return <PurchaseOrderForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.$lineId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.$lineId.tsx
index f46016f49b..86ce5ca64e 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.$lineId.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.$lineId.tsx
@@ -1,12 +1,10 @@
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 { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
import type { PurchaseOrderLineType } from "~/modules/purchasing";
-import { getPurchaseOrderLine } from "~/modules/purchasing";
import {
+ getPurchaseOrderLine,
PurchaseOrderLineForm,
purchaseOrderLineValidator,
upsertPurchaseOrderLine,
@@ -92,10 +90,6 @@ export async function action({ request, params }: ActionArgs) {
export default function EditPurchaseOrderLineRoute() {
const { purchaseOrderLine } = useLoaderData<typeof loader>();
- const sharedPurchaseOrdersData = useRouteData<{
- purchaseOrderLineTypes: PurchaseOrderLineType[];
- }>("/x/purchase-order");
-
const initialValues = {
id: purchaseOrderLine?.id ?? undefined,
purchaseOrderId: purchaseOrderLine?.purchaseOrderId ?? "",
@@ -103,6 +97,7 @@ export default function EditPurchaseOrderLineRoute() {
purchaseOrderLine?.purchaseOrderLineType ??
("Part" as PurchaseOrderLineType),
partId: purchaseOrderLine?.partId ?? "",
+ description: purchaseOrderLine?.description ?? "",
purchaseQuantity: purchaseOrderLine?.purchaseQuantity ?? 1,
unitPrice: purchaseOrderLine?.unitPrice ?? 0,
setupPrice: purchaseOrderLine?.setupPrice ?? 0,
@@ -110,12 +105,5 @@ export default function EditPurchaseOrderLineRoute() {
shelfId: purchaseOrderLine?.shelfId ?? "",
};
- return (
- <PurchaseOrderLineForm
- initialValues={initialValues}
- purchaseOrderLineTypes={
- sharedPurchaseOrdersData?.purchaseOrderLineTypes ?? []
- }
- />
- );
+ return <PurchaseOrderLineForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.delete.$lineId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.delete.$lineId.tsx
new file mode 100644
index 0000000000..7df13e2576
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.delete.$lineId.tsx
@@ -0,0 +1,84 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ deletePurchaseOrderLine,
+ getPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+ const { lineId, orderId } = params;
+ if (!lineId) throw notFound("lineId not found");
+ if (!orderId) throw notFound("orderId not found");
+
+ const purchaseOrderLine = await getPurchaseOrderLine(client, lineId);
+ if (purchaseOrderLine.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}/lines`,
+ await flash(
+ request,
+ error(purchaseOrderLine.error, "Failed to get purchase order line")
+ )
+ );
+ }
+
+ return json({ purchaseOrderLine: purchaseOrderLine.data });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { lineId, orderId } = params;
+ if (!lineId) throw notFound("Could not find lineId");
+ if (!orderId) throw notFound("Could not find orderId");
+
+ const { error: deleteTypeError } = await deletePurchaseOrderLine(
+ client,
+ lineId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ `/x/purchase-order/${orderId}/lines`,
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete purchase order line")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/purchase-order/${orderId}/lines`,
+ await flash(request, success("Successfully deleted purchase order line"))
+ );
+}
+
+export default function DeletePurchaseOrderLineRoute() {
+ const { lineId, orderId } = useParams();
+ const { purchaseOrderLine } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!lineId || !orderId || !purchaseOrderLine) return null; // TODO - handle this better (404?)
+
+ const onCancel = () => navigate(`/x/purchase-order/${orderId}/lines`);
+
+ return (
+ <ConfirmDelete
+ action={`/x/purchase-order/${orderId}/lines/delete/${lineId}`}
+ name="Purchase Order Line"
+ text={`Are you sure you want to delete the purchase order line for ${
+ purchaseOrderLine.purchaseQuantity ?? 0
+ } ${purchaseOrderLine.description ?? ""}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx
index 9876cb8763..65458f858b 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx
@@ -2,7 +2,6 @@ import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
import type { PurchaseOrderLineType } from "~/modules/purchasing";
import {
PurchaseOrderLineForm,
@@ -56,9 +55,6 @@ export async function action({ request, params }: ActionArgs) {
export default function NewPurchaseOrderLineRoute() {
const { orderId } = useParams();
- const sharedPurchaseOrdersData = useRouteData<{
- purchaseOrderLineTypes: PurchaseOrderLineType[];
- }>("/x/purchase-order");
if (!orderId) throw new Error("Could not find purchase order id");
@@ -73,12 +69,5 @@ export default function NewPurchaseOrderLineRoute() {
shelfId: "",
};
- return (
- <PurchaseOrderLineForm
- initialValues={initialValues}
- purchaseOrderLineTypes={
- sharedPurchaseOrdersData?.purchaseOrderLineTypes ?? []
- }
- />
- );
+ return <PurchaseOrderLineForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
index 1ba53f192e..d1fb668570 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
@@ -1,5 +1,5 @@
import { Grid } from "@chakra-ui/react";
-import type { LoaderArgs } from "@remix-run/node";
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import {
@@ -9,6 +9,7 @@ import {
PurchaseOrderHeader,
PurchaseOrderSidebar,
} from "~/modules/purchasing";
+import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { error } from "~/utils/result";
@@ -21,11 +22,12 @@ export async function loader({ request, params }: LoaderArgs) {
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
- const [purchaseOrder, externalDocuments, internalDocuments] =
+ const [purchaseOrder, externalDocuments, internalDocuments, locations] =
await Promise.all([
getPurchaseOrder(client, orderId),
getExternalDocuments(client, orderId),
getInternalDocuments(client, orderId),
+ getLocationsList(client),
]);
if (purchaseOrder.error) {
@@ -42,16 +44,21 @@ export async function loader({ request, params }: LoaderArgs) {
purchaseOrder: purchaseOrder.data,
externalDocuments: externalDocuments.data ?? [],
internalDocuments: internalDocuments.data ?? [],
+ locations: locations.data ?? [],
});
}
+export async function action({ request }: ActionArgs) {
+ return redirect(request.headers.get("Referer") ?? request.url);
+}
+
export default function PurchaseOrderRoute() {
return (
<>
<PurchaseOrderHeader />
<Grid
gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}
- gridColumnGap={4}
+ gridGap={4}
w="full"
>
<PurchaseOrderSidebar />
diff --git a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
index e3846763bd..11542d7845 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
@@ -1,44 +1,11 @@
import { VStack } from "@chakra-ui/react";
-import type { LoaderArgs, MetaFunction } from "@remix-run/node";
+import type { MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
-import {
- getPurchaseOrderApprovalStatuses,
- getPurchaseOrderLineTypes,
- getPurchaseOrderTypes,
-} from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth";
-
export const meta: MetaFunction = () => ({
title: "Carbon | Purchasing",
});
-export async function loader({ request }: LoaderArgs) {
- await requirePermissions(request, {
- view: "purchasing",
- });
-
- // const [paymentTerms] = await Promise.all([
- // getPaymentTermsList(client),
- // ]);
-
- // if (paymentTerms.error) {
- // return redirect(
- // "/x/purchasing/orders",
- // await flash(
- // request,
- // error(paymentTerms.error, "Failed to load payment terms")
- // )
- // );
- // }
-
- return {
- purchaseOrderApprovalStatuses: getPurchaseOrderApprovalStatuses(),
- purchaseOrderLineTypes: getPurchaseOrderLineTypes(),
- purchaseOrderTypes: getPurchaseOrderTypes(),
- };
-}
-
export default function PurchaseOrderRoute() {
return (
<VStack w="full" h="full" spacing={4} p={4}>
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
index 0fa7fe128c..e059482c4a 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -3,9 +3,9 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
+import { useUrlParams } from "~/hooks";
import type {
- PurchaseOrderApprovalStatus,
+ PurchaseOrderStatus,
PurchaseOrderType,
} from "~/modules/purchasing";
import {
@@ -74,16 +74,14 @@ export async function action({ request }: ActionArgs) {
}
export default function PurchaseOrderNewRoute() {
- const routeData = useRouteData<{
- purchaseOrderApprovalStatuses: PurchaseOrderApprovalStatus[];
- purchaseOrderTypes: PurchaseOrderType[];
- }>("/x/purchase-order");
-
+ const [params] = useUrlParams();
+ const supplierId = params.get("supplierId");
const initialValues = {
id: undefined,
purchaseOrderId: undefined,
+ supplierId: supplierId ?? undefined,
orderDate: today(getLocalTimeZone()).toString(),
- status: "Draft" as PurchaseOrderApprovalStatus,
+ status: "Open" as PurchaseOrderStatus,
type: "Purchase" as PurchaseOrderType,
};
@@ -92,10 +90,6 @@ export default function PurchaseOrderNewRoute() {
<PurchaseOrderForm
// @ts-expect-error
initialValues={initialValues}
- purchaseOrderApprovalStatuses={
- routeData?.purchaseOrderApprovalStatuses ?? []
- }
- purchaseOrderTypes={routeData?.purchaseOrderTypes ?? []}
/>
</Box>
);
diff --git a/apps/carbon/app/routes/x+/purchasing+/supplier-types.new.tsx b/apps/carbon/app/routes/x+/purchasing+/supplier-types.new.tsx
index e8a714cbed..03471edae5 100644
--- a/apps/carbon/app/routes/x+/purchasing+/supplier-types.new.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/supplier-types.new.tsx
@@ -50,7 +50,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const supplierTypeId = insertSupplierType.data[0]?.id;
+ const supplierTypeId = insertSupplierType.data?.id;
if (!supplierTypeId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
index 87e32e9783..c74fdd4637 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
@@ -39,7 +39,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const supplierId = createSupplier.data[0]?.id;
+ const supplierId = createSupplier.data?.id;
return redirect(
`/x/purchasing/suppliers/${supplierId}`,
diff --git a/apps/carbon/app/routes/x+/resources+/abilities.new.tsx b/apps/carbon/app/routes/x+/resources+/abilities.new.tsx
index d407112a35..165c914a03 100644
--- a/apps/carbon/app/routes/x+/resources+/abilities.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/abilities.new.tsx
@@ -68,7 +68,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const abilityId = createAbility.data[0]?.id;
+ const abilityId = createAbility.data?.id;
if (!abilityId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/sales+/customer-types.new.tsx b/apps/carbon/app/routes/x+/sales+/customer-types.new.tsx
index 8f5705a7fd..fc5b4c4d0a 100644
--- a/apps/carbon/app/routes/x+/sales+/customer-types.new.tsx
+++ b/apps/carbon/app/routes/x+/sales+/customer-types.new.tsx
@@ -50,7 +50,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const customerTypeId = insertCustomerType.data[0]?.id;
+ const customerTypeId = insertCustomerType.data?.id;
if (!customerTypeId) {
return json(
{},
diff --git a/apps/carbon/app/routes/x+/sales+/customers.new.tsx b/apps/carbon/app/routes/x+/sales+/customers.new.tsx
index e7dbc2f838..c0d9b92fc3 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.new.tsx
+++ b/apps/carbon/app/routes/x+/sales+/customers.new.tsx
@@ -39,7 +39,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const customerId = createCustomer.data[0]?.id;
+ const customerId = createCustomer.data?.id;
return redirect(
`/x/sales/customers/${customerId}`,
diff --git a/apps/carbon/app/routes/x+/users+/employee-types.new.tsx b/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
index 1b8a5f6315..bdc14ef55e 100644
--- a/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/employee-types.new.tsx
@@ -78,7 +78,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const employeeTypeId = createEmployeeType.data[0]?.id;
+ const employeeTypeId = createEmployeeType.data?.id;
if (!employeeTypeId) {
return json(
{},
@@ -123,10 +123,5 @@ export default function NewEmployeeTypesRoute() {
permissions,
};
- return (
- <EmployeeTypeForm
- //@ts-expect-error
- initialValues={initialValues}
- />
- );
+ return <EmployeeTypeForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/users+/groups.new.tsx b/apps/carbon/app/routes/x+/users+/groups.new.tsx
index 24bee2fd0c..16e52d4b5c 100644
--- a/apps/carbon/app/routes/x+/users+/groups.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/groups.new.tsx
@@ -36,7 +36,7 @@ export async function action({ request }: ActionArgs) {
);
}
- const groupId = createGroup.data[0]?.id;
+ const groupId = createGroup.data?.id;
if (!groupId) {
return json(
{},
diff --git a/apps/carbon/app/utils/query.ts b/apps/carbon/app/utils/query.ts
index 55608ce5cf..758ff9106e 100644
--- a/apps/carbon/app/utils/query.ts
+++ b/apps/carbon/app/utils/query.ts
@@ -127,8 +127,8 @@ export function setGenericQueryFilters<
});
}
- if (args.offset && args.limit) {
- query = query.range(args.offset, args.offset + args.limit - 1);
+ if (Number.isInteger(args.offset) && Number.isInteger(args.limit)) {
+ query = query.range(args.offset!, args.offset! + args.limit! - 1);
}
return query;
diff --git a/apps/carbon/public/android-chrome-192x192.png b/apps/carbon/public/android-chrome-192x192.png
new file mode 100644
index 0000000000..777cc381ef
Binary files /dev/null and b/apps/carbon/public/android-chrome-192x192.png differ
diff --git a/apps/carbon/public/android-chrome-512x512.png b/apps/carbon/public/android-chrome-512x512.png
new file mode 100644
index 0000000000..bd3fb48e59
Binary files /dev/null and b/apps/carbon/public/android-chrome-512x512.png differ
diff --git a/apps/carbon/public/apple-touch-icon.png b/apps/carbon/public/apple-touch-icon.png
new file mode 100644
index 0000000000..4f8712f2c1
Binary files /dev/null and b/apps/carbon/public/apple-touch-icon.png differ
diff --git a/apps/carbon/public/carbon-logo-dark.png b/apps/carbon/public/carbon-logo-dark.png
new file mode 100644
index 0000000000..75399c8d11
Binary files /dev/null and b/apps/carbon/public/carbon-logo-dark.png differ
diff --git a/apps/carbon/public/carbon-logo-light.png b/apps/carbon/public/carbon-logo-light.png
new file mode 100644
index 0000000000..c0f93e6fe2
Binary files /dev/null and b/apps/carbon/public/carbon-logo-light.png differ
diff --git a/apps/carbon/public/favicon-16x16.png b/apps/carbon/public/favicon-16x16.png
new file mode 100644
index 0000000000..eb216e453f
Binary files /dev/null and b/apps/carbon/public/favicon-16x16.png differ
diff --git a/apps/carbon/public/favicon-32x32.png b/apps/carbon/public/favicon-32x32.png
new file mode 100644
index 0000000000..a7064d2122
Binary files /dev/null and b/apps/carbon/public/favicon-32x32.png differ
diff --git a/apps/carbon/public/favicon.ico b/apps/carbon/public/favicon.ico
new file mode 100644
index 0000000000..ce92de6710
Binary files /dev/null and b/apps/carbon/public/favicon.ico differ
diff --git a/apps/carbon/public/serviceWorker.js b/apps/carbon/public/serviceWorker.js
new file mode 100644
index 0000000000..790bcf811a
--- /dev/null
+++ b/apps/carbon/public/serviceWorker.js
@@ -0,0 +1,31 @@
+self.addEventListener("fetch", (event) => {
+ let url = new URL(event.request.url);
+ let method = event.request.method;
+
+ // any non GET request is ignored
+ if (method.toLowerCase() !== "get") return;
+
+ // If the request is for the favicons, fonts, or the built files (which are hashed in the name)
+ if (
+ url.pathname.includes("logo") ||
+ url.pathname.includes("storage/v1/object/public/avatars")
+ ) {
+ event.respondWith(
+ // we will open the assets cache
+ caches.open("assets").then(async (cache) => {
+ // if the request is cached we will use the cache
+ let cacheResponse = await cache.match(event.request);
+ if (cacheResponse) return cacheResponse;
+
+ // if it's not cached we will run the fetch, cache it and return it
+ // this way the next time this asset it's needed it will load from the cache
+ let fetchResponse = await fetch(event.request);
+ cache.put(event.request, fetchResponse.clone());
+
+ return fetchResponse;
+ })
+ );
+ }
+
+ return;
+});
diff --git a/apps/carbon/public/site.webmanifest b/apps/carbon/public/site.webmanifest
new file mode 100644
index 0000000000..4e209ea8a1
--- /dev/null
+++ b/apps/carbon/public/site.webmanifest
@@ -0,0 +1,19 @@
+{
+ "name": "Carbon",
+ "short_name": "Carbon",
+ "icons": [
+ {
+ "src": "/android-chrome-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ },
+ {
+ "src": "/android-chrome-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ],
+ "theme_color": "#ffffff",
+ "background_color": "#ffffff",
+ "display": "standalone"
+}
diff --git a/apps/carbon/public/static/grid.svg b/apps/carbon/public/static/grid.svg
new file mode 100644
index 0000000000..76e3b29f0d
--- /dev/null
+++ b/apps/carbon/public/static/grid.svg
@@ -0,0 +1,5 @@
+
+<svg id="download" xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
+ <path id="Path_3" data-name="Path 3" d="M96,95h4v1H96v4H95V96H86v4H85V96H76v4H75V96H66v4H65V96H56v4H55V96H46v4H45V96H36v4H35V96H26v4H25V96H16v4H15V96H0V95H15V86H0V85H15V76H0V75H15V66H0V65H15V56H0V55H15V46H0V45H15V36H0V35H15V26H0V25H15V16H0V15H15V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h9V0h1V15h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96v9h4v1H96Zm-1,0V86H86v9ZM85,95V86H76v9ZM75,95V86H66v9ZM65,95V86H56v9ZM55,95V86H46v9ZM45,95V86H36v9ZM35,95V86H26v9ZM25,95V86H16v9ZM16,85h9V76H16Zm10,0h9V76H26Zm10,0h9V76H36Zm10,0h9V76H46Zm10,0h9V76H56Zm10,0h9V76H66Zm10,0h9V76H76Zm10,0h9V76H86Zm9-10V66H86v9ZM85,75V66H76v9ZM75,75V66H66v9ZM65,75V66H56v9ZM55,75V66H46v9ZM45,75V66H36v9ZM35,75V66H26v9ZM25,75V66H16v9ZM16,65h9V56H16Zm10,0h9V56H26Zm10,0h9V56H36Zm10,0h9V56H46Zm10,0h9V56H56Zm10,0h9V56H66Zm10,0h9V56H76Zm10,0h9V56H86Zm9-10V46H86v9ZM85,55V46H76v9ZM75,55V46H66v9ZM65,55V46H56v9ZM55,55V46H46v9ZM45,55V46H36v9ZM35,55V46H26v9ZM25,55V46H16v9ZM16,45h9V36H16Zm10,0h9V36H26Zm10,0h9V36H36Zm10,0h9V36H46Zm10,0h9V36H56Zm10,0h9V36H66Zm10,0h9V36H76Zm10,0h9V36H86Zm9-10V26H86v9ZM85,35V26H76v9ZM75,35V26H66v9ZM65,35V26H56v9ZM55,35V26H46v9ZM45,35V26H36v9ZM35,35V26H26v9ZM25,35V26H16v9ZM16,25h9V16H16Zm10,0h9V16H26Zm10,0h9V16H36Zm10,0h9V16H46Zm10,0h9V16H56Zm10,0h9V16H66Zm10,0h9V16H76Zm10,0h9V16H86Z" fill="rgba(255,255,255,0.1)" fill-rule="evenodd" opacity="0.5"/>
+ <path id="Path_4" data-name="Path 4" d="M6,5V0H5V5H0V6H5v94H6V6h94V5Z" fill="rgba(255,255,255,0.1)" fill-rule="evenodd"/>
+</svg>
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index 442f5bb2c8..db9aaa7910 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -75,11 +75,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "abilities_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "abilities_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "abilities_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -160,11 +172,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "account_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "account_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "account_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -206,11 +230,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "accountCategory_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "accountCategory_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "accountCategory_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -264,11 +300,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "accountSubcategory_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "accountSubcategory_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "accountSubcategory_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -450,6 +498,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "contractor_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "contractor_id_fkey";
columns: ["id"];
@@ -461,6 +515,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "contractor_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -507,6 +567,12 @@ export interface Database {
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "contractorAbility_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -560,6 +626,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "crew_crewLeaderId_fkey";
+ columns: ["crewLeaderId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "crew_groupId_fkey";
columns: ["groupId"];
@@ -655,11 +727,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "currency_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "currency_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "currency_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -710,12 +794,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "customer_accountManagerId_fkey";
+ columns: ["accountManagerId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "customer_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "customer_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "customer_customerStatusId_fkey";
columns: ["customerStatusId"];
@@ -733,6 +829,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customer_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -761,6 +863,12 @@ export interface Database {
columns: ["id"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customerAccount_id_fkey";
+ columns: ["id"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -810,6 +918,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customerContact_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -985,11 +1099,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "document_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "document_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "document_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1024,6 +1150,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "documentFavorites_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1061,6 +1193,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "documentLabels_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1104,6 +1242,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "documentTransaction_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1132,6 +1276,12 @@ export interface Database {
columns: ["id"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "employee_id_fkey";
+ columns: ["id"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1175,6 +1325,12 @@ export interface Database {
columns: ["employeeId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "employeeAbilities_employeeId_fkey";
+ columns: ["employeeId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1222,18 +1378,36 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeJob_id_fkey";
+ columns: ["id"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "employeeJob_locationId_fkey";
columns: ["locationId"];
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeJob_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "employeeJob_managerId_fkey";
columns: ["managerId"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeJob_managerId_fkey";
+ columns: ["managerId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "employeeJob_shiftId_fkey";
columns: ["shiftId"];
@@ -1271,6 +1445,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "employeeShift_employeeId_fkey";
+ columns: ["employeeId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "employeeShift_shiftId_fkey";
columns: ["shiftId"];
@@ -1408,6 +1588,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "equipment_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "equipment_equipmentTypeId_fkey";
columns: ["equipmentTypeId"];
@@ -1420,12 +1606,24 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "equipment_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "equipment_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "equipment_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "equipment_workCellId_fkey";
columns: ["workCellId"];
@@ -1478,6 +1676,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "equipmentType_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "equipmentType_requiredAbility_fkey";
columns: ["requiredAbility"];
@@ -1489,6 +1693,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "equipmentType_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1648,11 +1858,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "holiday_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "holiday_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "holiday_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1747,6 +1969,12 @@ export interface Database {
columns: ["memberUserId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "membership_memberUserId_fkey";
+ columns: ["memberUserId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1818,12 +2046,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "part_approvedBy_fkey";
+ columns: ["approvedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "part_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "part_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "part_partGroupId_fkey";
columns: ["partGroupId"];
@@ -1841,6 +2081,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "part_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -1906,6 +2152,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partGroup_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partGroup_discountAccountId_fkey";
columns: ["discountAccountId"];
@@ -1947,6 +2199,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partGroup_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2057,6 +2315,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partGroup_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partGroup_discountAccountId_fkey";
columns: ["discountAccountId"];
@@ -2098,6 +2362,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partGroup_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2105,33 +2375,27 @@ export interface Database {
Row: {
createdAt: string;
createdBy: string;
+ defaultShelfId: string | null;
+ locationId: string;
partId: string;
- shelfId: string | null;
- stockoutWarning: boolean;
- unitVolume: number;
- unitWeight: number;
updatedAt: string | null;
updatedBy: string | null;
};
Insert: {
createdAt?: string;
createdBy: string;
+ defaultShelfId?: string | null;
+ locationId: string;
partId: string;
- shelfId?: string | null;
- stockoutWarning?: boolean;
- unitVolume?: number;
- unitWeight?: number;
updatedAt?: string | null;
updatedBy?: string | null;
};
Update: {
createdAt?: string;
createdBy?: string;
+ defaultShelfId?: string | null;
+ locationId?: string;
partId?: string;
- shelfId?: string | null;
- stockoutWarning?: boolean;
- unitVolume?: number;
- unitWeight?: number;
updatedAt?: string | null;
updatedBy?: string | null;
};
@@ -2142,6 +2406,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partInventory_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
+ {
+ foreignKeyName: "partInventory_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "location";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partInventory_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partInventory_partId_fkey";
columns: ["partId"];
@@ -2156,15 +2438,21 @@ export interface Database {
},
{
foreignKeyName: "partInventory_shelfId_fkey";
- columns: ["shelfId"];
+ columns: ["defaultShelfId", "locationId"];
referencedRelation: "shelf";
- referencedColumns: ["id"];
+ referencedColumns: ["id", "locationId"];
},
{
foreignKeyName: "partInventory_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partInventory_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2236,6 +2524,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partLedger_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partLedger_partId_fkey";
columns: ["partId"];
@@ -2250,9 +2544,9 @@ export interface Database {
},
{
foreignKeyName: "partLedger_shelfId_fkey";
- columns: ["shelfId"];
+ columns: ["shelfId", "locationId"];
referencedRelation: "shelf";
- referencedColumns: ["id"];
+ referencedColumns: ["id", "locationId"];
}
];
};
@@ -2291,6 +2585,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partner_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partner_id_fkey";
columns: ["id"];
@@ -2302,6 +2602,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partner_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2337,6 +2643,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partnerAbility_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partnerAbility_partnerId_fkey";
columns: ["partnerId"];
@@ -2359,16 +2671,15 @@ export interface Database {
demandAccumulationIncludesInventory: boolean;
demandAccumulationPeriod: number;
demandReschedulingPeriod: number;
+ locationId: string;
maximumOrderQuantity: number;
minimumOrderQuantity: number;
orderMultiple: number;
partId: string;
reorderingPolicy: Database["public"]["Enums"]["partReorderingPolicy"];
reorderMaximumInventory: number;
- reorderOverflowLevel: number;
reorderPoint: number;
reorderQuantity: number;
- reorderTimeBucket: number;
safetyStockLeadTime: number;
safetyStockQuantity: number;
updatedAt: string | null;
@@ -2381,16 +2692,15 @@ export interface Database {
demandAccumulationIncludesInventory?: boolean;
demandAccumulationPeriod?: number;
demandReschedulingPeriod?: number;
+ locationId: string;
maximumOrderQuantity?: number;
minimumOrderQuantity?: number;
orderMultiple?: number;
partId: string;
reorderingPolicy?: Database["public"]["Enums"]["partReorderingPolicy"];
reorderMaximumInventory?: number;
- reorderOverflowLevel?: number;
reorderPoint?: number;
reorderQuantity?: number;
- reorderTimeBucket?: number;
safetyStockLeadTime?: number;
safetyStockQuantity?: number;
updatedAt?: string | null;
@@ -2403,16 +2713,15 @@ export interface Database {
demandAccumulationIncludesInventory?: boolean;
demandAccumulationPeriod?: number;
demandReschedulingPeriod?: number;
+ locationId?: string;
maximumOrderQuantity?: number;
minimumOrderQuantity?: number;
orderMultiple?: number;
partId?: string;
reorderingPolicy?: Database["public"]["Enums"]["partReorderingPolicy"];
reorderMaximumInventory?: number;
- reorderOverflowLevel?: number;
reorderPoint?: number;
reorderQuantity?: number;
- reorderTimeBucket?: number;
safetyStockLeadTime?: number;
safetyStockQuantity?: number;
updatedAt?: string | null;
@@ -2425,6 +2734,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partPlanning_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
+ {
+ foreignKeyName: "partPlanning_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "location";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partPlanning_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "partPlanning_partId_fkey";
columns: ["partId"];
@@ -2442,6 +2769,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partPlanning_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2507,6 +2840,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partReplenishment_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partReplenishment_partId_fkey";
columns: ["partId"];
@@ -2560,6 +2899,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partReplenishment_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2613,6 +2958,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partSupplier_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partSupplier_partId_fkey";
columns: ["partId"];
@@ -2660,6 +3011,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partSupplier_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2710,6 +3067,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "partUnitSalePrice_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "partUnitSalePrice_currencyCode_fkey";
columns: ["currencyCode"];
@@ -2739,6 +3102,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "partUnitSalePrice_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2789,17 +3158,28 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "paymentTerm_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "paymentTerm_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "paymentTerm_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
purchaseOrder: {
Row: {
- closed: boolean;
closedAt: string | null;
closedBy: string | null;
createdAt: string;
@@ -2808,7 +3188,7 @@ export interface Database {
notes: string | null;
orderDate: string;
purchaseOrderId: string;
- status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ status: Database["public"]["Enums"]["purchaseOrderStatus"];
supplierContactId: string | null;
supplierId: string;
supplierReference: string | null;
@@ -2817,7 +3197,6 @@ export interface Database {
updatedBy: string | null;
};
Insert: {
- closed?: boolean;
closedAt?: string | null;
closedBy?: string | null;
createdAt?: string;
@@ -2826,7 +3205,7 @@ export interface Database {
notes?: string | null;
orderDate?: string;
purchaseOrderId: string;
- status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ status?: Database["public"]["Enums"]["purchaseOrderStatus"];
supplierContactId?: string | null;
supplierId: string;
supplierReference?: string | null;
@@ -2835,7 +3214,6 @@ export interface Database {
updatedBy?: string | null;
};
Update: {
- closed?: boolean;
closedAt?: string | null;
closedBy?: string | null;
createdAt?: string;
@@ -2844,7 +3222,7 @@ export interface Database {
notes?: string | null;
orderDate?: string;
purchaseOrderId?: string;
- status?: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
+ status?: Database["public"]["Enums"]["purchaseOrderStatus"];
supplierContactId?: string | null;
supplierId?: string;
supplierReference?: string | null;
@@ -2859,12 +3237,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrder_closedBy_fkey";
+ columns: ["closedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "purchaseOrder_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrder_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "purchaseOrder_supplierContactId_fkey";
columns: ["supplierContactId"];
@@ -2906,6 +3296,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrder_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -2989,6 +3385,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrderDelivery_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "purchaseOrderDelivery_shippingMethodId_fkey";
columns: ["shippingMethodId"];
@@ -3006,6 +3408,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrderDelivery_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3040,6 +3448,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrderFavorites_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3052,10 +3466,15 @@ export interface Database {
description: string | null;
id: string;
invoiceComplete: boolean;
+ locationId: string | null;
partId: string | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity: number | null;
+ quantityInvoiced: number | null;
+ quantityReceived: number | null;
+ quantityToInvoice: number | null;
+ quantityToReceive: number | null;
receivedComplete: boolean;
requiresInspection: boolean;
setupPrice: number | null;
@@ -3073,10 +3492,15 @@ export interface Database {
description?: string | null;
id?: string;
invoiceComplete?: boolean;
+ locationId?: string | null;
partId?: string | null;
purchaseOrderId: string;
purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
+ quantityInvoiced?: number | null;
+ quantityReceived?: number | null;
+ quantityToInvoice?: number | null;
+ quantityToReceive?: number | null;
receivedComplete?: boolean;
requiresInspection?: boolean;
setupPrice?: number | null;
@@ -3094,10 +3518,15 @@ export interface Database {
description?: string | null;
id?: string;
invoiceComplete?: boolean;
+ locationId?: string | null;
partId?: string | null;
purchaseOrderId?: string;
purchaseOrderLineType?: Database["public"]["Enums"]["purchaseOrderLineType"];
purchaseQuantity?: number | null;
+ quantityInvoiced?: number | null;
+ quantityReceived?: number | null;
+ quantityToInvoice?: number | null;
+ quantityToReceive?: number | null;
receivedComplete?: boolean;
requiresInspection?: boolean;
setupPrice?: number | null;
@@ -3126,6 +3555,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrderLine_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "purchaseOrderLine_partId_fkey";
columns: ["partId"];
@@ -3152,9 +3587,9 @@ export interface Database {
},
{
foreignKeyName: "purchaseOrderLine_shelfId_fkey";
- columns: ["shelfId"];
+ columns: ["shelfId", "locationId"];
referencedRelation: "shelf";
- referencedColumns: ["id"];
+ referencedColumns: ["id", "locationId"];
},
{
foreignKeyName: "purchaseOrderLine_unitOfMeasureCode_fkey";
@@ -3167,6 +3602,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrderLine_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3313,6 +3754,245 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrderTransaction_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ }
+ ];
+ };
+ receipt: {
+ Row: {
+ createdAt: string;
+ createdBy: string;
+ id: string;
+ locationId: string | null;
+ postingDate: string | null;
+ receiptId: string;
+ sourceDocument:
+ | Database["public"]["Enums"]["receiptSourceDocument"]
+ | null;
+ sourceDocumentId: string | null;
+ sourceDocumentReadableId: string | null;
+ supplierId: string | null;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ };
+ Insert: {
+ createdAt?: string;
+ createdBy: string;
+ id?: string;
+ locationId?: string | null;
+ postingDate?: string | null;
+ receiptId: string;
+ sourceDocument?:
+ | Database["public"]["Enums"]["receiptSourceDocument"]
+ | null;
+ sourceDocumentId?: string | null;
+ sourceDocumentReadableId?: string | null;
+ supplierId?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ };
+ Update: {
+ createdAt?: string;
+ createdBy?: string;
+ id?: string;
+ locationId?: string | null;
+ postingDate?: string | null;
+ receiptId?: string;
+ sourceDocument?:
+ | Database["public"]["Enums"]["receiptSourceDocument"]
+ | null;
+ sourceDocumentId?: string | null;
+ sourceDocumentReadableId?: string | null;
+ supplierId?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "receipt_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receipt_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
+ {
+ foreignKeyName: "receipt_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "location";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receipt_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
+ {
+ 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"];
+ },
+ {
+ foreignKeyName: "receipt_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receipt_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ }
+ ];
+ };
+ receiptLine: {
+ Row: {
+ createdAt: string;
+ createdBy: string;
+ id: string;
+ lineId: string | null;
+ locationId: string | null;
+ orderQuantity: number;
+ outstandingQuantity: number;
+ partId: string;
+ receiptId: string;
+ receivedQuantity: number;
+ shelfId: string | null;
+ unitOfMeasure: string;
+ unitPrice: number;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ };
+ Insert: {
+ createdAt?: string;
+ createdBy: string;
+ id?: string;
+ lineId?: string | null;
+ locationId?: string | null;
+ orderQuantity: number;
+ outstandingQuantity?: number;
+ partId: string;
+ receiptId: string;
+ receivedQuantity?: number;
+ shelfId?: string | null;
+ unitOfMeasure: string;
+ unitPrice: number;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ };
+ Update: {
+ createdAt?: string;
+ createdBy?: string;
+ id?: string;
+ lineId?: string | null;
+ locationId?: string | null;
+ orderQuantity?: number;
+ outstandingQuantity?: number;
+ partId?: string;
+ receiptId?: string;
+ receivedQuantity?: number;
+ shelfId?: string | null;
+ unitOfMeasure?: string;
+ unitPrice?: number;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receiptLine_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
+ {
+ foreignKeyName: "receiptLine_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "location";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receiptLine_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
+ {
+ foreignKeyName: "receiptLine_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "part";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receiptLine_partId_fkey";
+ columns: ["partId"];
+ referencedRelation: "parts_view";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receiptLine_receiptId_fkey";
+ columns: ["receiptId"];
+ referencedRelation: "receipt";
+ referencedColumns: ["receiptId"];
+ },
+ {
+ foreignKeyName: "receiptLine_shelfId_fkey";
+ columns: ["shelfId", "locationId"];
+ referencedRelation: "shelf";
+ referencedColumns: ["id", "locationId"];
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "receiptLine_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3386,6 +4066,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "sequence_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3395,7 +4081,7 @@ export interface Database {
createdAt: string;
createdBy: string;
id: string;
- locationId: string | null;
+ locationId: string;
updatedAt: string | null;
updatedBy: string | null;
warehouseId: string | null;
@@ -3405,7 +4091,7 @@ export interface Database {
createdAt?: string;
createdBy: string;
id: string;
- locationId?: string | null;
+ locationId: string;
updatedAt?: string | null;
updatedBy?: string | null;
warehouseId?: string | null;
@@ -3415,7 +4101,7 @@ export interface Database {
createdAt?: string;
createdBy?: string;
id?: string;
- locationId?: string | null;
+ locationId?: string;
updatedAt?: string | null;
updatedBy?: string | null;
warehouseId?: string | null;
@@ -3427,18 +4113,36 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shelf_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "shelf_locationId_fkey";
columns: ["locationId"];
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shelf_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "shelf_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shelf_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "shelf_warehouseId_fkey";
columns: ["warehouseId"];
@@ -3499,6 +4203,12 @@ export interface Database {
columns: ["locationId"];
referencedRelation: "location";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "shifts_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
}
];
};
@@ -3558,11 +4268,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shippingMethod_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "shippingMethod_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "shippingMethod_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3601,11 +4323,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "shippingTerm_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "shippingTerm_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "shippingTerm_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3668,12 +4402,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "supplier_accountManagerId_fkey";
+ columns: ["accountManagerId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "supplier_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "supplier_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "supplier_defaultPaymentTermId_fkey";
columns: ["defaultPaymentTermId"];
@@ -3709,6 +4455,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplier_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3732,6 +4484,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "supplierAccount_id_fkey";
+ columns: ["id"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "supplierAccount_supplierId_fkey";
columns: ["supplierId"];
@@ -3834,6 +4592,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "supplierContact_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -3978,11 +4742,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "unitOfMeasure_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "unitOfMeasure_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "unitOfMeasure_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4084,12 +4860,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttribute_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttribute_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttribute_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttribute_userAttributeCategoryId_fkey";
columns: ["userAttributeCategoryId"];
@@ -4139,11 +4927,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttributeCategory_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttributeCategory_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "userAttributeCategory_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4197,12 +4997,24 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttributeValue_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttributeValue_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttributeValue_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttributeValue_userAttributeId_fkey";
columns: ["userAttributeId"];
@@ -4215,11 +5027,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "userAttributeValue_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "userAttributeValue_valueUser_fkey";
columns: ["valueUser"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "userAttributeValue_valueUser_fkey";
+ columns: ["valueUser"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4261,11 +5085,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "notes_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "notes_userId_fkey";
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "notes_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4404,17 +5240,35 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "warehouse_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "warehouse_locationId_fkey";
columns: ["locationId"];
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "warehouse_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "warehouse_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "warehouse_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4477,6 +5331,12 @@ export interface Database {
referencedRelation: "location";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "workCell_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ },
{
foreignKeyName: "workCell_workCellTypeId_fkey";
columns: ["workCellTypeId"];
@@ -4529,6 +5389,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "workCellType_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "workCellType_requiredAbility_fkey";
columns: ["requiredAbility"];
@@ -4540,6 +5406,12 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "workCellType_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4586,11 +5458,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "accountCategory_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "accountCategory_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "accountCategory_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4677,11 +5561,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "account_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "account_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "account_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4717,6 +5613,12 @@ export interface Database {
columns: ["userId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "documentLabels_userId_fkey";
+ columns: ["userId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4750,11 +5652,23 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "document_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "document_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "document_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4791,6 +5705,12 @@ export interface Database {
columns: ["memberUserId"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "membership_memberUserId_fkey";
+ columns: ["memberUserId"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
@@ -4881,7 +5801,6 @@ export interface Database {
};
purchase_order_view: {
Row: {
- closed: boolean | null;
closedAt: string | null;
closedByAvatar: string | null;
closedByFullName: string | null;
@@ -4893,15 +5812,14 @@ export interface Database {
favorite: boolean | null;
id: string | null;
lineCount: number | null;
+ locationId: string | null;
locationName: string | null;
notes: string | null;
orderDate: string | null;
purchaseOrderId: string | null;
receiptPromisedDate: string | null;
receiptRequestedDate: string | null;
- status:
- | Database["public"]["Enums"]["purchaseOrderApprovalStatus"]
- | null;
+ status: Database["public"]["Enums"]["purchaseOrderStatus"] | null;
supplierContactId: string | null;
supplierId: string | null;
supplierName: string | null;
@@ -4919,6 +5837,12 @@ export interface Database {
referencedRelation: "user";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrder_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ },
{
foreignKeyName: "purchaseOrder_supplierContactId_fkey";
columns: ["supplierContactId"];
@@ -4960,9 +5884,23 @@ export interface Database {
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "purchaseOrder_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
}
];
};
+ receipt_quantity_received_by_line: {
+ Row: {
+ lineId: string | null;
+ receivedQuantity: number | null;
+ sourceDocumentId: string | null;
+ };
+ Relationships: [];
+ };
suppliers_view: {
Row: {
id: string | null;
@@ -4989,6 +5927,26 @@ export interface Database {
}
];
};
+ user_default_view: {
+ Row: {
+ locationId: string | null;
+ userId: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "employeeJob_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "location";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "employeeJob_locationId_fkey";
+ columns: ["locationId"];
+ referencedRelation: "purchase_order_view";
+ referencedColumns: ["locationId"];
+ }
+ ];
+ };
};
Functions: {
_xid_machine_id: {
@@ -5216,14 +6174,15 @@ export interface Database {
partReplenishmentSystem: "Buy" | "Make" | "Buy and Make";
partType: "Inventory" | "Non-Inventory" | "Service";
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month";
- purchaseOrderApprovalStatus:
- | "Draft"
+ purchaseOrderLineType: "Comment" | "G/L Account" | "Part" | "Fixed Asset";
+ purchaseOrderStatus:
+ | "Open"
| "In Review"
| "In External Review"
| "Approved"
| "Rejected"
- | "Confirmed";
- purchaseOrderLineType: "Comment" | "G/L Account" | "Part" | "Fixed Asset";
+ | "Released"
+ | "Closed";
purchaseOrderTransactionType:
| "Edit"
| "Favorite"
@@ -5232,6 +6191,15 @@ export interface Database {
| "Reject"
| "Request Approval";
purchaseOrderType: "Draft" | "Purchase" | "Return";
+ receiptSourceDocument:
+ | "Sales Order"
+ | "Sales Return Order"
+ | "Purchase Order"
+ | "Purchase Return Order"
+ | "Inbound Transfer"
+ | "Outbound Transfer"
+ | "Manufacturing Consumption"
+ | "Manufacturing Output";
searchEntity:
| "Resource"
| "Person"
diff --git a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
index 4e0b0adbc3..f5428edc8f 100644
--- a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
+++ b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
@@ -105,7 +105,7 @@ CREATE VIEW "contractors_view" AS
ON s.id = sc."supplierId"
INNER JOIN "contact" c
ON c.id = sc."contactId"
- INNER JOIN "contractorAbility" pa
+ LEFT JOIN "contractorAbility" pa
ON pa."contractorId" = p.id
WHERE p."active" = true
GROUP BY p.id, p.active, p."hoursPerWeek", s.id, c.id, s.name, c."firstName", c."lastName", c."email"
diff --git a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
index 5e714d1d3b..0b4d735438 100644
--- a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
@@ -168,7 +168,7 @@ CREATE TABLE "part" (
CONSTRAINT "part_pkey" PRIMARY KEY ("id"),
CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL,
+ CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id"),
CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
CONSTRAINT "part_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
@@ -231,12 +231,6 @@ BEGIN
INSERT INTO public."partReplenishment"("partId", "createdBy")
VALUES (new.id, new."createdBy");
- INSERT INTO public."partPlanning"("partId", "createdBy")
- VALUES (new.id, new."createdBy");
-
- INSERT INTO public."partInventory"("partId", "createdBy")
- VALUES (new.id, new."createdBy");
-
INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")
-- TODO: get default currency
VALUES (new.id, 'USD', new."createdBy");
@@ -610,7 +604,7 @@ CREATE TABLE "warehouse" (
CREATE TABLE "shelf" (
"id" TEXT NOT NULL,
- "locationId" TEXT,
+ "locationId" TEXT NOT NULL,
"warehouseId" TEXT,
"active" BOOLEAN NOT NULL DEFAULT true,
"createdBy" TEXT NOT NULL,
@@ -618,14 +612,14 @@ CREATE TABLE "shelf" (
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "shelf_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shelf_pkey" PRIMARY KEY ("id", "locationId"),
CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,
CONSTRAINT "shelf_warehouseId_fkey" FOREIGN KEY ("warehouseId") REFERENCES "warehouse"("id") ON DELETE CASCADE,
CONSTRAINT "shelf_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "shelf_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "shelf_locationId_index" ON "shelf" ("locationId");
+CREATE INDEX "shelf_id_locationId_index" ON "shelf" ("id", "locationId");
CREATE INDEX "shelf_warehouseId_index" ON "shelf" ("warehouseId");
ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;
@@ -661,6 +655,7 @@ CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"
CREATE TABLE "partPlanning" (
"partId" TEXT NOT NULL,
+ "locationId" TEXT NOT NULL,
"reorderingPolicy" "partReorderingPolicy" NOT NULL DEFAULT 'Demand-Based Reorder',
"critical" BOOLEAN NOT NULL DEFAULT false,
"safetyStockQuantity" INTEGER NOT NULL DEFAULT 0,
@@ -671,8 +666,6 @@ CREATE TABLE "partPlanning" (
"reorderPoint" INTEGER NOT NULL DEFAULT 0,
"reorderQuantity" INTEGER NOT NULL DEFAULT 0,
"reorderMaximumInventory" INTEGER NOT NULL DEFAULT 0,
- "reorderOverflowLevel" INTEGER NOT NULL DEFAULT 0,
- "reorderTimeBucket" INTEGER NOT NULL DEFAULT 5,
"minimumOrderQuantity" INTEGER NOT NULL DEFAULT 0,
"maximumOrderQuantity" INTEGER NOT NULL DEFAULT 0,
"orderMultiple" INTEGER NOT NULL DEFAULT 1,
@@ -681,12 +674,15 @@ CREATE TABLE "partPlanning" (
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "partPlanning_partId_locationId_key" UNIQUE ("partId", "locationId"),
CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "partPlanning_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "partPlanning_partId_index" ON "partPlanning" ("partId");
+CREATE INDEX "partPlanning_partId_locationId_index" ON "partPlanning" ("partId", "locationId");
ALTER TABLE "partPlanning" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning"
@@ -696,6 +692,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+-- these are records are created lazily when a user attempts to view them
+CREATE POLICY "Employees with part_view can insert part planning" ON "partPlanning"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with parts_update can update part planning" ON "partPlanning"
FOR UPDATE
USING (
@@ -706,24 +710,23 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partPla
CREATE TABLE "partInventory" (
"partId" TEXT NOT NULL,
- "shelfId" TEXT,
- "stockoutWarning" BOOLEAN NOT NULL DEFAULT true,
- "unitVolume" NUMERIC(15,5) NOT NULL DEFAULT 0,
- "unitWeight" NUMERIC(15,5) NOT NULL DEFAULT 0,
+ "locationId" TEXT NOT NULL,
+ "defaultShelfId" TEXT,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
"updatedAt" TIMESTAMP WITH TIME ZONE,
- CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),
+ CONSTRAINT "partInventory_partId_locationId_key" UNIQUE ("partId", "locationId"),
CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,
+ CONSTRAINT "partInventory_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("defaultShelfId", "locationId") REFERENCES "shelf"("id", "locationId") ON DELETE SET NULL,
CONSTRAINT "partInventory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partInventory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
-CREATE INDEX "partInventory_partId_index" ON "partInventory" ("partId");
-CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("shelfId");
+CREATE INDEX "partInventory_partId_locationId_index" ON "partInventory" ("partId", "locationId");
+CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("defaultShelfId");
ALTER TABLE "partInventory" ENABLE ROW LEVEL SECURITY;
@@ -734,6 +737,14 @@ CREATE POLICY "Employees with part_view can view part planning" ON "partInventor
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+-- these are records are created lazily when a user attempts to view them
+CREATE POLICY "Employees with part_view can insert part planning" ON "partInventory"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with parts_update can update part planning" ON "partInventory"
FOR UPDATE
USING (
diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
index c8b03f5101..546378e71d 100644
--- a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
@@ -160,26 +160,26 @@ CREATE TYPE "purchaseOrderType" AS ENUM (
'Return'
);
-CREATE TYPE "purchaseOrderApprovalStatus" AS ENUM (
- 'Draft',
+CREATE TYPE "purchaseOrderStatus" AS ENUM (
+ 'Open',
'In Review',
'In External Review',
'Approved',
'Rejected',
- 'Confirmed'
+ 'Released',
+ 'Closed'
);
CREATE TABLE "purchaseOrder" (
"id" TEXT NOT NULL DEFAULT xid(),
"purchaseOrderId" TEXT NOT NULL,
"type" "purchaseOrderType" NOT NULL,
- "status" "purchaseOrderApprovalStatus" NOT NULL,
+ "status" "purchaseOrderStatus" NOT NULL DEFAULT 'Open',
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
"supplierContactId" TEXT,
"supplierReference" TEXT,
- "closed" BOOLEAN NOT NULL DEFAULT FALSE,
"closedAt" DATE,
"closedBy" TEXT,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
@@ -199,6 +199,7 @@ CREATE TABLE "purchaseOrder" (
CREATE INDEX "purchaseOrder_purchaseOrderId_idx" ON "purchaseOrder" ("purchaseOrderId");
CREATE INDEX "purchaseOrder_supplierId_idx" ON "purchaseOrder" ("supplierId");
CREATE INDEX "purchaseOrder_supplierContactId_idx" ON "purchaseOrder" ("supplierContactId");
+CREATE INDEX "purchaseOrder_status_idx" ON "purchaseOrder" ("status");
CREATE TYPE "purchaseOrderLineType" AS ENUM (
'Comment',
@@ -216,8 +217,13 @@ CREATE TABLE "purchaseOrderLine" (
"assetId" TEXT,
"description" TEXT,
"purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
+ "quantityToReceive" NUMERIC(9,2) DEFAULT 0,
+ "quantityReceived" NUMERIC(9,2) DEFAULT 0,
+ "quantityToInvoice" NUMERIC(9,2) DEFAULT 0,
+ "quantityInvoiced" NUMERIC(9,2) DEFAULT 0,
"unitPrice" NUMERIC(9,2),
"unitOfMeasureCode" TEXT,
+ "locationId" TEXT,
"shelfId" TEXT,
"setupPrice" NUMERIC(9,2),
"receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
@@ -262,7 +268,7 @@ CREATE TABLE "purchaseOrderLine" (
CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,
-- TODO: Add assetId foreign key
- CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "purchaseOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
@@ -387,6 +393,7 @@ CREATE VIEW "purchase_order_view" AS
pd."receiptPromisedDate",
pd."dropShipment",
pol."lineCount",
+ l."id" AS "locationId",
l."name" AS "locationName",
s."name" AS "supplierName",
u."avatarUrl" AS "createdByAvatar",
@@ -396,7 +403,6 @@ CREATE VIEW "purchase_order_view" AS
u2."avatarUrl" AS "updatedByAvatar",
u2."fullName" AS "updatedByFullName",
p."updatedAt",
- p."closed",
p."closedAt",
u3."avatarUrl" AS "closedByAvatar",
u3."fullName" AS "closedByFullName",
diff --git a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
index 88e9610133..189dcc4407 100644
--- a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
+++ b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
@@ -17,5 +17,5 @@ CREATE TABLE "sequence" (
);
INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
-VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 5, 1);
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 6, 1);
diff --git a/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql b/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql
index a1fda2f6d3..d37df15238 100644
--- a/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql
+++ b/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql
@@ -152,7 +152,7 @@ CREATE TABLE "partLedger" (
CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),
CONSTRAINT "partLedger_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT "partLedger_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,
- CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON UPDATE CASCADE ON DELETE SET NULL
+ CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf"("id", "locationId") ON UPDATE CASCADE ON DELETE SET NULL
);
ALTER TABLE "partLedger" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/carbon-database/supabase/migrations/20230728025201_receipts.sql b/packages/carbon-database/supabase/migrations/20230728025201_receipts.sql
new file mode 100644
index 0000000000..d95b9df03c
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230728025201_receipts.sql
@@ -0,0 +1,80 @@
+CREATE TYPE "receiptSourceDocument" AS ENUM (
+ 'Sales Order',
+ 'Sales Return Order',
+ 'Purchase Order',
+ 'Purchase Return Order',
+ 'Inbound Transfer',
+ 'Outbound Transfer',
+ 'Manufacturing Consumption',
+ 'Manufacturing Output'
+);
+
+CREATE TABLE "receipt" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "receiptId" TEXT NOT NULL,
+ "locationId" TEXT,
+ "sourceDocument" "receiptSourceDocument",
+ "sourceDocumentId" TEXT,
+ "sourceDocumentReadableId" TEXT,
+ "supplierId" TEXT,
+ "postingDate" DATE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "receipt_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "receipt_receiptId_key" UNIQUE ("receiptId"),
+ CONSTRAINT "receipt_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receipt_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receipt_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receipt_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX "receipt_receiptId_idx" ON "receipt" ("receiptId");
+CREATE INDEX "receipt_locationId_idx" ON "receipt" ("locationId");
+CREATE INDEX "receipt_sourceDocumentId_idx" ON "receipt" ("sourceDocumentId");
+CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId");
+
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
+VALUES ('receipt', 'Receipt', 'RE', NULL, 0, 6, 1);
+
+CREATE TABLE "receiptLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "receiptId" TEXT NOT NULL,
+ "lineId" TEXT,
+ "partId" TEXT NOT NULL,
+ "orderQuantity" NUMERIC(18, 4) NOT NULL,
+ "outstandingQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,
+ "receivedQuantity" NUMERIC(18, 4) NOT NULL DEFAULT 0,
+ "locationId" TEXT,
+ "shelfId" TEXT,
+ "unitOfMeasure" TEXT NOT NULL,
+ "unitPrice" NUMERIC(18, 4) NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "receiptLine_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("receiptId") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receiptLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX "receiptLine_receiptId_idx" ON "receiptLine" ("receiptId");
+CREATE INDEX "receiptLine_lineId_idx" ON "receiptLine" ("lineId");
+CREATE INDEX "receiptLine_receiptId_lineId_idx" ON "receiptLine" ("receiptId", "lineId");
+
+CREATE VIEW "receipt_quantity_received_by_line" AS
+ SELECT
+ r."sourceDocumentId",
+ l."lineId",
+ SUM(l."receivedQuantity") AS "receivedQuantity"
+ FROM "receipt" r
+ 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/carbon-database/supabase/migrations/20230810035313_defaults.sql
new file mode 100644
index 0000000000..dc76b94029
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230810035313_defaults.sql
@@ -0,0 +1,6 @@
+CREATE VIEW "user_default_view" AS
+ SELECT
+ u.id as "userId",
+ ej."locationId"
+ FROM "user" u
+ LEFT JOIN "employeeJob" ej ON ej.id = u.id;
\ No newline at end of file
diff --git a/packages/carbon-react/src/Count/Count.tsx b/packages/carbon-react/src/Count/Count.tsx
index 1e392b9ac3..07e7e270da 100644
--- a/packages/carbon-react/src/Count/Count.tsx
+++ b/packages/carbon-react/src/Count/Count.tsx
@@ -1,4 +1,4 @@
-import { Box } from "@chakra-ui/react";
+import { Flex } from "@chakra-ui/react";
import type { BoxProps } from "@chakra-ui/react";
export interface CountProps extends BoxProps {
@@ -8,16 +8,18 @@ export interface CountProps extends BoxProps {
const Count = ({ count, ...props }: CountProps) => {
const c = count > 99 ? "99+" : count;
return (
- <Box
+ <Flex
as="span"
bg="gray.700"
borderRadius="full"
fontSize="sm"
- py={1}
- px={2}
+ h={5}
+ minW={5}
+ alignItems="center"
+ justifyContent="center"
color="white"
{...props}
- >{`${c}`}</Box>
+ >{`${c}`}</Flex>
);
};
diff --git a/packages/carbon-react/src/Inputs/Select/components/containers.tsx b/packages/carbon-react/src/Inputs/Select/components/containers.tsx
index 7bf826e817..52f3c8bf55 100644
--- a/packages/carbon-react/src/Inputs/Select/components/containers.tsx
+++ b/packages/carbon-react/src/Inputs/Select/components/containers.tsx
@@ -72,7 +72,7 @@ export const ValueContainer = <
isMulti,
hasValue,
innerProps,
- selectProps: { size, chakraStyles },
+ selectProps: { size, chakraStyles, isReadOnly },
} = props;
// Getting the css from input instead of select
@@ -91,6 +91,7 @@ export const ValueContainer = <
WebkitOverflowScrolling: "touch",
position: "relative",
overflow: "hidden",
+ bg: isReadOnly ? "gray.100" : undefined,
};
const sx = chakraStyles?.valueContainer
@@ -127,7 +128,7 @@ export const IndicatorsContainer = <
className,
cx,
innerProps,
- selectProps: { chakraStyles },
+ selectProps: { chakraStyles, isReadOnly },
} = props;
const initialSx: SystemStyleObject = {
@@ -135,6 +136,7 @@ export const IndicatorsContainer = <
alignItems: "center",
alignSelf: "stretch",
flexShrink: 0,
+ bg: isReadOnly ? "gray.100" : undefined,
};
const sx = chakraStyles?.indicatorsContainer
diff --git a/packages/carbon-react/src/Menu/Menubar.tsx b/packages/carbon-react/src/Menu/Menubar.tsx
new file mode 100644
index 0000000000..30b46fba6f
--- /dev/null
+++ b/packages/carbon-react/src/Menu/Menubar.tsx
@@ -0,0 +1,65 @@
+import type {
+ ButtonProps,
+ MenuButtonProps,
+ StackProps,
+} from "@chakra-ui/react";
+import { Button, HStack, MenuButton } from "@chakra-ui/react";
+import { forwardRef } from "react";
+import { MdExpandMore } from "react-icons/md";
+import { useColor } from "../hooks";
+
+const Menubar = forwardRef<HTMLDivElement, StackProps>(
+ ({ children, ...props }, ref) => {
+ const borderColor = useColor("gray.200");
+ return (
+ <HStack
+ ref={ref}
+ {...props}
+ alignItems="center"
+ bg="white"
+ borderWidth={1}
+ borderColor={borderColor}
+ borderRadius="md"
+ boxShadow="sm"
+ justifyContent="start"
+ p={1}
+ spacing={1}
+ w="full"
+ >
+ {children}
+ </HStack>
+ );
+ }
+);
+Menubar.displayName = "Menubar";
+
+const MenubarTrigger = forwardRef<HTMLButtonElement, MenuButtonProps>(
+ ({ children, ...props }, ref) => {
+ return (
+ <MenuButton
+ ref={ref}
+ as={Button}
+ size="sm"
+ variant="ghost"
+ rightIcon={<MdExpandMore />}
+ {...props}
+ >
+ {children}
+ </MenuButton>
+ );
+ }
+);
+MenubarTrigger.displayName = "MenubarTrigger";
+
+const MenubarItem = forwardRef<HTMLButtonElement, ButtonProps>(
+ ({ children, ...props }, ref) => {
+ return (
+ <Button ref={ref} size="sm" variant="ghost" {...props}>
+ {children}
+ </Button>
+ );
+ }
+);
+MenubarItem.displayName = "MenubarItem";
+
+export { Menubar, MenubarItem, MenubarTrigger };
diff --git a/packages/carbon-react/src/Menu/index.ts b/packages/carbon-react/src/Menu/index.ts
new file mode 100644
index 0000000000..44e02171c4
--- /dev/null
+++ b/packages/carbon-react/src/Menu/index.ts
@@ -0,0 +1,3 @@
+import { Menubar, MenubarItem, MenubarTrigger } from "./Menubar";
+
+export { Menubar, MenubarItem, MenubarTrigger };
diff --git a/packages/carbon-react/src/Theme/theme.ts b/packages/carbon-react/src/Theme/theme.ts
index cd303914be..be27e49d83 100644
--- a/packages/carbon-react/src/Theme/theme.ts
+++ b/packages/carbon-react/src/Theme/theme.ts
@@ -83,6 +83,12 @@ export const theme = {
overlay: {
backdropFilter: "blur(3px)",
},
+ header: {
+ borderColor: "gray.200",
+ borderBottomWidth: "1px",
+ borderBottomStyle: "solid",
+ marginBottom: 4,
+ },
footer: {
borderColor: "gray.200",
borderTopWidth: "1px",
@@ -115,6 +121,13 @@ export const theme = {
},
},
},
+ NumberInput: {
+ variants: {
+ outline: focusRingOutlined,
+ filled: focusRingFilled,
+ flushed: focusRingFlushed,
+ },
+ },
Radio: {
defaultProps: {
colorScheme: "blackAlpha",
@@ -135,6 +148,17 @@ export const theme = {
colorScheme: "green",
},
},
+ Tabs: {
+ variants: {
+ line: {
+ tab: {
+ _selected: {
+ color: "black",
+ },
+ },
+ },
+ },
+ },
Textarea: {
variants: {
outline: () => focusRingOutlined,
diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsx
index 924694c3de..170c3d6c0f 100644
--- a/packages/carbon-react/src/index.tsx
+++ b/packages/carbon-react/src/index.tsx
@@ -17,8 +17,9 @@ import {
useEditor,
} from "./Inputs";
import Loading from "./Loading";
-import { ActionMenu, ContextMenu } from "./Overlay";
+import { Menubar, MenubarItem, MenubarTrigger } from "./Menu";
import { useNotification } from "./Message";
+import { ActionMenu, ContextMenu } from "./Overlay";
import ThemeProvider, { theme } from "./Theme";
import { ClientOnly } from "./SSR";
import {
@@ -49,6 +50,9 @@ export {
File,
HTML,
Loading,
+ Menubar,
+ MenubarItem,
+ MenubarTrigger,
Select,
ThemeProvider,
TimePicker,