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.

Purchase Order Lines (#32)

Brad Barbin5d2207350c07
diff --git a/SCHEMA.md b/SCHEMA.md
index 039b5dd157..4051ad89a8 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -742,7 +742,6 @@ CREATE TABLE "supplierType" (
CREATE TABLE "supplier" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"name" TEXT NOT NULL,
- "description" TEXT,
"supplierTypeId" TEXT,
"supplierStatusId" TEXT,
"taxId" TEXT,
@@ -825,7 +824,6 @@ CREATE TABLE "customerType" (
CREATE TABLE "customer" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"name" TEXT NOT NULL,
- "description" TEXT,
"customerTypeId" TEXT,
"customerStatusId" TEXT,
"taxId" TEXT,
@@ -1493,29 +1491,18 @@ CREATE POLICY "Employees with sales_view can search for customers and sales orde
-- AND entity = 'Sales Order'
-- AND (get_my_claim('role'::text)) = '"customer"'::jsonb
-- AND uuid IN (
--- SELECT "customerId" FROM "salesOrder" WHERE "customerId" IN (
--- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
--- )
--- )
+-- SELECT id FROM "salesOrder" WHERE "customerId" IN (
+-- SELECT "customerId" FROM "salesOrder" WHERE "customerId" IN (
+-- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
-- )
CREATE POLICY "Employees with purchasing_view can search for suppliers and purchase orders" ON "search"
FOR SELECT
USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND entity IN ('Supplier', 'Purchase Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
--- TODO: suppliers should be able to search for their purchase orders
--- CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
--- FOR SELECT
--- USING (
--- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
--- AND entity = 'Purchase Order'
--- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
--- AND uuid IN (
--- SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
CREATE POLICY "Employees with resources_view can search for resources" ON "search"
FOR SELECT
@@ -2120,6 +2107,12 @@ CREATE POLICY "Employees with resources_delete can delete employeeAbilities" ON
CREATE TABLE "location" (
"id" TEXT NOT NULL DEFAULT xid(),
"name" TEXT NOT NULL,
+ "addressLine1" TEXT NOT NULL,
+ "addressLine2" TEXT,
+ "city" TEXT NOT NULL,
+ "state" TEXT NOT NULL,
+ "postalCode" TEXT NOT NULL,
+ "country" TEXT,
"timezone" TEXT NOT NULL,
"latitude" NUMERIC,
"longitude" NUMERIC,
@@ -2799,7 +2792,7 @@ CREATE TABLE "partnerAbility" (
CONSTRAINT "partnerAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
);
-CREATE VIEW "partners_query" AS
+CREATE VIEW "partners_view" AS
SELECT
p.id AS "supplierLocationId",
p."active",
@@ -2917,7 +2910,7 @@ CREATE POLICY "Employees with resources_delete can delete contractorAbilities" O
);
-CREATE VIEW "contractors_query" AS
+CREATE VIEW "contractors_view" AS
SELECT
p.id AS "supplierContactId",
p."active",
@@ -3522,12 +3515,96 @@ CREATE POLICY "Employees with parts_update can update part sale prices" ON "part
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+CREATE TABLE "partSupplier" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "partId" TEXT NOT NULL,
+ "supplierId" TEXT NOT NULL,
+ "supplierPartId" TEXT,
+ "supplierUnitOfMeasureCode" TEXT,
+ "minimumOrderQuantity" INTEGER DEFAULT 1,
+ "conversionFactor" NUMERIC(15,5) NOT NULL DEFAULT 1,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "partSupplier_id_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "partSupplier_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,
+ CONSTRAINT "partSupplier_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,
+ CONSTRAINT "partSupplier_part_supplier_unique" UNIQUE ("partId", "supplierId"),
+ CONSTRAINT "partSupplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "partSupplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX "partSupplier_partId_index" ON "partSupplier"("partId");
+
+ALTER TABLE "partSupplier" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with part_view can view part suppliers" ON "partSupplier"
+ FOR SELECT
+ USING (
+ 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 suppliers" ON "partSupplier"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('parts_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Employees with parts_create can create part suppliers" ON "partSupplier"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "partSupplier"
+ FOR DELETE
+ USING (
+ coalesce(get_my_claim('parts_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "partSupplier"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('parts_update')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Suppliers with parts_create can create part suppliers" ON "partSupplier"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
CREATE TABLE "partReplenishment" (
"partId" TEXT NOT NULL,
- "supplierId" TEXT,
- "supplierPartNumber" TEXT,
+ "preferredSupplierId" TEXT,
"purchasingLeadTime" INTEGER NOT NULL DEFAULT 0,
"purchasingUnitOfMeasureCode" TEXT,
+ "conversionFactor" NUMERIC(15,5) NOT NULL DEFAULT 1,
"purchasingBlocked" BOOLEAN NOT NULL DEFAULT false,
"manufacturingPolicy" "partManufacturingPolicy" NOT NULL DEFAULT 'Make to Stock',
"manufacturingLeadTime" INTEGER NOT NULL DEFAULT 0,
@@ -3541,14 +3618,14 @@ CREATE TABLE "partReplenishment" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,
- CONSTRAINT "partReplenishment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,
- CONSTRAINT "partReplenishment_purchaseUnitOfMeasureId_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,
+ CONSTRAINT "partReplenishment_preferredSupplierId_fkey" FOREIGN KEY ("preferredSupplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,
+ CONSTRAINT "partReplenishment_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,
CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
CREATE INDEX "partReplenishment_partId_index" ON "partReplenishment" ("partId");
-CREATE INDEX "partReplenishment_supplierId_index" ON "partReplenishment" ("supplierId");
+CREATE INDEX "partReplenishment_preferredSupplierId_index" ON "partReplenishment" ("preferredSupplierId");
ALTER TABLE "partReplenishment" ENABLE ROW LEVEL SECURITY;
@@ -3566,6 +3643,7 @@ CREATE POLICY "Employees with parts_update can update part costs" ON "partReplen
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+
CREATE POLICY "Suppliers with parts_view can view parts they created or supply" ON "part"
FOR SELECT
USING (
@@ -3575,7 +3653,7 @@ CREATE POLICY "Suppliers with parts_view can view parts they created or supply"
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -3599,7 +3677,7 @@ CREATE POLICY "Suppliers with parts_update can update parts that they created or
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -3616,7 +3694,7 @@ CREATE POLICY "Suppliers with parts_delete can delete parts that they created or
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -3631,7 +3709,7 @@ CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "pa
AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
AND (
"partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -3645,7 +3723,7 @@ CREATE POLICY "Suppliers with parts_update can update parts costs that they supp
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
AND (
"partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -3658,8 +3736,10 @@ CREATE POLICY "Suppliers with parts_view can view part replenishments they suppl
coalesce(get_my_claim('parts_view')::boolean, false) = true
AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
AND (
- "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ "partId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
)
)
);
@@ -3670,9 +3750,11 @@ CREATE POLICY "Suppliers with parts_update can update parts replenishments that
coalesce(get_my_claim('parts_update')::boolean, false) = true
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
AND (
- "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
+ "partId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
)
);
@@ -3806,33 +3888,33 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partInv
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
- FOR SELECT
- USING (
- coalesce(get_my_claim('parts_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
- AND (
- "partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
+-- CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
+-- FOR SELECT
+-- USING (
+-- coalesce(get_my_claim('parts_view')::boolean, false) = true
+-- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+-- AND (
+-- "partId" IN (
+-- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+-- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
+-- );
-CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
- FOR UPDATE
- USING (
- coalesce(get_my_claim('parts_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- AND (
- "partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
+-- CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
+-- FOR UPDATE
+-- USING (
+-- coalesce(get_my_claim('parts_update')::boolean, false) = true
+-- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+-- AND (
+-- "partId" IN (
+-- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+-- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
+-- );
```
@@ -4159,6 +4241,22 @@ CREATE TABLE "shippingMethod" (
CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");
+CREATE TABLE "shippingTerm" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "shippingTerm_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shippingTerm_name_key" UNIQUE ("name"),
+ CONSTRAINT "shippingTerm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "shippingTerm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+
CREATE TYPE "purchaseOrderType" AS ENUM (
'Draft',
'Purchase',
@@ -4180,27 +4278,10 @@ CREATE TABLE "purchaseOrder" (
"type" "purchaseOrderType" NOT NULL,
"status" "purchaseOrderApprovalStatus" NOT NULL,
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
- "orderDueDate" DATE,
- "receivedDate" DATE,
- "orderSubTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderTax" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderDiscount" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderShipping" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
"supplierContactId" TEXT,
"supplierReference" TEXT,
- "invoiceSupplierId" TEXT,
- "invoiceSupplierLocationId" TEXT,
- "invoiceSupplierContactId" TEXT,
- "paymentTermId" TEXT,
- "shippingMethodId" TEXT,
- "currencyCode" TEXT NOT NULL,
- -- "approvalRequestDate" DATE,
- -- "approvalDecisionDate" DATE,
- -- "approvalDecisionUserId" TEXT,
- -- "approvalDecisionNotes" TEXT,
"closed" BOOLEAN NOT NULL DEFAULT FALSE,
"closedAt" DATE,
"closedBy" TEXT,
@@ -4213,13 +4294,6 @@ CREATE TABLE "purchaseOrder" (
CONSTRAINT "purchaseOrder_purchaseOrderId_key" UNIQUE ("purchaseOrderId"),
CONSTRAINT "purchaseOrder_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_supplierContactId_fkey" FOREIGN KEY ("supplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE,
- -- CONSTRAINT "purchaseOrder_approvalDecisionUserId_fkey" FOREIGN KEY ("approvalDecisionUserId") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_closedBy_fkey" FOREIGN KEY ("closedBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
@@ -4228,10 +4302,124 @@ 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_invoiceSupplierId_idx" ON "purchaseOrder" ("invoiceSupplierId");
-CREATE INDEX "purchaseOrder_invoiceSupplierLocationId_idx" ON "purchaseOrder" ("invoiceSupplierLocationId");
-CREATE INDEX "purchaseOrder_invoiceSupplierContactId_idx" ON "purchaseOrder" ("invoiceSupplierContactId");
--- CREATE INDEX "purchaseOrder_approvalDecisionUserId_idx" ON "purchaseOrder" ("approvalDecisionUserId");
+
+CREATE TYPE "purchaseOrderLineType" AS ENUM (
+ 'Comment',
+ 'G/L Account',
+ 'Part',
+ 'Fixed Asset'
+);
+
+CREATE TABLE "purchaseOrderLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "purchaseOrderLineType" "purchaseOrderLineType" NOT NULL,
+ "partId" TEXT,
+ "accountNumber" TEXT,
+ "assetId" TEXT,
+ "description" TEXT,
+ "purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
+ "unitPrice" NUMERIC(9,2),
+ "unitOfMeasureCode" TEXT,
+ "shelfId" TEXT,
+ "setupPrice" NUMERIC(9,2),
+ "receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "invoiceComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrderLineType_number"
+ CHECK (
+ (
+ "purchaseOrderLineType" = 'Comment' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NULL AND
+ "description" IS NOT NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'G/L Account' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NOT NULL AND
+ "assetId" IS NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'Part' AND
+ "partId" IS NOT NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'Fixed Asset' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NOT NULL
+ )
+ ),
+
+ CONSTRAINT "purchaseOrderLine_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderLine_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE,
+ -- TODO: Add assetId foreign key
+ CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE 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
+);
+
+CREATE TABLE "purchaseOrderPayment" (
+ "id" TEXT NOT NULL,
+ "invoiceSupplierId" TEXT,
+ "invoiceSupplierLocationId" TEXT,
+ "invoiceSupplierContactId" TEXT,
+ "paymentTermId" TEXT,
+ "paymentComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "currencyCode" TEXT NOT NULL DEFAULT 'USD',
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrderPayment_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderPayment_id_fkey" FOREIGN KEY ("id") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierId_idx" ON "purchaseOrderPayment" ("invoiceSupplierId");
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierLocationId_idx" ON "purchaseOrderPayment" ("invoiceSupplierLocationId");
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierContactId_idx" ON "purchaseOrderPayment" ("invoiceSupplierContactId");
+
+CREATE TABLE "purchaseOrderDelivery" (
+ "id" TEXT NOT NULL,
+ "locationId" TEXT,
+ "shippingMethodId" TEXT,
+ "shippingTermId" TEXT,
+ "receiptRequestedDate" DATE,
+ "receiptPromisedDate" DATE,
+ "deliveryDate" DATE,
+ "notes" TEXT,
+ "trackingNumber" TEXT,
+ "dropShipment" BOOLEAN NOT NULL DEFAULT FALSE,
+ "customerId" TEXT,
+ "customerLocationId" TEXT,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "purchaseOrderDelivery_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderDelivery_id_fkey" FOREIGN KEY ("id") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_shippingTermId_fkey" FOREIGN KEY ("shippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
CREATE TYPE "purchaseOrderTransactionType" AS ENUM (
'Edit',
@@ -4293,8 +4481,16 @@ CREATE VIEW "purchase_order_view" AS
p."status",
p."type",
p."orderDate",
- p."orderDueDate",
+ p."notes",
+ p."supplierId",
+ p."supplierContactId",
+ p."supplierReference",
p."createdBy",
+ pd."receiptRequestedDate",
+ pd."receiptPromisedDate",
+ pd."dropShipment",
+ pol."lineCount",
+ l."name" AS "locationName",
s."name" AS "supplierName",
u."avatarUrl" AS "createdByAvatar",
u."fullName" AS "createdByFullName",
@@ -4309,11 +4505,29 @@ CREATE VIEW "purchase_order_view" AS
u3."fullName" AS "closedByFullName",
EXISTS(SELECT 1 FROM "purchaseOrderFavorite" pf WHERE pf."purchaseOrderId" = p.id AND pf."userId" = auth.uid()::text) AS favorite
FROM "purchaseOrder" p
+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"
+ LEFT JOIN (
+ SELECT "purchaseOrderId", COUNT(*) AS "lineCount"
+ FROM "purchaseOrderLine"
+ GROUP BY "purchaseOrderId"
+ ) pol ON pol."purchaseOrderId" = p."id"
+ LEFT JOIN "location" l ON l."id" = pd."locationId"
LEFT JOIN "supplier" s ON s."id" = p."supplierId"
LEFT JOIN "user" u ON u."id" = p."createdBy"
LEFT JOIN "user" u2 ON u2."id" = p."updatedBy"
LEFT JOIN "user" u3 ON u3."id" = p."closedBy";
+ALTER TABLE "supplier"
+ ADD COLUMN "defaultCurrencyCode" TEXT,
+ ADD COLUMN "defaultPaymentTermId" TEXT,
+ ADD COLUMN "defaultShippingMethodId" TEXT,
+ ADD COLUMN "defaultShippingTermId" TEXT;
+
+ALTER TABLE "supplier"
+ ADD CONSTRAINT "supplier_defaultPaymentTermId_fkey" FOREIGN KEY ("defaultPaymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "supplier_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "supplier_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
+
```
@@ -4334,15 +4548,218 @@ CREATE TABLE "sequence" (
"updatedBy" TEXT,
CONSTRAINT "sequence_pkey" PRIMARY KEY ("table"),
- CONSTRAINT "sequence_next_check" CHECK ("next" >= 1),
+ CONSTRAINT "sequence_next_check" CHECK ("next" >= 0),
CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
CONSTRAINT "sequence_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
-VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 1, 5, 1);
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 5, 1);
+
+
+```
+
+
+
+## `purchasing-files`
+
+```sql
+INSERT INTO storage.buckets (id, name, public)
+VALUES
+ ('purchasing-internal', 'purchasing-internal', false),
+ ('purchasing-external', 'purchasing-external', false);
+
+-- Internal purchasing documents
+
+CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
+FOR SELECT USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
+FOR UPDATE USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
+FOR DELETE USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+-- External purchasing documents
+
+CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
+FOR SELECT USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
+FOR UPDATE USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
+FOR DELETE USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+```
+
+
+
+## `view-rls`
+
+```sql
+-- TODO: after Postgres 15, we can use security_invoker = on
+-- ALTER VIEW "contractors_view" SET (security_invoker = on);
+-- ALTER VIEW "partners_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_labels_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_view" SET (security_invoker = on);
+-- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
+```
+
+
+
+## `purchasing-rls`
+
+```sql
+ALTER TABLE "purchaseOrder" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purchaseOrder"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "purchaseOrder"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+CREATE POLICY "Employees with purchasing_create can create purchase orders" ON "purchaseOrder"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+
+CREATE POLICY "Employees with purchasing_update can update purchase orders" ON "purchaseOrder"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" ON "purchaseOrder"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase orders" ON "purchaseOrder"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+-- Search
+
+CREATE FUNCTION public.create_purchase_order_search_result()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public.search(name, entity, uuid, link)
+ VALUES (new."purchaseOrderId", 'Purchase Order', new.id, '/x/purchase-order/' || new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER create_purchase_order_search_result
+ AFTER INSERT on public."purchaseOrder"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_purchase_order_search_result();
+
+CREATE FUNCTION public.update_purchase_order_search_result()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF (old."purchaseOrderId" <> new."purchaseOrderId") THEN
+ UPDATE public.search SET name = new."purchaseOrderId"
+ WHERE entity = 'Purchase Order' AND uuid = new.id;
+ END IF;
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER update_purchase_order_search_result
+ AFTER UPDATE on public.customer
+ FOR EACH ROW EXECUTE PROCEDURE public.update_purchase_order_search_result();
+
+
+CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND entity = 'Purchase Order'
+ AND uuid IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
```
diff --git a/apps/carbon/app/components/Editable/EditableList.tsx b/apps/carbon/app/components/Editable/EditableList.tsx
new file mode 100644
index 0000000000..0f303f8bd0
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditableList.tsx
@@ -0,0 +1,51 @@
+/* eslint-disable react/display-name */
+import { Select } from "@carbon/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+
+const EditableList =
+ <T extends object>(
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: T
+ ) => Promise<PostgrestResponse<unknown>>,
+ options: { label: string; value: string }[]
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<T>) => {
+ const onChange = async ({ value }: { value: string; label: string }) => {
+ // this is the optimistic update on the FE
+ onUpdate(accessorKey, value);
+
+ // the is the actual update on the BE
+ mutation(accessorKey, value, row)
+ .then(({ error }) => {
+ if (error) {
+ onError();
+ onUpdate(accessorKey, value);
+ }
+ })
+ .catch(() => {
+ onError();
+ onUpdate(accessorKey, value);
+ });
+ };
+
+ return (
+ <Select
+ autoFocus
+ options={options}
+ // @ts-ignore
+ onChange={onChange}
+ size="sm"
+ />
+ );
+ };
+
+export default EditableList;
diff --git a/apps/carbon/app/components/Editable/EditableNumber.tsx b/apps/carbon/app/components/Editable/EditableNumber.tsx
new file mode 100644
index 0000000000..327d2bcfe1
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditableNumber.tsx
@@ -0,0 +1,66 @@
+/* eslint-disable react/display-name */
+import { NumberInput, NumberInputField } from "@chakra-ui/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { FocusEvent, KeyboardEvent } from "react";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+
+const EditableNumber =
+ <T extends object>(
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: T
+ ) => Promise<PostgrestResponse<unknown>>
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<T>) => {
+ const updateNumber = async (newValue: string) => {
+ const numberValue = Number(newValue);
+ // this is the optimistic update on the FE
+ onUpdate(accessorKey, numberValue);
+
+ // the is the actual update on the BE
+ // @ts-ignore
+ mutation(accessorKey, numberValue, row)
+ .then(({ error }) => {
+ if (error) {
+ onError();
+ onUpdate(accessorKey, numberValue);
+ }
+ })
+ .catch(() => {
+ onError();
+ onUpdate(accessorKey, numberValue);
+ });
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ // only run the update if they click enter
+ if (event.key === "Enter" || event.key === "Tab") {
+ if (event.currentTarget.value !== value) {
+ updateNumber(event.currentTarget.value);
+ }
+ }
+ };
+
+ // run update if focus is lost
+ const onBlur = (event: FocusEvent<HTMLInputElement>) => {
+ if (event.currentTarget.value !== value) {
+ updateNumber(event.currentTarget.value);
+ }
+ };
+
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ return (
+ <NumberInput defaultValue={value as number} size="sm" w="full">
+ <NumberInputField autoFocus onKeyDown={onKeyDown} onBlur={onBlur} />
+ </NumberInput>
+ );
+ };
+
+export default EditableNumber;
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
new file mode 100644
index 0000000000..124b8af3c3
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -0,0 +1,163 @@
+/* eslint-disable react/display-name */
+import type { Database } from "@carbon/database";
+import { Select } from "@carbon/react";
+import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+
+const EditablePurchaseOrderLineNumber =
+ (
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: PurchaseOrderLine
+ ) => Promise<PostgrestResponse<unknown>>,
+ options: {
+ client?: SupabaseClient<Database>;
+ parts: { label: string; value: string }[];
+ accounts: { label: string; value: string }[];
+ }
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<PurchaseOrderLine>) => {
+ const { client, parts, accounts } = options;
+ const selectOptions =
+ row.purchaseOrderLineType === "Part"
+ ? parts
+ : row.purchaseOrderLineType === "G/L Account"
+ ? accounts
+ : [];
+
+ const onAccountChange = async ({
+ value,
+ label,
+ }: {
+ value: string;
+ label: string;
+ }) => {
+ if (!client) throw new Error("Supabase client not found");
+
+ const account = await client
+ .from("account")
+ .select("name")
+ .eq("number", value)
+ .single();
+
+ onUpdate("description", account.data?.name ?? "");
+ onUpdate("partId", null);
+ onUpdate("assetId", null);
+ onUpdate("accountNumber", value);
+ onUpdate("unitOfMeasureCode", null);
+ onUpdate("shelfId", null);
+
+ try {
+ const { error } = await client
+ .from("purchaseOrderLine")
+ .update({
+ partId: null,
+ assetId: null,
+ accountNumber: value,
+ description: account.data?.name ?? "",
+ unitOfMeasureCode: null,
+ shelfId: null,
+ })
+ .eq("id", row.id);
+
+ if (error) onError();
+ } catch (error) {
+ console.error(error);
+ onError();
+ }
+ };
+
+ const onPartChange = async ({
+ value: partId,
+ }: {
+ value: string;
+ label: string;
+ }) => {
+ if (!client) throw new Error("Supabase client not found");
+ const [part, shelf, cost] = await Promise.all([
+ client
+ .from("part")
+ .select("name, unitOfMeasureCode")
+ .eq("id", partId)
+ .single(),
+ client
+ .from("partInventory")
+ .select("shelfId")
+ .eq("partId", partId)
+ .single(),
+ client
+ .from("partCost")
+ .select("unitCost")
+ .eq("partId", partId)
+ .single(),
+ ]);
+
+ if (part.error) {
+ onError();
+ return;
+ }
+
+ 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("unitPrice", cost.data?.unitCost ?? null);
+
+ try {
+ const { error } = await client
+ .from("purchaseOrderLine")
+ .update({
+ partId: partId,
+ assetId: null,
+ accountNumber: null,
+ description: part.data?.name,
+ unitOfMeasureCode: part.data?.unitOfMeasureCode ?? null,
+ shelfId: shelf.data?.shelfId ?? null,
+ unitPrice: cost.data?.unitCost ?? null,
+ })
+ .eq("id", row.id);
+
+ if (error) onError();
+ } catch (error) {
+ console.error(error);
+ onError();
+ }
+ };
+
+ const onChange = (newValue: { value: string; label: string } | null) => {
+ if (!newValue) return;
+
+ if (row.purchaseOrderLineType === "Part") {
+ onPartChange(newValue);
+ } else if (row.purchaseOrderLineType === "G/L Account") {
+ onAccountChange(newValue);
+ }
+ };
+
+ const controlledValue = selectOptions.find(
+ (option) => option.value === value
+ );
+
+ return (
+ <Select
+ autoFocus
+ value={controlledValue}
+ options={selectOptions}
+ onChange={onChange}
+ // @ts-ignore
+ size="sm"
+ />
+ );
+ };
+
+export default EditablePurchaseOrderLineNumber;
diff --git a/apps/carbon/app/components/Editable/EditableText.tsx b/apps/carbon/app/components/Editable/EditableText.tsx
new file mode 100644
index 0000000000..b40ae0fd96
--- /dev/null
+++ b/apps/carbon/app/components/Editable/EditableText.tsx
@@ -0,0 +1,69 @@
+/* eslint-disable react/display-name */
+import { Input } from "@chakra-ui/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import type { FocusEvent, KeyboardEvent } from "react";
+import type { EditableTableCellComponentProps } from "~/components/Editable";
+
+const EditableText =
+ <T extends object>(
+ mutation: (
+ accessorKey: string,
+ newValue: string,
+ row: T
+ ) => Promise<PostgrestResponse<unknown>>
+ ) =>
+ ({
+ value,
+ row,
+ accessorKey,
+ onError,
+ onUpdate,
+ }: EditableTableCellComponentProps<T>) => {
+ const updateText = async (newValue: string) => {
+ // this is the optimistic update on the FE
+ onUpdate(accessorKey, newValue);
+
+ // the is the actual update on the BE
+ mutation(accessorKey, newValue, row)
+ .then(({ error }) => {
+ if (error) {
+ onError();
+ onUpdate(accessorKey, value);
+ }
+ })
+ .catch(() => {
+ onError();
+ onUpdate(accessorKey, value);
+ });
+ };
+
+ const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ // only run the update if they click enter
+ if (event.key === "Enter" || event.key === "Tab") {
+ if (event.currentTarget.value !== value) {
+ updateText(event.currentTarget.value);
+ }
+ }
+ };
+
+ // run update if focus is lost
+ const onBlur = (event: FocusEvent<HTMLInputElement>) => {
+ if (event.currentTarget.value !== value) {
+ updateText(event.currentTarget.value);
+ }
+ };
+
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ return (
+ <Input
+ autoFocus
+ defaultValue={value as string}
+ size="sm"
+ w="full"
+ onBlur={onBlur}
+ onKeyDown={onKeyDown}
+ />
+ );
+ };
+
+export default EditableText;
diff --git a/apps/carbon/app/components/Editable/index.ts b/apps/carbon/app/components/Editable/index.ts
new file mode 100644
index 0000000000..517e1b9a3f
--- /dev/null
+++ b/apps/carbon/app/components/Editable/index.ts
@@ -0,0 +1,12 @@
+import EditableList from "./EditableList";
+import EditableNumber from "./EditableNumber";
+import EditablePurchaseOrderLineNumber from "./EditablePurchaseOrderLineNumber";
+import EditableText from "./EditableText";
+
+export {
+ EditableList,
+ EditableNumber,
+ EditablePurchaseOrderLineNumber,
+ EditableText,
+};
+export * from "./types";
diff --git a/apps/carbon/app/components/Editable/types.ts b/apps/carbon/app/components/Editable/types.ts
new file mode 100644
index 0000000000..848313fd18
--- /dev/null
+++ b/apps/carbon/app/components/Editable/types.ts
@@ -0,0 +1,20 @@
+export type EditableTableCellComponent<TData> = (
+ props: EditableTableCellComponentProps<TData>
+) => JSX.Element;
+
+export type EditableTableCellComponentProps<T> = {
+ value: unknown;
+ row: T;
+ accessorKey: string;
+ onUpdate: (columnId: string, value: unknown) => void;
+ onError: () => void;
+};
+
+export type Position = null | { row: number; column: number };
+
+declare module "@tanstack/react-table" {
+ interface TableMeta<TData> {
+ editableComponents?: Record<string, EditableTableCellComponent<TData>>;
+ updateData?: (rowIndex: number, columnId: string, value: unknown) => void;
+ }
+}
diff --git a/apps/carbon/app/components/Form/Abilities.tsx b/apps/carbon/app/components/Form/Abilities.tsx
index a93bee2afc..5309ffa10a 100644
--- a/apps/carbon/app/components/Form/Abilities.tsx
+++ b/apps/carbon/app/components/Form/Abilities.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -74,8 +73,7 @@ const Abilities = ({
[value, options]
);
- // TODO: hack for default value
- return abilityFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
{value.map((selection, index) => (
@@ -102,16 +100,6 @@ const Abilities = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Ability.tsx b/apps/carbon/app/components/Form/Ability.tsx
index 4efd52165d..8e918239bc 100644
--- a/apps/carbon/app/components/Form/Ability.tsx
+++ b/apps/carbon/app/components/Form/Ability.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -74,8 +73,7 @@ const Ability = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return abilityFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<input type="hidden" name={name} id={name} value={value} />
@@ -94,16 +92,6 @@ const Ability = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Account.tsx b/apps/carbon/app/components/Form/Account.tsx
new file mode 100644
index 0000000000..a0390473bc
--- /dev/null
+++ b/apps/carbon/app/components/Form/Account.tsx
@@ -0,0 +1,100 @@
+import { Select } from "@carbon/react";
+import {
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { getAccountsList } from "~/modules/accounting";
+import type { SelectProps } from "./Select";
+
+type AccountSelectProps = Omit<SelectProps, "options"> & {
+ account?: string;
+};
+
+const Account = ({
+ name,
+ label = "Account",
+ account,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Account",
+ onChange,
+ ...props
+}: AccountSelectProps) => {
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const accountFetcher =
+ useFetcher<Awaited<ReturnType<typeof getAccountsList>>>();
+
+ useEffect(() => {
+ accountFetcher.load("/api/accounting/accounts");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = useMemo(
+ () =>
+ accountFetcher.data?.data
+ ? accountFetcher.data?.data.map((c) => ({
+ value: c.number,
+ label: c.name,
+ }))
+ : [],
+ [accountFetcher.data]
+ );
+
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [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>}
+ <input type="hidden" name={name} id={name} value={value} />
+ <Select
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+};
+
+Account.displayName = "Account";
+
+export default Account;
diff --git a/apps/carbon/app/components/Form/Boolean.tsx b/apps/carbon/app/components/Form/Boolean.tsx
index 0695393d70..2f353a552f 100644
--- a/apps/carbon/app/components/Form/Boolean.tsx
+++ b/apps/carbon/app/components/Form/Boolean.tsx
@@ -14,14 +14,15 @@ import {
import { forwardRef, useMemo } from "react";
import { useControlField, useField } from "remix-validated-form";
-type FormBooleanProps = SwitchProps & {
+type FormBooleanProps = Omit<SwitchProps, "onChange"> & {
name: string;
label?: string;
description?: string;
+ onChange?: (value: boolean) => void;
};
const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(
- ({ name, label, description, ...props }, ref) => {
+ ({ name, label, description, onChange, ...props }, ref) => {
const { getInputProps, error } = useField(name);
const [value, setValue] = useControlField<boolean>(name);
@@ -72,11 +73,15 @@ const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(
<input
ref={ref}
type="checkbox"
+ disabled={props.isDisabled}
{...getInputProps({
type: "checkbox",
id: name,
})}
- onChange={(e) => setValue(e.target.checked)}
+ onChange={(e) => {
+ setValue(e.target.checked);
+ onChange?.(e.target.checked);
+ }}
/>
</VisuallyHidden>
<HStack>
diff --git a/apps/carbon/app/components/Form/CreatableMultiSelect.tsx b/apps/carbon/app/components/Form/CreatableMultiSelect.tsx
index 9fbedcb095..b29a9abb70 100644
--- a/apps/carbon/app/components/Form/CreatableMultiSelect.tsx
+++ b/apps/carbon/app/components/Form/CreatableMultiSelect.tsx
@@ -70,7 +70,6 @@ const Select = ({
value.some((v) => option.value === v)
) ?? [];
- // TODO: hack for default value
return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
diff --git a/apps/carbon/app/components/Form/CreatableSelect.tsx b/apps/carbon/app/components/Form/CreatableSelect.tsx
index ea4e1cc8cb..6514fcbb63 100644
--- a/apps/carbon/app/components/Form/CreatableSelect.tsx
+++ b/apps/carbon/app/components/Form/CreatableSelect.tsx
@@ -59,7 +59,6 @@ const Select = ({
(option) => option.value === value
);
- // TODO: hack for default value
return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
diff --git a/apps/carbon/app/components/Form/Currency.tsx b/apps/carbon/app/components/Form/Currency.tsx
index e895b5bc57..e305b74a03 100644
--- a/apps/carbon/app/components/Form/Currency.tsx
+++ b/apps/carbon/app/components/Form/Currency.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -74,8 +73,7 @@ const Currency = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return currencyFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<input type="hidden" name={name} id={name} value={value} />
@@ -94,16 +92,6 @@ const Currency = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Customer.tsx b/apps/carbon/app/components/Form/Customer.tsx
index 661cae6213..a4054a42bb 100644
--- a/apps/carbon/app/components/Form/Customer.tsx
+++ b/apps/carbon/app/components/Form/Customer.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -72,8 +71,7 @@ const Customer = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return customerFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<Select
@@ -97,17 +95,6 @@ const Customer = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- // @ts-ignore
- w="full"
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/CustomerContact.tsx b/apps/carbon/app/components/Form/CustomerContact.tsx
index 256a696a0d..55c29d6aa9 100644
--- a/apps/carbon/app/components/Form/CustomerContact.tsx
+++ b/apps/carbon/app/components/Form/CustomerContact.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -20,7 +19,7 @@ type CustomerContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {
const CustomerContact = ({
name,
- label = "CustomerContact",
+ label = "Customer Contact",
customer,
helperText,
isLoading,
@@ -93,8 +92,7 @@ const CustomerContact = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return customerContactFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<input type="hidden" name={name} id={name} value={value} />
@@ -114,11 +112,6 @@ const CustomerContact = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select isDisabled isLoading={isLoading} options={[]} />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/CustomerLocation.tsx b/apps/carbon/app/components/Form/CustomerLocation.tsx
new file mode 100644
index 0000000000..b5bdc0300a
--- /dev/null
+++ b/apps/carbon/app/components/Form/CustomerLocation.tsx
@@ -0,0 +1,120 @@
+import { Select } from "@carbon/react";
+import {
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { CustomerLocation as CustomerLocationType } from "~/modules/sales";
+import type { getCustomerLocations } from "~/modules/sales";
+import type { SelectProps } from "./Select";
+
+type CustomerLocationSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ customer?: string;
+ onChange?: (customerLocation: CustomerLocationType | undefined) => void;
+};
+
+const CustomerLocation = ({
+ name,
+ label = "Customer Location",
+ customer,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Customer Location",
+ onChange,
+ ...props
+}: CustomerLocationSelectProps) => {
+ const initialLoad = useRef(true);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const customerLocationFetcher =
+ useFetcher<Awaited<ReturnType<typeof getCustomerLocations>>>();
+
+ useEffect(() => {
+ customerLocationFetcher.load(
+ `/api/sales/customer-locations?customerId=${customer}`
+ );
+ if (initialLoad.current) {
+ initialLoad.current = false;
+ } else {
+ setValue(undefined);
+ if (onChange) {
+ onChange(undefined);
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [customer]);
+
+ const options = useMemo(
+ () =>
+ customerLocationFetcher.data?.data
+ ? customerLocationFetcher.data?.data.map((c) => ({
+ value: c.id,
+ // @ts-ignore
+ label: `${c.address?.addressLine1} ${c.address?.city}, ${c.address?.state}`,
+ }))
+ : [],
+ [customerLocationFetcher.data]
+ );
+
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ if (newValue === undefined) onChange(newValue);
+ const contact = customerLocationFetcher.data?.data?.find(
+ (c) => c.id === newValue
+ );
+
+ onChange(contact);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [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>}
+ <input type="hidden" name={name} id={name} value={value} />
+ <Select
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ w="full"
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+};
+
+CustomerLocation.displayName = "CustomerLocation";
+
+export default CustomerLocation;
diff --git a/apps/carbon/app/components/Form/DatePicker.tsx b/apps/carbon/app/components/Form/DatePicker.tsx
index 2bf3b50ffb..5ec6b0b6ad 100644
--- a/apps/carbon/app/components/Form/DatePicker.tsx
+++ b/apps/carbon/app/components/Form/DatePicker.tsx
@@ -5,9 +5,9 @@ import { FormControl, FormErrorMessage, FormLabel } from "@chakra-ui/react";
import { useState } from "react";
import { useField } from "remix-validated-form";
-type DatePickerProps = { name: string; label?: string };
+type DatePickerProps = { name: string; label?: string; isDisabled?: boolean };
-const DatePicker = ({ name, label }: DatePickerProps) => {
+const DatePicker = ({ name, label, isDisabled = false }: DatePickerProps) => {
const { error, defaultValue, validate } = useField(name);
const [date, setDate] = useState<CalendarDate | undefined>(
defaultValue ? parseDate(defaultValue) : undefined
@@ -26,6 +26,7 @@ const DatePicker = ({ name, label }: DatePickerProps) => {
value={date}
//@ts-ignore
onChange={onChange}
+ isDisabled={isDisabled}
/>
{error && <FormErrorMessage>{error}</FormErrorMessage>}
</FormControl>
diff --git a/apps/carbon/app/components/Form/Department.tsx b/apps/carbon/app/components/Form/Department.tsx
index 0cc715f0e3..627f4a3716 100644
--- a/apps/carbon/app/components/Form/Department.tsx
+++ b/apps/carbon/app/components/Form/Department.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -74,8 +73,7 @@ const Department = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return departmentFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<input type="hidden" name={name} id={name} value={value} />
@@ -94,16 +92,6 @@ const Department = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Location.tsx b/apps/carbon/app/components/Form/Location.tsx
index 957753fd30..bfde7068ee 100644
--- a/apps/carbon/app/components/Form/Location.tsx
+++ b/apps/carbon/app/components/Form/Location.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -12,8 +11,15 @@ import { useControlField, useField } from "remix-validated-form";
import type { getLocations } from "~/modules/resources";
import type { SelectProps } from "./Select";
-type LocationSelectProps = Omit<SelectProps, "options"> & {
+type LocationSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ isClearable?: boolean;
location?: string;
+ onChange?: (
+ selected: {
+ value: string | number;
+ label: string;
+ } | null
+ ) => void;
};
const Location = ({
@@ -22,13 +28,13 @@ const Location = ({
location,
helperText,
isLoading,
- isReadOnly,
+ isClearable,
placeholder = "Select Location",
onChange,
...props
}: LocationSelectProps) => {
const { error, defaultValue } = useField(name);
- const [value, setValue] = useControlField<string | undefined>(name);
+ const [value, setValue] = useControlField<string | null>(name);
const locationFetcher =
useFetcher<Awaited<ReturnType<typeof getLocations>>>();
@@ -49,15 +55,15 @@ const Location = ({
[locationFetcher.data]
);
- const handleChange = (selection: {
- value: string | number;
- label: string;
- }) => {
- const newValue = (selection.value as string) || undefined;
+ const handleChange = (
+ selection: {
+ value: string | number;
+ label: string;
+ } | null
+ ) => {
+ const newValue = (selection?.value as string) ?? null;
setValue(newValue);
- if (onChange && typeof onChange === "function") {
- onChange(selection);
- }
+ onChange?.(selection);
};
const controlledValue = useMemo(
@@ -74,14 +80,14 @@ const Location = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return locationFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
- <input type="hidden" name={name} id={name} value={value} />
+ <input type="hidden" name={name} id={name} value={value ?? ""} />
<Select
{...props}
value={controlledValue}
+ isClearable={isClearable}
isLoading={isLoading}
options={options}
placeholder={placeholder}
@@ -94,16 +100,6 @@ const Location = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Part.tsx b/apps/carbon/app/components/Form/Part.tsx
new file mode 100644
index 0000000000..8f20af6361
--- /dev/null
+++ b/apps/carbon/app/components/Form/Part.tsx
@@ -0,0 +1,110 @@
+import { Select } from "@carbon/react";
+import {
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { getPartsList, PartReplenishmentSystem } from "~/modules/parts";
+import { mapRowsToOptions } from "~/utils/form";
+import type { SelectProps } from "./Select";
+
+type PartSelectProps = Omit<SelectProps, "options"> & {
+ partReplenishmentSystem?: PartReplenishmentSystem;
+};
+
+const Part = ({
+ name,
+ label = "Part",
+ partReplenishmentSystem,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Part",
+ onChange,
+ ...props
+}: PartSelectProps) => {
+ const { getInputProps, error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const partFetcher = useFetcher<Awaited<ReturnType<typeof getPartsList>>>();
+
+ useEffect(() => {
+ if (partFetcher.type === "init") {
+ let url = "/api/parts/list?";
+ if (partReplenishmentSystem) {
+ url += `replenishmentSystem=${partReplenishmentSystem}`;
+ }
+
+ partFetcher.load(url);
+ }
+ }, [partFetcher, partReplenishmentSystem]);
+
+ const options = useMemo(
+ () =>
+ mapRowsToOptions({
+ data: partFetcher.data?.data,
+ value: "id",
+ label: (part) => `${part.id} - ${part.name}`,
+ }),
+ [partFetcher.data]
+ );
+
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [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>}
+ <Select
+ {...getInputProps({
+ // @ts-ignore
+ id: name,
+ })}
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ w="full"
+ isReadOnly={isReadOnly}
+ onChange={handleChange}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+};
+
+Part.displayName = "Part";
+
+export default Part;
diff --git a/apps/carbon/app/components/Form/Select.tsx b/apps/carbon/app/components/Form/Select.tsx
index a689f153bd..09a8328175 100644
--- a/apps/carbon/app/components/Form/Select.tsx
+++ b/apps/carbon/app/components/Form/Select.tsx
@@ -1,6 +1,5 @@
import { Select as CarbonSelect } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -37,42 +36,41 @@ const Select = ({
[defaultValue, options]
);
- // TODO: hack for default value
- return options.length > 0 ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
- <CarbonSelect
- {...getInputProps({
+ {options.length > 0 ? (
+ <CarbonSelect
+ {...getInputProps({
+ // @ts-ignore
+ id: name,
+ })}
+ {...props}
+ defaultValue={initialValue}
+ isReadOnly={isReadOnly}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
// @ts-ignore
- id: name,
- })}
- {...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
- isLoading={isLoading}
- options={options}
- placeholder={placeholder}
- // @ts-ignore
- w="full"
- // @ts-ignore
- onChange={onChange ?? undefined}
- />
+ w="full"
+ // @ts-ignore
+ onChange={onChange ?? undefined}
+ />
+ ) : (
+ <CarbonSelect
+ isLoading={isLoading}
+ options={[]}
+ // @ts-ignore
+ w="full"
+ />
+ )}
+
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
) : (
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box w="full">
- {label && <FormLabel>{label}</FormLabel>}
- <CarbonSelect
- isLoading={isLoading}
- options={[]}
- // @ts-ignore
- w="full"
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/Supplier.tsx b/apps/carbon/app/components/Form/Supplier.tsx
index 8005cc77a7..3deabd766b 100644
--- a/apps/carbon/app/components/Form/Supplier.tsx
+++ b/apps/carbon/app/components/Form/Supplier.tsx
@@ -1,6 +1,5 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
FormErrorMessage,
FormHelperText,
@@ -72,8 +71,7 @@ const Supplier = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [controlledValue?.value]);
- // TODO: hack for default value
- return supplierFetcher.state !== "loading" ? (
+ return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<Select
@@ -97,17 +95,6 @@ const Supplier = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- // @ts-ignore
- w="full"
- />
- </Box>
);
};
diff --git a/apps/carbon/app/components/Form/SupplierContact.tsx b/apps/carbon/app/components/Form/SupplierContact.tsx
index f81ed7f999..b04f4c97f9 100644
--- a/apps/carbon/app/components/Form/SupplierContact.tsx
+++ b/apps/carbon/app/components/Form/SupplierContact.tsx
@@ -1,112 +1,111 @@
import { Select } from "@carbon/react";
import {
- Box,
FormControl,
+ FormLabel,
FormErrorMessage,
FormHelperText,
- FormLabel,
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
-import { useEffect, useMemo, useRef } from "react";
-import { useControlField, useField } from "remix-validated-form";
-import type {
- SupplierContact as SupplierContactType,
- getSupplierContacts,
-} from "~/modules/purchasing";
-import type { SelectProps } from "./Select";
-
-type SupplierContactSelectProps = Omit<SelectProps, "options" | "onChange"> & {
- supplier?: string;
- onChange?: (supplierContact: SupplierContactType | undefined) => void;
-};
+import { useEffect, useMemo } from "react";
+import { useField, useControlField } from "remix-validated-form";
+import type { getSupplierContacts } from "~/modules/purchasing";
+import { mapRowsToOptions } from "~/utils/form";
const SupplierContact = ({
name,
- label = "SupplierContact",
+ label = "Supplier Contact",
supplier,
helperText,
- isLoading,
- isReadOnly,
- placeholder = "Select Supplier Contact",
+ isReadOnly = false,
onChange,
- ...props
-}: SupplierContactSelectProps) => {
- const initialLoad = useRef(true);
- const { error, defaultValue } = useField(name);
- const [value, setValue] = useControlField<string | undefined>(name);
+}: {
+ name: string;
+ label?: string;
+ supplier?: string;
+ helperText?: string;
+ isReadOnly?: boolean;
+ onChange?: (value?: {
+ firstName: string;
+ lastName: string;
+ email: string;
+ }) => void;
+}) => {
+ const { error, getInputProps, defaultValue } = useField(name);
+
+ const [supplierContact, setSupplierContact] = useControlField<{
+ value: string | number;
+ label: string;
+ } | null>(name);
- const supplierContactFetcher =
+ const supplierContactsFetcher =
useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();
useEffect(() => {
- supplierContactFetcher.load(
- `/api/purchasing/supplier-contacts?supplierId=${supplier}`
- );
- if (initialLoad.current) {
- initialLoad.current = false;
- } else {
- setValue(undefined);
- if (onChange) {
- onChange(undefined);
- }
- }
+ if (supplier)
+ supplierContactsFetcher.load(
+ `/api/purchasing/supplier-contacts?supplierId=${supplier}`
+ );
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [supplier]);
- const options = useMemo(
+ const supplierContacts = useMemo(
() =>
- supplierContactFetcher.data?.data
- ? supplierContactFetcher.data?.data.map((c) => ({
- value: c.id,
- // @ts-ignore
- label: `${c.contact?.firstName} ${c.contact?.lastName}`,
- }))
- : [],
- [supplierContactFetcher.data]
+ mapRowsToOptions({
+ data: supplierContactsFetcher.data?.data ?? [],
+ value: "id",
+ // @ts-ignore
+ label: (row) => `${row.contact.firstName} ${row.contact.lastName}`,
+ }),
+ [supplierContactsFetcher.data]
);
- const handleChange = (selection: {
- value: string | number;
- label: string;
- }) => {
- const newValue = (selection.value as string) || undefined;
- setValue(newValue);
- if (onChange && typeof onChange === "function") {
- if (newValue === undefined) onChange(newValue);
- const contact = supplierContactFetcher.data?.data?.find(
- (c) => c.id === newValue
+ useEffect(() => {
+ // if the initial value is in the options, set it, otherwise set to null
+ if (supplierContacts) {
+ setSupplierContact(
+ supplierContacts.find((s) => s.value === defaultValue) ?? null
);
- onChange(contact);
- }
- };
- const controlledValue = useMemo(
- // @ts-ignore
- () => options.find((option) => option.value === value),
- [value, options]
- );
+ if (onChange) {
+ const contact =
+ supplierContactsFetcher.data?.data?.find((c) => c.id === defaultValue)
+ ?.contact ?? undefined;
- // so that we can call onChange on load
- useEffect(() => {
- if (controlledValue && controlledValue.value === defaultValue) {
- handleChange(controlledValue);
+ if (Array.isArray(contact)) throw new Error("Contact is an array");
+ if (contact) onChange(contact);
+ }
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [controlledValue?.value]);
+ }, [supplierContacts, defaultValue]);
+
+ const onContactChange = (newValue?: { label: string; value: string }) => {
+ setSupplierContact(newValue ?? null);
+ if (onChange) {
+ const contact =
+ supplierContactsFetcher.data?.data?.find(
+ (c) => c.id === newValue?.value
+ )?.contact ?? undefined;
- // TODO: hack for default value
- return supplierContactFetcher.state !== "loading" ? (
+ if (Array.isArray(contact)) throw new Error("Contact is an array");
+
+ onChange(contact);
+ }
+ };
+
+ return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
- <input type="hidden" name={name} id={name} value={value} />
+ <FormLabel htmlFor={name}>{label}</FormLabel>
<Select
- {...props}
- value={controlledValue}
- isLoading={isLoading}
- options={options}
- placeholder={placeholder}
+ {...getInputProps({
+ // @ts-ignore
+ id: name,
+ })}
+ options={supplierContacts}
+ value={supplierContact}
+ onChange={onContactChange}
// @ts-ignore
- onChange={handleChange}
+ isReadOnly={isReadOnly}
+ w="full"
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
@@ -114,19 +113,7 @@ const SupplierContact = ({
helperText && <FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
- ) : (
- <Box>
- {label && <FormLabel>{label}</FormLabel>}
- <Select
- isDisabled
- isLoading={isLoading}
- options={[]}
- //@ts-ignore
- />
- </Box>
);
};
-SupplierContact.displayName = "SupplierContact";
-
export default SupplierContact;
diff --git a/apps/carbon/app/components/Form/SupplierLocation.tsx b/apps/carbon/app/components/Form/SupplierLocation.tsx
new file mode 100644
index 0000000000..9b62e4e27a
--- /dev/null
+++ b/apps/carbon/app/components/Form/SupplierLocation.tsx
@@ -0,0 +1,120 @@
+import { Select } from "@carbon/react";
+import {
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo, useRef } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { SupplierLocation as SupplierLocationType } from "~/modules/purchasing";
+import type { getSupplierLocations } from "~/modules/purchasing";
+import type { SelectProps } from "./Select";
+
+type SupplierLocationSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ supplier?: string;
+ onChange?: (supplierLocation: SupplierLocationType | undefined) => void;
+};
+
+const SupplierLocation = ({
+ name,
+ label = "Supplier Location",
+ supplier,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Supplier Location",
+ onChange,
+ ...props
+}: SupplierLocationSelectProps) => {
+ const initialLoad = useRef(true);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
+
+ const supplierLocationFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSupplierLocations>>>();
+
+ useEffect(() => {
+ supplierLocationFetcher.load(
+ `/api/purchasing/supplier-locations?supplierId=${supplier}`
+ );
+ if (initialLoad.current) {
+ initialLoad.current = false;
+ } else {
+ setValue(undefined);
+ if (onChange) {
+ onChange(undefined);
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [supplier]);
+
+ const options = useMemo(
+ () =>
+ supplierLocationFetcher.data?.data
+ ? supplierLocationFetcher.data?.data.map((c) => ({
+ value: c.id,
+ // @ts-ignore
+ label: `${c.address?.addressLine1} ${c.address?.city}, ${c.address?.state}`,
+ }))
+ : [],
+ [supplierLocationFetcher.data]
+ );
+
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ if (newValue === undefined) onChange(newValue);
+ const contact = supplierLocationFetcher.data?.data?.find(
+ (c) => c.id === newValue
+ );
+
+ onChange(contact);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [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>}
+ <input type="hidden" name={name} id={name} value={value} />
+ <Select
+ {...props}
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ w="full"
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ );
+};
+
+SupplierLocation.displayName = "SupplierLocation";
+
+export default SupplierLocation;
diff --git a/apps/carbon/app/components/Form/Timezone.tsx b/apps/carbon/app/components/Form/Timezone.tsx
index 39615ba18b..545097c991 100644
--- a/apps/carbon/app/components/Form/Timezone.tsx
+++ b/apps/carbon/app/components/Form/Timezone.tsx
@@ -38,7 +38,6 @@ const Timezone = ({
[defaultValue]
);
- // TODO: hack for default value
return (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index aa50d662b9..dfc476b309 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -1,5 +1,6 @@
import Abilities from "./Abilities";
import Ability from "./Ability";
+import Account from "./Account";
import Array from "./Array";
import Boolean from "./Boolean";
import Color from "./Color";
@@ -7,6 +8,7 @@ import CreatableMultiSelect from "./CreatableMultiSelect";
import CreatableSelect from "./CreatableSelect";
import Customer from "./Customer";
import CustomerContact from "./CustomerContact";
+import CustomerLocation from "./CustomerLocation";
import Currency from "./Currency";
import DatePicker from "./DatePicker";
import Department from "./Department";
@@ -16,6 +18,7 @@ import Hidden from "./Hidden";
import Input from "./Input";
import Location from "./Location";
import Number from "./Number";
+import Part from "./Part";
import Password from "./Password";
import Phone from "./Phone";
import Radios from "./Radios";
@@ -25,6 +28,7 @@ import Slider from "./Slider";
import Submit from "./Submit";
import Supplier from "./Supplier";
import SupplierContact from "./SupplierContact";
+import SupplierLocation from "./SupplierLocation";
import TextArea from "./Textarea";
import TimePicker from "./TimePicker";
import Timezone from "./Timezone";
@@ -34,6 +38,7 @@ import Users from "./Users";
export {
Abilities,
Ability,
+ Account,
Array,
Boolean,
Color,
@@ -42,6 +47,7 @@ export {
Currency,
Customer,
CustomerContact,
+ CustomerLocation,
DatePicker,
Department,
Employee,
@@ -50,6 +56,7 @@ export {
Input,
Location,
Number,
+ Part,
Password,
Phone,
Radios,
@@ -59,6 +66,7 @@ export {
Submit,
Supplier,
SupplierContact,
+ SupplierLocation,
TextArea,
TimePicker,
Timezone,
diff --git a/apps/carbon/app/components/Grid/Grid.tsx b/apps/carbon/app/components/Grid/Grid.tsx
new file mode 100644
index 0000000000..fc5aa36a0c
--- /dev/null
+++ b/apps/carbon/app/components/Grid/Grid.tsx
@@ -0,0 +1,466 @@
+import { useColor, useEscape } from "@carbon/react";
+import { clip } from "@carbon/utils";
+import {
+ Box,
+ Flex,
+ HStack,
+ Icon,
+ Table,
+ Tbody,
+ Text,
+ Thead,
+ Td,
+ Th,
+ Tr,
+ VStack,
+} from "@chakra-ui/react";
+import type { ColumnDef, ColumnOrderState } from "@tanstack/react-table";
+import {
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+} 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 { getAccessorKey, updateNestedProperty } from "./utils";
+
+interface GridProps<T extends object> {
+ canEdit?: boolean;
+ columns: ColumnDef<T>[];
+ data: T[];
+ defaultColumnOrder?: string[];
+ defaultColumnVisibility?: Record<string, boolean>;
+ editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ withColumnOrdering?: boolean;
+ withNewRow?: boolean;
+ withSimpleSorting?: boolean;
+ onEditRow?: (row: T) => void;
+ onNewRow?: () => void;
+}
+
+const Grid = <T extends object>({
+ canEdit = true,
+ columns,
+ data,
+ editableComponents,
+ defaultColumnOrder,
+ defaultColumnVisibility,
+ withColumnOrdering = false,
+ withSimpleSorting = true,
+ onEditRow,
+ onNewRow,
+}: GridProps<T>) => {
+ const tableContainerRef = useRef<HTMLDivElement>(null);
+
+ /* Data for Optimistic Updates */
+ const [internalData, setInternalData] = useState<T[]>(data);
+ useEffect(() => {
+ setInternalData(data);
+ }, [data]);
+
+ /* Column Visibility */
+ const [columnVisibility, setColumnVisibility] = useState(
+ defaultColumnVisibility ?? {}
+ );
+
+ /* Column Ordering */
+ const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(
+ defaultColumnOrder ?? []
+ );
+
+ /* Sorting */
+ // const { isSorted, toggleSortBy } = useSort();
+
+ // const columnAccessors = useMemo(
+ // () =>
+ // columns.reduce<Record<string, string>>((acc, column) => {
+ // const accessorKey: string | undefined = getAccessorKey(column);
+ // if (accessorKey?.includes("_"))
+ // throw new Error(
+ // `Invalid accessorKey ${accessorKey}. Cannot contain '_'`
+ // );
+ // if (accessorKey && column.header && typeof column.header === "string") {
+ // return {
+ // ...acc,
+ // [accessorKey]: column.header,
+ // };
+ // }
+ // return acc;
+ // }, {}),
+ // [columns]
+ // );
+
+ const table = useReactTable({
+ data: internalData,
+ columns: columns,
+ state: {
+ columnVisibility,
+ columnOrder,
+ },
+ onColumnVisibilityChange: setColumnVisibility,
+ onColumnOrderChange: setColumnOrder,
+ getCoreRowModel: getCoreRowModel(),
+ meta: {
+ // These are not part of the standard API, but are accessible via table.options.meta
+ editableComponents,
+ updateData: (rowIndex, columnId, value) => {
+ setInternalData((previousData) =>
+ previousData.map((row, index) => {
+ if (index === rowIndex) {
+ if (columnId.includes("_") && !(columnId in row)) {
+ updateNestedProperty(row, columnId, value);
+ return row;
+ } else {
+ return {
+ ...row,
+ [columnId]: value,
+ };
+ }
+ }
+ return row;
+ })
+ );
+ },
+ },
+ });
+
+ const [isEditing, setIsEditing] = useState(false);
+ const [selectedCell, setSelectedCell] = useState<Position>(null);
+
+ const focusOnSelectedCell = useCallback(() => {
+ if (selectedCell == null) return;
+ const cell = tableContainerRef.current?.querySelector(
+ `[data-row="${selectedCell.row}"][data-column="${selectedCell.column}"]`
+ ) as HTMLDivElement;
+ if (cell) cell.focus();
+ }, [selectedCell, tableContainerRef]);
+
+ useEscape(() => {
+ setIsEditing(false);
+ focusOnSelectedCell();
+ });
+
+ const onSelectedCellChange = useCallback(
+ (position: Position) => {
+ if (
+ selectedCell == null ||
+ position == null ||
+ selectedCell.row !== position?.row ||
+ selectedCell.column !== position.column
+ )
+ setSelectedCell(position);
+ },
+ [selectedCell]
+ );
+
+ const isColumnEditable = useCallback(
+ (selectedColumn: number) => {
+ const tableColumns = [
+ ...table.getLeftVisibleLeafColumns(),
+ ...table.getCenterVisibleLeafColumns(),
+ ];
+
+ const column = tableColumns[selectedColumn];
+ if (!column) return false;
+
+ const accessorKey = getAccessorKey(column.columnDef);
+ return (
+ accessorKey && editableComponents && accessorKey in editableComponents
+ );
+ },
+ [table, editableComponents]
+ );
+
+ const onCellClick = useCallback(
+ (row: number, column: number) => {
+ // ignore row select checkbox column
+ if (
+ selectedCell?.row === row &&
+ selectedCell?.column === column &&
+ isColumnEditable(column)
+ ) {
+ setIsEditing(true);
+ return;
+ }
+ // ignore row select checkbox column
+ if (column === -1) return;
+ setIsEditing(false);
+ onSelectedCellChange({ row, column });
+ },
+ [selectedCell, isColumnEditable, onSelectedCellChange]
+ );
+
+ const onCellUpdate = useCallback(
+ (rowIndex: number) => (columnId: string, value: unknown) =>
+ table.options.meta?.updateData
+ ? table.options.meta?.updateData(rowIndex, columnId, value)
+ : undefined,
+ [table]
+ );
+
+ const onKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (!selectedCell) return;
+
+ const { code, shiftKey } = event;
+
+ const commandCodes: {
+ [key: string]: [number, number];
+ } = {
+ Tab: [0, 1],
+ Enter: [1, 0],
+ };
+
+ const navigationCodes: {
+ [key: string]: [number, number];
+ } = {
+ ArrowRight: [0, 1],
+ ArrowLeft: [0, -1],
+ ArrowDown: [1, 0],
+ ArrowUp: [-1, 0],
+ };
+
+ const lastRow = table.getRowModel().rows.length - 1;
+ const lastColumn = table.getVisibleLeafColumns().length - 1;
+
+ const navigate = (
+ delta: [number, number],
+ tabWrap = false
+ ): [number, number] => {
+ const x0 = selectedCell?.column || 0;
+ const y0 = selectedCell?.row || 0;
+
+ let x1 = x0 + delta[1];
+ let y1 = y0 + delta[0];
+
+ if (tabWrap) {
+ if (delta[1] > 0) {
+ // wrap to the next row if we're on the last column
+ if (x1 > lastColumn) {
+ x1 = 0;
+ y1 += 1;
+ }
+ // don't wrap to the next row if we're on the last row
+ if (y1 > lastRow) {
+ x1 = x0;
+ y1 = y0;
+ }
+ } else {
+ // reverse tab wrap
+ if (x1 < 0) {
+ x1 = lastColumn;
+ y1 -= 1;
+ }
+
+ if (y1 < 0) {
+ x1 = x0;
+ y1 = y0;
+ }
+ }
+ } else {
+ x1 = clip(x1, 0, lastColumn);
+ }
+
+ y1 = clip(y1, 0, lastRow);
+
+ return [x1, y1];
+ };
+
+ if (code in commandCodes) {
+ event.preventDefault();
+
+ if (
+ canEdit &&
+ !isEditing &&
+ code === "Enter" &&
+ !shiftKey &&
+ isColumnEditable(selectedCell.column)
+ ) {
+ setIsEditing(true);
+ return;
+ }
+
+ let direction = commandCodes[code];
+
+ if (shiftKey) direction = [-direction[0], -direction[1]];
+ const [x1, y1] = navigate(direction, code === "Tab");
+ setSelectedCell({
+ row: y1,
+ column: x1,
+ });
+ if (isEditing) {
+ setIsEditing(false);
+ }
+ } else if (code in navigationCodes) {
+ // arrow key navigation should't work if we're editing
+ if (isEditing) return;
+ event.preventDefault();
+ const [x1, y1] = navigate(navigationCodes[code], code === "Tab");
+ setIsEditing(false);
+ setSelectedCell({
+ row: y1,
+ column: x1,
+ });
+ // any other key (besides shift) activates editing
+ // if the column is editable and a cell is selected
+ } else if (
+ !["ShiftLeft", "ShiftRight"].includes(code) &&
+ !isEditing &&
+ selectedCell &&
+ isColumnEditable(selectedCell.column)
+ ) {
+ setIsEditing(true);
+ }
+ },
+ [canEdit, isColumnEditable, isEditing, selectedCell, table]
+ );
+
+ // reset the selected cell when the table data changes
+ useEffect(() => {
+ setSelectedCell(null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [columnOrder, columnVisibility]);
+
+ useEffect(() => {
+ setColumnOrder(table.getAllLeafColumns().map((column) => column.id));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const rows = table.getRowModel().rows;
+
+ const borderColor = useColor("gray.200");
+ const rowBackground = useColor("gray.50");
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ {/* {withColumnOrdering && (
+ <GridHeader
+ columnAccessors={columnAccessors}
+ columnOrder={columnOrder}
+ columns={table.getAllLeafColumns()}
+ setColumnOrder={setColumnOrder}
+ withColumnOrdering={withColumnOrdering}
+ />
+ )} */}
+ <Box
+ w="full"
+ h="full"
+ bg={useColor("white")}
+ overflow="scroll"
+ style={{ contain: "strict" }}
+ ref={tableContainerRef}
+ onKeyDown={onKeyDown}
+ >
+ <Table>
+ <Thead>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <Tr key={headerGroup.id} h={10}>
+ {headerGroup.headers.map((header) => {
+ const accessorKey = getAccessorKey(header.column.columnDef);
+
+ const sortable =
+ withSimpleSorting &&
+ accessorKey &&
+ !accessorKey.endsWith(".id") &&
+ header.column.columnDef.enableSorting !== false;
+ // const sorted = isSorted(accessorKey ?? "");
+
+ return (
+ <Th
+ key={header.id}
+ colSpan={header.colSpan}
+ // onClick={
+ // sortable
+ // ? () => toggleSortBy(accessorKey ?? "")
+ // : undefined
+ // }
+ borderRightColor={borderColor}
+ borderRightStyle="solid"
+ borderRightWidth={1}
+ cursor={sortable ? "pointer" : undefined}
+ px={4}
+ py={3}
+ w={header.getSize()}
+ whiteSpace="nowrap"
+ >
+ {header.isPlaceholder ? null : (
+ <Flex
+ justify="flex-start"
+ align="center"
+ fontSize="xs"
+ color="gray.500"
+ >
+ {flexRender(
+ header.column.columnDef.header,
+ header.getContext()
+ )}
+ {/* <chakra.span pl="4">
+ {sorted ? (
+ sorted === -1 ? (
+ <FaSortDown aria-label="sorted descending" />
+ ) : (
+ <FaSortUp aria-label="sorted ascending" />
+ )
+ ) : sortable ? (
+ <FaSort
+ aria-label="sort"
+ style={{ opacity: 0.4 }}
+ />
+ ) : null}
+ </chakra.span> */}
+ </Flex>
+ )}
+ </Th>
+ );
+ })}
+ </Tr>
+ ))}
+ </Thead>
+ <Tbody>
+ {rows.map((row) => {
+ return (
+ <Row
+ key={row.id}
+ borderColor={borderColor}
+ backgroundColor={rowBackground}
+ editableComponents={canEdit ? editableComponents : {}}
+ isEditing={isEditing}
+ selectedCell={selectedCell}
+ row={row}
+ rowIsSelected={selectedCell?.row === row.index}
+ onCellClick={onCellClick}
+ onCellUpdate={onCellUpdate}
+ onEditRow={onEditRow}
+ />
+ );
+ })}
+ {onNewRow && (
+ <Tr
+ onClick={onNewRow}
+ cursor="pointer"
+ h={10}
+ _hover={{
+ backgroundColor: "gray.100",
+ }}
+ >
+ <Td colSpan={24}>
+ <HStack spacing={2}>
+ <Icon color="gray.500" as={BsPlus} w={6} h={6} />
+ <Text color="gray.500">New</Text>
+ </HStack>
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ </Box>
+ </VStack>
+ );
+};
+
+export default Grid;
diff --git a/apps/carbon/app/components/Grid/components/Cell/Cell.tsx b/apps/carbon/app/components/Grid/components/Cell/Cell.tsx
new file mode 100644
index 0000000000..40b5356fcb
--- /dev/null
+++ b/apps/carbon/app/components/Grid/components/Cell/Cell.tsx
@@ -0,0 +1,112 @@
+import { Box, Td } from "@chakra-ui/react";
+import type { Cell as CellType } from "@tanstack/react-table";
+import { flexRender } from "@tanstack/react-table";
+import { memo, useState } from "react";
+import type { EditableTableCellComponent } from "~/components/Editable";
+import { useMovingCellRef } from "~/hooks";
+import { getAccessorKey } from "../../utils";
+
+type CellProps<T> = {
+ borderColor: string;
+ cell: CellType<T, unknown>;
+ columnIndex: number;
+ editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ editedCells?: string[];
+ isEditing: boolean;
+ isSelected: boolean;
+ onClick?: () => void;
+ onUpdate?: (columnId: string, value: unknown) => void;
+};
+
+const Cell = <T extends object>({
+ borderColor,
+ cell,
+ columnIndex,
+ editableComponents,
+ editedCells,
+ isEditing,
+ isSelected,
+ onClick,
+ onUpdate,
+}: CellProps<T>) => {
+ const { ref, tabIndex, onFocus } = useMovingCellRef(isSelected);
+ const [hasError, setHasError] = useState(false);
+ const accessorKey = getAccessorKey(cell.column.columnDef);
+
+ const wasEdited =
+ !!editedCells && !!accessorKey && editedCells.includes(accessorKey);
+
+ const hasEditableTableCellComponent =
+ accessorKey !== undefined &&
+ editableComponents &&
+ accessorKey in editableComponents;
+
+ const editableCell = hasEditableTableCellComponent
+ ? editableComponents?.[accessorKey]
+ : null;
+
+ return (
+ <Td
+ ref={ref}
+ data-row={cell.row.index}
+ data-column={columnIndex}
+ tabIndex={tabIndex}
+ position="relative"
+ bgColor={
+ wasEdited
+ ? "yellow.100"
+ : hasEditableTableCellComponent
+ ? undefined
+ : "gray.50"
+ }
+ borderRightColor={borderColor}
+ borderRightStyle="solid"
+ borderRightWidth={1}
+ boxShadow={
+ hasError
+ ? "inset 0 0 0 3px var(--chakra-colors-red-500)"
+ : isSelected
+ ? "inset 0 0 0 3px var(--chakra-ui-focus-ring-color)"
+ : undefined
+ }
+ fontSize="sm"
+ outline="none"
+ px={4}
+ py={2}
+ whiteSpace="nowrap"
+ onClick={onClick}
+ onFocus={onFocus}
+ >
+ {isSelected && isEditing && hasEditableTableCellComponent ? (
+ <Box position="absolute" w="full" left={0} top="2px">
+ {hasEditableTableCellComponent
+ ? flexRender(editableCell, {
+ accessorKey,
+ value: cell.renderValue(),
+ row: cell.row.original,
+ onUpdate: onUpdate
+ ? onUpdate
+ : () => console.error("No update function provided"),
+ onError: () => {
+ setHasError(true);
+ },
+ })
+ : null}
+ </Box>
+ ) : (
+ <div ref={ref}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </div>
+ )}
+ </Td>
+ );
+};
+
+export const MemoizedCell = memo(
+ Cell,
+ (prev, next) =>
+ next.isSelected === prev.isSelected &&
+ next.isEditing === prev.isEditing &&
+ next.cell.getValue() === prev.cell.getValue() &&
+ next.cell.getContext() === prev.cell.getContext()
+) as typeof Cell;
diff --git a/apps/carbon/app/components/Grid/components/Cell/index.ts b/apps/carbon/app/components/Grid/components/Cell/index.ts
new file mode 100644
index 0000000000..619f44dbca
--- /dev/null
+++ b/apps/carbon/app/components/Grid/components/Cell/index.ts
@@ -0,0 +1,3 @@
+import { MemoizedCell as Cell } from "./Cell";
+
+export default Cell;
diff --git a/apps/carbon/app/components/Grid/components/Row/Row.tsx b/apps/carbon/app/components/Grid/components/Row/Row.tsx
new file mode 100644
index 0000000000..c29cfff44f
--- /dev/null
+++ b/apps/carbon/app/components/Grid/components/Row/Row.tsx
@@ -0,0 +1,89 @@
+import { Tr } from "@chakra-ui/react";
+import type { Row as RowType } from "@tanstack/react-table";
+import type { MutableRefObject } from "react";
+import { memo } from "react";
+import type {
+ EditableTableCellComponent,
+ Position,
+} from "~/components/Editable";
+import Cell from "../Cell";
+
+type RowProps<T> = {
+ borderColor: string;
+ backgroundColor: string;
+ editableComponents?: Record<string, EditableTableCellComponent<T> | object>;
+ editedCells?: string[];
+ isEditing: boolean;
+ selectedCell: Position;
+ row: RowType<T>;
+ rowIsClickable?: boolean;
+ rowIsSelected: boolean;
+ rowRef?: MutableRefObject<HTMLTableRowElement | null>;
+ onCellClick: (row: number, column: number) => void;
+ onCellUpdate: (row: number) => (columnId: string, value: unknown) => void;
+ onEditRow?: (row: T) => void;
+};
+
+const Row = <T extends object>({
+ borderColor,
+ backgroundColor,
+ editableComponents,
+ editedCells,
+ isEditing,
+ row,
+ rowIsClickable = false,
+ rowIsSelected,
+ rowRef,
+ selectedCell,
+ onCellClick,
+ onCellUpdate,
+}: RowProps<T>) => {
+ return (
+ <Tr
+ key={row.id}
+ ref={rowRef}
+ _hover={{
+ cursor: rowIsClickable ? "pointer" : undefined,
+ backgroundColor,
+ }}
+ >
+ {row.getVisibleCells().map((cell, columnIndex) => {
+ const isSelected =
+ selectedCell?.row === cell.row.index &&
+ selectedCell?.column === columnIndex;
+
+ return (
+ <Cell<T>
+ key={cell.id}
+ borderColor={borderColor}
+ cell={cell}
+ columnIndex={columnIndex}
+ // @ts-ignore
+ editableComponents={editableComponents}
+ editedCells={editedCells}
+ isSelected={isSelected}
+ isEditing={isEditing}
+ onClick={() => onCellClick(cell.row.index, columnIndex)}
+ onUpdate={onCellUpdate(cell.row.index)}
+ />
+ );
+ })}
+ </Tr>
+ );
+};
+
+const MemoizedRow = memo(
+ Row,
+ (prev, next) =>
+ next.rowIsSelected === false &&
+ prev.rowIsSelected === false &&
+ next.selectedCell?.row === prev.row.index &&
+ next.row.index === prev.selectedCell?.row &&
+ next.selectedCell?.column === prev.selectedCell?.column &&
+ next.isEditing === prev.isEditing
+) as typeof Row;
+
+// props are equal if:
+// - the row is not the selected row
+
+export default MemoizedRow;
diff --git a/apps/carbon/app/components/Grid/components/Row/index.ts b/apps/carbon/app/components/Grid/components/Row/index.ts
new file mode 100644
index 0000000000..2e964c396d
--- /dev/null
+++ b/apps/carbon/app/components/Grid/components/Row/index.ts
@@ -0,0 +1,3 @@
+import Row from "./Row";
+
+export default Row;
diff --git a/apps/carbon/app/components/Grid/components/index.ts b/apps/carbon/app/components/Grid/components/index.ts
new file mode 100644
index 0000000000..f278220db3
--- /dev/null
+++ b/apps/carbon/app/components/Grid/components/index.ts
@@ -0,0 +1,3 @@
+import Row from "./Row";
+
+export { Row };
diff --git a/apps/carbon/app/components/Grid/index.ts b/apps/carbon/app/components/Grid/index.ts
new file mode 100644
index 0000000000..a291900e05
--- /dev/null
+++ b/apps/carbon/app/components/Grid/index.ts
@@ -0,0 +1,3 @@
+import Grid from "./Grid";
+
+export default Grid;
diff --git a/apps/carbon/app/components/Grid/utils.ts b/apps/carbon/app/components/Grid/utils.ts
new file mode 100644
index 0000000000..278ebdc510
--- /dev/null
+++ b/apps/carbon/app/components/Grid/utils.ts
@@ -0,0 +1,22 @@
+import type { ColumnDef } from "@tanstack/react-table";
+
+export function getAccessorKey<T>(columnDef: ColumnDef<T, unknown>) {
+ return "accessorKey" in columnDef
+ ? columnDef?.accessorKey.toString()
+ : undefined;
+}
+
+export function updateNestedProperty(
+ obj: object,
+ path: string | string[],
+ value: unknown
+): unknown {
+ if (typeof path == "string")
+ return updateNestedProperty(obj, path.split("_"), value);
+ else if (path.length == 1 && value !== undefined)
+ // @ts-ignore
+ return (obj[path[0]] = value);
+ else if (path.length == 0) return obj;
+ // @ts-ignore
+ else return updateNestedProperty(obj[path[0]], path.slice(1), value);
+}
diff --git a/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
index c016e409a2..976d66beb5 100644
--- a/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
@@ -12,6 +12,8 @@ import useNewMenu from "./useNewMenu";
const NewMenu = () => {
const newMenuLinks = useNewMenu();
+ if (!newMenuLinks.length) return null;
+
return (
<Menu>
<MenuButton
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index 03548ba7b9..a3f345e0da 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -85,6 +85,16 @@ export default function useBreadcrumbs(): Route[] {
to: match.pathname,
});
case "routes/x+/purchase-order+/_layout":
+ return acc.concat(
+ {
+ name: "Purchasing",
+ to: "/x/purchasing",
+ },
+ {
+ name: "Orders",
+ to: "/x/purchasing/orders",
+ }
+ );
case "routes/x+/purchasing+/_layout":
return acc.concat({
name: "Purchasing",
diff --git a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
index df1ecea3cb..ff5fbc8224 100644
--- a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
@@ -1,4 +1,6 @@
import { useMemo } from "react";
+import { AiOutlinePartition } from "react-icons/ai";
+import { BsCartDash, BsShieldLock } from "react-icons/bs";
import { usePermissions } from "~/hooks";
import type { Route } from "~/types";
@@ -12,6 +14,7 @@ export default function useNewMenu(): Route[] {
links.push({
name: "New Part",
to: "/x/part/new",
+ icon: <AiOutlinePartition />,
});
}
@@ -19,6 +22,7 @@ export default function useNewMenu(): Route[] {
links.push({
name: "New Purchase Order",
to: "/x/purchase-order/new",
+ icon: <BsCartDash />,
});
}
@@ -26,6 +30,7 @@ export default function useNewMenu(): Route[] {
links.push({
name: "New Employee",
to: "/x/users/employees/new",
+ icon: <BsShieldLock />,
});
}
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 5fdf436fcf..188210db2d 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -28,6 +28,10 @@ import {
} from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { FaSort, FaSortUp, FaSortDown } from "react-icons/fa";
+import type {
+ EditableTableCellComponent,
+ Position,
+} from "~/components/Editable";
import {
TableHeader,
IndeterminateCheckbox,
@@ -36,11 +40,7 @@ import {
useSort,
Row,
} from "./components";
-import type {
- EditableTableCellComponent,
- Position,
- TableAction,
-} from "./types";
+import type { TableAction } from "./types";
import { getAccessorKey, updateNestedProperty } from "./utils";
interface TableProps<T extends object> {
@@ -266,8 +266,8 @@ const Table = <T extends object>({
[selectedCell, isColumnEditable, onSelectedCellChange]
);
- const onCellEditUpdate = useCallback(
- (rowIndex: number, columnId: string) => (value: unknown) => {
+ const onCellUpdate = useCallback(
+ (rowIndex: number) => (columnId: string, value: unknown) => {
return table.options.meta?.updateData
? table.options.meta?.updateData(rowIndex, columnId, value)
: undefined;
@@ -553,9 +553,10 @@ const Table = <T extends object>({
// @ts-ignore
row={row}
rowRef={ref}
+ rowIsSelected={selectedCell?.row === row.index}
withColumnOrdering={withColumnOrdering}
onCellClick={onCellClick}
- onCellUpdate={onCellEditUpdate}
+ onCellUpdate={onCellUpdate}
onRowClick={
rowsAreClickable
? () => onRowClick(row.original)
@@ -579,9 +580,10 @@ const Table = <T extends object>({
selectedCell={selectedCell}
// @ts-ignore
row={row}
+ rowIsSelected={selectedCell?.row === row.index}
withColumnOrdering={withColumnOrdering}
onCellClick={onCellClick}
- onCellUpdate={onCellEditUpdate}
+ onCellUpdate={onCellUpdate}
onRowClick={
rowsAreClickable
? () => onRowClick(row.original)
@@ -693,10 +695,11 @@ const Table = <T extends object>({
// @ts-ignore
row={row}
rowIsClickable={rowsAreClickable}
+ rowIsSelected={selectedCell?.row === row.index}
rowRef={ref}
withColumnOrdering={withColumnOrdering}
onCellClick={onCellClick}
- onCellUpdate={onCellEditUpdate}
+ onCellUpdate={onCellUpdate}
onRowClick={
rowsAreClickable
? () => onRowClick(row.original)
@@ -727,9 +730,10 @@ const Table = <T extends object>({
// @ts-ignore
row={row}
rowIsClickable={rowsAreClickable}
+ rowIsSelected={selectedCell?.row === row.index}
withColumnOrdering={withColumnOrdering}
onCellClick={onCellClick}
- onCellUpdate={onCellEditUpdate}
+ onCellUpdate={onCellUpdate}
onRowClick={
rowsAreClickable
? () => onRowClick(row.original)
diff --git a/apps/carbon/app/components/Table/components/Cell/Cell.tsx b/apps/carbon/app/components/Table/components/Cell/Cell.tsx
index fee03eb766..8787d93fb4 100644
--- a/apps/carbon/app/components/Table/components/Cell/Cell.tsx
+++ b/apps/carbon/app/components/Table/components/Cell/Cell.tsx
@@ -1,17 +1,9 @@
-import {
- Box,
- HStack,
- Popover,
- PopoverAnchor,
- PopoverBody,
- PopoverContent,
- Td,
-} from "@chakra-ui/react";
+import { Box, Td } from "@chakra-ui/react";
import type { Cell as CellType } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
-import { useMovingCellRef } from "../../hooks/useMovingCellRef";
-import { memo } from "react";
-import type { EditableTableCellComponent } from "../../types";
+import { memo, useState } from "react";
+import { useMovingCellRef } from "~/hooks";
+import type { EditableTableCellComponent } from "~/components/Editable";
import { getAccessorKey } from "../../utils";
type CellProps<T> = {
@@ -19,12 +11,13 @@ type CellProps<T> = {
cell: CellType<T, unknown>;
columnIndex: number;
editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ editedCells?: string[];
isEditing: boolean;
isEditMode: boolean;
isRowSelected: boolean;
isSelected: boolean;
onClick?: () => void;
- onUpdate?: (value: unknown) => void;
+ onUpdate?: (columnId: string, value: unknown) => void;
};
const Cell = <T extends object>({
@@ -32,6 +25,7 @@ const Cell = <T extends object>({
cell,
columnIndex,
editableComponents,
+ editedCells,
isEditing,
isEditMode,
isSelected,
@@ -39,24 +33,19 @@ const Cell = <T extends object>({
onUpdate,
}: CellProps<T>) => {
const { ref, tabIndex, onFocus } = useMovingCellRef(isSelected);
+ const [hasError, setHasError] = useState(false);
const accessorKey = getAccessorKey(cell.column.columnDef);
+ const wasEdited =
+ !!editedCells && !!accessorKey && editedCells.includes(accessorKey);
+
const hasEditableTableCellComponent =
accessorKey !== undefined &&
editableComponents &&
accessorKey in editableComponents;
const editableCell = hasEditableTableCellComponent
- ? editableComponents[accessorKey]({
- accessorKey,
- value: cell.getValue(),
- row: cell.row.original,
- onUpdate:
- onUpdate ||
- (() => {
- console.error("failed to pass an onUpdate function to the popover");
- }),
- })
+ ? editableComponents[accessorKey]
: null;
return (
@@ -65,14 +54,21 @@ const Cell = <T extends object>({
data-row={cell.row.index}
data-column={columnIndex}
tabIndex={tabIndex}
+ position="relative"
bgColor={
- isEditMode && !hasEditableTableCellComponent ? "gray.50" : undefined
+ wasEdited
+ ? "yellow.100"
+ : isEditMode && !hasEditableTableCellComponent
+ ? "gray.50"
+ : undefined
}
borderRightColor={borderColor}
borderRightStyle="solid"
borderRightWidth={isEditMode ? 1 : undefined}
boxShadow={
- isSelected
+ hasError
+ ? "inset 0 0 0 3px var(--chakra-colors-red-500)"
+ : isSelected
? "inset 0 0 0 3px var(--chakra-ui-focus-ring-color)"
: undefined
}
@@ -84,31 +80,27 @@ const Cell = <T extends object>({
onClick={onClick}
onFocus={onFocus}
>
- <Box ref={ref}>
- {isSelected && isEditing && hasEditableTableCellComponent ? (
- <Popover
- isOpen
- onOpen={() => console.log("opened")}
- onClose={() => console.log("closed")}
- closeOnBlur
- isLazy
- >
- <PopoverAnchor>
- <Box>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </Box>
- </PopoverAnchor>
-
- <PopoverContent>
- <PopoverBody>
- <HStack spacing={2}>{editableCell}</HStack>
- </PopoverBody>
- </PopoverContent>
- </Popover>
- ) : (
- flexRender(cell.column.columnDef.cell, cell.getContext())
- )}
- </Box>
+ {isSelected && isEditing && hasEditableTableCellComponent ? (
+ <Box position="absolute" w="full" left={0} top="2px">
+ {hasEditableTableCellComponent
+ ? flexRender(editableCell, {
+ accessorKey,
+ value: cell.renderValue(),
+ row: cell.row.original,
+ onUpdate: onUpdate
+ ? onUpdate
+ : () => console.error("No update function provided"),
+ onError: () => {
+ setHasError(true);
+ },
+ })
+ : null}
+ </Box>
+ ) : (
+ <div ref={ref}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </div>
+ )}
</Td>
);
};
diff --git a/apps/carbon/app/components/Table/components/Row/Row.tsx b/apps/carbon/app/components/Table/components/Row/Row.tsx
index 81ca5cc8a8..18f7a9aabb 100644
--- a/apps/carbon/app/components/Table/components/Row/Row.tsx
+++ b/apps/carbon/app/components/Table/components/Row/Row.tsx
@@ -4,12 +4,16 @@ import type { Row as RowType } from "@tanstack/react-table";
import type { MutableRefObject } from "react";
import { memo } from "react";
import Cell from "../Cell";
-import type { EditableTableCellComponent, Position } from "../../types";
+import type {
+ EditableTableCellComponent,
+ Position,
+} from "~/components/Editable";
type RowProps<T> = {
borderColor: string;
backgroundColor: string;
editableComponents?: Record<string, EditableTableCellComponent<T> | object>;
+ editedCells?: string[];
isEditing: boolean;
isEditMode: boolean;
isFrozenColumn?: boolean;
@@ -18,10 +22,11 @@ type RowProps<T> = {
selectedCell: Position;
row: RowType<T>;
rowIsClickable?: boolean;
+ rowIsSelected: boolean;
rowRef?: MutableRefObject<HTMLTableRowElement | null>;
withColumnOrdering: boolean;
onCellClick: (row: number, column: number) => void;
- onCellUpdate: (row: number, columnId: string) => (value: unknown) => void;
+ onCellUpdate: (row: number) => (columnId: string, value: unknown) => void;
onRowClick?: () => void;
};
@@ -29,6 +34,7 @@ const Row = <T extends object>({
borderColor,
backgroundColor,
editableComponents,
+ editedCells,
isEditing,
isEditMode,
isFrozenColumn = false,
@@ -36,6 +42,7 @@ const Row = <T extends object>({
pinnedColumns = 0,
row,
rowIsClickable = false,
+ rowIsSelected,
rowRef,
selectedCell,
withColumnOrdering,
@@ -75,6 +82,7 @@ const Row = <T extends object>({
columnIndex={columnIndex}
// @ts-ignore
editableComponents={editableComponents}
+ editedCells={editedCells}
isRowSelected={isRowSelected}
isSelected={isSelected}
isEditing={isEditing}
@@ -90,11 +98,7 @@ const Row = <T extends object>({
)
: undefined
}
- onUpdate={
- isEditMode
- ? onCellUpdate(cell.row.index, cell.column.id)
- : undefined
- }
+ onUpdate={isEditMode ? onCellUpdate(cell.row.index) : undefined}
/>
);
})}
@@ -105,6 +109,8 @@ const Row = <T extends object>({
const MemoizedRow = memo(
Row,
(prev, next) =>
+ next.rowIsSelected === false &&
+ prev.rowIsSelected === false &&
next.isRowSelected === prev.isRowSelected &&
next.selectedCell?.row === prev.row.index &&
next.row.index === prev.selectedCell?.row &&
diff --git a/apps/carbon/app/components/Table/editable/EditableList.tsx b/apps/carbon/app/components/Table/editable/EditableList.tsx
deleted file mode 100644
index e98b8e7e75..0000000000
--- a/apps/carbon/app/components/Table/editable/EditableList.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-/* eslint-disable react/display-name */
-import { Select } from "@carbon/react";
-import type { EditableTableCellComponentProps } from "../types";
-
-const EditableList =
- <T extends object>(
- mutation: (
- accessorKey: string,
- newValue: string | undefined,
- row: T
- ) => void,
- options: { label: string; value: string | number }[]
- ) =>
- ({
- value,
- row,
- accessorKey,
- onUpdate,
- }: EditableTableCellComponentProps<T>) => {
- const updateSelection = (newValue: string | null) => {
- if (newValue === value || (newValue === null && value === undefined))
- return;
- // this is the optimistic update on the FE
- onUpdate(newValue);
- // the is the actual update on the BE
- mutation(accessorKey, newValue ?? undefined, row);
- };
-
- return (
- <Select
- autoFocus
- bordered={false}
- defaultOpen
- defaultValue={value as string}
- // @ts-ignore
- options={options}
- optionFilterProp="label"
- showSearch
- style={{ margin: "0 -0.75rem", minWidth: 100 }}
- onChange={updateSelection}
- />
- );
- };
-
-export default EditableList;
diff --git a/apps/carbon/app/components/Table/editable/EditableText.tsx b/apps/carbon/app/components/Table/editable/EditableText.tsx
deleted file mode 100644
index 864e3a649d..0000000000
--- a/apps/carbon/app/components/Table/editable/EditableText.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-/* eslint-disable react/display-name */
-import { Input } from "@chakra-ui/react";
-import type { EditableTableCellComponentProps } from "../types";
-
-const EditableText =
- <T extends object>(
- mutation: (accessorKey: string, newValue: string, row: T) => void
- ) =>
- ({
- value,
- row,
- accessorKey,
- onUpdate,
- }: EditableTableCellComponentProps<T>) => {
- const updateText = async (newValue: string) => {
- // this is the optimistic update on the FE
- onUpdate(newValue);
- // the is the actual update on the BE
- mutation(accessorKey, newValue, row);
- };
-
- const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
- // only run the update if they click enter
- if (event.key === "Enter" || event.key === "Tab") {
- if (event.currentTarget.value !== value) {
- updateText(event.currentTarget.value);
- }
- }
- };
-
- // eslint-disable-next-line jsx-a11y/no-autofocus
- return (
- <Input
- border="none"
- autoFocus
- defaultValue={value as string}
- style={{ margin: "0 -0.75rem" }}
- onKeyDown={onKeyDown}
- />
- );
- };
-
-export default EditableText;
diff --git a/apps/carbon/app/components/Table/types.ts b/apps/carbon/app/components/Table/types.ts
index 460abec7ef..473bbe3da2 100644
--- a/apps/carbon/app/components/Table/types.ts
+++ b/apps/carbon/app/components/Table/types.ts
@@ -1,25 +1,3 @@
-export type EditableTableCellComponent<TData> = (props: {
- accessorKey: string;
- row: TData;
- value: unknown;
- onUpdate: (value: unknown) => void;
-}) => JSX.Element;
-
-export type EditableTableCellComponentProps<T> = {
- value: unknown;
- row: T;
- accessorKey: string;
- onUpdate: (value: unknown) => void;
-};
-
-declare module "@tanstack/react-table" {
- interface TableMeta<TData> {
- editableComponents?: Record<string, EditableTableCellComponent<TData>>;
- updateData?: (rowIndex: number, columnId: string, value: unknown) => void;
- }
-}
-
-export type Position = null | { row: number; column: number };
export interface TableAction<T> {
label: string;
onClick: (rows: T[]) => void;
diff --git a/apps/carbon/app/components/Table/utils.ts b/apps/carbon/app/components/Table/utils.ts
index f990706293..278ebdc510 100644
--- a/apps/carbon/app/components/Table/utils.ts
+++ b/apps/carbon/app/components/Table/utils.ts
@@ -20,10 +20,3 @@ export function updateNestedProperty(
// @ts-ignore
else return updateNestedProperty(obj[path[0]], path.slice(1), value);
}
-
-export function scrollIntoView(element: HTMLElement | undefined | null) {
- element?.scrollIntoView({
- inline: "nearest",
- block: "nearest",
- });
-}
diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.ts
index a46831c5a0..8baef2ccb3 100644
--- a/apps/carbon/app/hooks/index.ts
+++ b/apps/carbon/app/hooks/index.ts
@@ -1,6 +1,13 @@
+import { useMovingCellRef } from "./useMovingCellRef";
import { usePermissions } from "./usePermissions";
import { useRouteData } from "./useRouteData";
import { useUser } from "./useUser";
import { useUrlParams } from "./useUrlParams";
-export { usePermissions, useRouteData, useUser, useUrlParams };
+export {
+ useMovingCellRef,
+ usePermissions,
+ useRouteData,
+ useUser,
+ useUrlParams,
+};
diff --git a/apps/carbon/app/components/Table/hooks/useMovingCellRef.tsx b/apps/carbon/app/hooks/useMovingCellRef.tsx
similarity index 95%
rename from apps/carbon/app/components/Table/hooks/useMovingCellRef.tsx
rename to apps/carbon/app/hooks/useMovingCellRef.tsx
index 7de9b0f6cd..cd95b17077 100644
--- a/apps/carbon/app/components/Table/hooks/useMovingCellRef.tsx
+++ b/apps/carbon/app/hooks/useMovingCellRef.tsx
@@ -1,5 +1,5 @@
import { useCallback, useState } from "react";
-import { scrollIntoView } from "../utils";
+import { scrollIntoView } from "~/utils/dom";
// https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_roving_tabindex
export function useMovingCellRef(isSelected: boolean) {
diff --git a/apps/carbon/app/modules/account/services/account.server.ts b/apps/carbon/app/modules/account/services/account.server.ts
index 835d2a7d38..c2108d59e1 100644
--- a/apps/carbon/app/modules/account/services/account.server.ts
+++ b/apps/carbon/app/modules/account/services/account.server.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { sanitize } from "~/utils/supabase";
export async function deleteUserAttributeValue(
client: SupabaseClient<Database>,
@@ -65,9 +66,11 @@ export async function updateAvatar(
) {
return client
.from("user")
- .update({
- avatarUrl,
- })
+ .update(
+ sanitize({
+ avatarUrl,
+ })
+ )
.eq("id", userId);
}
@@ -83,11 +86,13 @@ export async function updatePublicAccount(
const { id, firstName, lastName, about } = args;
return client
.from("user")
- .update({
- firstName,
- lastName,
- about,
- })
+ .update(
+ sanitize({
+ firstName,
+ lastName,
+ about,
+ })
+ )
.eq("id", id);
}
diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.ts
index 93f3702fb4..1619316159 100644
--- a/apps/carbon/app/modules/accounting/services/accounting.server.ts
+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts
@@ -3,6 +3,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
import type { paymentTermValidator } from "./accounting.form";
export async function deletePaymentTerm(
@@ -62,6 +63,14 @@ export async function getPaymentTerms(
return query;
}
+export async function getPaymentTermsList(client: SupabaseClient<Database>) {
+ return client
+ .from("paymentTerm")
+ .select("id, name")
+ .eq("active", true)
+ .order("name", { ascending: true });
+}
+
export async function upsertPaymentTerm(
client: SupabaseClient<Database>,
paymentTerm:
@@ -78,7 +87,7 @@ export async function upsertPaymentTerm(
}
return client
.from("paymentTerm")
- .update(paymentTerm)
+ .update(sanitize(paymentTerm))
.eq("id", paymentTerm.id)
.select("id");
}
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx
index 36b7e4ac30..48f558d4b6 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentCreateForm/DocumentCreateForm.tsx
@@ -15,6 +15,7 @@ const DocumentCreateForm = () => {
if (e.target.files && supabase) {
const file = e.target.files[0];
const fileExtension = file.name.substring(file.name.lastIndexOf(".") + 1);
+ // TODO: refactor to use uuid
const fileName = `${user.id}/${Math.random()
.toString(32)
.slice(2)}.${fileExtension}`;
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
index f8fc6e6d84..f31f191983 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/DocumentsTable/DocumentsTable.tsx
@@ -32,8 +32,8 @@ import { VscOpenPreview } from "react-icons/vsc";
import { Avatar, Table } from "~/components";
import { Confirm, ConfirmDelete } from "~/components/Modals";
import { useUrlParams } from "~/hooks";
+import { DocumentIcon } from "~/modules/documents";
import type { Document, DocumentLabel } from "~/modules/documents";
-import DocumentIcon from "../DocumentIcon";
import { useDocument } from "../useDocument";
type DocumentsTableProps = {
diff --git a/apps/carbon/app/modules/documents/interfaces/Documents/index.ts b/apps/carbon/app/modules/documents/interfaces/Documents/index.ts
index 171f509e62..8d629feb00 100644
--- a/apps/carbon/app/modules/documents/interfaces/Documents/index.ts
+++ b/apps/carbon/app/modules/documents/interfaces/Documents/index.ts
@@ -1,5 +1,6 @@
import DocumentForm from "./DocumentForm";
+import DocumentIcon from "./DocumentIcon";
import DocumentsTable from "./DocumentsTable";
import DocumentsTableFilters from "./DocumentsTableFilters";
-export { DocumentForm, DocumentsTable, DocumentsTableFilters };
+export { DocumentForm, DocumentIcon, DocumentsTable, DocumentsTableFilters };
diff --git a/apps/carbon/app/modules/documents/services/documents.server.ts b/apps/carbon/app/modules/documents/services/documents.server.ts
index 4f1a630407..acaa544729 100644
--- a/apps/carbon/app/modules/documents/services/documents.server.ts
+++ b/apps/carbon/app/modules/documents/services/documents.server.ts
@@ -3,6 +3,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
import type {
documentLabelsValidator,
documentValidator,
@@ -206,10 +207,12 @@ export async function upsertDocument(
}
return client
.from("document")
- .update({
- ...document,
- updatedAt: new Date().toISOString(),
- })
+ .update(
+ sanitize({
+ ...document,
+ updatedAt: new Date().toISOString(),
+ })
+ )
.eq("id", document.id);
}
diff --git a/apps/carbon/app/modules/inventory/services/inventory.server.ts b/apps/carbon/app/modules/inventory/services/inventory.server.ts
index 8ae017eca1..8348f32514 100644
--- a/apps/carbon/app/modules/inventory/services/inventory.server.ts
+++ b/apps/carbon/app/modules/inventory/services/inventory.server.ts
@@ -3,6 +3,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
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";
export async function deleteShippingMethod(
@@ -47,6 +48,22 @@ export async function getShippingMethods(
return query;
}
+export async function getShippingMethodsList(client: SupabaseClient<Database>) {
+ return client
+ .from("shippingMethod")
+ .select("id, name")
+ .eq("active", true)
+ .order("name", { ascending: true });
+}
+
+export async function getShippingTermsList(client: SupabaseClient<Database>) {
+ return client
+ .from("shippingTerm")
+ .select("id, name")
+ .eq("active", true)
+ .order("name", { ascending: true });
+}
+
export async function upsertShippingMethod(
client: SupabaseClient<Database>,
shippingMethod:
@@ -63,7 +80,7 @@ export async function upsertShippingMethod(
}
return client
.from("shippingMethod")
- .update(shippingMethod)
+ .update(sanitize(shippingMethod))
.eq("id", shippingMethod.id)
.select("id");
}
diff --git a/apps/carbon/app/modules/inventory/types.ts b/apps/carbon/app/modules/inventory/types.ts
index a47d478b6c..a120fd18a3 100644
--- a/apps/carbon/app/modules/inventory/types.ts
+++ b/apps/carbon/app/modules/inventory/types.ts
@@ -1,8 +1,8 @@
import type { Database } from "@carbon/database";
-import type { getShippingMethod } from "./services";
+import type { getShippingMethods } from "./services";
export type ShippingCarrier = Database["public"]["Enums"]["shippingCarrier"];
export type ShippingMethod = NonNullable<
- Awaited<ReturnType<typeof getShippingMethod>>["data"]
+ Awaited<ReturnType<typeof getShippingMethods>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx
index fd1096b1c5..12b80ed07b 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx
@@ -11,7 +11,6 @@ import { ValidatedForm } from "remix-validated-form";
import {
Boolean,
Hidden,
- Input,
Number,
Select,
Submit,
@@ -57,16 +56,20 @@ const PartPurchasingForm = ({
w="full"
>
<VStack alignItems="start" spacing={2} w="full">
- <Supplier name="supplierId" label="Supplier" />
- <Input name="supplierPartNumber" label="Supplier Part Number" />
+ <Supplier name="preferredSupplierId" label="Preferred Supplier" />
+ <Number name="purchasingLeadTime" label="Lead Time (Days)" />
</VStack>
<VStack alignItems="start" spacing={2} w="full">
- <Number name="purchasingLeadTime" label="Lead Time (Days)" />
<Select
name="purchasingUnitOfMeasureCode"
label="Purchasing Unit of Measure"
options={unitOfMeasureOptions}
/>
+ <Number
+ name="conversionFactor"
+ label="Conversion Factor"
+ min={0}
+ />
</VStack>
<VStack alignItems="start" spacing={2} w="full">
<Boolean name="purchasingBlocked" label="Purchasing Blocked" />
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 d085551aec..f962c1b5b1 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx
@@ -1,3 +1,4 @@
+import { useColor } from "@carbon/react";
import { Button, Box, VStack } from "@chakra-ui/react";
import { Link, useMatches, useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
@@ -6,6 +7,7 @@ import { usePartSidebar } from "./usePartSidebar";
const PartSidebar = () => {
const { partId } = useParams();
+ const borderColor = useColor("gray.200");
if (!partId)
throw new Error(
"PartSidebar requires a partId and could not find partId in params"
@@ -36,7 +38,8 @@ const PartSidebar = () => {
as={Link}
to={route.to}
variant={isActive ? "solid" : "ghost"}
- border="none"
+ border={isActive ? "1px solid" : "none"}
+ borderColor={borderColor}
fontWeight={isActive ? "bold" : "normal"}
justifyContent="start"
size="md"
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx
index c276a4c0d6..a7a3caf8dd 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx
@@ -15,6 +15,12 @@ export function usePartSidebar(replenishment: PartReplenishmentSystem) {
isDisabled: replenishment === "Make",
role: ["employee", "supplier"],
},
+ {
+ name: "Suppliers",
+ to: "suppliers",
+ isDisabled: replenishment === "Make",
+ role: ["employee", "supplier"],
+ },
{
name: "Manufacturing",
to: "manufacturing",
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx
new file mode 100644
index 0000000000..0ebb5470fc
--- /dev/null
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/PartSupplierForm.tsx
@@ -0,0 +1,109 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useMemo } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Hidden,
+ Input,
+ Number,
+ Select,
+ Submit,
+ Supplier,
+} from "~/components/Form";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { UnitOfMeasureListItem } from "~/modules/parts";
+import { partSupplierValidator } from "~/modules/parts";
+import type { TypeOfValidator } from "~/types/validators";
+
+type PartSupplierFormProps = {
+ initialValues: TypeOfValidator<typeof partSupplierValidator>;
+};
+
+const PartSupplierForm = ({ initialValues }: PartSupplierFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const { partId } = useParams();
+
+ const sharedPartData = useRouteData<{
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>("/x/part");
+
+ const unitOfMeasureOptions = useMemo(() => {
+ return (
+ sharedPartData?.unitOfMeasures.map((unitOfMeasure) => ({
+ label: unitOfMeasure.code,
+ value: unitOfMeasure.code,
+ })) ?? []
+ );
+ }, [sharedPartData?.unitOfMeasures]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts");
+
+ const onClose = () => navigate(-1);
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ defaultValues={initialValues}
+ validator={partSupplierValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/part/${partId}/suppliers/${initialValues.id}`
+ : `/x/part/${partId}/suppliers/new`
+ }
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Purchase Order Line
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="partId" />
+
+ <VStack spacing={4} alignItems="start">
+ <Supplier name="supplierId" label="Supplier" />
+ <Input name="supplierPartId" label="Supplier Part ID" />
+ <Select
+ name="supplierUnitOfMeasureCode"
+ label="Unit of Measure"
+ options={unitOfMeasureOptions}
+ />
+ <Number
+ name="minimumOrderQuantity"
+ label="Minimum Order Quantity"
+ />
+ <Number name="conversionFactor" label="Conversion Factor" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default PartSupplierForm;
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/index.ts
new file mode 100644
index 0000000000..2cc49a0875
--- /dev/null
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSupplierForm/index.ts
@@ -0,0 +1,3 @@
+import PartSupplierForm from "./PartSupplierForm";
+
+export default PartSupplierForm;
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/PartSuppliers.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/PartSuppliers.tsx
new file mode 100644
index 0000000000..985776c451
--- /dev/null
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/PartSuppliers.tsx
@@ -0,0 +1,137 @@
+import {
+ Box,
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ HStack,
+ IconButton,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+import Grid from "~/components/Grid";
+import {
+ EditableList,
+ EditableNumber,
+ EditableText,
+} from "~/components/Editable";
+import type { PartSupplier, UnitOfMeasureListItem } from "~/modules/parts";
+import usePartSuppliers from "./usePartSuppliers";
+import { useRouteData } from "~/hooks";
+import { MdMoreHoriz } from "react-icons/md";
+
+type PartSuppliersProps = {
+ partSuppliers: PartSupplier[];
+};
+
+const PartSuppliers = ({ partSuppliers }: PartSuppliersProps) => {
+ const navigate = useNavigate();
+ const { canEdit, handleCellEdit } = usePartSuppliers();
+ const sharedPartData = useRouteData<{
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>("/x/part");
+
+ const unitOfMeasureOptions = useMemo(() => {
+ return (
+ sharedPartData?.unitOfMeasures.map((unitOfMeasure) => ({
+ label: unitOfMeasure.code,
+ value: unitOfMeasure.code,
+ })) ?? []
+ );
+ }, [sharedPartData?.unitOfMeasures]);
+
+ const columns = useMemo<ColumnDef<PartSupplier>[]>(() => {
+ return [
+ {
+ accessorKey: "supplier.id",
+ header: "Supplier",
+ cell: ({ row }) => (
+ <HStack justify="space-between">
+ {/* @ts-ignore */}
+ <span>{row.original.supplier.name}</span>
+ {canEdit && (
+ <Box position="relative" w={6} h={5}>
+ <IconButton
+ aria-label="Edit part supplier"
+ as={Link}
+ icon={<MdMoreHoriz />}
+ size="sm"
+ position="absolute"
+ right={-1}
+ top={-1}
+ to={`${row.original.id}`}
+ onClick={(e) => e.stopPropagation()}
+ variant="ghost"
+ />
+ </Box>
+ )}
+ </HStack>
+ ),
+ },
+ {
+ accessorKey: "supplierPartId",
+ header: "Part ID",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "supplierUnitOfMeasureCode",
+ header: "Unit of Measure",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "minimumOrderQuantity",
+ header: "Minimum Order Quantity",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "conversionFactor",
+ header: "Conversion Factor",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, [canEdit]);
+
+ const editableComponents = useMemo(
+ () => ({
+ supplierPartId: EditableText(handleCellEdit),
+ supplierUnitOfMeasureCode: EditableList(
+ handleCellEdit,
+ unitOfMeasureOptions
+ ),
+ minimumOrderQuantity: EditableNumber(handleCellEdit),
+ conversionFactor: EditableNumber(handleCellEdit),
+ }),
+ [handleCellEdit, unitOfMeasureOptions]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Suppliers
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ <Grid<PartSupplier>
+ data={partSuppliers}
+ columns={columns}
+ canEdit={canEdit}
+ editableComponents={editableComponents}
+ onNewRow={canEdit ? () => navigate("new") : undefined}
+ />
+ </CardBody>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default PartSuppliers;
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/index.ts
new file mode 100644
index 0000000000..f630a09f37
--- /dev/null
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/index.ts
@@ -0,0 +1,3 @@
+import PartSuppliers from "./PartSuppliers";
+
+export default PartSuppliers;
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/usePartSuppliers.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/usePartSuppliers.tsx
new file mode 100644
index 0000000000..ebef6d3e47
--- /dev/null
+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSuppliers/usePartSuppliers.tsx
@@ -0,0 +1,32 @@
+import { useCallback } from "react";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { PartSupplier } from "~/modules/parts";
+
+export default function usePartSuppliers() {
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const canEdit = permissions.can("update", "parts");
+ const canDelete = permissions.can("delete", "parts");
+
+ const handleCellEdit = useCallback(
+ async (id: string, value: unknown, row: PartSupplier) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("partSupplier")
+ .update({
+ [id]: value,
+ })
+ .eq("id", row.id);
+ },
+ [supabase]
+ );
+
+ return {
+ canDelete,
+ canEdit,
+ supabase,
+ handleCellEdit,
+ };
+}
diff --git a/apps/carbon/app/modules/parts/interfaces/Part/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/index.ts
index 28b261070d..ee73974235 100644
--- a/apps/carbon/app/modules/parts/interfaces/Part/index.ts
+++ b/apps/carbon/app/modules/parts/interfaces/Part/index.ts
@@ -7,6 +7,8 @@ import PartPreview from "./PartPreview";
import PartPurchasingForm from "./PartPurchasingForm";
import PartSalePriceForm from "./PartSalePriceForm";
import PartSidebar from "./PartSidebar";
+import PartSupplierForm from "./PartSupplierForm";
+import PartSuppliers from "./PartSuppliers";
export {
PartCostingForm,
@@ -18,4 +20,6 @@ export {
PartPurchasingForm,
PartSalePriceForm,
PartSidebar,
+ PartSupplierForm,
+ PartSuppliers,
};
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 539b970d63..a17b3734f1 100644
--- a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx
+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx
@@ -68,7 +68,7 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
navigate(`/x/parts/groups/${row.id}?${params.toString()}`);
}}
>
- Edit Part Group
+ View Part Group
</MenuItem>
<MenuItem
isDisabled={!permissions.can("delete", "parts")}
diff --git a/apps/carbon/app/modules/parts/services/parts.form.ts b/apps/carbon/app/modules/parts/services/parts.form.ts
index 2ef77dfa74..7b4a0b08fe 100644
--- a/apps/carbon/app/modules/parts/services/parts.form.ts
+++ b/apps/carbon/app/modules/parts/services/parts.form.ts
@@ -118,14 +118,26 @@ export const partPlanningValidator = withZod(
export const partPurchasingValidator = withZod(
z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
- supplierId: zfd.text(z.string().optional()),
- supplierPartNumber: zfd.text(z.string().optional()),
+ preferredSupplierId: zfd.text(z.string().optional()),
+ conversionFactor: zfd.numeric(z.number().min(0)),
purchasingLeadTime: zfd.numeric(z.number().min(0)),
purchasingUnitOfMeasureCode: zfd.text(z.string().optional()),
purchasingBlocked: zfd.checkbox(),
})
);
+export const partSupplierValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ partId: z.string().min(1, { message: "Part ID is required" }),
+ supplierId: z.string().min(36, { message: "Supplier ID is required" }),
+ supplierPartId: z.string().optional(),
+ supplierUnitOfMeasureCode: zfd.text(z.string().optional()),
+ minimumOrderQuantity: zfd.numeric(z.number().min(0)),
+ conversionFactor: zfd.numeric(z.number().min(0)),
+ })
+);
+
export const partUnitSalePriceValidator = withZod(
z.object({
partId: z.string().min(1, { message: "Part ID is required" }),
diff --git a/apps/carbon/app/modules/parts/services/parts.server.ts b/apps/carbon/app/modules/parts/services/parts.server.ts
index 96b7092c88..599534d060 100644
--- a/apps/carbon/app/modules/parts/services/parts.server.ts
+++ b/apps/carbon/app/modules/parts/services/parts.server.ts
@@ -3,12 +3,15 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
+import type { PartReplenishmentSystem } from "../types";
import type {
partCostValidator,
partInventoryValidator,
partManufacturingValidator,
partPlanningValidator,
partPurchasingValidator,
+ partSupplierValidator,
partUnitSalePriceValidator,
partValidator,
} from "./parts.form";
@@ -157,6 +160,19 @@ export async function getParts(
return query;
}
+export async function getPartsList(
+ client: SupabaseClient<Database>,
+ replenishmentSystem: PartReplenishmentSystem | null
+) {
+ let query = client.from("part").select("id, name");
+ if (replenishmentSystem) {
+ query = query.or(
+ `replenishmentSystem.eq.${replenishmentSystem},replenishmentSystem.eq.Buy and Make`
+ );
+ }
+ return query;
+}
+
export async function getPartSummary(
client: SupabaseClient<Database>,
id: string
@@ -170,6 +186,23 @@ export async function getPartSummary(
.single();
}
+export async function getPartSuppliers(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("partSupplier")
+ .select(
+ `
+ id, supplier(id, name),
+ supplierPartId, supplierUnitOfMeasureCode,
+ minimumOrderQuantity, conversionFactor
+ `
+ )
+ .eq("active", true)
+ .eq("partId", id);
+}
+
export async function getPartUnitSalePrice(
client: SupabaseClient<Database>,
id: string
@@ -271,14 +304,17 @@ export async function upsertPart(
if ("createdBy" in part) {
return client.from("part").insert(part).select("id");
}
- return client.from("part").update(part).eq("id", part.id);
+ return client.from("part").update(sanitize(part)).eq("id", part.id);
}
export async function upsertPartCost(
client: SupabaseClient<Database>,
partCost: TypeOfValidator<typeof partCostValidator> & { updatedBy: string }
) {
- return client.from("partCost").update(partCost).eq("partId", partCost.partId);
+ return client
+ .from("partCost")
+ .update(sanitize(partCost))
+ .eq("partId", partCost.partId);
}
export async function upsertPartInventory(
@@ -292,10 +328,7 @@ export async function upsertPartInventory(
) {
return client
.from("partInventory")
- .update({
- ...partInventory,
- shelfId: partInventory.shelfId || null,
- })
+ .update(sanitize(partInventory))
.eq("partId", partInventory.partId);
}
@@ -307,7 +340,7 @@ export async function upsertPartManufacturing(
) {
return client
.from("partReplenishment")
- .update(partManufacturing)
+ .update(sanitize(partManufacturing))
.eq("partId", partManufacturing.partId);
}
@@ -319,7 +352,7 @@ export async function upsertPartPlanning(
) {
return client
.from("partPlanning")
- .update(partPlanning)
+ .update(sanitize(partPlanning))
.eq("partId", partPlanning.partId);
}
@@ -331,7 +364,7 @@ export async function upsertPartPurchasing(
) {
return client
.from("partReplenishment")
- .update(partPurchasing)
+ .update(sanitize(partPurchasing))
.eq("partId", partPurchasing.partId);
}
@@ -362,13 +395,34 @@ export async function upsertPartGroup(
return (
client
.from("partGroup")
- .update(partGroup)
+ .update(sanitize(partGroup))
// @ts-ignore
.eq("id", partGroup.id)
.select("id")
);
}
+export async function upsertPartSupplier(
+ client: SupabaseClient<Database>,
+ partSupplier:
+ | (Omit<TypeOfValidator<typeof partSupplierValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof partSupplierValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("createdBy" in partSupplier) {
+ return client.from("partSupplier").insert([partSupplier]).select("id");
+ }
+ return client
+ .from("partSupplier")
+ .update(sanitize(partSupplier))
+ .eq("id", partSupplier.id)
+ .select("id");
+}
+
export async function upsertPartUnitSalePrice(
client: SupabaseClient<Database>,
partUnitSalePrice: TypeOfValidator<typeof partUnitSalePriceValidator> & {
@@ -377,7 +431,7 @@ export async function upsertPartUnitSalePrice(
) {
return client
.from("partUnitSalePrice")
- .update(partUnitSalePrice)
+ .update(sanitize(partUnitSalePrice))
.eq("partId", partUnitSalePrice.partId);
}
@@ -390,7 +444,7 @@ export async function upsertUnitOfMeasure(
if ("id" in unitOfMeasure) {
return client
.from("unitOfMeasure")
- .update(unitOfMeasure)
+ .update(sanitize(unitOfMeasure))
.eq("id", unitOfMeasure.id)
.select("id");
}
diff --git a/apps/carbon/app/modules/parts/types.ts b/apps/carbon/app/modules/parts/types.ts
index e1acc3ef1d..e37e13d599 100644
--- a/apps/carbon/app/modules/parts/types.ts
+++ b/apps/carbon/app/modules/parts/types.ts
@@ -5,6 +5,7 @@ import type {
getPartGroupsList,
getParts,
getPartSummary,
+ getPartSuppliers,
getUnitOfMeasure,
getUnitOfMeasuresList,
} from "./services";
@@ -34,6 +35,10 @@ export type PartSummary = NonNullable<
Awaited<ReturnType<typeof getPartSummary>>
>["data"];
+export type PartSupplier = NonNullable<
+ Awaited<ReturnType<typeof getPartSuppliers>>["data"]
+>[number];
+
export type PartManufacturingPolicy =
Database["public"]["Enums"]["partManufacturingPolicy"];
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/PurchaseOrderDeliveryForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/PurchaseOrderDeliveryForm.tsx
new file mode 100644
index 0000000000..add811c52a
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/PurchaseOrderDeliveryForm.tsx
@@ -0,0 +1,136 @@
+import {
+ Card,
+ CardBody,
+ CardFooter,
+ CardHeader,
+ Grid,
+ Heading,
+ VStack,
+} from "@chakra-ui/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Boolean,
+ Customer,
+ CustomerLocation,
+ DatePicker,
+ Hidden,
+ Input,
+ Location,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { purchaseOrderDeliveryValidator } from "~/modules/purchasing";
+import type { ListItem } from "~/types";
+import type { TypeOfValidator } from "~/types/validators";
+
+type PurchaseOrderDeliveryFormProps = {
+ initialValues: TypeOfValidator<typeof purchaseOrderDeliveryValidator>;
+ shippingMethods: ListItem[];
+ shippingTerms: ListItem[];
+};
+
+const PurchaseOrderDeliveryForm = ({
+ initialValues,
+ shippingMethods,
+ shippingTerms,
+}: PurchaseOrderDeliveryFormProps) => {
+ const permissions = usePermissions();
+ const [dropShip, setDropShip] = useState<boolean>(
+ initialValues.dropShipment ?? false
+ );
+ const [customer, setCustomer] = useState<string | undefined>(
+ initialValues.customerId
+ );
+
+ const shippingMethodOptions = shippingMethods.map((method) => ({
+ label: method.name,
+ value: method.id,
+ }));
+
+ const shippingTermOptions = shippingTerms.map((term) => ({
+ label: term.name,
+ value: term.id,
+ }));
+
+ const isSupplier = permissions.is("supplier");
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={purchaseOrderDeliveryValidator}
+ defaultValues={initialValues}
+ >
+ <Card w="full">
+ <CardHeader>
+ <Heading size="md">Delivery</Heading>
+ </CardHeader>
+ <CardBody>
+ <Hidden name="id" />
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={2}
+ w="full"
+ >
+ <VStack alignItems="start" spacing={2} w="full">
+ <Location
+ name="locationId"
+ label="Delivery Location"
+ isReadOnly={isSupplier}
+ isClearable
+ />
+ <Select
+ name="shippingMethodId"
+ label="Shipping Method"
+ options={shippingMethodOptions}
+ />
+ <Select
+ name="shippingTermId"
+ label="Shipping Terms"
+ isReadOnly={isSupplier}
+ options={shippingTermOptions}
+ />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <DatePicker name="receiptRequestedDate" label="Requested Date" />
+ <DatePicker name="receiptPromisedDate" label="Promised Date" />
+ <DatePicker name="deliveryDate" label="Delivery Date" />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Input name="trackingNumber" label="Tracking Number" />
+ {/* <TextArea name="notes" label="Shipping Notes" /> */}
+ <Boolean
+ name="dropShipment"
+ label="Drop Shipment"
+ onChange={setDropShip}
+ />
+ {dropShip && (
+ <>
+ <Customer
+ name="customerId"
+ label="Customer"
+ onChange={({ value }) => setCustomer(value as string)}
+ />
+ <CustomerLocation
+ name="customerLocationId"
+ label="Location"
+ customer={customer}
+ />
+ </>
+ )}
+ </VStack>
+ </Grid>
+ </CardBody>
+ <CardFooter>
+ <Submit isDisabled={!permissions.can("update", "purchasing")}>
+ Save
+ </Submit>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default PurchaseOrderDeliveryForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/index.ts
new file mode 100644
index 0000000000..dae56ba98c
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDeliveryForm/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderDeliveryForm from "./PurchaseOrderDeliveryForm";
+
+export default PurchaseOrderDeliveryForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/PurchaseOrderDocumentForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/PurchaseOrderDocumentForm.tsx
new file mode 100644
index 0000000000..e21fcc30f4
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/PurchaseOrderDocumentForm.tsx
@@ -0,0 +1,50 @@
+import { File, useNotification } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import type { ChangeEvent } from "react";
+import { IoMdAdd } from "react-icons/io";
+import { useSupabase } from "~/lib/supabase";
+
+type PurchaseOrderDocumentFormProps = {
+ orderId: string;
+ isExternal: boolean;
+};
+
+const PurchaseOrderDocumentForm = ({
+ orderId,
+ isExternal,
+}: PurchaseOrderDocumentFormProps) => {
+ const fetcher = useFetcher();
+ const notification = useNotification();
+ const { supabase } = useSupabase();
+
+ const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files && supabase) {
+ const file = e.target.files[0];
+ const fileName = `${orderId}/${file.name}`;
+
+ const fileUpload = await supabase.storage
+ .from(`purchasing-${isExternal ? "external" : "internal"}`)
+ .upload(fileName, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ });
+
+ if (fileUpload.error) {
+ notification.copyableError(fileUpload.error, "Failed to upload file");
+ }
+
+ if (fileUpload.data?.path) {
+ notification.success("File uploaded");
+ // refetch the loaders
+ fetcher.submit(null, { method: "post" });
+ }
+ }
+ };
+
+ return (
+ <File leftIcon={<IoMdAdd />} onChange={uploadFile}>
+ New
+ </File>
+ );
+};
+
+export default PurchaseOrderDocumentForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/index.ts
new file mode 100644
index 0000000000..80f0733510
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderDocumentForm/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderDocumentForm from "./PurchaseOrderDocumentForm";
+
+export default PurchaseOrderDocumentForm;
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 a39f7ede33..114241255a 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx
@@ -8,15 +8,18 @@ import {
Text,
VStack,
} from "@chakra-ui/react";
+import { useState } from "react";
import { ValidatedForm } from "remix-validated-form";
import {
Boolean,
- Currency,
DatePicker,
+ Hidden,
Input,
Select,
Submit,
Supplier,
+ SupplierContact,
+ TextArea,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
import type {
@@ -24,14 +27,9 @@ import type {
PurchaseOrderType,
} from "~/modules/purchasing";
import { purchaseOrderValidator } from "~/modules/purchasing";
+import type { TypeOfValidator } from "~/types/validators";
-type PurchaseOrderFormValues = {
- id?: string;
- purchaseOrderId?: string;
- status: PurchaseOrderApprovalStatus;
- type: PurchaseOrderType;
- currencyCode: string;
-};
+type PurchaseOrderFormValues = TypeOfValidator<typeof purchaseOrderValidator>;
type PurchaseOrderFormProps = {
initialValues: PurchaseOrderFormValues;
@@ -45,7 +43,11 @@ const PurchaseOrderForm = ({
purchaseOrderTypes,
}: PurchaseOrderFormProps) => {
const permissions = usePermissions();
+ const [supplier, setSupplier] = useState<string | undefined>(
+ initialValues.supplierId
+ );
const isEditing = initialValues.id !== undefined;
+ const isSupplier = permissions.is("supplier");
const approvalOptions = purchaseOrderApprovalStatuses.map((approval) => ({
label: approval,
@@ -66,7 +68,7 @@ const PurchaseOrderForm = ({
<Card w="full">
<CardHeader>
<Heading size="md">
- {isEditing ? "Purchase Order Basics" : "New Purchase Order"}
+ {isEditing ? "Purchase Order" : "New Purchase Order"}
</Heading>
{!isEditing && (
<Text color="gray.500">
@@ -76,6 +78,7 @@ const PurchaseOrderForm = ({
)}
</CardHeader>
<CardBody>
+ <Hidden name="purchaseOrderId" />
<Grid
gridTemplateColumns={
isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"
@@ -85,28 +88,52 @@ const PurchaseOrderForm = ({
w="full"
>
<VStack alignItems="start" spacing={2} w="full">
+ <Supplier
+ name="supplierId"
+ label="Supplier"
+ onChange={(newValue) =>
+ setSupplier(newValue?.value as string | undefined)
+ }
+ />
{isEditing && (
- <Input
- name="id"
- label="Purchase Order ID"
- isReadOnly={isEditing}
+ <SupplierContact
+ name="supplierContactId"
+ label="Supplier Contact"
+ supplier={supplier}
/>
)}
- <Supplier name="supplierId" label="Supplier" />
- <DatePicker name="orderDate" label="Order Date" />
+ <Input name="supplierReference" label="Supplier Invoice Number" />
</VStack>
<VStack alignItems="start" spacing={2} w="full">
+ <DatePicker
+ name="orderDate"
+ label="Order Date"
+ isDisabled={isSupplier}
+ />
<Select name="type" label="Type" options={typeOptions} />
<Select
name="status"
label="Approval Status"
+ isReadOnly={isSupplier}
options={approvalOptions}
/>
</VStack>
<VStack alignItems="start" spacing={2} w="full">
- <Currency name="currencyCode" label="Currency" />
- <Boolean name="blocked" label="Blocked" />
- {isEditing && <Boolean name="active" label="Active" />}
+ {isEditing && (
+ <>
+ <Boolean
+ name="closed"
+ label="Closed"
+ isReadOnly={isSupplier}
+ isDisabled={isSupplier}
+ />
+ <TextArea
+ name="notes"
+ label="Notes"
+ isReadOnly={isSupplier}
+ />
+ </>
+ )}
</VStack>
</Grid>
</CardBody>
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 4febcbf25e..02f03fa3dd 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
@@ -16,18 +16,24 @@ import type { PurchaseOrder } from "~/modules/purchasing";
const PartPreview = () => {
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
- const routeData = useRouteData<PurchaseOrder>(`/x/purchase-order/${orderId}`);
+ const routeData = useRouteData<{ purchaseOrder: PurchaseOrder }>(
+ `/x/purchase-order/${orderId}`
+ );
return (
<Card w="full">
<CardHeader>
<HStack justifyContent="space-between" alignItems="start">
<Stack direction="column" spacing={2}>
- <Heading size="md">{routeData?.purchaseOrderId}</Heading>
- <Text color="gray.500">{routeData?.supplierName}</Text>
+ <Heading size="md">
+ {routeData?.purchaseOrder?.purchaseOrderId}
+ </Heading>
+ <Text color="gray.500">
+ {routeData?.purchaseOrder?.supplierName}
+ </Text>
</Stack>
<Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
- View History
+ Supplier Details
</Button>
</HStack>
</CardHeader>
@@ -39,15 +45,29 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Order Date</Text>
- <Text fontWeight="bold">{routeData?.orderDate}</Text>
+ <Text fontWeight="bold">{routeData?.purchaseOrder?.orderDate}</Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <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"
>
- <Text color="gray.500">Due Date</Text>
- <Text fontWeight="bold">{routeData?.orderDueDate}</Text>
+ <Text color="gray.500">Promised Date</Text>
+ <Text fontWeight="bold">
+ {routeData?.purchaseOrder?.receiptPromisedDate}
+ </Text>
</Stack>
<Stack
direction={["row", "row", "column"]}
@@ -55,7 +75,7 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Order Type</Text>
- <Text fontWeight="bold">{routeData?.type}</Text>
+ <Text fontWeight="bold">{routeData?.purchaseOrder?.type}</Text>
</Stack>
<Stack
direction={["row", "row", "column"]}
@@ -63,7 +83,7 @@ const PartPreview = () => {
justifyContent="space-between"
>
<Text color="gray.500">Order Status</Text>
- <Text fontWeight="bold">{routeData?.status}</Text>
+ <Text fontWeight="bold">{routeData?.purchaseOrder?.status}</Text>
</Stack>
</Stack>
</CardBody>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/PurchaseOrderDocuments.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/PurchaseOrderDocuments.tsx
new file mode 100644
index 0000000000..63246d7f1e
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/PurchaseOrderDocuments.tsx
@@ -0,0 +1,135 @@
+import { convertKbToString } from "@carbon/utils";
+import {
+ Card,
+ CardBody,
+ CardHeader,
+ Flex,
+ Heading,
+ HStack,
+ IconButton,
+ Link,
+ Menu,
+ MenuButton,
+ MenuItem,
+ MenuList,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+} from "@chakra-ui/react";
+import { Outlet } from "@remix-run/react";
+import { MdMoreVert } from "react-icons/md";
+import { DocumentIcon } from "~/modules/documents";
+import type { PurchaseOrderAttachment } from "~/modules/purchasing";
+import { PurchaseOrderDocumentForm } from "~/modules/purchasing";
+import { usePurchaseOrderDocuments } from "./usePurchaseOrderDocuments";
+
+type PurchaseOrderDocumentsProps = {
+ attachments: PurchaseOrderAttachment[];
+ isExternal: boolean;
+ orderId: string;
+};
+
+const PurchaseOrderDocuments = ({
+ attachments,
+ isExternal,
+ orderId,
+}: PurchaseOrderDocumentsProps) => {
+ const { canDelete, download, deleteAttachment } = usePurchaseOrderDocuments({
+ attachments,
+ isExternal,
+ orderId,
+ });
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ {isExternal ? "External" : "Internal"} Attachments
+ </Heading>
+ <PurchaseOrderDocumentForm
+ isExternal={isExternal}
+ orderId={orderId}
+ />
+ </CardHeader>
+ <CardBody>
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ {/* <Th>Uploaded By</Th> */}
+ <Th></Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {attachments.length ? (
+ attachments.map((attachment) => (
+ <Tr key={attachment.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon fileName={attachment.name} />
+ <Link onClick={() => download(attachment)}>
+ {attachment.name}
+ </Link>
+ </HStack>
+ </Td>
+ <Td>
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ {/* <Td>
+ <HStack>
+ <Avatar
+ size="sm"
+ path={getAvatarPath(attachment.owner) ?? null}
+ />
+ <Text>{getFullName(attachment.owner)}</Text>
+ </HStack>
+ </Td> */}
+ <Td>
+ <Flex w="full" justifyContent="flex-end">
+ <Menu>
+ <MenuButton
+ aria-label="More"
+ as={IconButton}
+ icon={<MdMoreVert />}
+ variant="outline"
+ />
+ <MenuList>
+ <MenuItem onClick={() => download(attachment)}>
+ Download
+ </MenuItem>
+ <MenuItem
+ isDisabled={!canDelete}
+ onClick={() => deleteAttachment(attachment)}
+ >
+ Delete
+ </MenuItem>
+ </MenuList>
+ </Menu>
+ </Flex>
+ </Td>
+ </Tr>
+ ))
+ ) : (
+ <Tr>
+ <Td colSpan={24} py={8} color="gray.500" textAlign="center">
+ No {isExternal ? "external" : "internal"} attachments
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ </CardBody>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default PurchaseOrderDocuments;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/index.ts
new file mode 100644
index 0000000000..34b4c070ad
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderDocuments from "./PurchaseOrderDocuments";
+
+export default PurchaseOrderDocuments;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/usePurchaseOrderDocuments.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/usePurchaseOrderDocuments.ts
new file mode 100644
index 0000000000..143400518b
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderInternalDocuments/usePurchaseOrderDocuments.ts
@@ -0,0 +1,164 @@
+import { useNotification } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useCallback } from "react";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { PurchaseOrderAttachment } from "~/modules/purchasing/types";
+
+type Props = {
+ attachments: PurchaseOrderAttachment[];
+ isExternal: boolean;
+ orderId: string;
+};
+
+export const usePurchaseOrderDocuments = ({
+ attachments,
+ isExternal,
+ orderId,
+}: Props) => {
+ const notification = useNotification();
+ const fetcher = useFetcher();
+ const permissions = usePermissions();
+ const { supabase } = useSupabase();
+
+ // const [users, setUsers] = useState<
+ // {
+ // id: string;
+ // firstName: string | null;
+ // lastName: string | null;
+ // avatarUrl: string | null;
+ // }[]
+ // >([]);
+
+ const canDelete = permissions.can("delete", "purchasing"); // TODO: or is document owner
+
+ const refresh = useCallback(
+ () => fetcher.submit(null, { method: "post" }),
+ [fetcher]
+ );
+
+ // const getUsers = useCallback(async () => {
+ // const userIds = [
+ // ...new Set(attachments.map((attachment) => attachment.owner)),
+ // ];
+
+ // if (!supabase) return {};
+
+ // const { data, error } = await supabase
+ // .from("users")
+ // .select("*")
+ // .in("id", userIds);
+
+ // if (error) {
+ // setUsers([]);
+ // } else {
+ // console.log(data);
+ // setUsers(data);
+ // }
+ // }, [attachments, supabase]);
+
+ // useEffect(() => {
+ // getUsers();
+ // }, [getUsers]);
+
+ // const usersMap = useMemo<
+ // Record<string, { fullName: string; avatarUrl: string | null }>
+ // >(() => {
+ // return users.reduce<
+ // Record<string, { fullName: string; avatarUrl: string | null }>
+ // >((acc, user) => {
+ // acc[user.id] = {
+ // fullName: `${user.firstName} ${user.lastName}`,
+ // avatarUrl: user.avatarUrl,
+ // };
+ // return acc;
+ // }, {});
+ // }, [users]);
+
+ const deleteAttachment = useCallback(
+ async (attachment: PurchaseOrderAttachment) => {
+ const result = await supabase?.storage
+ .from(isExternal ? "purchasing-external" : "purchasing-internal")
+ .remove([`${orderId}/${attachment.name}`]);
+
+ if (!result || result.error) {
+ notification.error(result?.error?.message || "Error deleting file");
+ return;
+ }
+
+ notification.success("File deleted successfully");
+ refresh();
+ },
+ [supabase, notification, orderId, isExternal, refresh]
+ );
+
+ const download = useCallback(
+ async (attachment: PurchaseOrderAttachment) => {
+ const result = await supabase?.storage
+ .from(isExternal ? "purchasing-external" : "purchasing-internal")
+ .download(`${orderId}/${attachment.name}`);
+
+ if (!result || result.error) {
+ notification.error(result?.error?.message || "Error downloading file");
+ return;
+ }
+
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ const url = window.URL.createObjectURL(result.data);
+ a.href = url;
+ a.download = attachment.name;
+ a.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }, 0);
+ },
+ [supabase, notification, orderId, isExternal]
+ );
+
+ // const getAvatarPath = useCallback(
+ // (userId: string) => {
+ // return usersMap[userId]?.avatarUrl;
+ // },
+ // [usersMap]
+ // );
+
+ // const getFullName = useCallback(
+ // (userId: string) => {
+ // return usersMap[userId]?.fullName;
+ // },
+ // [usersMap]
+ // );
+
+ const isImage = useCallback((fileType: string) => {
+ return ["png", "jpg", "jpeg", "gif", "svg", "avif"].includes(fileType);
+ }, []);
+
+ const makePreview = useCallback(
+ async (attachment: PurchaseOrderAttachment) => {
+ const result = await supabase?.storage
+ .from(isExternal ? "purchasing-external" : "purchasing-internal")
+ .download(`${orderId}/${attachment.name}`);
+
+ if (!result || result.error) {
+ notification.error(result?.error?.message || "Error previewing file");
+ return null;
+ }
+
+ return window.URL.createObjectURL(result.data);
+ },
+ [isExternal, notification, orderId, supabase?.storage]
+ );
+
+ return {
+ canDelete,
+ deleteAttachment,
+ download,
+ // getAvatarPath,
+ // getFullName,
+ isImage,
+ makePreview,
+ };
+};
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
new file mode 100644
index 0000000000..a6e6065b4c
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
@@ -0,0 +1,226 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ FormControl,
+ FormLabel,
+ HStack,
+ Input as ChakraInput,
+ NumberDecrementStepper,
+ NumberIncrementStepper,
+ NumberInput,
+ NumberInputField,
+ NumberInputStepper,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Account,
+ Hidden,
+ Number,
+ Part,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { PurchaseOrderLineType } from "~/modules/purchasing";
+import { purchaseOrderLineValidator } from "~/modules/purchasing";
+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 { orderId } = useParams();
+
+ const [type, setType] = useState(initialValues.purchaseOrderLineType);
+ const [partData, setPartData] = useState<{
+ description: string;
+ unitPrice: string;
+ uom: string;
+ shelfId: string;
+ }>({
+ description: initialValues.description ?? "",
+ unitPrice: initialValues.unitPrice?.toString() ?? "0",
+ uom: initialValues.unitOfMeasureCode ?? "",
+ shelfId: initialValues.shelfId ?? "",
+ });
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "purchasing")
+ : !permissions.can("create", "purchasing");
+
+ const purchaseOrderLineTypeOptions = purchaseOrderLineTypes.map((type) => ({
+ label: type,
+ value: type,
+ }));
+
+ const onClose = () => navigate(-1);
+
+ const onTypeChange = (type: PurchaseOrderLineType) => {
+ setType(type);
+ setPartData({
+ description: "",
+ unitPrice: "0",
+ uom: "EA",
+ shelfId: "",
+ });
+ };
+
+ const onPartChange = async (partId: string) => {
+ if (!supabase) return;
+ const [part, shelf, cost] = await Promise.all([
+ supabase
+ .from("part")
+ .select("name, unitOfMeasureCode")
+ .eq("id", partId)
+ .single(),
+ supabase
+ .from("partInventory")
+ .select("shelfId")
+ .eq("partId", partId)
+ .single(),
+ supabase
+ .from("partCost")
+ .select("unitCost")
+ .eq("partId", partId)
+ .single(),
+ ]);
+
+ setPartData({
+ description: part.data?.name ?? "",
+ unitPrice: cost.data?.unitCost?.toString() ?? "0",
+ uom: part.data?.unitOfMeasureCode ?? "EA",
+ shelfId: shelf.data?.shelfId ?? "",
+ });
+ };
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ defaultValues={initialValues}
+ validator={purchaseOrderLineValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/purchase-order/${orderId}/lines/${initialValues.id}`
+ : `/x/purchase-order/${orderId}/lines/new`
+ }
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>
+ {isEditing ? "Edit" : "New"} Purchase Order Line
+ </DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <Hidden name="purchaseOrderId" />
+ <Hidden name="description" value={partData.description} />
+ <VStack spacing={4} alignItems="start">
+ <Select
+ name="purchaseOrderLineType"
+ label="Type"
+ options={purchaseOrderLineTypeOptions}
+ onChange={({ value }) => {
+ onTypeChange(value as PurchaseOrderLineType);
+ }}
+ />
+ {type === "Part" && (
+ <Part
+ name="partId"
+ label="Part"
+ partReplenishmentSystem="Buy"
+ onChange={({ value }) => {
+ onPartChange(value as string);
+ }}
+ />
+ )}
+
+ {type === "G/L Account" && (
+ <Account
+ name="accountNumber"
+ label="Account"
+ onChange={({ label }) => {
+ setPartData({
+ description: label,
+ unitPrice: "0",
+ uom: "EA",
+ shelfId: "",
+ });
+ }}
+ />
+ )}
+ {type === "Fixed Asset" && (
+ // TODO: implement Fixed Asset
+ <Select name="assetId" label="Asset" options={[]} />
+ )}
+ <FormControl>
+ <FormLabel>Description</FormLabel>
+ <ChakraInput
+ value={partData.description}
+ onChange={(e) =>
+ setPartData((d) => ({ ...d, description: e.target.value }))
+ }
+ />
+ </FormControl>
+ <Number name="purchaseQuantity" label="Quantity" />
+ {/*
+ // TODO: implement this and replace the UoM in PartForm */}
+ {/* <UnitOfMeasure name="unitOfMeasureCode" label="Unit of Measure" value={uom} /> */}
+ <FormControl>
+ <FormLabel htmlFor="unitPrice">Unit Cost</FormLabel>
+ <NumberInput
+ name="unitPrice"
+ value={partData.unitPrice}
+ onChange={(value) =>
+ setPartData((d) => ({
+ ...d,
+ unitPrice: value,
+ }))
+ }
+ >
+ <NumberInputField />
+ <NumberInputStepper>
+ <NumberIncrementStepper />
+ <NumberDecrementStepper />
+ </NumberInputStepper>
+ </NumberInput>
+ </FormControl>
+ {/*
+ // TODO:
+ <Shelf name="shelfId" label="Shelf" value={shelf}/> */}
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default PurchaseOrderLineForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/index.ts
new file mode 100644
index 0000000000..38cb8fce07
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLineForm/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderLineForm from "./PurchaseOrderLineForm";
+
+export default PurchaseOrderLineForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
new file mode 100644
index 0000000000..6cab8c39de
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -0,0 +1,186 @@
+import {
+ Button,
+ Box,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ HStack,
+ IconButton,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+import Grid from "~/components/Grid";
+import {
+ EditablePurchaseOrderLineNumber,
+ EditableNumber,
+ EditableText,
+} from "~/components/Editable";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
+import usePurchaseOrderLines from "./usePurchaseOrderLines";
+import { MdMoreHoriz } from "react-icons/md";
+
+type PurchaseOrderLinesProps = {
+ purchaseOrderLines: PurchaseOrderLine[];
+};
+
+const PurchaseOrderLines = ({
+ purchaseOrderLines,
+}: PurchaseOrderLinesProps) => {
+ const navigate = useNavigate();
+ const { canEdit, supabase, partOptions, accountOptions, handleCellEdit } =
+ usePurchaseOrderLines();
+
+ const columns = useMemo<ColumnDef<PurchaseOrderLine>[]>(() => {
+ return [
+ {
+ accessorKey: "purchaseOrderLineType",
+ header: "Type",
+ cell: ({ row }) => (
+ <HStack justify="space-between">
+ <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"
+ />
+ </Box>
+ </HStack>
+ ),
+ },
+ {
+ accessorKey: "partId",
+ header: "Number",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Part":
+ return <span>{row.original.partId}</span>;
+ case "G/L Account":
+ return <span>{row.original.accountNumber}</span>;
+ case "Comment":
+ return null;
+ case "Fixed Asset":
+ return <span>{row.original.assetId}</span>;
+ default:
+ return null;
+ }
+ },
+ },
+ {
+ accessorKey: "description",
+ header: "Description",
+ cell: ({ row }) => {
+ let description = row.original.description ?? "";
+ if (description.length > 50) {
+ description = description.substring(0, 50) + "...";
+ }
+ return <span>{description}</span>;
+ },
+ },
+ {
+ accessorKey: "purchaseQuantity",
+ header: "Quantity",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <span>{row.original.purchaseQuantity}</span>;
+ }
+ },
+ },
+ {
+ accessorKey: "unitPrice",
+ header: "Unit Price",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <span>{row.original.unitPrice}</span>;
+ }
+ },
+ },
+ {
+ accessorKey: "shelfId",
+ header: "Shelf",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <span>{row.original.shelfId}</span>;
+ }
+ },
+ },
+ {
+ id: "totalPrice",
+ header: "Total Price",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ if (!row.original.unitPrice || !row.original.purchaseQuantity)
+ return 0;
+ return (
+ row.original.unitPrice * row.original.purchaseQuantity
+ ).toFixed(2);
+ }
+ },
+ },
+ ];
+ }, []);
+
+ const editableComponents = useMemo(
+ () => ({
+ description: EditableText(handleCellEdit),
+ purchaseQuantity: EditableNumber(handleCellEdit),
+ unitPrice: EditableNumber(handleCellEdit),
+ partId: EditablePurchaseOrderLineNumber(handleCellEdit, {
+ client: supabase,
+ parts: partOptions,
+ accounts: accountOptions,
+ }),
+ }),
+ [handleCellEdit, supabase, partOptions, accountOptions]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Purchase Order Lines
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ <Grid<PurchaseOrderLine>
+ data={purchaseOrderLines}
+ columns={columns}
+ canEdit={canEdit}
+ editableComponents={editableComponents}
+ onNewRow={canEdit ? () => navigate("new") : undefined}
+ />
+ </CardBody>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default PurchaseOrderLines;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/index.ts
new file mode 100644
index 0000000000..9fca338e3a
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderLines from "./PurchaseOrderLines";
+
+export default PurchaseOrderLines;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx
new file mode 100644
index 0000000000..76ccb8f239
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx
@@ -0,0 +1,75 @@
+import { useFetcher } from "@remix-run/react";
+import { useCallback, useEffect, useMemo } from "react";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { getAccountsList } from "~/modules/accounting";
+import type { getPartsList } from "~/modules/parts";
+import type { PurchaseOrderLine } from "~/modules/purchasing";
+
+export default function usePurchaseOrderLines() {
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const canEdit = permissions.can("update", "purchasing");
+ const canDelete = permissions.can("delete", "purchasing");
+
+ const partsFetcher = useFetcher<Awaited<ReturnType<typeof getPartsList>>>();
+ const accountsFetcher =
+ useFetcher<Awaited<ReturnType<typeof getAccountsList>>>();
+
+ useEffect(() => {
+ if (partsFetcher.type === "init") {
+ partsFetcher.load("/api/parts/list?replenishmentSystem=Buy");
+ }
+ }, [partsFetcher]);
+
+ useEffect(() => {
+ if (accountsFetcher.type === "init") {
+ accountsFetcher.load("/api/accounting/accounts");
+ }
+ }, [accountsFetcher]);
+
+ const partOptions = useMemo(
+ () =>
+ partsFetcher.data?.data
+ ? partsFetcher.data?.data.map((p) => ({
+ value: p.id,
+ label: p.id,
+ }))
+ : [],
+ [partsFetcher.data]
+ );
+
+ const accountOptions = useMemo(
+ () =>
+ accountsFetcher.data?.data
+ ? accountsFetcher.data?.data.map((c) => ({
+ value: c.number,
+ label: c.number,
+ }))
+ : [],
+ [accountsFetcher.data]
+ );
+
+ const handleCellEdit = useCallback(
+ async (id: string, value: unknown, row: PurchaseOrderLine) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("purchaseOrderLine")
+ .update({
+ [id]: value,
+ })
+ .eq("id", row.id);
+ },
+ [supabase]
+ );
+
+ return {
+ accountOptions,
+ canDelete,
+ canEdit,
+ partOptions,
+ supabase,
+ handleCellEdit,
+ };
+}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/PurchaseOrderPaymentForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/PurchaseOrderPaymentForm.tsx
new file mode 100644
index 0000000000..c3424bea07
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/PurchaseOrderPaymentForm.tsx
@@ -0,0 +1,105 @@
+import {
+ Card,
+ CardBody,
+ CardFooter,
+ CardHeader,
+ Grid,
+ Heading,
+ VStack,
+} from "@chakra-ui/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Currency,
+ Boolean,
+ Hidden,
+ Supplier,
+ SupplierContact,
+ SupplierLocation,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { purchaseOrderPaymentValidator } from "~/modules/purchasing";
+import type { ListItem } from "~/types";
+import type { TypeOfValidator } from "~/types/validators";
+
+type PurchaseOrderPaymentFormProps = {
+ initialValues: TypeOfValidator<typeof purchaseOrderPaymentValidator>;
+ paymentTerms: ListItem[];
+};
+
+const PurchaseOrderPaymentForm = ({
+ initialValues,
+ paymentTerms,
+}: PurchaseOrderPaymentFormProps) => {
+ const permissions = usePermissions();
+
+ const [supplier, setSupplier] = useState<string | undefined>(
+ initialValues.invoiceSupplierId
+ );
+
+ const paymentTermOptions = paymentTerms.map((term) => ({
+ label: term.name,
+ value: term.id,
+ }));
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={purchaseOrderPaymentValidator}
+ defaultValues={initialValues}
+ >
+ <Card w="full">
+ <CardHeader>
+ <Heading size="md">Payment</Heading>
+ </CardHeader>
+ <CardBody>
+ <Hidden name="id" />
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={2}
+ w="full"
+ >
+ <VStack alignItems="start" spacing={2} w="full">
+ <Supplier
+ name="invoiceSupplierId"
+ label="Invoice Supplier"
+ onChange={({ value }) => setSupplier(value as string)}
+ />
+ <SupplierLocation
+ name="invoiceSupplierLocationId"
+ label="Invoice Location"
+ supplier={supplier}
+ />
+ <SupplierContact
+ name="invoiceSupplierContactId"
+ label="Invoice Contact"
+ supplier={supplier}
+ />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Select
+ name="paymentTermId"
+ label="Payment Terms"
+ options={paymentTermOptions}
+ />
+ <Currency name="currencyCode" label="Currency" />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Boolean name="paymentComplete" label="Payment Complete" />
+ </VStack>
+ </Grid>
+ </CardBody>
+ <CardFooter>
+ <Submit isDisabled={!permissions.can("update", "purchasing")}>
+ Save
+ </Submit>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default PurchaseOrderPaymentForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/index.ts
new file mode 100644
index 0000000000..0e8f0f6b07
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderPaymentForm/index.ts
@@ -0,0 +1,3 @@
+import PurchaseOrderPaymentForm from "./PurchaseOrderPaymentForm";
+
+export default PurchaseOrderPaymentForm;
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
index 6bfc7851cf..da3e8f9c79 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/PurchaseOrderSidebar.tsx
@@ -1,15 +1,31 @@
+import { Count, useColor } from "@carbon/react";
import { Button, Box, VStack } from "@chakra-ui/react";
import { Link, useMatches, useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type {
+ PurchaseOrder,
+ PurchaseOrderAttachment,
+} from "~/modules/purchasing";
import { usePurchaseOrderSidebar } from "./usePurchaseOrderSidebar";
const PurchaseOrderSidebar = () => {
const { orderId } = useParams();
+ const borderColor = useColor("gray.200");
if (!orderId)
throw new Error(
"PurchaseOrderSidebar requires an orderId and could not find orderId in params"
);
- const links = usePurchaseOrderSidebar();
+ const routeData = useRouteData<{
+ purchaseOrder: PurchaseOrder;
+ internalDocuments: PurchaseOrderAttachment[];
+ externalDocuments: PurchaseOrderAttachment[];
+ }>(`/x/purchase-order/${orderId}`);
+ const links = usePurchaseOrderSidebar({
+ lines: routeData?.purchaseOrder?.lineCount ?? 0,
+ internalDocuments: routeData?.internalDocuments.length ?? 0,
+ externalDocuments: routeData?.externalDocuments.length ?? 0,
+ });
const matches = useMatches();
return (
@@ -30,13 +46,17 @@ const PurchaseOrderSidebar = () => {
as={Link}
to={route.to}
variant={isActive ? "solid" : "ghost"}
- border="none"
+ border={isActive ? "1px solid" : "none"}
+ borderColor={borderColor}
fontWeight={isActive ? "bold" : "normal"}
- justifyContent="start"
+ justifyContent={
+ route.count === undefined ? "start" : "space-between"
+ }
size="md"
w="full"
>
- {route.name}
+ <span>{route.name}</span>
+ {route.count !== undefined && <Count count={route.count} />}
</Button>
);
})}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx
index 05e418397b..1a6a7d93d1 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderSidebar/usePurchaseOrderSidebar.tsx
@@ -1,17 +1,28 @@
import { usePermissions } from "~/hooks";
import type { Role } from "~/types";
-export function usePurchaseOrderSidebar() {
+type Props = {
+ lines?: number;
+ externalDocuments?: number;
+ internalDocuments?: number;
+};
+
+export function usePurchaseOrderSidebar({
+ lines = 0,
+ internalDocuments = 0,
+ externalDocuments = 0,
+}: Props) {
const permissions = usePermissions();
return [
{
- name: "Header",
+ name: "Summary",
to: "",
},
{
- name: "Line Items",
- to: "items",
+ name: "Lines",
+ to: "lines",
role: ["employee", "supplier"],
+ count: lines,
},
{
name: "Delivery",
@@ -19,24 +30,21 @@ export function usePurchaseOrderSidebar() {
role: ["employee", "supplier"],
},
{
- name: "Taxes",
- to: "taxes",
- role: ["employee"],
- },
- {
- name: "Approvals",
- to: "approvals",
+ name: "Payment",
+ to: "payment",
role: ["employee"],
},
{
name: "Internal Attachments",
- to: "internal-attachments",
+ to: "internal",
role: ["employee"],
+ count: internalDocuments,
},
{
name: "External Attachments",
- to: "external-attachments",
+ to: "external",
role: ["employee", "supplier"],
+ count: externalDocuments,
},
].filter(
(item) =>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts
index 07d4c7afc2..d33cd9f680 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/index.ts
@@ -1,5 +1,21 @@
+import PurchaseOrderDeliveryForm from "./PurchaseOrderDeliveryForm";
+import PurchaseOrderDocuments from "./PurchaseOrderInternalDocuments";
+import PurchaseOrderDocumentForm from "./PurchaseOrderDocumentForm";
import PurchaseOrderForm from "./PurchaseOrderForm";
import PurchaseOrderHeader from "./PurchaseOrderHeader";
+import PurchaseOrderLineForm from "./PurchaseOrderLineForm";
+import PurchaseOrderLines from "./PurchaseOrderLines";
+import PurchaseOrderPaymentForm from "./PurchaseOrderPaymentForm";
import PurchaseOrderSidebar from "./PurchaseOrderSidebar";
-export { PurchaseOrderForm, PurchaseOrderHeader, PurchaseOrderSidebar };
+export {
+ PurchaseOrderDeliveryForm,
+ PurchaseOrderDocumentForm,
+ PurchaseOrderDocuments,
+ PurchaseOrderForm,
+ PurchaseOrderHeader,
+ PurchaseOrderLineForm,
+ PurchaseOrderLines,
+ PurchaseOrderPaymentForm,
+ PurchaseOrderSidebar,
+};
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 d6ba8a727f..aa929c5f52 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrders/PurchaseOrdersTable/PurchaseOrdersTable.tsx
@@ -80,8 +80,8 @@ const PurchaseOrdersTable = memo(
cell: (item) => item.getValue(),
},
{
- accessorKey: "orderDueDate",
- header: "Due Date",
+ accessorKey: "receiptPromisedDate",
+ header: "Promised Date",
cell: (item) => item.getValue(),
},
{
@@ -144,10 +144,10 @@ const PurchaseOrdersTable = memo(
<>
<MenuItem
icon={<BsPencilSquare />}
- isDisabled={!permissions.can("update", "purchasing")}
+ isDisabled={!permissions.can("view", "purchasing")}
onClick={() => edit(row)}
>
- Edit
+ View
</MenuItem>
<MenuItem
icon={<BsStar />}
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/SupplierForm.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/SupplierForm.tsx
index 827bc688e1..5c6c3a7805 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/SupplierForm.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/SupplierForm.tsx
@@ -19,8 +19,8 @@ import {
Input,
Select,
Submit,
- TextArea,
Hidden,
+ Currency,
} from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import { supplierValidator } from "~/modules/purchasing";
@@ -33,6 +33,7 @@ import type {
import { mapRowsToOptions } from "~/utils/form";
import type { TypeOfValidator } from "~/types/validators";
import { SupplierContacts, SupplierLocations } from "./components";
+import type { ListItem } from "~/types";
type SupplierFormProps = {
initialValues: TypeOfValidator<typeof supplierValidator>;
@@ -52,6 +53,9 @@ const SupplierForm = ({
const routeData = useRouteData<{
supplierTypes: SupplierType[];
supplierStatuses: SupplierStatus[];
+ paymentTerms: ListItem[];
+ shippingMethods: ListItem[];
+ shippingTerms: ListItem[];
}>("/x/purchasing/suppliers");
const supplierTypeOptions = routeData?.supplierTypes
@@ -70,6 +74,30 @@ const SupplierForm = ({
})
: [];
+ const paymentTermOptions = routeData?.paymentTerms
+ ? mapRowsToOptions({
+ data: routeData.paymentTerms,
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const shippingMethodOptions = routeData?.shippingMethods
+ ? mapRowsToOptions({
+ data: routeData.shippingMethods,
+ value: "id",
+ label: "name",
+ })
+ : [];
+
+ const shippingTermOptions = routeData?.shippingTerms
+ ? mapRowsToOptions({
+ data: routeData.shippingTerms,
+ value: "id",
+ label: "name",
+ })
+ : [];
+
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
? !permissions.can("update", "purchasing")
@@ -123,14 +151,30 @@ const SupplierForm = ({
options={supplierStatusOptions}
placeholder="Select Supplier Status"
/>
+ <Currency
+ name="defaultCurrencyCode"
+ label="Currency"
+ placeholder="Default Currency"
+ />
+ <Select
+ name="defaultPaymentTermId"
+ label="Payment Term"
+ options={paymentTermOptions}
+ placeholder="Default Payment Term"
+ />
+ <Select
+ name="defaultShippingMethodId"
+ label="Shipping Method"
+ options={shippingMethodOptions}
+ placeholder="Default Shipping Method"
+ />
+ <Select
+ name="defaultShippingTermId"
+ label="Shipping Term"
+ options={shippingTermOptions}
+ placeholder="Default Shipping Term"
+ />
</Grid>
-
- <TextArea
- name="description"
- label="Description"
- characterLimit={500}
- my={2}
- />
</VStack>
</Box>
<VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
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 dab5697096..e648ec2874 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx
@@ -87,7 +87,7 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
navigate(`/x/purchasing/suppliers/${row.id}?${params.toString()}`)
}
>
- View Supplier
+ Edit Supplier
</MenuItem>
),
[navigate, params]
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
index 944d1b9a9c..d4b85cde3c 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.form.ts
@@ -28,17 +28,122 @@ export const purchaseOrderValidator = withZod(
}),
}
),
- orderDueDate: zfd.text(z.string().optional()),
- receivedDate: zfd.text(z.string().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(),
+ })
+);
+
+export const purchaseOrderDeliveryValidator = withZod(
+ z
+ .object({
+ id: z.string(),
+ locationId: zfd.text(z.string().optional()),
+ shippingMethodId: zfd.text(z.string().optional()),
+ shippingTermId: zfd.text(z.string().optional()),
+ trackingNumber: z.string(),
+ deliveryDate: zfd.text(z.string().optional()),
+ receiptRequestedDate: zfd.text(z.string().optional()),
+ receiptPromisedDate: zfd.text(z.string().optional()),
+ dropShipment: zfd.checkbox(),
+ customerId: zfd.text(z.string().optional()),
+ customerLocationId: zfd.text(z.string().optional()),
+ notes: zfd.text(z.string().optional()),
+ })
+ .refine(
+ (data) => {
+ if (data.dropShipment) {
+ return data.customerId && data.customerLocationId;
+ }
+ return true;
+ },
+ {
+ message: "Drop shipment requires customer and location",
+ path: ["dropShipment"], // path of error
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.locationId) {
+ return !data.dropShipment;
+ }
+ return true;
+ },
+ {
+ message: "Location is not required for drop shipment",
+ path: ["locationId"], // path of error
+ }
+ )
+);
+
+export const purchaseOrderLineValidator = withZod(
+ z
+ .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",
+ }),
+ }
+ ),
+ partId: zfd.text(z.string().optional()),
+ accountNumber: zfd.text(z.string().optional()),
+ assetId: zfd.text(z.string().optional()),
+ description: zfd.text(z.string().optional()),
+ purchaseQuantity: zfd.numeric(z.number().optional()),
+ unitOfMeasureCode: zfd.text(z.string().optional()),
+ unitPrice: zfd.numeric(z.number().optional()),
+ setupPrice: zfd.numeric(z.number().optional()),
+ shelfId: zfd.text(z.string().optional()),
+ })
+ .refine(
+ (data) => (data.purchaseOrderLineType === "Part" ? data.partId : true),
+ {
+ message: "Part is required",
+ path: ["partId"], // path of error
+ }
+ )
+ .refine(
+ (data) =>
+ data.purchaseOrderLineType === "G/L Account"
+ ? data.accountNumber
+ : true,
+ {
+ message: "Account is required",
+ path: ["accountNumber"], // path of error
+ }
+ )
+ .refine(
+ (data) =>
+ data.purchaseOrderLineType === "Fixed Asset" ? data.assetId : true,
+ {
+ message: "Asset is required",
+ path: ["assetId"], // path of error
+ }
+ )
+ .refine(
+ (data) =>
+ data.purchaseOrderLineType === "Comment" ? data.description : true,
+ {
+ message: "Comment is required",
+ path: ["description"], // path of error
+ }
+ )
+);
+
+export const purchaseOrderPaymentValidator = withZod(
+ z.object({
+ id: z.string(),
invoiceSupplierId: zfd.text(z.string().optional()),
invoiceSupplierLocationId: zfd.text(z.string().optional()),
invoiceSupplierContactId: zfd.text(z.string().optional()),
paymentTermId: zfd.text(z.string().optional()),
- shippingMethodId: zfd.text(z.string().optional()),
+ paymentComplete: zfd.checkbox(),
currencyCode: zfd.text(z.string().optional()),
})
);
@@ -47,11 +152,14 @@ export const supplierValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
- description: zfd.text(z.string().optional()),
supplierTypeId: zfd.text(z.string().optional()),
supplierStatusId: zfd.text(z.string().optional()),
taxId: zfd.text(z.string().optional()),
accountManagerId: zfd.text(z.string().optional()),
+ defaultCurrencyCode: zfd.text(z.string().optional()),
+ defaultPaymentTermId: zfd.text(z.string().optional()),
+ defaultShippingTermId: zfd.text(z.string().optional()),
+ defaultShippingMethodId: zfd.text(z.string().optional()),
})
);
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index dff230e9bb..f8351b534e 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -1,10 +1,18 @@
import type { Database } from "@carbon/database";
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 type { purchaseOrderValidator } from "./purchasing.form";
+import type {
+ purchaseOrderDeliveryValidator,
+ purchaseOrderLineValidator,
+ purchaseOrderPaymentValidator,
+ purchaseOrderValidator,
+ supplierValidator,
+} from "./purchasing.form";
export async function closePurchaseOrder(
client: SupabaseClient<Database>,
@@ -22,6 +30,17 @@ export async function closePurchaseOrder(
.select("id");
}
+export async function deletePurchaseOrder(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return Promise.all([
+ client.from("purchaseOrder").delete().eq("id", purchaseOrderId),
+ client.from("purchaseOrderDelivery").delete().eq("id", purchaseOrderId),
+ client.from("purchaseOrderPayment").delete().eq("id", purchaseOrderId),
+ ]);
+}
+
export async function deleteSupplierContact(
client: SupabaseClient<Database>,
supplierId: string,
@@ -52,17 +71,19 @@ export async function deleteSupplierType(
) {
return client.from("supplierType").delete().eq("id", supplierTypeId);
}
-export async function getSupplier(
+
+export async function getExternalDocuments(
client: SupabaseClient<Database>,
- supplierId: string
+ purchaseOrderId: string
) {
- return client
- .from("supplier")
- .select(
- "id, name, description, supplierTypeId, supplierStatusId, taxId, accountManagerId"
- )
- .eq("id", supplierId)
- .single();
+ return client.storage.from("purchasing-external").list(purchaseOrderId);
+}
+
+export async function getInternalDocuments(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client.storage.from("purchasing-internal").list(purchaseOrderId);
}
export async function getPurchaseOrder(
@@ -108,6 +129,28 @@ export async function getPurchaseOrders(
return query;
}
+export async function getPurchaseOrderDelivery(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client
+ .from("purchaseOrderDelivery")
+ .select("*")
+ .eq("id", purchaseOrderId)
+ .single();
+}
+
+export async function getPurchaseOrderPayment(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client
+ .from("purchaseOrderPayment")
+ .select("*")
+ .eq("id", purchaseOrderId)
+ .single();
+}
+
export function getPurchaseOrderApprovalStatuses(): Database["public"]["Enums"]["purchaseOrderApprovalStatus"][] {
return [
"Draft",
@@ -119,10 +162,42 @@ export function getPurchaseOrderApprovalStatuses(): Database["public"]["Enums"][
];
}
+export async function getPurchaseOrderLines(
+ client: SupabaseClient<Database>,
+ purchaseOrderId: string
+) {
+ return client
+ .from("purchaseOrderLine")
+ .select("*")
+ .eq("purchaseOrderId", purchaseOrderId);
+}
+
+export async function getPurchaseOrderLine(
+ client: SupabaseClient<Database>,
+ purchaseOrderLineId: string
+) {
+ return client
+ .from("purchaseOrderLine")
+ .select("*")
+ .eq("id", purchaseOrderLineId)
+ .single();
+}
+
+export function getPurchaseOrderLineTypes(): Database["public"]["Enums"]["purchaseOrderLineType"][] {
+ return ["Part", "G/L Account", "Fixed Asset", "Comment"];
+}
+
export function getPurchaseOrderTypes(): Database["public"]["Enums"]["purchaseOrderType"][] {
return ["Draft", "Purchase", "Return"];
}
+export async function getSupplier(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client.from("supplier").select("*").eq("id", supplierId).single();
+}
+
export async function getSupplierLocations(
client: SupabaseClient<Database>,
supplierId: string
@@ -170,7 +245,7 @@ export async function getSuppliers(
) {
let query = client
.from("supplier")
- .select("id, name, description, supplierType(name), supplierStatus(name)", {
+ .select("id, name, supplierType(name), supplierStatus(name)", {
count: "exact",
});
@@ -245,13 +320,7 @@ export async function getSupplierTypes(
export async function insertSupplier(
client: SupabaseClient<Database>,
- supplier: {
- name: string;
- supplierTypeId?: string;
- supplierStatusId?: string;
- taxId?: string;
- accountManagerId?: string;
- description?: string;
+ supplier: TypeOfValidator<typeof supplierValidator> & {
createdBy: string;
}
) {
@@ -275,7 +344,6 @@ export async function insertSupplierContact(
addressLine2?: string;
city?: string;
state?: string;
- // countryId: string;
postalCode?: string;
birthday?: string;
notes?: string;
@@ -348,20 +416,14 @@ export async function insertSupplierLocation(
export async function updateSupplier(
client: SupabaseClient<Database>,
- supplier: {
+ supplier: Omit<TypeOfValidator<typeof supplierValidator>, "id"> & {
id: string;
- name: string;
- supplierTypeId?: string;
- supplierStatusId?: string;
- taxId?: string;
- accountManagerId?: string;
- description?: string;
updatedBy: string;
}
) {
return client
.from("supplier")
- .update(supplier)
+ .update(sanitize(supplier))
.eq("id", supplier.id)
.select("id");
}
@@ -392,7 +454,7 @@ export async function updateSupplierContact(
) {
return client
.from("contact")
- .update(supplierContact.contact)
+ .update(sanitize(supplierContact.contact))
.eq("id", supplierContact.contactId)
.select("id");
}
@@ -413,7 +475,7 @@ export async function updateSupplierLocation(
) {
return client
.from("address")
- .update(supplierLocation.address)
+ .update(sanitize(supplierLocation.address))
.eq("id", supplierLocation.addressId)
.select("id");
}
@@ -440,16 +502,137 @@ export async function upsertPurchaseOrder(
if ("id" in purchaseOrder) {
return client
.from("purchaseOrder")
- .update(purchaseOrder)
+ .update(sanitize(purchaseOrder))
.eq("id", purchaseOrder.id)
.select("id, purchaseOrderId");
}
- return client
+
+ const [supplier, purchaser] = await Promise.all([
+ getSupplier(client, purchaseOrder.supplierId),
+ getEmployeeJob(client, purchaseOrder.createdBy),
+ ]);
+
+ if (supplier.error) return supplier;
+
+ const {
+ defaultCurrencyCode,
+ defaultPaymentTermId,
+ defaultShippingMethodId,
+ defaultShippingTermId,
+ } = supplier.data;
+
+ const locationId = purchaser?.data?.locationId ?? null;
+
+ const order = await client
.from("purchaseOrder")
- .insert([
- { ...purchaseOrder, currencyCode: purchaseOrder.currencyCode || "USD" },
- ])
+ .insert([{ ...purchaseOrder }])
.select("id, purchaseOrderId");
+
+ if (order.error) return order;
+
+ const purchaseOrderId = order.data[0].id;
+
+ const [delivery, payment] = await Promise.all([
+ client.from("purchaseOrderDelivery").insert([
+ {
+ id: purchaseOrderId,
+ locationId: locationId,
+ shippingMethodId: defaultShippingMethodId,
+ shippingTermId: defaultShippingTermId,
+ },
+ ]),
+ client.from("purchaseOrderPayment").insert([
+ {
+ id: purchaseOrderId,
+ currencyCode: defaultCurrencyCode ?? "USD",
+ invoiceSupplierId: purchaseOrder.supplierId,
+ paymentTermId: defaultPaymentTermId,
+ },
+ ]),
+ ]);
+
+ if (delivery.error) {
+ await deletePurchaseOrder(client, purchaseOrderId);
+ return payment;
+ }
+ if (payment.error) {
+ await deletePurchaseOrder(client, purchaseOrderId);
+ return payment;
+ }
+
+ return order;
+}
+
+export async function upsertPurchaseOrderDelivery(
+ client: SupabaseClient<Database>,
+ purchaseOrderDelivery:
+ | (TypeOfValidator<typeof purchaseOrderDeliveryValidator> & {
+ createdBy: string;
+ })
+ | (TypeOfValidator<typeof purchaseOrderDeliveryValidator> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in purchaseOrderDelivery) {
+ return client
+ .from("purchaseOrderDelivery")
+ .update(sanitize(purchaseOrderDelivery))
+ .eq("id", purchaseOrderDelivery.id)
+ .select("id");
+ }
+ return client
+ .from("purchaseOrderDelivery")
+ .insert([purchaseOrderDelivery])
+ .select("id");
+}
+
+export async function upsertPurchaseOrderLine(
+ client: SupabaseClient<Database>,
+ purchaseOrderLine:
+ | (Omit<TypeOfValidator<typeof purchaseOrderLineValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof purchaseOrderLineValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in purchaseOrderLine) {
+ return client
+ .from("purchaseOrderLine")
+ .update(sanitize(purchaseOrderLine))
+ .eq("id", purchaseOrderLine.id)
+ .select("id");
+ }
+ return client
+ .from("purchaseOrderLine")
+ .insert([purchaseOrderLine])
+ .select("id");
+}
+
+export async function upsertPurchaseOrderPayment(
+ client: SupabaseClient<Database>,
+ purchaseOrderPayment:
+ | (TypeOfValidator<typeof purchaseOrderPaymentValidator> & {
+ createdBy: string;
+ })
+ | (TypeOfValidator<typeof purchaseOrderPaymentValidator> & {
+ id: string;
+ updatedBy: string;
+ })
+) {
+ if ("id" in purchaseOrderPayment) {
+ return client
+ .from("purchaseOrderPayment")
+ .update(sanitize(purchaseOrderPayment))
+ .eq("id", purchaseOrderPayment.id)
+ .select("id");
+ }
+ return client
+ .from("purchaseOrderPayment")
+ .insert([purchaseOrderPayment])
+ .select("id");
}
export async function upsertSupplierType(
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index bf53f06e8e..ba99fa0a6d 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -1,5 +1,7 @@
import type { Database } from "@carbon/database";
import type {
+ getExternalDocuments,
+ getPurchaseOrderLines,
getPurchaseOrders,
getSupplierContacts,
getSupplierLocations,
@@ -8,10 +10,22 @@ import type {
getSupplierTypes,
} from "./services";
+// TODO: we should just use the FileObject type from supabase
+export type PurchaseOrderAttachment = NonNullable<
+ Awaited<ReturnType<typeof getExternalDocuments>>["data"]
+>[number];
+
export type PurchaseOrder = NonNullable<
Awaited<ReturnType<typeof getPurchaseOrders>>["data"]
>[number];
+export type PurchaseOrderLine = NonNullable<
+ Awaited<ReturnType<typeof getPurchaseOrderLines>>["data"]
+>[number];
+
+export type PurchaseOrderLineType =
+ Database["public"]["Enums"]["purchaseOrderLineType"];
+
export type PurchaseOrderApprovalStatus =
Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx
index 83ae4d3668..b1b66a362c 100644
--- a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx
@@ -1,4 +1,3 @@
-import { Select } from "@carbon/react";
import {
Button,
Drawer,
@@ -8,21 +7,22 @@ import {
DrawerFooter,
DrawerHeader,
DrawerOverlay,
- FormControl,
- FormErrorMessage,
- FormLabel,
HStack,
VStack,
} from "@chakra-ui/react";
-import { useFetcher, useNavigate } from "@remix-run/react";
-import { useEffect, useMemo } from "react";
-import { useControlField, useField, ValidatedForm } from "remix-validated-form";
-import { Abilities, Number, Submit, Supplier } from "~/components/Form";
+import { useLocation, useNavigate } from "@remix-run/react";
+import { useState } from "react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Abilities,
+ Number,
+ Submit,
+ Supplier,
+ SupplierContact,
+} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { getSupplierContacts } from "~/modules/purchasing";
import { contractorValidator } from "~/modules/resources";
import type { TypeOfValidator } from "~/types/validators";
-import { mapRowsToOptions } from "~/utils/form";
type ContractorFormProps = {
initialValues: TypeOfValidator<typeof contractorValidator>;
@@ -31,42 +31,18 @@ type ContractorFormProps = {
const ContractorForm = ({ initialValues }: ContractorFormProps) => {
const permissions = usePermissions();
const navigate = useNavigate();
+ const location = useLocation();
const onClose = () => navigate(-1);
- const isEditing = initialValues.id !== "";
+ const [supplier, setSupplier] = useState<string | null>(
+ initialValues?.supplierId ?? null
+ );
+
+ const isEditing = !location.pathname.includes("new");
const isDisabled = isEditing
? !permissions.can("update", "resources")
: !permissions.can("create", "resources");
- const supplierContactsFetcher =
- useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();
-
- const onSupplierChange = ({ value }: { value: string | number }) => {
- if (value)
- supplierContactsFetcher.load(
- `/api/purchasing/supplier-contacts?supplierId=${value}`
- );
- };
-
- useEffect(() => {
- if (initialValues.supplierId)
- supplierContactsFetcher.load(
- `/api/purchasing/supplier-locations?supplierId=${initialValues.supplierId}`
- );
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- const supplierContacts = useMemo(
- () =>
- mapRowsToOptions({
- data: supplierContactsFetcher.data?.data ?? [],
- value: "id",
- // @ts-ignore
- label: (row) => `${row.contact.firstName} ${row.contact.lastName}`,
- }),
- [supplierContactsFetcher.data]
- );
-
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
<ValidatedForm
@@ -89,11 +65,11 @@ const ContractorForm = ({ initialValues }: ContractorFormProps) => {
name="supplierId"
label="Supplier"
isReadOnly={isEditing}
- onChange={onSupplierChange}
+ onChange={({ value }) => setSupplier(value as string)}
/>
- <SupplierContactsBySupplier
- supplierContacts={supplierContacts}
- initialContact={initialValues.id}
+ <SupplierContact
+ name="id"
+ supplier={supplier ?? undefined}
isReadOnly={isEditing}
/>
<Abilities name="abilities" label="Abilities" />
@@ -124,52 +100,5 @@ const ContractorForm = ({ initialValues }: ContractorFormProps) => {
</Drawer>
);
};
-const SUPPLIER_CONTACT_FIELD = "id";
-
-const SupplierContactsBySupplier = ({
- supplierContacts,
- initialContact,
- isReadOnly,
-}: {
- supplierContacts: { value: string | number; label: string }[];
- initialContact?: string;
- isReadOnly: boolean;
-}) => {
- const { error, getInputProps } = useField(SUPPLIER_CONTACT_FIELD);
-
- const [supplierContact, setSupplierContact] = useControlField<{
- value: string | number;
- label: string;
- } | null>(SUPPLIER_CONTACT_FIELD);
-
- useEffect(() => {
- // if the initial value is in the options, set it, otherwise set to null
- if (supplierContacts) {
- setSupplierContact(
- supplierContacts.find((s) => s.value === initialContact) ?? null
- );
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [supplierContacts, initialContact]);
-
- return (
- <FormControl isInvalid={!!error}>
- <FormLabel htmlFor={SUPPLIER_CONTACT_FIELD}>Supplier Contact</FormLabel>
- <Select
- {...getInputProps({
- // @ts-ignore
- id: SUPPLIER_CONTACT_FIELD,
- })}
- options={supplierContacts}
- value={supplierContact}
- onChange={setSupplierContact}
- // @ts-ignore
- isReadOnly={isReadOnly}
- w="full"
- />
- {error && <FormErrorMessage>{error}</FormErrorMessage>}
- </FormControl>
- );
-};
export default ContractorForm;
diff --git a/apps/carbon/app/modules/resources/interfaces/Locations/LocationForm/LocationForm.tsx b/apps/carbon/app/modules/resources/interfaces/Locations/LocationForm/LocationForm.tsx
index 05338bc67e..02dc2c6507 100644
--- a/apps/carbon/app/modules/resources/interfaces/Locations/LocationForm/LocationForm.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Locations/LocationForm/LocationForm.tsx
@@ -51,6 +51,12 @@ const LocationForm = ({ initialValues }: LocationFormProps) => {
<Hidden name="id" />
<VStack spacing={4} alignItems="start">
<Input name="name" label="Location Name" />
+ <Input name="addressLine1" label="Address Line 1" />
+ <Input name="addressLine2" label="Address Line 2" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Postal Code" />
+ {/* <Country name="country" label="Country" /> */}
<Timezone name="timezone" label="Timezone" />
<Number name="latitude" label="Latitude" min={-90} max={90} />
<Number name="longitude" label="Longitude" min={-180} max={180} />
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 52db75f2e9..67e4afb45d 100644
--- a/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Locations/LocationsTable/LocationsTable.tsx
@@ -30,18 +30,24 @@ const LocationsTable = memo(({ data, count }: LocationsTableProps) => {
cell: (item) => item.getValue(),
},
{
- accessorKey: "timezone",
- header: "Timezone",
+ accessorKey: "addressLine1",
+ header: "Address",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "city",
+ header: "City",
cell: (item) => item.getValue(),
},
{
- accessorKey: "latitude",
- header: "Latitude",
+ accessorKey: "state",
+ header: "State",
cell: (item) => item.getValue(),
},
+
{
- accessorKey: "longitude",
- header: "Longitude",
+ accessorKey: "timezone",
+ header: "Timezone",
cell: (item) => item.getValue(),
},
];
diff --git a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
index 51885cfbf7..f4e57715f8 100644
--- a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
@@ -71,7 +71,7 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
);
}}
>
- Edit Partner
+ View Partner
</MenuItem>
<MenuItem
isDisabled={!permissions.can("delete", "resources")}
diff --git a/apps/carbon/app/modules/resources/services/resources.form.ts b/apps/carbon/app/modules/resources/services/resources.form.ts
index ad26f3bd4c..a6478074bc 100644
--- a/apps/carbon/app/modules/resources/services/resources.form.ts
+++ b/apps/carbon/app/modules/resources/services/resources.form.ts
@@ -83,7 +83,7 @@ export const contractorValidator = withZod(
),
abilities: z
.array(z.string().min(20, { message: "Invalid ability" }))
- .min(1, { message: "An ability is required" }),
+ .optional(),
})
);
@@ -107,7 +107,7 @@ export const employeeAbilityValidator = withZod(
export const employeeJobValidator = withZod(
z.object({
- title: z.string().min(1, { message: "Title is required" }),
+ title: zfd.text(z.string().optional()),
startDate: zfd.text(z.string().optional()),
locationId: zfd.text(z.string().optional()),
shiftId: zfd.text(z.string().optional()),
@@ -151,6 +151,12 @@ export const locationValidator = withZod(
.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
+ addressLine1: z.string().min(1, { message: "Address is required" }),
+ addressLine2: z.string().optional(),
+ city: z.string().min(1, { message: "City is required" }),
+ state: z.string().min(1, { message: "State is required" }),
+ postalCode: z.string().min(1, { message: "Postal Code is required" }),
+ // country: z.string().min(1, { message: "Country is required" }),
timezone: z.string().min(1, { message: "Timezone is required" }),
latitude: zfd.numeric(z.number().optional()),
longitude: zfd.numeric(z.number().optional()),
diff --git a/apps/carbon/app/modules/resources/services/resources.server.ts b/apps/carbon/app/modules/resources/services/resources.server.ts
index 5639db326f..90e4adfb04 100644
--- a/apps/carbon/app/modules/resources/services/resources.server.ts
+++ b/apps/carbon/app/modules/resources/services/resources.server.ts
@@ -2,8 +2,11 @@ import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { DataType, Employee } from "~/modules/users";
import { getEmployees } from "~/modules/users";
+import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
+import type { locationValidator } from "./resources.form";
export async function deleteAbility(
client: SupabaseClient<Database>,
@@ -270,7 +273,7 @@ export async function getContractor(
contractorId: string
) {
return client
- .from("contractors_query")
+ .from("contractors_view")
.select("*")
.eq("supplierContactId", contractorId)
.single();
@@ -280,7 +283,7 @@ export async function getContractors(
client: SupabaseClient<Database>,
args?: GenericQueryFilters & { name: string | null; ability: string | null }
) {
- let query = client.from("contractors_query").select("*").eq("active", true);
+ let query = client.from("contractors_view").select("*").eq("active", true);
if (args?.name) {
query = query.ilike("supplierName", `%${args.name}%`);
@@ -469,20 +472,14 @@ export async function getLocation(
client: SupabaseClient<Database>,
locationId: string
) {
- return client
- .from("location")
- .select(`id, name, latitude, longitude, timezone`)
- .eq("id", locationId)
- .single();
+ return client.from("location").select("*").eq("id", locationId).single();
}
export async function getLocations(
client: SupabaseClient<Database>,
args?: GenericQueryFilters & { name: string | null }
) {
- let query = client
- .from("location")
- .select(`id, name, latitude, longitude, timezone`, { count: "exact" });
+ let query = client.from("location").select("*", { count: "exact" });
if (args?.name) {
query = query.ilike("name", `%${args.name}%`);
@@ -520,7 +517,7 @@ export async function getPartner(
partnerId: string
) {
return client
- .from("partners_query")
+ .from("partners_view")
.select("*")
.eq("supplierLocationId", partnerId)
.single();
@@ -530,7 +527,7 @@ export async function getPartners(
client: SupabaseClient<Database>,
args?: GenericQueryFilters & { name: string | null; ability: string | null }
) {
- let query = client.from("partners_query").select("*").eq("active", true);
+ let query = client.from("partners_view").select("*").eq("active", true);
if (args?.name) {
query = query.ilike("supplierName", `%${args.name}%`);
@@ -872,7 +869,7 @@ export async function updateAbility(
shadowWeeks: number;
}>
) {
- return client.from("ability").update(ability).eq("id", id);
+ return client.from("ability").update(sanitize(ability)).eq("id", id);
}
export async function updateAttribute(
@@ -888,12 +885,14 @@ export async function updateAttribute(
if (!attribute.id) throw new Error("id is required");
return client
.from("userAttribute")
- .update({
- name: attribute.name,
- listOptions: attribute.listOptions,
- canSelfManage: attribute.canSelfManage,
- updatedBy: attribute.updatedBy,
- })
+ .update(
+ sanitize({
+ name: attribute.name,
+ listOptions: attribute.listOptions,
+ canSelfManage: attribute.canSelfManage,
+ updatedBy: attribute.updatedBy,
+ })
+ )
.eq("id", attribute.id);
}
@@ -907,7 +906,10 @@ export async function updateAttributeCategory(
}
) {
const { id, ...update } = attributeCategory;
- return client.from("userAttributeCategory").update(update).eq("id", id);
+ return client
+ .from("userAttributeCategory")
+ .update(sanitize(update))
+ .eq("id", id);
}
export async function updateAttributeSortOrder(
@@ -944,7 +946,7 @@ export async function upsertContractor(
if ("updatedBy" in contractor) {
const updateContractor = await client
.from("contractor")
- .update(contractor)
+ .update(sanitize(contractor))
.eq("id", contractor.id);
if (updateContractor.error) {
return updateContractor;
@@ -995,7 +997,10 @@ export async function upsertDepartment(
}
) {
if ("id" in department) {
- return client.from("department").update(department).eq("id", department.id);
+ return client
+ .from("department")
+ .update(sanitize(department))
+ .eq("id", department.id);
}
return client.from("department").insert(department).select("id");
}
@@ -1012,10 +1017,7 @@ export async function upsertEmployeeAbility(
) {
const { id, ...update } = employeeAbility;
if (id) {
- return client
- .from("employeeAbility")
- .update({ ...update })
- .eq("id", id);
+ return client.from("employeeAbility").update(sanitize(update)).eq("id", id);
}
const deactivatedId = await client
@@ -1029,7 +1031,7 @@ export async function upsertEmployeeAbility(
if (deactivatedId.data?.id) {
return client
.from("employeeAbility")
- .update({ ...update, active: true })
+ .update(sanitize({ ...update, active: true }))
.eq("id", deactivatedId.data.id);
}
@@ -1081,10 +1083,7 @@ export async function upsertEquipment(
) {
if ("id" in equipment) {
const { id, ...update } = equipment;
- return client
- .from("equipment")
- .update({ ...update })
- .eq("id", id);
+ return client.from("equipment").update(sanitize(update)).eq("id", id);
}
return client.from("equipment").insert([equipment]).select("id");
}
@@ -1110,10 +1109,7 @@ export async function upsertEquipmentType(
) {
if ("id" in equipmentType) {
const { id, ...update } = equipmentType;
- return client
- .from("equipmentType")
- .update({ ...update })
- .eq("id", id);
+ return client.from("equipmentType").update(sanitize(update)).eq("id", id);
}
return client.from("equipmentType").insert([equipmentType]).select("id");
}
@@ -1134,7 +1130,10 @@ export async function upsertHoliday(
}
) {
if ("id" in holiday) {
- return client.from("holiday").update(holiday).eq("id", holiday.id);
+ return client
+ .from("holiday")
+ .update(sanitize(holiday))
+ .eq("id", holiday.id);
}
return client.from("holiday").insert(holiday).select("id");
}
@@ -1142,24 +1141,19 @@ export async function upsertHoliday(
export async function upsertLocation(
client: SupabaseClient<Database>,
location:
- | {
- name: string;
- timezone: string;
- latitude: number | null;
- longitude: number | null;
+ | (Omit<TypeOfValidator<typeof locationValidator>, "id"> & {
createdBy: string;
- }
- | {
+ })
+ | (Omit<TypeOfValidator<typeof locationValidator>, "id"> & {
id: string;
- name: string;
- timezone: string;
- latitude: number | null;
- longitude: number | null;
updatedBy: string;
- }
+ })
) {
if ("id" in location) {
- return client.from("location").update(location).eq("id", location.id);
+ return client
+ .from("location")
+ .update(sanitize(location))
+ .eq("id", location.id);
}
return client.from("location").insert([location]).select("id");
}
@@ -1184,7 +1178,7 @@ export async function upsertPartner(
if ("updatedBy" in partner) {
const updatePartner = await client
.from("partner")
- .update(partner)
+ .update(sanitize(partner))
.eq("id", partner.id);
if (updatePartner.error) {
return updatePartner;
@@ -1233,10 +1227,7 @@ export async function upsertShift(
) {
const { id, ...update } = shift;
if (id) {
- return client
- .from("shift")
- .update({ ...update })
- .eq("id", id);
+ return client.from("shift").update(sanitize(update)).eq("id", id);
}
return client.from("shift").insert([update]).select("id");
@@ -1267,10 +1258,7 @@ export async function upsertWorkCell(
) {
if ("id" in workCell) {
const { id, ...update } = workCell;
- return client
- .from("workCell")
- .update({ ...update })
- .eq("id", id);
+ return client.from("workCell").update(sanitize(update)).eq("id", id);
}
return client.from("workCell").insert([workCell]).select("id");
}
@@ -1296,10 +1284,7 @@ export async function upsertWorkCellType(
) {
if ("id" in workCellType) {
const { id, ...update } = workCellType;
- return client
- .from("workCellType")
- .update({ ...update })
- .eq("id", id);
+ return client.from("workCellType").update(sanitize(update)).eq("id", id);
}
return client.from("workCellType").insert([workCellType]).select("id");
}
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/CustomerForm.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/CustomerForm.tsx
index 47e2446b67..4b2512268e 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/CustomerForm.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/CustomerForm.tsx
@@ -14,14 +14,7 @@ import {
} from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
-import {
- Employee,
- Input,
- Select,
- Submit,
- TextArea,
- Hidden,
-} from "~/components/Form";
+import { Employee, Input, Select, Submit, Hidden } from "~/components/Form";
import { customerValidator } from "~/modules/sales";
import type {
CustomerContact,
@@ -124,13 +117,6 @@ const CustomerForm = ({
placeholder="Select Customer Status"
/>
</Grid>
-
- <TextArea
- name="description"
- label="Description"
- characterLimit={500}
- my={2}
- />
</VStack>
</Box>
<VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
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..189e35ffb5 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx
@@ -86,7 +86,7 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
navigate(`/x/sales/customers/${row.id}?${params.toString()}`)
}
>
- View Customer
+ Edit Customer
</MenuItem>
),
[navigate, params]
diff --git a/apps/carbon/app/modules/sales/services/sales.form.ts b/apps/carbon/app/modules/sales/services/sales.form.ts
index 9b74eeef14..f2ac4bc94c 100644
--- a/apps/carbon/app/modules/sales/services/sales.form.ts
+++ b/apps/carbon/app/modules/sales/services/sales.form.ts
@@ -7,7 +7,6 @@ export const customerValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
- description: zfd.text(z.string().optional()),
customerTypeId: zfd.text(z.string().optional()),
customerStatusId: zfd.text(z.string().optional()),
taxId: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/sales/services/sales.server.ts b/apps/carbon/app/modules/sales/services/sales.server.ts
index b3ec82f00a..7885d94850 100644
--- a/apps/carbon/app/modules/sales/services/sales.server.ts
+++ b/apps/carbon/app/modules/sales/services/sales.server.ts
@@ -1,8 +1,11 @@
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getSupabaseServiceRole } from "~/lib/supabase";
+import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
+import { sanitize } from "~/utils/supabase";
+import type { customerValidator } from "./sales.form";
export async function deleteCustomerContact(
client: SupabaseClient<Database>,
@@ -42,7 +45,7 @@ export async function getCustomer(
return client
.from("customer")
.select(
- "id, name, description, customerTypeId, customerStatusId, taxId, accountManagerId"
+ "id, name, customerTypeId, customerStatusId, taxId, accountManagerId"
)
.eq("id", customerId)
.single();
@@ -95,7 +98,7 @@ export async function getCustomers(
) {
let query = client
.from("customer")
- .select("id, name, description, customerType(name), customerStatus(name)", {
+ .select("id, name, customerType(name), customerStatus(name)", {
count: "exact",
});
@@ -170,13 +173,7 @@ export async function getCustomerTypes(
export async function insertCustomer(
client: SupabaseClient<Database>,
- customer: {
- name: string;
- customerTypeId?: string;
- customerStatusId?: string;
- taxId?: string;
- accountManagerId?: string;
- description?: string;
+ customer: TypeOfValidator<typeof customerValidator> & {
createdBy: string;
}
) {
@@ -273,20 +270,14 @@ export async function insertCustomerLocation(
export async function updateCustomer(
client: SupabaseClient<Database>,
- customer: {
+ customer: Omit<TypeOfValidator<typeof customerValidator>, "id"> & {
id: string;
- name: string;
- customerTypeId?: string;
- customerStatusId?: string;
- taxId?: string;
- accountManagerId?: string;
- description?: string;
updatedBy: string;
}
) {
return client
.from("customer")
- .update(customer)
+ .update(sanitize(customer))
.eq("id", customer.id)
.select("id");
}
@@ -317,7 +308,7 @@ export async function updateCustomerContact(
) {
return client
.from("contact")
- .update(customerContact.contact)
+ .update(sanitize(customerContact.contact))
.eq("id", customerContact.contactId)
.select("id");
}
@@ -338,7 +329,7 @@ export async function updateCustomerLocation(
) {
return client
.from("address")
- .update(customerLocation.address)
+ .update(sanitize(customerLocation.address))
.eq("id", customerLocation.addressId)
.select("id");
}
diff --git a/apps/carbon/app/modules/settings/services/settings.server.ts b/apps/carbon/app/modules/settings/services/settings.server.ts
index c2f0c1b971..f482de045d 100644
--- a/apps/carbon/app/modules/settings/services/settings.server.ts
+++ b/apps/carbon/app/modules/settings/services/settings.server.ts
@@ -4,6 +4,7 @@ import type { TypeOfValidator } from "~/types/validators";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { interpolateDate } from "~/utils/string";
+import { sanitize } from "~/utils/supabase";
import type { sequenceValidator } from "./settings.form";
export async function getNextSequence(
@@ -62,6 +63,27 @@ export async function getSequences(
return query;
}
+export async function rollbackNextSequence(
+ client: SupabaseClient<Database>,
+ table: string,
+ userId: string
+) {
+ // TODO: add transaction through stored procedure: https://www.postgresql.org/docs/current/plpgsql-transactions.html
+ const sequence = await getSequence(client, table);
+ if (sequence.error) {
+ return sequence;
+ }
+
+ const { next } = sequence.data;
+
+ const nextValue = next - 1;
+
+ return await updateSequence(client, table, {
+ next: nextValue,
+ updatedBy: userId,
+ });
+}
+
export async function updateSequence(
client: SupabaseClient<Database>,
table: string,
@@ -69,5 +91,5 @@ export async function updateSequence(
updatedBy: string;
}
) {
- return client.from("sequence").update(sequence).eq("table", table);
+ return client.from("sequence").update(sanitize(sequence)).eq("table", table);
}
diff --git a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
index bfc2a8995f..afd3d7c009 100644
--- a/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
+++ b/apps/carbon/app/modules/users/interfaces/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx
@@ -71,10 +71,7 @@ const CreateSupplierModal = () => {
name="id"
label="Supplier Contact"
supplier={supplier}
- onChange={(newValue) => {
- // @ts-ignore
- setContact(newValue?.contact);
- }}
+ onChange={setContact}
/>
{contact && (
<>
diff --git a/apps/carbon/app/routes/api+/accounting.accounts.tsx b/apps/carbon/app/routes/api+/accounting.accounts.tsx
new file mode 100644
index 0000000000..2ce8182797
--- /dev/null
+++ b/apps/carbon/app/routes/api+/accounting.accounts.tsx
@@ -0,0 +1,10 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getAccountsList } from "~/modules/accounting";
+import { requirePermissions } from "~/services/auth";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {});
+
+ return json(await getAccountsList(authorized.client));
+}
diff --git a/apps/carbon/app/routes/api+/parts.list.tsx b/apps/carbon/app/routes/api+/parts.list.tsx
new file mode 100644
index 0000000000..9a84b750f5
--- /dev/null
+++ b/apps/carbon/app/routes/api+/parts.list.tsx
@@ -0,0 +1,27 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import type { PartReplenishmentSystem } from "~/modules/parts";
+import { getPartsList } from "~/modules/parts";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {});
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const replenishmentSystem = searchParams.get(
+ "replenishmentSystem"
+ ) as PartReplenishmentSystem | null;
+
+ const parts = await getPartsList(authorized.client, replenishmentSystem);
+ if (parts.error) {
+ return json(
+ parts,
+ await flash(request, error(parts.error, "Failed to get parts"))
+ );
+ }
+
+ return json(parts);
+}
diff --git a/apps/carbon/app/routes/api+/parts.uom.tsx b/apps/carbon/app/routes/api+/parts.uom.tsx
new file mode 100644
index 0000000000..466a1204cf
--- /dev/null
+++ b/apps/carbon/app/routes/api+/parts.uom.tsx
@@ -0,0 +1,10 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getUnitOfMeasuresList } from "~/modules/parts";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {});
+
+ return json(getUnitOfMeasuresList(authorized.client));
+}
diff --git a/apps/carbon/app/routes/api+/resources.departments.tsx b/apps/carbon/app/routes/api+/resources.departments.tsx
index 7405931d91..795bb6d95b 100644
--- a/apps/carbon/app/routes/api+/resources.departments.tsx
+++ b/apps/carbon/app/routes/api+/resources.departments.tsx
@@ -4,9 +4,7 @@ import { getDepartmentsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
export async function loader({ request }: LoaderArgs) {
- const authorized = await requirePermissions(request, {
- view: "resources",
- });
+ const authorized = await requirePermissions(request, {});
return json(await getDepartmentsList(authorized.client));
}
diff --git a/apps/carbon/app/routes/api+/resources.locations.tsx b/apps/carbon/app/routes/api+/resources.locations.tsx
index 293f002f2a..c194939f08 100644
--- a/apps/carbon/app/routes/api+/resources.locations.tsx
+++ b/apps/carbon/app/routes/api+/resources.locations.tsx
@@ -4,9 +4,7 @@ import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
export async function loader({ request }: LoaderArgs) {
- const authorized = await requirePermissions(request, {
- view: "resources",
- });
+ const authorized = await requirePermissions(request, {});
return json(await getLocationsList(authorized.client));
}
diff --git a/apps/carbon/app/routes/api+/resources.shifts.tsx b/apps/carbon/app/routes/api+/resources.shifts.tsx
index a407975080..ac6c900834 100644
--- a/apps/carbon/app/routes/api+/resources.shifts.tsx
+++ b/apps/carbon/app/routes/api+/resources.shifts.tsx
@@ -4,9 +4,7 @@ import { getShiftsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
export async function loader({ request }: LoaderArgs) {
- const authorized = await requirePermissions(request, {
- view: "resources",
- });
+ const authorized = await requirePermissions(request, {});
const url = new URL(request.url);
const location = url.searchParams.get("location");
diff --git a/apps/carbon/app/routes/api+/sales.customer-locations.tsx b/apps/carbon/app/routes/api+/sales.customer-locations.tsx
new file mode 100644
index 0000000000..a387567212
--- /dev/null
+++ b/apps/carbon/app/routes/api+/sales.customer-locations.tsx
@@ -0,0 +1,34 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getCustomerLocations } from "~/modules/sales";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const customerId = searchParams.get("customerId") as string;
+
+ if (!customerId || customerId === "undefined")
+ return json({
+ data: [],
+ });
+
+ const locations = await getCustomerLocations(authorized.client, customerId);
+ if (locations.error) {
+ return json(
+ locations,
+ await flash(
+ request,
+ error(locations.error, "Failed to get supplier locations")
+ )
+ );
+ }
+
+ return json(locations);
+}
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 98b3ffffda..b7e41be63f 100644
--- a/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx
@@ -77,8 +77,6 @@ export default function EditShippingMethodsRoute() {
accounts: { name: string; number: string }[];
}>("/x/inventory/shipping-methods");
- console.log(shippingMethod);
-
const initialValues = {
id: shippingMethod?.id ?? undefined,
name: shippingMethod?.name ?? "",
diff --git a/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx b/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx
index 083389eded..08a8fe8b85 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx
@@ -87,10 +87,12 @@ export default function PartPurchasingRoute() {
const initialValues = {
...partPurchasing,
- supplierId: partPurchasing?.supplierId ?? undefined,
- supplierPartNumber: partPurchasing?.supplierPartNumber ?? undefined,
+ preferredSupplierId: partPurchasing?.preferredSupplierId ?? undefined,
+ purchasingLeadTime: partPurchasing?.purchasingLeadTime ?? "",
+ purchasingBlocked: partPurchasing?.purchasingBlocked ?? false,
purchasingUnitOfMeasureCode:
partPurchasing?.purchasingUnitOfMeasureCode ?? "",
+ conversionFactor: partPurchasing?.conversionFactor ?? 1,
};
return (
diff --git a/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx b/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx
new file mode 100644
index 0000000000..4b22915707
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$partId.suppliers.new.tsx
@@ -0,0 +1,67 @@
+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 {
+ PartSupplierForm,
+ partSupplierValidator,
+ upsertPartSupplier,
+} from "~/modules/parts";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "parts",
+ });
+
+ const { partId } = params;
+ if (!partId) throw new Error("Could not find partId");
+
+ const validation = await partSupplierValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createPartSupplier = await upsertPartSupplier(client, {
+ ...data,
+ createdBy: userId,
+ });
+
+ if (createPartSupplier.error) {
+ return redirect(
+ `/x/part/${partId}/suppliers`,
+ await flash(
+ request,
+ error(createPartSupplier.error, "Failed to create part supplier.")
+ )
+ );
+ }
+
+ return redirect(`/x/part/${partId}/suppliers`);
+}
+
+export default function NewPartSupplierRoute() {
+ const { partId } = useParams();
+
+ if (!partId) throw new Error("Could not find purchase order id");
+
+ const initialValues = {
+ partId: partId,
+ supplierId: "",
+ supplierPartId: "",
+ supplierUnitOfMeasureCode: "EA",
+ minimumOrderQuantity: 1,
+ conversionFactor: 1,
+ };
+
+ return <PartSupplierForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.suppliers.tsx b/apps/carbon/app/routes/x+/part+/$partId.suppliers.tsx
new file mode 100644
index 0000000000..01119f6fd0
--- /dev/null
+++ b/apps/carbon/app/routes/x+/part+/$partId.suppliers.tsx
@@ -0,0 +1,38 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { getPartSuppliers, PartSuppliers } from "~/modules/parts";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ });
+
+ const { partId } = params;
+ if (!partId) throw new Error("Could not find partId");
+
+ const [partSuppliers] = await Promise.all([getPartSuppliers(client, partId)]);
+
+ if (partSuppliers.error) {
+ return redirect(
+ `/x/part/${partId}`,
+ await flash(
+ request,
+ error(partSuppliers.error, "Failed to load part suppliers")
+ )
+ );
+ }
+
+ return json({
+ partSuppliers: partSuppliers.data ?? [],
+ });
+}
+
+export default function PartSuppliersRoute() {
+ const { partSuppliers } = useLoaderData<typeof loader>();
+
+ return <PartSuppliers partSuppliers={partSuppliers} />;
+}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$partId.tsx
index 2b1d8564a8..4346854d77 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.tsx
@@ -35,7 +35,7 @@ export default function PartRoute() {
<PartPreview />
<Grid
gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}
- gridColumnGap={8}
+ gridColumnGap={4}
w="full"
>
<PartSidebar />
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx
new file mode 100644
index 0000000000..b9234e0c6a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.delivery.tsx
@@ -0,0 +1,146 @@
+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 {
+ getShippingMethodsList,
+ getShippingTermsList,
+} from "~/modules/inventory";
+import {
+ getPurchaseOrderDelivery,
+ PurchaseOrderDeliveryForm,
+ purchaseOrderDeliveryValidator,
+ upsertPurchaseOrderDelivery,
+} from "~/modules/purchasing";
+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, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const [purchaseOrderDelivery, shippingMethods, shippingTerms] =
+ await Promise.all([
+ getPurchaseOrderDelivery(client, orderId),
+ getShippingMethodsList(client),
+ getShippingTermsList(client),
+ ]);
+
+ if (purchaseOrderDelivery.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}`,
+ await flash(
+ request,
+ error(
+ purchaseOrderDelivery.error,
+ "Failed to load purchase order delivery"
+ )
+ )
+ );
+ }
+
+ if (shippingMethods.error) {
+ return redirect(
+ "/x/purchasing/orders",
+ await flash(
+ request,
+ error(shippingMethods.error, "Failed to load shipping methods")
+ )
+ );
+ }
+
+ if (shippingTerms.error) {
+ return redirect(
+ "/x/purchasing/orders",
+ await flash(
+ request,
+ error(shippingTerms.error, "Failed to load shipping terms")
+ )
+ );
+ }
+
+ return json({
+ purchaseOrderDelivery: purchaseOrderDelivery.data,
+ shippingMethods: shippingMethods.data ?? [],
+ shippingTerms: shippingTerms.data ?? [],
+ });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ // validate with purchasingValidator
+ const validation = await purchaseOrderDeliveryValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updatePurchaseOrderDelivery = await upsertPurchaseOrderDelivery(
+ client,
+ {
+ ...validation.data,
+ id: orderId,
+ updatedBy: userId,
+ }
+ );
+ if (updatePurchaseOrderDelivery.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}/delivery`,
+ await flash(
+ request,
+ error(
+ updatePurchaseOrderDelivery.error,
+ "Failed to update purchase order delivery"
+ )
+ )
+ );
+ }
+
+ return redirect(
+ `/x/purchase-order/${orderId}/delivery`,
+ await flash(request, success("Updated purchase order delivery"))
+ );
+}
+
+export default function PurchaseOrderDeliveryRoute() {
+ const { purchaseOrderDelivery, shippingMethods, shippingTerms } =
+ useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: purchaseOrderDelivery.id,
+ locationId: purchaseOrderDelivery.locationId ?? "",
+ shippingMethodId: purchaseOrderDelivery.shippingMethodId ?? "",
+ shippingTermId: purchaseOrderDelivery.shippingTermId ?? "",
+ trackingNumber: purchaseOrderDelivery.trackingNumber ?? "",
+ receiptRequestedDate: purchaseOrderDelivery.receiptRequestedDate ?? "",
+ receiptPromisedDate: purchaseOrderDelivery.receiptPromisedDate ?? "",
+ deliveryDate: purchaseOrderDelivery.deliveryDate ?? "",
+ notes: purchaseOrderDelivery.notes ?? "",
+ dropShipment: purchaseOrderDelivery.dropShipment ?? false,
+ customerId: purchaseOrderDelivery.customerId ?? "",
+ customerLocationId: purchaseOrderDelivery.customerLocationId ?? "",
+ };
+
+ return (
+ <PurchaseOrderDeliveryForm
+ initialValues={initialValues}
+ shippingMethods={shippingMethods}
+ shippingTerms={shippingTerms}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.external.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.external.tsx
new file mode 100644
index 0000000000..ff95a2aee5
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.external.tsx
@@ -0,0 +1,26 @@
+import { useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type { PurchaseOrderAttachment } from "~/modules/purchasing";
+import { PurchaseOrderDocuments } from "~/modules/purchasing";
+
+export function action() {
+ // used for reloading the data via fetcher.submit(null, { method: 'post'})
+ return null;
+}
+
+export default function PurchaseOrderExternalDocumentsRoute() {
+ const { orderId } = useParams();
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const routeData = useRouteData<{
+ externalDocuments: PurchaseOrderAttachment[];
+ }>(`/x/purchase-order/${orderId}`);
+
+ return (
+ <PurchaseOrderDocuments
+ attachments={routeData?.externalDocuments ?? []}
+ isExternal
+ orderId={orderId}
+ />
+ );
+}
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 f87e59aea6..75d1866b3e 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.index.tsx
@@ -1,3 +1,100 @@
-export default function PurchaseOrderHeaderRoute() {
- return null;
+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 {
+ PurchaseOrder,
+ PurchaseOrderApprovalStatus,
+ PurchaseOrderType,
+} from "~/modules/purchasing";
+import {
+ PurchaseOrderForm,
+ purchaseOrderValidator,
+ upsertPurchaseOrder,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ // validate with purchasingValidator
+ const validation = await purchaseOrderValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { purchaseOrderId, ...data } = validation.data;
+ if (!purchaseOrderId) throw new Error("Could not find purchaseOrderId");
+
+ const updatePurchaseOrder = await upsertPurchaseOrder(client, {
+ id: orderId,
+ purchaseOrderId,
+ ...data,
+ updatedBy: userId,
+ });
+ if (updatePurchaseOrder.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}`,
+ await flash(
+ request,
+ error(updatePurchaseOrder.error, "Failed to update purchase order")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/purchase-order/${orderId}`,
+ await flash(request, success("Updated purchase order"))
+ );
+}
+
+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}`
+ );
+ if (!orderData) throw new Error("Could not find part data");
+
+ const initialValues = {
+ id: orderData?.purchaseOrder?.id ?? "",
+ purchaseOrderId: orderData?.purchaseOrder?.purchaseOrderId ?? "",
+ supplierId: orderData?.purchaseOrder?.supplierId ?? "",
+ supplierContactId: orderData?.purchaseOrder?.supplierContactId ?? "",
+ supplierReference: orderData?.purchaseOrder?.supplierReference ?? "",
+ orderDate: orderData?.purchaseOrder?.orderDate ?? "",
+ type: orderData?.purchaseOrder?.type ?? "Draft",
+ status: orderData?.purchaseOrder?.status ?? "Draft",
+ 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 ?? []}
+ />
+ );
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.internal.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.internal.tsx
new file mode 100644
index 0000000000..c69d2cc541
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.internal.tsx
@@ -0,0 +1,26 @@
+import { useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type { PurchaseOrderAttachment } from "~/modules/purchasing";
+import { PurchaseOrderDocuments } from "~/modules/purchasing";
+
+export function action() {
+ // used for reloading the data via fetcher.submit(null, { method: 'post'})
+ return null;
+}
+
+export default function PurchaseOrderInternalDocumentsRoute() {
+ const { orderId } = useParams();
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const routeData = useRouteData<{
+ internalDocuments: PurchaseOrderAttachment[];
+ }>(`/x/purchase-order/${orderId}`);
+
+ return (
+ <PurchaseOrderDocuments
+ attachments={routeData?.internalDocuments ?? []}
+ isExternal={false}
+ orderId={orderId}
+ />
+ );
+}
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
new file mode 100644
index 0000000000..f46016f49b
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.$lineId.tsx
@@ -0,0 +1,121 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { 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 {
+ PurchaseOrderLineForm,
+ purchaseOrderLineValidator,
+ upsertPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const { lineId } = params;
+ if (!lineId) throw notFound("lineId not found");
+
+ const purchaseOrderLine = await getPurchaseOrderLine(client, lineId);
+
+ return json({
+ purchaseOrderLine: purchaseOrderLine?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { orderId, lineId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const validation = await purchaseOrderLineValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ if (data.purchaseOrderLineType === "Part") {
+ data.accountNumber = undefined;
+ data.assetId = undefined;
+ } else if (data.purchaseOrderLineType === "G/L Account") {
+ data.assetId = undefined;
+ data.partId = undefined;
+ } else if (data.purchaseOrderLineType === "Fixed Asset") {
+ data.accountNumber = undefined;
+ data.partId = undefined;
+ } else if (data.purchaseOrderLineType === "Comment") {
+ data.accountNumber = undefined;
+ data.assetId = undefined;
+ data.partId = undefined;
+ }
+
+ const updatePurchaseOrderLine = await upsertPurchaseOrderLine(client, {
+ id: lineId,
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (updatePurchaseOrderLine.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}/lines`,
+ await flash(
+ request,
+ error(
+ updatePurchaseOrderLine.error,
+ "Failed to update purchaseOrderLine."
+ )
+ )
+ );
+ }
+
+ return redirect(`/x/purchase-order/${orderId}/lines`);
+}
+
+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 ?? "",
+ purchaseOrderLineType:
+ purchaseOrderLine?.purchaseOrderLineType ??
+ ("Part" as PurchaseOrderLineType),
+ partId: purchaseOrderLine?.partId ?? "",
+ purchaseQuantity: purchaseOrderLine?.purchaseQuantity ?? 1,
+ unitPrice: purchaseOrderLine?.unitPrice ?? 0,
+ setupPrice: purchaseOrderLine?.setupPrice ?? 0,
+ unitOfMeasureCode: purchaseOrderLine?.unitOfMeasureCode ?? "",
+ shelfId: purchaseOrderLine?.shelfId ?? "",
+ };
+
+ return (
+ <PurchaseOrderLineForm
+ initialValues={initialValues}
+ purchaseOrderLineTypes={
+ sharedPurchaseOrdersData?.purchaseOrderLineTypes ?? []
+ }
+ />
+ );
+}
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
new file mode 100644
index 0000000000..9876cb8763
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.new.tsx
@@ -0,0 +1,84 @@
+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,
+ purchaseOrderLineValidator,
+ upsertPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const validation = await purchaseOrderLineValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createPurchaseOrderLine = await upsertPurchaseOrderLine(client, {
+ ...data,
+ createdBy: userId,
+ });
+
+ if (createPurchaseOrderLine.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}/lines`,
+ await flash(
+ request,
+ error(
+ createPurchaseOrderLine.error,
+ "Failed to create purchase order line."
+ )
+ )
+ );
+ }
+
+ return redirect(`/x/purchase-order/${orderId}/lines`);
+}
+
+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");
+
+ const initialValues = {
+ purchaseOrderId: orderId,
+ purchaseOrderLineType: "Part" as PurchaseOrderLineType,
+ partId: "",
+ purchaseQuantity: 1,
+ unitPrice: 0,
+ setupPrice: 0,
+ unitOfMeasureCode: "",
+ shelfId: "",
+ };
+
+ return (
+ <PurchaseOrderLineForm
+ initialValues={initialValues}
+ purchaseOrderLineTypes={
+ sharedPurchaseOrdersData?.purchaseOrderLineTypes ?? []
+ }
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.tsx
new file mode 100644
index 0000000000..c65d68ab6b
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.lines.tsx
@@ -0,0 +1,43 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import {
+ getPurchaseOrderLines,
+ PurchaseOrderLines,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const [purchaseOrderLines] = await Promise.all([
+ getPurchaseOrderLines(client, orderId),
+ ]);
+
+ if (purchaseOrderLines.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}`,
+ await flash(
+ request,
+ error(purchaseOrderLines.error, "Failed to load purchase order lines")
+ )
+ );
+ }
+
+ return json({
+ purchaseOrderLines: purchaseOrderLines.data ?? [],
+ });
+}
+
+export default function PurchaseOrderLinesRoute() {
+ const { purchaseOrderLines } = useLoaderData<typeof loader>();
+
+ return <PurchaseOrderLines purchaseOrderLines={purchaseOrderLines} />;
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx
new file mode 100644
index 0000000000..3525e55de8
--- /dev/null
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.payment.tsx
@@ -0,0 +1,122 @@
+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 { getPaymentTermsList } from "~/modules/accounting";
+import {
+ getPurchaseOrderPayment,
+ PurchaseOrderPaymentForm,
+ purchaseOrderPaymentValidator,
+ upsertPurchaseOrderPayment,
+} from "~/modules/purchasing";
+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, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const [purchaseOrderPayment, paymentTerms] = await Promise.all([
+ getPurchaseOrderPayment(client, orderId),
+ getPaymentTermsList(client),
+ ]);
+
+ if (purchaseOrderPayment.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}`,
+ await flash(
+ request,
+ error(
+ purchaseOrderPayment.error,
+ "Failed to load purchase order payment"
+ )
+ )
+ );
+ }
+
+ if (paymentTerms.error) {
+ return redirect(
+ "/x/purchasing/orders",
+ await flash(
+ request,
+ error(paymentTerms.error, "Failed to load payment terms")
+ )
+ );
+ }
+
+ return json({
+ purchaseOrderPayment: purchaseOrderPayment.data,
+ paymentTerms: paymentTerms.data ?? [],
+ });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ // validate with purchasingValidator
+ const validation = await purchaseOrderPaymentValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updatePurchaseOrderPayment = await upsertPurchaseOrderPayment(client, {
+ ...validation.data,
+ id: orderId,
+ updatedBy: userId,
+ });
+ if (updatePurchaseOrderPayment.error) {
+ return redirect(
+ `/x/purchase-order/${orderId}/payment`,
+ await flash(
+ request,
+ error(
+ updatePurchaseOrderPayment.error,
+ "Failed to update purchase order payment"
+ )
+ )
+ );
+ }
+
+ return redirect(
+ `/x/purchase-order/${orderId}/payment`,
+ await flash(request, success("Updated purchase order payment"))
+ );
+}
+
+export default function PurchaseOrderPaymentRoute() {
+ const { purchaseOrderPayment, paymentTerms } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: purchaseOrderPayment.id,
+ invoiceSupplierId: purchaseOrderPayment.invoiceSupplierId ?? "",
+ invoiceSupplierLocationId:
+ purchaseOrderPayment.invoiceSupplierLocationId ?? undefined,
+ invoiceSupplierContactId:
+ purchaseOrderPayment.invoiceSupplierContactId ?? undefined,
+ paymentTermId: purchaseOrderPayment.paymentTermId ?? undefined,
+ paymentComplete: purchaseOrderPayment.paymentComplete ?? undefined,
+ currencyCode: purchaseOrderPayment.currencyCode ?? "USD",
+ };
+
+ return (
+ <PurchaseOrderPaymentForm
+ initialValues={initialValues}
+ paymentTerms={paymentTerms}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
index df34bda5d3..704884b3c3 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx
@@ -3,6 +3,8 @@ import type { LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import {
+ getExternalDocuments,
+ getInternalDocuments,
getPurchaseOrder,
PurchaseOrderHeader,
PurchaseOrderSidebar,
@@ -19,7 +21,13 @@ export async function loader({ request, params }: LoaderArgs) {
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
- const purchaseOrder = await getPurchaseOrder(client, orderId);
+ const [purchaseOrder, externalDocuments, internalDocuments] =
+ await Promise.all([
+ getPurchaseOrder(client, orderId),
+ getExternalDocuments(client, orderId),
+ getInternalDocuments(client, orderId),
+ ]);
+
if (purchaseOrder.error) {
return redirect(
"/x/purchasing/orders",
@@ -30,7 +38,11 @@ export async function loader({ request, params }: LoaderArgs) {
);
}
- return json(purchaseOrder.data);
+ return json({
+ purchaseOrder: purchaseOrder.data,
+ externalDocuments: externalDocuments.data ?? [],
+ internalDocuments: internalDocuments.data ?? [],
+ });
}
export default function PurchaseOrderRoute() {
@@ -39,7 +51,7 @@ export default function PurchaseOrderRoute() {
<PurchaseOrderHeader />
<Grid
gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}
- gridColumnGap={8}
+ gridColumnGap={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 8b18a460cf..e3846763bd 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/_layout.tsx
@@ -1,8 +1,10 @@
import { VStack } from "@chakra-ui/react";
import type { LoaderArgs, MetaFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
+
import {
getPurchaseOrderApprovalStatuses,
+ getPurchaseOrderLineTypes,
getPurchaseOrderTypes,
} from "~/modules/purchasing";
import { requirePermissions } from "~/services/auth";
@@ -16,10 +18,23 @@ export async function loader({ request }: LoaderArgs) {
view: "purchasing",
});
- // const [] = await Promise.all([]);
+ // 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(),
};
}
diff --git a/apps/carbon/app/routes/x+/purchase-order+/new.tsx b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
index faf1280c05..0fa7fe128c 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/new.tsx
@@ -13,7 +13,7 @@ import {
purchaseOrderValidator,
upsertPurchaseOrder,
} from "~/modules/purchasing";
-import { getNextSequence } from "~/modules/settings";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
@@ -49,7 +49,10 @@ export async function action({ request }: ActionArgs) {
purchaseOrderId: nextSequence.data,
createdBy: userId,
});
+
if (createPurchaseOrder.error) {
+ // TODO: this should be done as a transaction
+ await rollbackNextSequence(client, "purchaseOrder", userId);
return redirect(
"/x/purchasing/orders",
await flash(
@@ -59,11 +62,14 @@ export async function action({ request }: ActionArgs) {
);
}
- const { id, purchaseOrderId } = createPurchaseOrder.data[0];
+ const order = createPurchaseOrder.data?.[0];
return redirect(
- `/x/purchase-order/${id}`,
- await flash(request, success(`Created purchase order ${purchaseOrderId}`))
+ `/x/purchase-order/${order?.id}`,
+ await flash(
+ request,
+ success(`Created purchase order ${order?.purchaseOrderId}`)
+ )
);
}
@@ -79,12 +85,12 @@ export default function PurchaseOrderNewRoute() {
orderDate: today(getLocalTimeZone()).toString(),
status: "Draft" as PurchaseOrderApprovalStatus,
type: "Purchase" as PurchaseOrderType,
- currencyCode: "USD",
};
return (
<Box w="50%" maxW={720} minW={420}>
<PurchaseOrderForm
+ // @ts-expect-error
initialValues={initialValues}
purchaseOrderApprovalStatuses={
routeData?.purchaseOrderApprovalStatuses ?? []
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx
index bb099c1cfb..afe8f010ff 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx
@@ -71,15 +71,7 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const {
- id,
- name,
- supplierTypeId,
- supplierStatusId,
- accountManagerId,
- taxId,
- description,
- } = validation.data;
+ const { id, ...data } = validation.data;
if (!id) {
return redirect(
@@ -90,12 +82,7 @@ export async function action({ request }: ActionArgs) {
const update = await updateSupplier(client, {
id,
- name,
- supplierTypeId,
- supplierStatusId,
- accountManagerId,
- taxId,
- description,
+ ...data,
updatedBy: userId,
});
if (update.error) {
@@ -108,7 +95,7 @@ export async function action({ request }: ActionArgs) {
return json(null, await flash(request, success("Updated supplier")));
}
-export default function SuppliersNewRoute() {
+export default function SupplierEditRoute() {
const { supplier, contacts, locations } = useLoaderData<typeof loader>();
const initialValues = {
@@ -118,7 +105,10 @@ export default function SuppliersNewRoute() {
supplierStatusId: supplier.supplierStatusId ?? undefined,
accountManagerId: supplier.accountManagerId ?? undefined,
taxId: supplier.taxId ?? "",
- description: supplier.description ?? "",
+ defaultCurrencyCode: supplier.defaultCurrencyCode ?? "",
+ defaultPaymentTermId: supplier.defaultPaymentTermId ?? undefined,
+ defaultShippingMethodId: supplier.defaultShippingMethodId ?? undefined,
+ defaultShippingTermId: supplier.defaultShippingTermId ?? undefined,
};
return (
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
index a24a9ef440..87e32e9783 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
@@ -23,22 +23,10 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const {
- name,
- supplierTypeId,
- supplierStatusId,
- accountManagerId,
- taxId,
- description,
- } = validation.data;
+ const { id, ...data } = validation.data;
const createSupplier = await insertSupplier(client, {
- name,
- supplierTypeId,
- supplierStatusId,
- accountManagerId,
- taxId,
- description,
+ ...data,
createdBy: userId,
});
if (createSupplier.error) {
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
index 10cd218619..01d6595618 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
@@ -3,6 +3,11 @@ 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 { getPaymentTermsList } from "~/modules/accounting";
+import {
+ getShippingMethodsList,
+ getShippingTermsList,
+} from "~/modules/inventory";
import {
SuppliersTable,
SuppliersTableFilters,
@@ -29,10 +34,20 @@ export async function loader({ request }: LoaderArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [suppliers, supplierTypes, supplierStatuses] = await Promise.all([
+ const [
+ suppliers,
+ supplierTypes,
+ supplierStatuses,
+ paymentTerms,
+ shippingMethods,
+ shippingTerms,
+ ] = await Promise.all([
getSuppliers(client, { name, type, status, limit, offset, sorts, filters }),
getSupplierTypes(client),
getSupplierStatuses(client),
+ getPaymentTermsList(client),
+ getShippingMethodsList(client),
+ getShippingTermsList(client),
]);
if (suppliers.error) {
@@ -47,6 +62,9 @@ export async function loader({ request }: LoaderArgs) {
suppliers: suppliers.data ?? [],
supplierStatuses: supplierStatuses.data ?? [],
supplierTypes: supplierTypes.data ?? [],
+ paymentTerms: paymentTerms.data ?? [],
+ shippingMethods: shippingMethods.data ?? [],
+ shippingTerms: shippingTerms.data ?? [],
});
}
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx b/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx
index 2c6ddd4352..ea6ce812b4 100644
--- a/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx
@@ -56,7 +56,7 @@ export async function action({ request }: ActionArgs) {
const updateContractor = await upsertContractor(client, {
id,
hoursPerWeek,
- abilities,
+ abilities: abilities ?? [],
updatedBy: userId,
});
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.new.tsx b/apps/carbon/app/routes/x+/resources+/contractors.new.tsx
index 25d7832c5d..8b727aa0ac 100644
--- a/apps/carbon/app/routes/x+/resources+/contractors.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/contractors.new.tsx
@@ -31,7 +31,7 @@ export async function action({ request }: ActionArgs) {
const createContractor = await upsertContractor(client, {
id,
hoursPerWeek,
- abilities,
+ abilities: abilities ?? [],
createdBy: userId,
});
diff --git a/apps/carbon/app/routes/x+/resources+/locations.$locationId.tsx b/apps/carbon/app/routes/x+/resources+/locations.$locationId.tsx
index 08129fad82..9698375e4a 100644
--- a/apps/carbon/app/routes/x+/resources+/locations.$locationId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/locations.$locationId.tsx
@@ -49,15 +49,12 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const { id, name, timezone, latitude, longitude } = validation.data;
+ const { id, ...data } = validation.data;
if (!id) throw notFound("Location ID was not found");
const createLocation = await upsertLocation(client, {
id,
- name,
- timezone,
- latitude: latitude ?? null,
- longitude: longitude ?? null,
+ ...data,
updatedBy: userId,
});
@@ -83,6 +80,11 @@ export default function LocationRoute() {
const initialValues = {
id: location.id,
name: location.name,
+ addressLine1: location.addressLine1 ?? undefined,
+ addressLine2: location.addressLine2 ?? undefined,
+ city: location.city ?? undefined,
+ state: location.state ?? undefined,
+ postalCode: location.postalCode ?? undefined,
timezone: location.timezone ?? getLocalTimeZone(),
latitude: location.latitude ?? undefined,
longitude: location.longitude ?? undefined,
diff --git a/apps/carbon/app/routes/x+/resources+/locations.new.tsx b/apps/carbon/app/routes/x+/resources+/locations.new.tsx
index 5472cfdf69..dc10d4330c 100644
--- a/apps/carbon/app/routes/x+/resources+/locations.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/locations.new.tsx
@@ -24,13 +24,10 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const { name, timezone, latitude, longitude } = validation.data;
+ const { id, ...data } = validation.data;
const createLocation = await upsertLocation(client, {
- name,
- timezone,
- latitude: latitude ?? null,
- longitude: longitude ?? null,
+ ...data,
createdBy: userId,
});
@@ -54,6 +51,11 @@ export default function NewLocationRoute() {
const initialValues = {
name: "",
timezone: getLocalTimeZone(),
+ addressLine1: "",
+ addressLine2: "",
+ city: "",
+ state: "",
+ postalCode: "",
};
return <LocationForm initialValues={initialValues} />;
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx b/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx
index 22b5c15c09..d0a14d9694 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx
+++ b/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx
@@ -71,15 +71,7 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const {
- id,
- name,
- customerTypeId,
- customerStatusId,
- accountManagerId,
- taxId,
- description,
- } = validation.data;
+ const { id, ...data } = validation.data;
if (!id) {
return redirect(
@@ -90,12 +82,7 @@ export async function action({ request }: ActionArgs) {
const update = await updateCustomer(client, {
id,
- name,
- customerTypeId,
- customerStatusId,
- accountManagerId,
- taxId,
- description,
+ ...data,
updatedBy: userId,
});
if (update.error) {
@@ -118,7 +105,6 @@ export default function CustomersNewRoute() {
customerStatusId: customer.customerStatusId ?? undefined,
accountManagerId: customer.accountManagerId ?? undefined,
taxId: customer.taxId ?? "",
- description: customer.description ?? "",
};
return (
diff --git a/apps/carbon/app/routes/x+/sales+/customers.new.tsx b/apps/carbon/app/routes/x+/sales+/customers.new.tsx
index 8fbbacb804..e7dbc2f838 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.new.tsx
+++ b/apps/carbon/app/routes/x+/sales+/customers.new.tsx
@@ -23,22 +23,10 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const {
- name,
- customerTypeId,
- customerStatusId,
- accountManagerId,
- taxId,
- description,
- } = validation.data;
+ const { id, ...data } = validation.data;
const createCustomer = await insertCustomer(client, {
- name,
- customerTypeId,
- customerStatusId,
- accountManagerId,
- taxId,
- description,
+ ...data,
createdBy: userId,
});
if (createCustomer.error) {
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index f330d63c16..cadf75eb93 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -102,12 +102,13 @@ export async function requirePermissions(
if (action === "role") {
return myClaims.role === permission;
}
- return myClaims.permissions![permission][
+ if (!(permission in myClaims.permissions)) return false;
+ return myClaims.permissions[permission][
action as "view" | "create" | "update" | "delete"
];
} else if (Array.isArray(permission)) {
return permission.every((p) => {
- return myClaims.permissions![p][
+ return myClaims.permissions[p][
action as "view" | "create" | "update" | "delete"
];
});
@@ -122,7 +123,7 @@ export async function requirePermissions(
"/x",
await flash(
request,
- error({ myClaims, requirePermissions }, "Access Denied")
+ error({ myClaims, requiredPermissions }, "Access Denied")
)
);
}
diff --git a/apps/carbon/app/types/index.ts b/apps/carbon/app/types/index.ts
index e89598725b..70141f67b5 100644
--- a/apps/carbon/app/types/index.ts
+++ b/apps/carbon/app/types/index.ts
@@ -24,6 +24,11 @@ export type FormActionData = Promise<
TypedResponse<ValidationErrorResponseData> | TypedResponse<Result>
>;
+export type ListItem = {
+ id: string;
+ name: string;
+};
+
export type NavItem = Omit<Route, "icon"> & {
icon: ReactElement;
color?: string;
diff --git a/apps/carbon/app/utils/dom.ts b/apps/carbon/app/utils/dom.ts
new file mode 100644
index 0000000000..d5aa965c86
--- /dev/null
+++ b/apps/carbon/app/utils/dom.ts
@@ -0,0 +1,6 @@
+export function scrollIntoView(element: HTMLElement | undefined | null) {
+ element?.scrollIntoView({
+ inline: "nearest",
+ block: "nearest",
+ });
+}
diff --git a/apps/carbon/app/utils/supabase.ts b/apps/carbon/app/utils/supabase.ts
new file mode 100644
index 0000000000..4631ac61cb
--- /dev/null
+++ b/apps/carbon/app/utils/supabase.ts
@@ -0,0 +1,7 @@
+export const sanitize = (input: Record<string, any>) => {
+ const output = { ...input };
+ Object.keys(output).forEach((key) => {
+ if (output[key] === undefined && key !== "id") output[key] = null;
+ });
+ return output;
+};
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index a02413ff1c..4fd35ff647 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -417,7 +417,6 @@ export interface Database {
customer: {
Row: {
name: string;
- description: string | null;
customerTypeId: string | null;
customerStatusId: string | null;
taxId: string | null;
@@ -431,7 +430,6 @@ export interface Database {
};
Insert: {
name: string;
- description?: string | null;
customerTypeId?: string | null;
customerStatusId?: string | null;
taxId?: string | null;
@@ -445,7 +443,6 @@ export interface Database {
};
Update: {
name?: string;
- description?: string | null;
customerTypeId?: string | null;
customerStatusId?: string | null;
taxId?: string | null;
@@ -1022,6 +1019,12 @@ export interface Database {
location: {
Row: {
name: string;
+ addressLine1: string;
+ addressLine2: string | null;
+ city: string;
+ state: string;
+ postalCode: string;
+ country: string | null;
timezone: string;
latitude: number | null;
longitude: number | null;
@@ -1033,6 +1036,12 @@ export interface Database {
};
Insert: {
name: string;
+ addressLine1: string;
+ addressLine2?: string | null;
+ city: string;
+ state: string;
+ postalCode: string;
+ country?: string | null;
timezone: string;
latitude?: number | null;
longitude?: number | null;
@@ -1044,6 +1053,12 @@ export interface Database {
};
Update: {
name?: string;
+ addressLine1?: string;
+ addressLine2?: string | null;
+ city?: string;
+ state?: string;
+ postalCode?: string;
+ country?: string | null;
timezone?: string;
latitude?: number | null;
longitude?: number | null;
@@ -1388,14 +1403,14 @@ export interface Database {
partReplenishment: {
Row: {
partId: string;
- supplierId: string | null;
- supplierPartNumber: string | null;
+ preferredSupplierId: string | null;
purchasingUnitOfMeasureCode: string | null;
lotSize: number | null;
createdBy: string;
updatedBy: string | null;
updatedAt: string | null;
purchasingLeadTime: number;
+ conversionFactor: number;
purchasingBlocked: boolean;
manufacturingPolicy: Database["public"]["Enums"]["partManufacturingPolicy"];
manufacturingLeadTime: number;
@@ -1406,14 +1421,14 @@ export interface Database {
};
Insert: {
partId: string;
- supplierId?: string | null;
- supplierPartNumber?: string | null;
+ preferredSupplierId?: string | null;
purchasingUnitOfMeasureCode?: string | null;
lotSize?: number | null;
createdBy: string;
updatedBy?: string | null;
updatedAt?: string | null;
purchasingLeadTime?: number;
+ conversionFactor?: number;
purchasingBlocked?: boolean;
manufacturingPolicy?: Database["public"]["Enums"]["partManufacturingPolicy"];
manufacturingLeadTime?: number;
@@ -1424,14 +1439,14 @@ export interface Database {
};
Update: {
partId?: string;
- supplierId?: string | null;
- supplierPartNumber?: string | null;
+ preferredSupplierId?: string | null;
purchasingUnitOfMeasureCode?: string | null;
lotSize?: number | null;
createdBy?: string;
updatedBy?: string | null;
updatedAt?: string | null;
purchasingLeadTime?: number;
+ conversionFactor?: number;
purchasingBlocked?: boolean;
manufacturingPolicy?: Database["public"]["Enums"]["partManufacturingPolicy"];
manufacturingLeadTime?: number;
@@ -1441,6 +1456,50 @@ export interface Database {
createdAt?: string;
};
};
+ partSupplier: {
+ Row: {
+ partId: string;
+ supplierId: string;
+ supplierPartId: string | null;
+ supplierUnitOfMeasureCode: string | null;
+ createdBy: string;
+ updatedBy: string | null;
+ updatedAt: string | null;
+ id: string;
+ minimumOrderQuantity: number | null;
+ conversionFactor: number;
+ active: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ partId: string;
+ supplierId: string;
+ supplierPartId?: string | null;
+ supplierUnitOfMeasureCode?: string | null;
+ createdBy: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ id?: string;
+ minimumOrderQuantity?: number | null;
+ conversionFactor?: number;
+ active?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ partId?: string;
+ supplierId?: string;
+ supplierPartId?: string | null;
+ supplierUnitOfMeasureCode?: string | null;
+ createdBy?: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ id?: string;
+ minimumOrderQuantity?: number | null;
+ conversionFactor?: number;
+ active?: boolean;
+ createdAt?: string;
+ };
+ };
partUnitSalePrice: {
Row: {
partId: string;
@@ -1528,18 +1587,10 @@ export interface Database {
purchaseOrderId: string;
type: Database["public"]["Enums"]["purchaseOrderType"];
status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
- orderDueDate: string | null;
- receivedDate: string | null;
notes: string | null;
supplierId: string;
supplierContactId: string | null;
supplierReference: string | null;
- invoiceSupplierId: string | null;
- invoiceSupplierLocationId: string | null;
- invoiceSupplierContactId: string | null;
- paymentTermId: string | null;
- shippingMethodId: string | null;
- currencyCode: string;
closedAt: string | null;
closedBy: string | null;
createdBy: string;
@@ -1547,11 +1598,6 @@ export interface Database {
updatedBy: string | null;
id: string;
orderDate: string;
- orderSubTotal: number;
- orderTax: number;
- orderDiscount: number;
- orderShipping: number;
- orderTotal: number;
closed: boolean;
createdAt: string;
};
@@ -1559,18 +1605,10 @@ export interface Database {
purchaseOrderId: string;
type: Database["public"]["Enums"]["purchaseOrderType"];
status: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
- orderDueDate?: string | null;
- receivedDate?: string | null;
notes?: string | null;
supplierId: string;
supplierContactId?: string | null;
supplierReference?: string | null;
- invoiceSupplierId?: string | null;
- invoiceSupplierLocationId?: string | null;
- invoiceSupplierContactId?: string | null;
- paymentTermId?: string | null;
- shippingMethodId?: string | null;
- currencyCode: string;
closedAt?: string | null;
closedBy?: string | null;
createdBy: string;
@@ -1578,11 +1616,6 @@ export interface Database {
updatedBy?: string | null;
id?: string;
orderDate?: string;
- orderSubTotal?: number;
- orderTax?: number;
- orderDiscount?: number;
- orderShipping?: number;
- orderTotal?: number;
closed?: boolean;
createdAt?: string;
};
@@ -1590,18 +1623,10 @@ export interface Database {
purchaseOrderId?: string;
type?: Database["public"]["Enums"]["purchaseOrderType"];
status?: Database["public"]["Enums"]["purchaseOrderApprovalStatus"];
- orderDueDate?: string | null;
- receivedDate?: string | null;
notes?: string | null;
supplierId?: string;
supplierContactId?: string | null;
supplierReference?: string | null;
- invoiceSupplierId?: string | null;
- invoiceSupplierLocationId?: string | null;
- invoiceSupplierContactId?: string | null;
- paymentTermId?: string | null;
- shippingMethodId?: string | null;
- currencyCode?: string;
closedAt?: string | null;
closedBy?: string | null;
createdBy?: string;
@@ -1609,15 +1634,60 @@ export interface Database {
updatedBy?: string | null;
id?: string;
orderDate?: string;
- orderSubTotal?: number;
- orderTax?: number;
- orderDiscount?: number;
- orderShipping?: number;
- orderTotal?: number;
closed?: boolean;
createdAt?: string;
};
};
+ purchaseOrderDelivery: {
+ Row: {
+ id: string;
+ locationId: string | null;
+ shippingMethodId: string | null;
+ shippingTermId: string | null;
+ receiptRequestedDate: string | null;
+ receiptPromisedDate: string | null;
+ deliveryDate: string | null;
+ notes: string | null;
+ trackingNumber: string | null;
+ customerId: string | null;
+ customerLocationId: string | null;
+ updatedBy: string | null;
+ updatedAt: string | null;
+ dropShipment: boolean;
+ };
+ Insert: {
+ id: string;
+ locationId?: string | null;
+ shippingMethodId?: string | null;
+ shippingTermId?: string | null;
+ receiptRequestedDate?: string | null;
+ receiptPromisedDate?: string | null;
+ deliveryDate?: string | null;
+ notes?: string | null;
+ trackingNumber?: string | null;
+ customerId?: string | null;
+ customerLocationId?: string | null;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ dropShipment?: boolean;
+ };
+ Update: {
+ id?: string;
+ locationId?: string | null;
+ shippingMethodId?: string | null;
+ shippingTermId?: string | null;
+ receiptRequestedDate?: string | null;
+ receiptPromisedDate?: string | null;
+ deliveryDate?: string | null;
+ notes?: string | null;
+ trackingNumber?: string | null;
+ customerId?: string | null;
+ customerLocationId?: string | null;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ dropShipment?: boolean;
+ };
+ };
purchaseOrderFavorite: {
Row: {
purchaseOrderId: string;
@@ -1632,6 +1702,106 @@ export interface Database {
userId?: string;
};
};
+ purchaseOrderLine: {
+ Row: {
+ purchaseOrderId: string;
+ purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
+ partId: string | null;
+ accountNumber: string | null;
+ assetId: string | null;
+ description: string | null;
+ unitPrice: number | null;
+ unitOfMeasureCode: string | null;
+ shelfId: string | null;
+ setupPrice: number | null;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ id: string;
+ purchaseQuantity: number | null;
+ receivedComplete: boolean;
+ invoiceComplete: boolean;
+ requiresInspection: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ purchaseOrderId: string;
+ purchaseOrderLineType: Database["public"]["Enums"]["purchaseOrderLineType"];
+ partId?: string | null;
+ accountNumber?: string | null;
+ assetId?: string | null;
+ description?: string | null;
+ unitPrice?: number | null;
+ unitOfMeasureCode?: string | null;
+ shelfId?: string | null;
+ setupPrice?: number | null;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ purchaseQuantity?: number | null;
+ receivedComplete?: boolean;
+ invoiceComplete?: boolean;
+ requiresInspection?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ purchaseOrderId?: string;
+ purchaseOrderLineType?: Database["public"]["Enums"]["purchaseOrderLineType"];
+ partId?: string | null;
+ accountNumber?: string | null;
+ assetId?: string | null;
+ description?: string | null;
+ unitPrice?: number | null;
+ unitOfMeasureCode?: string | null;
+ shelfId?: string | null;
+ setupPrice?: number | null;
+ createdBy?: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ purchaseQuantity?: number | null;
+ receivedComplete?: boolean;
+ invoiceComplete?: boolean;
+ requiresInspection?: boolean;
+ createdAt?: string;
+ };
+ };
+ purchaseOrderPayment: {
+ Row: {
+ id: string;
+ invoiceSupplierId: string | null;
+ invoiceSupplierLocationId: string | null;
+ invoiceSupplierContactId: string | null;
+ paymentTermId: string | null;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ paymentComplete: boolean;
+ currencyCode: string;
+ };
+ Insert: {
+ id: string;
+ invoiceSupplierId?: string | null;
+ invoiceSupplierLocationId?: string | null;
+ invoiceSupplierContactId?: string | null;
+ paymentTermId?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ paymentComplete?: boolean;
+ currencyCode?: string;
+ };
+ Update: {
+ id?: string;
+ invoiceSupplierId?: string | null;
+ invoiceSupplierLocationId?: string | null;
+ invoiceSupplierContactId?: string | null;
+ paymentTermId?: string | null;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ paymentComplete?: boolean;
+ currencyCode?: string;
+ };
+ };
purchaseOrderTransaction: {
Row: {
purchaseOrderId: string;
@@ -1833,10 +2003,38 @@ export interface Database {
createdAt?: string;
};
};
+ shippingTerm: {
+ Row: {
+ name: string;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ id: string;
+ active: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ name: string;
+ createdBy: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ active?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ name?: string;
+ createdBy?: string;
+ updatedAt?: string | null;
+ updatedBy?: string | null;
+ id?: string;
+ active?: boolean;
+ createdAt?: string;
+ };
+ };
supplier: {
Row: {
name: string;
- description: string | null;
supplierTypeId: string | null;
supplierStatusId: string | null;
taxId: string | null;
@@ -1847,10 +2045,13 @@ export interface Database {
updatedBy: string | null;
id: string;
createdAt: string;
+ defaultCurrencyCode: string | null;
+ defaultPaymentTermId: string | null;
+ defaultShippingMethodId: string | null;
+ defaultShippingTermId: string | null;
};
Insert: {
name: string;
- description?: string | null;
supplierTypeId?: string | null;
supplierStatusId?: string | null;
taxId?: string | null;
@@ -1861,10 +2062,13 @@ export interface Database {
updatedBy?: string | null;
id?: string;
createdAt?: string;
+ defaultCurrencyCode?: string | null;
+ defaultPaymentTermId?: string | null;
+ defaultShippingMethodId?: string | null;
+ defaultShippingTermId?: string | null;
};
Update: {
name?: string;
- description?: string | null;
supplierTypeId?: string | null;
supplierStatusId?: string | null;
taxId?: string | null;
@@ -1875,6 +2079,10 @@ export interface Database {
updatedBy?: string | null;
id?: string;
createdAt?: string;
+ defaultCurrencyCode?: string | null;
+ defaultPaymentTermId?: string | null;
+ defaultShippingMethodId?: string | null;
+ defaultShippingTermId?: string | null;
};
};
supplierAccount: {
@@ -2178,30 +2386,30 @@ export interface Database {
userId: string;
note: string;
id: string;
- createdBy: string;
- updatedAt: string | null;
noteRichText: Json;
active: boolean;
+ createdBy: string;
+ updatedAt: string | null;
createdAt: string;
};
Insert: {
userId: string;
note: string;
id?: string;
- createdBy: string;
- updatedAt?: string | null;
noteRichText?: Json;
active?: boolean;
+ createdBy: string;
+ updatedAt?: string | null;
createdAt?: string;
};
Update: {
userId?: string;
note?: string;
id?: string;
- createdBy?: string;
- updatedAt?: string | null;
noteRichText?: Json;
active?: boolean;
+ createdBy?: string;
+ updatedAt?: string | null;
createdAt?: string;
};
};
@@ -2292,7 +2500,7 @@ export interface Database {
};
};
Views: {
- contractors_query: {
+ contractors_view: {
Row: {
supplierContactId: string | null;
active: boolean | null;
@@ -2383,7 +2591,7 @@ export interface Database {
year: number | null;
};
};
- partners_query: {
+ partners_view: {
Row: {
supplierLocationId: string | null;
active: boolean | null;
@@ -2404,8 +2612,16 @@ export interface Database {
| null;
type: Database["public"]["Enums"]["purchaseOrderType"] | null;
orderDate: string | null;
- orderDueDate: string | null;
+ notes: string | null;
+ supplierId: string | null;
+ supplierContactId: string | null;
+ supplierReference: string | null;
createdBy: string | null;
+ receiptRequestedDate: string | null;
+ receiptPromisedDate: string | null;
+ dropShipment: boolean | null;
+ lineCount: number | null;
+ locationName: string | null;
supplierName: string | null;
createdByAvatar: string | null;
createdByFullName: string | null;
@@ -2565,6 +2781,7 @@ export interface Database {
| "Approved"
| "Rejected"
| "Confirmed";
+ purchaseOrderLineType: "Comment" | "G/L Account" | "Part" | "Fixed Asset";
purchaseOrderTransactionType:
| "Edit"
| "Favorite"
diff --git a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql
index a52a21d831..379d688c45 100644
--- a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql
+++ b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql
@@ -69,7 +69,6 @@ CREATE TABLE "supplierType" (
CREATE TABLE "supplier" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"name" TEXT NOT NULL,
- "description" TEXT,
"supplierTypeId" TEXT,
"supplierStatusId" TEXT,
"taxId" TEXT,
@@ -152,7 +151,6 @@ CREATE TABLE "customerType" (
CREATE TABLE "customer" (
"id" TEXT NOT NULL DEFAULT uuid_generate_v4(),
"name" TEXT NOT NULL,
- "description" TEXT,
"customerTypeId" TEXT,
"customerStatusId" TEXT,
"taxId" TEXT,
diff --git a/packages/carbon-database/supabase/migrations/20230123212853_search.sql b/packages/carbon-database/supabase/migrations/20230123212853_search.sql
index e2b6504f5c..d74fc40126 100644
--- a/packages/carbon-database/supabase/migrations/20230123212853_search.sql
+++ b/packages/carbon-database/supabase/migrations/20230123212853_search.sql
@@ -124,29 +124,18 @@ CREATE POLICY "Employees with sales_view can search for customers and sales orde
-- AND entity = 'Sales Order'
-- AND (get_my_claim('role'::text)) = '"customer"'::jsonb
-- AND uuid IN (
--- SELECT "customerId" FROM "salesOrder" WHERE "customerId" IN (
--- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
--- )
--- )
+-- SELECT id FROM "salesOrder" WHERE "customerId" IN (
+-- SELECT "customerId" FROM "salesOrder" WHERE "customerId" IN (
+-- SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
-- )
CREATE POLICY "Employees with purchasing_view can search for suppliers and purchase orders" ON "search"
FOR SELECT
USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND entity IN ('Supplier', 'Purchase Order') AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
--- TODO: suppliers should be able to search for their purchase orders
--- CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
--- FOR SELECT
--- USING (
--- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
--- AND entity = 'Purchase Order'
--- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
--- AND uuid IN (
--- SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
--- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
--- )
--- )
--- )
CREATE POLICY "Employees with resources_view can search for resources" ON "search"
FOR SELECT
diff --git a/packages/carbon-database/supabase/migrations/20230224035103_shifts.sql b/packages/carbon-database/supabase/migrations/20230224035103_shifts.sql
index 0feda08d77..3544adb5aa 100644
--- a/packages/carbon-database/supabase/migrations/20230224035103_shifts.sql
+++ b/packages/carbon-database/supabase/migrations/20230224035103_shifts.sql
@@ -1,6 +1,12 @@
CREATE TABLE "location" (
"id" TEXT NOT NULL DEFAULT xid(),
"name" TEXT NOT NULL,
+ "addressLine1" TEXT NOT NULL,
+ "addressLine2" TEXT,
+ "city" TEXT NOT NULL,
+ "state" TEXT NOT NULL,
+ "postalCode" TEXT NOT NULL,
+ "country" TEXT,
"timezone" TEXT NOT NULL,
"latitude" NUMERIC,
"longitude" NUMERIC,
diff --git a/packages/carbon-database/supabase/migrations/20230319224154_partners.sql b/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
index c3f598bc98..fa5b2156ec 100644
--- a/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
+++ b/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
@@ -25,7 +25,7 @@ CREATE TABLE "partnerAbility" (
CONSTRAINT "partnerAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
);
-CREATE VIEW "partners_query" AS
+CREATE VIEW "partners_view" AS
SELECT
p.id AS "supplierLocationId",
p."active",
diff --git a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
index 10f056210f..4e0b0adbc3 100644
--- a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
+++ b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
@@ -87,7 +87,7 @@ CREATE POLICY "Employees with resources_delete can delete contractorAbilities" O
);
-CREATE VIEW "contractors_query" AS
+CREATE VIEW "contractors_view" AS
SELECT
p.id AS "supplierContactId",
p."active",
diff --git a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
index 57e964f7cf..e2ef9b55d7 100644
--- a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql
@@ -343,12 +343,96 @@ CREATE POLICY "Employees with parts_update can update part sale prices" ON "part
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+CREATE TABLE "partSupplier" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "partId" TEXT NOT NULL,
+ "supplierId" TEXT NOT NULL,
+ "supplierPartId" TEXT,
+ "supplierUnitOfMeasureCode" TEXT,
+ "minimumOrderQuantity" INTEGER DEFAULT 1,
+ "conversionFactor" NUMERIC(15,5) NOT NULL DEFAULT 1,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "partSupplier_id_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "partSupplier_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,
+ CONSTRAINT "partSupplier_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE CASCADE,
+ CONSTRAINT "partSupplier_part_supplier_unique" UNIQUE ("partId", "supplierId"),
+ CONSTRAINT "partSupplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "partSupplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE INDEX "partSupplier_partId_index" ON "partSupplier"("partId");
+
+ALTER TABLE "partSupplier" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with part_view can view part suppliers" ON "partSupplier"
+ FOR SELECT
+ USING (
+ 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 suppliers" ON "partSupplier"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('parts_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Employees with parts_create can create part suppliers" ON "partSupplier"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Employees with parts_delete can delete part suppliers" ON "partSupplier"
+ FOR DELETE
+ USING (
+ coalesce(get_my_claim('parts_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+CREATE POLICY "Suppliers with parts_view can view their own part suppliers" ON "partSupplier"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('parts_view')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Suppliers with parts_update can update their own part suppliers" ON "partSupplier"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('parts_update')::boolean,false)
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Suppliers with parts_create can create part suppliers" ON "partSupplier"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('parts_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
CREATE TABLE "partReplenishment" (
"partId" TEXT NOT NULL,
- "supplierId" TEXT,
- "supplierPartNumber" TEXT,
+ "preferredSupplierId" TEXT,
"purchasingLeadTime" INTEGER NOT NULL DEFAULT 0,
"purchasingUnitOfMeasureCode" TEXT,
+ "conversionFactor" NUMERIC(15,5) NOT NULL DEFAULT 1,
"purchasingBlocked" BOOLEAN NOT NULL DEFAULT false,
"manufacturingPolicy" "partManufacturingPolicy" NOT NULL DEFAULT 'Make to Stock',
"manufacturingLeadTime" INTEGER NOT NULL DEFAULT 0,
@@ -362,14 +446,14 @@ CREATE TABLE "partReplenishment" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,
- CONSTRAINT "partReplenishment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,
- CONSTRAINT "partReplenishment_purchaseUnitOfMeasureId_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,
+ CONSTRAINT "partReplenishment_preferredSupplierId_fkey" FOREIGN KEY ("preferredSupplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,
+ CONSTRAINT "partReplenishment_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,
CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
CREATE INDEX "partReplenishment_partId_index" ON "partReplenishment" ("partId");
-CREATE INDEX "partReplenishment_supplierId_index" ON "partReplenishment" ("supplierId");
+CREATE INDEX "partReplenishment_preferredSupplierId_index" ON "partReplenishment" ("preferredSupplierId");
ALTER TABLE "partReplenishment" ENABLE ROW LEVEL SECURITY;
@@ -387,6 +471,7 @@ CREATE POLICY "Employees with parts_update can update part costs" ON "partReplen
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
+
CREATE POLICY "Suppliers with parts_view can view parts they created or supply" ON "part"
FOR SELECT
USING (
@@ -396,7 +481,7 @@ CREATE POLICY "Suppliers with parts_view can view parts they created or supply"
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -420,7 +505,7 @@ CREATE POLICY "Suppliers with parts_update can update parts that they created or
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -437,7 +522,7 @@ CREATE POLICY "Suppliers with parts_delete can delete parts that they created or
"createdBy" = auth.uid()::text
OR (
id IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -452,7 +537,7 @@ CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "pa
AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
AND (
"partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -466,7 +551,7 @@ CREATE POLICY "Suppliers with parts_update can update parts costs that they supp
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
AND (
"partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
)
)
@@ -479,8 +564,10 @@ CREATE POLICY "Suppliers with parts_view can view part replenishments they suppl
coalesce(get_my_claim('parts_view')::boolean, false) = true
AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
AND (
- "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ "partId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
)
)
);
@@ -491,9 +578,11 @@ CREATE POLICY "Suppliers with parts_update can update parts replenishments that
coalesce(get_my_claim('parts_update')::boolean, false) = true
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
AND (
- "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
+ "partId" IN (
+ SELECT "partId" FROM "partSupplier" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
)
);
@@ -627,30 +716,30 @@ CREATE POLICY "Employees with parts_update can update part planning" ON "partInv
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
- FOR SELECT
- USING (
- coalesce(get_my_claim('parts_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
- AND (
- "partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
-
-CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
- FOR UPDATE
- USING (
- coalesce(get_my_claim('parts_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- AND (
- "partId" IN (
- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
- )
- )
- )
- );
\ No newline at end of file
+-- CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"
+-- FOR SELECT
+-- USING (
+-- coalesce(get_my_claim('parts_view')::boolean, false) = true
+-- AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+-- AND (
+-- "partId" IN (
+-- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+-- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
+-- );
+
+-- CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"
+-- FOR UPDATE
+-- USING (
+-- coalesce(get_my_claim('parts_update')::boolean, false) = true
+-- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+-- AND (
+-- "partId" IN (
+-- SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (
+-- SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+-- )
+-- )
+-- )
+-- );
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
index 24275a7357..aff0084df8 100644
--- a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql
@@ -65,6 +65,22 @@ CREATE TABLE "shippingMethod" (
CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");
+CREATE TABLE "shippingTerm" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "shippingTerm_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "shippingTerm_name_key" UNIQUE ("name"),
+ CONSTRAINT "shippingTerm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
+ CONSTRAINT "shippingTerm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
+
+
CREATE TYPE "purchaseOrderType" AS ENUM (
'Draft',
'Purchase',
@@ -86,27 +102,10 @@ CREATE TABLE "purchaseOrder" (
"type" "purchaseOrderType" NOT NULL,
"status" "purchaseOrderApprovalStatus" NOT NULL,
"orderDate" DATE NOT NULL DEFAULT CURRENT_DATE,
- "orderDueDate" DATE,
- "receivedDate" DATE,
- "orderSubTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderTax" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderDiscount" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderShipping" NUMERIC(10,5) NOT NULL DEFAULT 0,
- "orderTotal" NUMERIC(10,5) NOT NULL DEFAULT 0,
"notes" TEXT,
"supplierId" TEXT NOT NULL,
"supplierContactId" TEXT,
"supplierReference" TEXT,
- "invoiceSupplierId" TEXT,
- "invoiceSupplierLocationId" TEXT,
- "invoiceSupplierContactId" TEXT,
- "paymentTermId" TEXT,
- "shippingMethodId" TEXT,
- "currencyCode" TEXT NOT NULL,
- -- "approvalRequestDate" DATE,
- -- "approvalDecisionDate" DATE,
- -- "approvalDecisionUserId" TEXT,
- -- "approvalDecisionNotes" TEXT,
"closed" BOOLEAN NOT NULL DEFAULT FALSE,
"closedAt" DATE,
"closedBy" TEXT,
@@ -119,13 +118,6 @@ CREATE TABLE "purchaseOrder" (
CONSTRAINT "purchaseOrder_purchaseOrderId_key" UNIQUE ("purchaseOrderId"),
CONSTRAINT "purchaseOrder_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_supplierContactId_fkey" FOREIGN KEY ("supplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrder_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE,
- -- CONSTRAINT "purchaseOrder_approvalDecisionUserId_fkey" FOREIGN KEY ("approvalDecisionUserId") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_closedBy_fkey" FOREIGN KEY ("closedBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,
CONSTRAINT "purchaseOrder_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
@@ -134,10 +126,124 @@ 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_invoiceSupplierId_idx" ON "purchaseOrder" ("invoiceSupplierId");
-CREATE INDEX "purchaseOrder_invoiceSupplierLocationId_idx" ON "purchaseOrder" ("invoiceSupplierLocationId");
-CREATE INDEX "purchaseOrder_invoiceSupplierContactId_idx" ON "purchaseOrder" ("invoiceSupplierContactId");
--- CREATE INDEX "purchaseOrder_approvalDecisionUserId_idx" ON "purchaseOrder" ("approvalDecisionUserId");
+
+CREATE TYPE "purchaseOrderLineType" AS ENUM (
+ 'Comment',
+ 'G/L Account',
+ 'Part',
+ 'Fixed Asset'
+);
+
+CREATE TABLE "purchaseOrderLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "purchaseOrderId" TEXT NOT NULL,
+ "purchaseOrderLineType" "purchaseOrderLineType" NOT NULL,
+ "partId" TEXT,
+ "accountNumber" TEXT,
+ "assetId" TEXT,
+ "description" TEXT,
+ "purchaseQuantity" NUMERIC(9,2) DEFAULT 0,
+ "unitPrice" NUMERIC(9,2),
+ "unitOfMeasureCode" TEXT,
+ "shelfId" TEXT,
+ "setupPrice" NUMERIC(9,2),
+ "receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "invoiceComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrderLineType_number"
+ CHECK (
+ (
+ "purchaseOrderLineType" = 'Comment' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NULL AND
+ "description" IS NOT NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'G/L Account' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NOT NULL AND
+ "assetId" IS NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'Part' AND
+ "partId" IS NOT NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NULL
+ )
+ OR (
+ "purchaseOrderLineType" = 'Fixed Asset' AND
+ "partId" IS NULL AND
+ "accountNumber" IS NULL AND
+ "assetId" IS NOT NULL
+ )
+ ),
+
+ CONSTRAINT "purchaseOrderLine_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderLine_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE,
+ -- TODO: Add assetId foreign key
+ CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE 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
+);
+
+CREATE TABLE "purchaseOrderPayment" (
+ "id" TEXT NOT NULL,
+ "invoiceSupplierId" TEXT,
+ "invoiceSupplierLocationId" TEXT,
+ "invoiceSupplierContactId" TEXT,
+ "paymentTermId" TEXT,
+ "paymentComplete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "currencyCode" TEXT NOT NULL DEFAULT 'USD',
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "purchaseOrderPayment_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderPayment_id_fkey" FOREIGN KEY ("id") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierId_fkey" FOREIGN KEY ("invoiceSupplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierLocationId_fkey" FOREIGN KEY ("invoiceSupplierLocationId") REFERENCES "supplierLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_invoiceSupplierContactId_fkey" FOREIGN KEY ("invoiceSupplierContactId") REFERENCES "supplierContact" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_paymentTermId_fkey" FOREIGN KEY ("paymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderPayment_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE
+);
+
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierId_idx" ON "purchaseOrderPayment" ("invoiceSupplierId");
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierLocationId_idx" ON "purchaseOrderPayment" ("invoiceSupplierLocationId");
+CREATE INDEX "purchaseOrderPayment_invoiceSupplierContactId_idx" ON "purchaseOrderPayment" ("invoiceSupplierContactId");
+
+CREATE TABLE "purchaseOrderDelivery" (
+ "id" TEXT NOT NULL,
+ "locationId" TEXT,
+ "shippingMethodId" TEXT,
+ "shippingTermId" TEXT,
+ "receiptRequestedDate" DATE,
+ "receiptPromisedDate" DATE,
+ "deliveryDate" DATE,
+ "notes" TEXT,
+ "trackingNumber" TEXT,
+ "dropShipment" BOOLEAN NOT NULL DEFAULT FALSE,
+ "customerId" TEXT,
+ "customerLocationId" TEXT,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "purchaseOrderDelivery_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "purchaseOrderDelivery_id_fkey" FOREIGN KEY ("id") REFERENCES "purchaseOrder" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_shippingMethodId_fkey" FOREIGN KEY ("shippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_shippingTermId_fkey" FOREIGN KEY ("shippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "purchaseOrderDelivery_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE
+);
CREATE TYPE "purchaseOrderTransactionType" AS ENUM (
'Edit',
@@ -199,8 +305,16 @@ CREATE VIEW "purchase_order_view" AS
p."status",
p."type",
p."orderDate",
- p."orderDueDate",
+ p."notes",
+ p."supplierId",
+ p."supplierContactId",
+ p."supplierReference",
p."createdBy",
+ pd."receiptRequestedDate",
+ pd."receiptPromisedDate",
+ pd."dropShipment",
+ pol."lineCount",
+ l."name" AS "locationName",
s."name" AS "supplierName",
u."avatarUrl" AS "createdByAvatar",
u."fullName" AS "createdByFullName",
@@ -215,8 +329,26 @@ CREATE VIEW "purchase_order_view" AS
u3."fullName" AS "closedByFullName",
EXISTS(SELECT 1 FROM "purchaseOrderFavorite" pf WHERE pf."purchaseOrderId" = p.id AND pf."userId" = auth.uid()::text) AS favorite
FROM "purchaseOrder" p
+ LEFT JOIN "purchaseOrderDelivery" pd ON pd."id" = p."id"
+ LEFT JOIN (
+ SELECT "purchaseOrderId", COUNT(*) AS "lineCount"
+ FROM "purchaseOrderLine"
+ GROUP BY "purchaseOrderId"
+ ) pol ON pol."purchaseOrderId" = p."id"
+ LEFT JOIN "location" l ON l."id" = pd."locationId"
LEFT JOIN "supplier" s ON s."id" = p."supplierId"
LEFT JOIN "user" u ON u."id" = p."createdBy"
LEFT JOIN "user" u2 ON u2."id" = p."updatedBy"
LEFT JOIN "user" u3 ON u3."id" = p."closedBy";
+ALTER TABLE "supplier"
+ ADD COLUMN "defaultCurrencyCode" TEXT,
+ ADD COLUMN "defaultPaymentTermId" TEXT,
+ ADD COLUMN "defaultShippingMethodId" TEXT,
+ ADD COLUMN "defaultShippingTermId" TEXT;
+
+ALTER TABLE "supplier"
+ ADD CONSTRAINT "supplier_defaultPaymentTermId_fkey" FOREIGN KEY ("defaultPaymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "supplier_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "supplier_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
+
diff --git a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
index 6a08670886..88e9610133 100644
--- a/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
+++ b/packages/carbon-database/supabase/migrations/20230525025310_sequences.sql
@@ -10,12 +10,12 @@ CREATE TABLE "sequence" (
"updatedBy" TEXT,
CONSTRAINT "sequence_pkey" PRIMARY KEY ("table"),
- CONSTRAINT "sequence_next_check" CHECK ("next" >= 1),
+ CONSTRAINT "sequence_next_check" CHECK ("next" >= 0),
CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
CONSTRAINT "sequence_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
-VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 1, 5, 1);
+VALUES ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 5, 1);
diff --git a/packages/carbon-database/supabase/migrations/20230629113514_purchasing-files.sql b/packages/carbon-database/supabase/migrations/20230629113514_purchasing-files.sql
new file mode 100644
index 0000000000..ab8f2b7755
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230629113514_purchasing-files.sql
@@ -0,0 +1,92 @@
+INSERT INTO storage.buckets (id, name, public)
+VALUES
+ ('purchasing-internal', 'purchasing-internal', false),
+ ('purchasing-external', 'purchasing-external', false);
+
+-- Internal purchasing documents
+
+CREATE POLICY "Internal purchasing documents view requires purchasing_view" ON storage.objects
+FOR SELECT USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents insert requires purchasing_create" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents update requires purchasing_update" ON storage.objects
+FOR UPDATE USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+CREATE POLICY "Internal purchasing documents delete requires purchasing_delete" ON storage.objects
+FOR DELETE USING (
+ bucket_id = 'purchasing-internal'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+);
+
+-- External purchasing documents
+
+CREATE POLICY "External purchasing documents view requires purchasing_view" ON storage.objects
+FOR SELECT USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents insert requires purchasing_view" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents update requires purchasing_update" ON storage.objects
+FOR UPDATE USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
+
+CREATE POLICY "External purchasing documents delete requires purchasing_delete" ON storage.objects
+FOR DELETE USING (
+ bucket_id = 'purchasing-external'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('purchasing_delete')::boolean, false) = true
+ AND (
+ (get_my_claim('role'::text)) = '"employee"'::jsonb OR
+ (
+ (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ )
+ )
+);
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql b/packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql
new file mode 100644
index 0000000000..8428052f46
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230702105831_view-rls.sql
@@ -0,0 +1,6 @@
+-- TODO: after Postgres 15, we can use security_invoker = on
+-- ALTER VIEW "contractors_view" SET (security_invoker = on);
+-- ALTER VIEW "partners_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_labels_view" SET (security_invoker = on);
+-- ALTER VIEW "documents_view" SET (security_invoker = on);
+-- ALTER VIEW "purchase_order_view" SET (security_invoker = on);
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
new file mode 100644
index 0000000000..26d219474c
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230702114301_purchasing-rls.sql
@@ -0,0 +1,84 @@
+ALTER TABLE "purchaseOrder" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purchaseOrder"
+ FOR SELECT
+ USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_view can their own organization" ON "purchaseOrder"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_create can create purchase orders" ON "purchaseOrder"
+ FOR INSERT
+ WITH CHECK (coalesce(get_my_claim('purchasing_create')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+
+CREATE POLICY "Employees with purchasing_update can update purchase orders" ON "purchaseOrder"
+ FOR UPDATE
+ USING (coalesce(get_my_claim('purchasing_update')::boolean,false) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+CREATE POLICY "Suppliers with purchasing_update can their own purchase orders" ON "purchaseOrder"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('purchasing_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ );
+
+CREATE POLICY "Employees with purchasing_delete can delete purchase orders" ON "purchaseOrder"
+ FOR DELETE
+ USING (coalesce(get_my_claim('purchasing_delete')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+
+-- Search
+
+CREATE FUNCTION public.create_purchase_order_search_result()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public.search(name, entity, uuid, link)
+ VALUES (new."purchaseOrderId", 'Purchase Order', new.id, '/x/purchase-order/' || new.id);
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER create_purchase_order_search_result
+ AFTER INSERT on public."purchaseOrder"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_purchase_order_search_result();
+
+CREATE FUNCTION public.update_purchase_order_search_result()
+RETURNS TRIGGER AS $$
+BEGIN
+ IF (old."purchaseOrderId" <> new."purchaseOrderId") THEN
+ UPDATE public.search SET name = new."purchaseOrderId"
+ WHERE entity = 'Purchase Order' AND uuid = new.id;
+ END IF;
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER update_purchase_order_search_result
+ AFTER UPDATE on public.customer
+ FOR EACH ROW EXECUTE PROCEDURE public.update_purchase_order_search_result();
+
+
+CREATE POLICY "Suppliers with purchasing_view can search for their own purchase orders" ON "search"
+ FOR SELECT
+ USING (
+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb
+ AND entity = 'Purchase Order'
+ AND uuid IN (
+ SELECT id FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "purchaseOrder" WHERE "supplierId" IN (
+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ )
+ );
\ No newline at end of file
diff --git a/packages/carbon-react/src/Count/Count.tsx b/packages/carbon-react/src/Count/Count.tsx
new file mode 100644
index 0000000000..1e392b9ac3
--- /dev/null
+++ b/packages/carbon-react/src/Count/Count.tsx
@@ -0,0 +1,24 @@
+import { Box } from "@chakra-ui/react";
+import type { BoxProps } from "@chakra-ui/react";
+
+export interface CountProps extends BoxProps {
+ count: number;
+}
+
+const Count = ({ count, ...props }: CountProps) => {
+ const c = count > 99 ? "99+" : count;
+ return (
+ <Box
+ as="span"
+ bg="gray.700"
+ borderRadius="full"
+ fontSize="sm"
+ py={1}
+ px={2}
+ color="white"
+ {...props}
+ >{`${c}`}</Box>
+ );
+};
+
+export default Count;
diff --git a/packages/carbon-react/src/Count/index.ts b/packages/carbon-react/src/Count/index.ts
new file mode 100644
index 0000000000..8267d0cfbb
--- /dev/null
+++ b/packages/carbon-react/src/Count/index.ts
@@ -0,0 +1,3 @@
+import Count from "./Count";
+
+export default Count;
diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsx
index 70daaac9df..2e0f20ffaa 100644
--- a/packages/carbon-react/src/index.tsx
+++ b/packages/carbon-react/src/index.tsx
@@ -1,4 +1,5 @@
import Button from "./Button";
+import Count from "./Count";
import Dot from "./Dot";
import HTML from "./HTML";
import type { OptionBase, OptionProps, GroupBase } from "./Inputs";
@@ -35,6 +36,7 @@ export {
Button,
ClientOnly,
ContextMenu,
+ Count,
CreatableSelect,
DatePicker,
DateTimePicker,
diff --git a/www/pages/docs/core-concepts/fetching.mdx b/www/pages/docs/core-concepts/fetching.mdx
index 729c40206c..b781300a42 100644
--- a/www/pages/docs/core-concepts/fetching.mdx
+++ b/www/pages/docs/core-concepts/fetching.mdx
@@ -123,7 +123,7 @@ If a query becomes complex, the convention is to create a SQL view in the databa
>
<Tab>
```sql
-CREATE VIEW "partners_query" AS
+CREATE VIEW "partners_view" WITH (security_invoker=on) AS
SELECT
p.id AS "supplierLocationId",
p."active",
@@ -154,7 +154,7 @@ export async function getPartner(
partnerId: string
) {
return client
- .from("partners_query")
+ .from("partners_view")
.select("*")
.eq("supplierLocationId", partnerId)
.single();