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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Part and General Ledgers (#34)
Brad Barbin999dfba71f88
diff --git a/SCHEMA.md b/SCHEMA.mdindex 7a82aa6c6e..5c52e07a38 100644--- a/SCHEMA.md+++ b/SCHEMA.md@@ -1,6 +1,4 @@-# Carbon Database Schema--This file is generated by `scripts/generate-schema-md.ts` using the migrations in `packages/carbon-database/supabase/migrations`.+# Carbon Database Schema by `scripts/generate-schema-md.ts` using the migrations in `packages/carbon-database/supabase/migrations`.@@ -452,8 +450,8 @@ CREATE TABLE "userAttributeCategory" ("updatedBy" TEXT,CONSTRAINT "userAttributeCategory_pkey" PRIMARY KEY ("id"),- CONSTRAINT "userAttributeCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),- CONSTRAINT "userAttributeCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+ CONSTRAINT "userAttributeCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "userAttributeCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE);-- ALTER TABLE "userAttributeCategory" ENABLE ROW LEVEL SECURITY;@@ -550,8 +548,8 @@ CREATE TABLE "userAttribute" (CONSTRAINT "userAttribute_pkey" PRIMARY KEY ("id"),CONSTRAINT "userAttribute_userAttributeCategoryId_fkey" FOREIGN KEY ("userAttributeCategoryId") REFERENCES "userAttributeCategory"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "userAttribute_attributeDataTypeId_fkey" FOREIGN KEY ("attributeDataTypeId") REFERENCES "attributeDataType"("id") ON DELETE CASCADE ON UPDATE CASCADE,- CONSTRAINT "userAttribute_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),- CONSTRAINT "userAttribute_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+ CONSTRAINT "userAttribute_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "userAttribute_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE);@@ -756,8 +754,8 @@ CREATE TABLE "supplier" (CONSTRAINT "supplier_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_supplierStatusId_fkey" FOREIGN KEY ("supplierStatusId") REFERENCES "supplierStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,CONSTRAINT "supplier_name_unique" UNIQUE ("name"));@@ -2937,7 +2935,7 @@ CREATE VIEW "contractors_view" AS-## `chart-of-accounts`+## `accounts````sqlCREATE TABLE "currency" (@@ -2945,10 +2943,9 @@ CREATE TABLE "currency" ("name" TEXT NOT NULL,"code" TEXT NOT NULL,"symbol" TEXT,- "symbolPlacementBefore" BOOLEAN NOT NULL DEFAULT true,"exchangeRate" NUMERIC(10,4) NOT NULL DEFAULT 1.0000,- "currencyPrecision" INTEGER NOT NULL DEFAULT 2,"isBaseCurrency" BOOLEAN NOT NULL DEFAULT false,+ "active" BOOLEAN NOT NULL DEFAULT true,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT,@@ -2956,12 +2953,13 @@ CREATE TABLE "currency" (CONSTRAINT "currency_pkey" PRIMARY KEY ("id"),CONSTRAINT "currency_code_key" UNIQUE ("code"),+ CONSTRAINT "currency_exchangeRate_check" CHECK ("exchangeRate" > 0),CONSTRAINT "currency_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "currency_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "currency" ("name", "code", "symbol", "symbolPlacementBefore", "exchangeRate", "currencyPrecision", "isBaseCurrency", "createdBy")-VALUES ('US Dollar', 'USD', '$', true, 1.0000, 2, true, 'system');+INSERT INTO "currency" ("name", "code", "symbol", "exchangeRate", "isBaseCurrency", "createdBy")+VALUES ('US Dollar', 'USD', '$', 1.0000, true, 'system');CREATE INDEX "currency_code_index" ON "currency" ("code");@@ -3015,20 +3013,29 @@ CREATE TYPE "glAccountCategory" AS ENUM ('Other Expense');-CREATE TYPE "glAccountType" AS ENUM (+CREATE TYPE "glIncomeBalance" AS ENUM ('Balance Sheet','Income Statement');CREATE TYPE "glNormalBalance" AS ENUM ('Debit',- 'Credit'+ 'Credit',+ 'Both'+);++CREATE TYPE "glAccountType" AS ENUM (+ 'Posting',+ 'Heading',+ -- 'Total',+ 'Begin Total',+ 'End Total');CREATE TABLE "accountCategory" ("id" TEXT NOT NULL DEFAULT xid(),- "category" "glAccountCategory" NOT NULL,- "type" "glAccountType" NOT NULL,+ "category" TEXT NOT NULL,+ "incomeBalance" "glIncomeBalance" NOT NULL,"normalBalance" "glNormalBalance" NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),@@ -3036,12 +3043,12 @@ CREATE TABLE "accountCategory" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "accountCategory_pkey" PRIMARY KEY ("id"),- CONSTRAINT "accountCategory_category_type_key" UNIQUE ("category"),+ CONSTRAINT "accountCategory_unique_category" UNIQUE ("category"),CONSTRAINT "accountCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "accountCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "accountCategory" ("category", "type", "normalBalance", "createdBy")+INSERT INTO "accountCategory" ("category", "incomeBalance", "normalBalance", "createdBy")VALUES('Bank', 'Balance Sheet', 'Credit', 'system'),('Accounts Receivable', 'Balance Sheet', 'Credit', 'system'),@@ -3093,39 +3100,93 @@ CREATE POLICY "Employees with accounting_delete can delete account categories" OAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE TYPE "consolidatedRate" AS ENUM (+CREATE TYPE "glConsolidatedRate" AS ENUM ('Average','Current','Historical');+CREATE TABLE "accountSubcategory" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "accountCategoryId" TEXT NOT NULL,+ "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 "accountSubcategory_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "accountSubcategory_name_key" UNIQUE ("name"),+ CONSTRAINT "accountSubcategory_accountCategoryId_fkey" FOREIGN KEY ("accountCategoryId") REFERENCES "accountCategory"("id"),+ CONSTRAINT "accountSubcategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "accountSubcategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "accountSubcategory_accountCategoryId_idx" ON "accountSubcategory" ("accountCategoryId");++ALTER TABLE "accountSubcategory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view account subcategories" ON "accountSubcategory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert account subcategories" ON "accountSubcategory"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with accounting_update can update account subcategories" ON "accountSubcategory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('accounting_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with accounting_delete can delete account subcategories" ON "accountSubcategory"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "account" (+ "id" TEXT NOT NULL DEFAULT xid(),"number" TEXT NOT NULL,"name" TEXT NOT NULL,- "description" TEXT,+ "type" "glAccountType" NOT NULL,"accountCategoryId" TEXT,- "controlAccount" BOOLEAN NOT NULL DEFAULT false,- "cashAccount" BOOLEAN NOT NULL DEFAULT false,- "consolidatedRate" "consolidatedRate",- "currencyCode" TEXT,- "parentAccountNumber" TEXT,+ "accountSubcategoryId" TEXT,+ "incomeBalance" "glIncomeBalance" NOT NULL,+ "normalBalance" "glNormalBalance" NOT NULL,+ "consolidatedRate" "glConsolidatedRate",+ "directPosting" BOOLEAN NOT NULL DEFAULT false,"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 "account_pkey" PRIMARY KEY ("number"),+ CONSTRAINT "account_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "account_number_key" UNIQUE ("number"),CONSTRAINT "account_name_key" UNIQUE ("name"),CONSTRAINT "account_accountCategoryId_fkey" FOREIGN KEY ("accountCategoryId") REFERENCES "accountCategory"("id"),- CONSTRAINT "account_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL,- CONSTRAINT "account_parentAccountNumber_fkey" FOREIGN KEY ("parentAccountNumber") REFERENCES "account"("number"),CONSTRAINT "account_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "account_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "account" ("number", "name", "consolidatedRate", "currencyCode", "createdBy")-VALUES ('999999', 'Unassigned', 'Average', 'USD', 'system');+CREATE INDEX "account_number_idx" ON "account" ("number");+CREATE INDEX "account_type_idx" ON "account" ("type");+CREATE INDEX "account_incomeBalance_idx" ON "account" ("incomeBalance");+CREATE INDEX "account_accountCategoryId_idx" ON "account" ("accountCategoryId");+CREATE INDEX "account_accountSubcategoryId_idx" ON "account" ("accountSubcategoryId");+ALTER TABLE "account" ENABLE ROW LEVEL SECURITY;@@ -3163,6 +3224,42 @@ CREATE POLICY "Employees with accounting_delete can delete accounts" ON "accountcoalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb);++CREATE VIEW "account_categories_view" AS+ SELECT+ "id",+ "category",+ "incomeBalance",+ "normalBalance",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt",+ (SELECT count(*) FROM "accountSubcategory" WHERE "accountSubcategory"."accountCategoryId" = "accountCategory"."id" AND "accountSubcategory"."active" = true) AS "subCategoriesCount"+ FROM "accountCategory"+;++CREATE VIEW "accounts_view" AS+ SELECT+ "id",+ "number",+ "name",+ "type",+ "accountCategoryId",+ (SELECT "category" FROM "accountCategory" WHERE "accountCategory"."id" = "account"."accountCategoryId") AS "accountCategory",+ "accountSubcategoryId",+ (SELECT "name" FROM "accountSubcategory" WHERE "accountSubcategory"."id" = "account"."accountSubcategoryId") AS "accountSubCategory",+ "incomeBalance",+ "normalBalance",+ "consolidatedRate",+ "directPosting",+ "active",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt"+ FROM "account"+;```@@ -3189,13 +3286,13 @@ CREATE TABLE "partGroup" (CONSTRAINT "partGroup_pkey" PRIMARY KEY ("id"),CONSTRAINT "partGroup_name_key" UNIQUE ("name"),- CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldLaborAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldLaborAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldMaterialAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldMaterialAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldOverheadAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldOverheadAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldSubcontractorAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldSubcontractorAccountId") REFERENCES "account"("number") ON DELETE CASCADE,+ CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldLaborAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldLaborAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldMaterialAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldMaterialAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldOverheadAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldOverheadAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldSubcontractorAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldSubcontractorAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -3324,7 +3421,7 @@ CREATE TABLE "part" ("description" TEXT,"blocked" BOOLEAN NOT NULL DEFAULT false,"replenishmentSystem" "partReplenishmentSystem" NOT NULL,- "partGroupId" TEXT NOT NULL,+ "partGroupId" TEXT,"partType" "partType" NOT NULL,"manufacturerPartNumber" TEXT,"unitOfMeasureCode" TEXT NOT NULL,@@ -3339,7 +3436,7 @@ CREATE TABLE "part" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "part_pkey" PRIMARY KEY ("id"),- CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,+ CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL,CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),CONSTRAINT "part_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),@@ -3451,10 +3548,10 @@ CREATE TABLE "partCost" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partCost_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,- CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE,+ CONSTRAINT "partCost_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -3490,8 +3587,8 @@ CREATE TABLE "partUnitSalePrice" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partUnitSalePrice_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,- CONSTRAINT "partUnitSalePrice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL,+ CONSTRAINT "partUnitSalePrice_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partUnitSalePrice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "partUnitSalePrice_salesUnitOfMeasureId_fkey" FOREIGN KEY ("salesUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,CONSTRAINT "partUnitSalePrice_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partUnitSalePrice_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")@@ -3530,7 +3627,7 @@ CREATE TABLE "partSupplier" ("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_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE 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"),@@ -3617,9 +3714,9 @@ CREATE TABLE "partReplenishment" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,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_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -3758,9 +3855,32 @@ CREATE POLICY "Suppliers with parts_update can update parts replenishments that));+CREATE TABLE "warehouse" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "requiresPick" BOOLEAN NOT NULL DEFAULT false,+ "requiresPutAway" BOOLEAN NOT NULL DEFAULT false,+ "requiresBin" BOOLEAN NOT NULL DEFAULT false,+ "requiresReceive" BOOLEAN NOT NULL DEFAULT false,+ "requiresShipment" BOOLEAN NOT NULL DEFAULT false,+ "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 "warehouse_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "warehouse_name_key" UNIQUE ("name"),+ CONSTRAINT "warehouse_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id"),+ CONSTRAINT "warehouse_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "warehouse_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);+CREATE TABLE "shelf" ("id" TEXT NOT NULL,"locationId" TEXT,+ "warehouseId" TEXT,"active" BOOLEAN NOT NULL DEFAULT true,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),@@ -3769,11 +3889,13 @@ CREATE TABLE "shelf" (CONSTRAINT "shelf_pkey" PRIMARY KEY ("id"),CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,+ CONSTRAINT "shelf_warehouseId_fkey" FOREIGN KEY ("warehouseId") REFERENCES "warehouse"("id") ON DELETE CASCADE,CONSTRAINT "shelf_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "shelf_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));CREATE INDEX "shelf_locationId_index" ON "shelf" ("locationId");+CREATE INDEX "shelf_warehouseId_index" ON "shelf" ("warehouseId");ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;@@ -3828,7 +3950,7 @@ CREATE TABLE "partPlanning" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -3863,7 +3985,7 @@ CREATE TABLE "partInventory" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),- CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,CONSTRAINT "partInventory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partInventory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")@@ -4210,6 +4332,43 @@ VALUES('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),('Due on Receipt', 0, 'Net', 0, 0, 'system'),('Net EOM 10', 10, 'End of Month', 0, 0, 'system');++ALTER TABLE "paymentTerm" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true OR+ coalesce(get_my_claim('resources_view')::boolean, false) = true OR+ coalesce(get_my_claim('sales_view')::boolean, false) = true OR+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert payment terms" ON "paymentTerm"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with accounting_update can update payment terms" ON "paymentTerm"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('accounting_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with accounting_delete can delete payment terms" ON "paymentTerm"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );CREATE TYPE "shippingCarrier" AS ENUM (@@ -4234,13 +4393,49 @@ CREATE TABLE "shippingMethod" (CONSTRAINT "shippingMethod_pkey" PRIMARY KEY ("id"),CONSTRAINT "shippingMethod_name_key" UNIQUE ("name"),- CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE,+ CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "shippingMethod_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,CONSTRAINT "shippingMethod_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE);CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");++CREATE POLICY "Certain employees can view shipping methods" ON "shippingMethod"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('inventory_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true OR+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true OR+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with inventory_create can insert shipping methods" ON "shippingMethod"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('inventory_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with inventory_update can update shipping methods" ON "shippingMethod"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('inventory_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with inventory_delete can delete shipping methods" ON "shippingMethod"+ FOR DELETE+ USING (+ coalesce(get_my_claim('inventory_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "shippingTerm" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -4362,11 +4557,11 @@ CREATE TABLE "purchaseOrderLine" (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,+ CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,-- TODO: Add assetId foreign keyCONSTRAINT "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_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "purchaseOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,CONSTRAINT "purchaseOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE);@@ -4388,7 +4583,7 @@ CREATE TABLE "purchaseOrderPayment" (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+ CONSTRAINT "purchaseOrderPayment_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE ON UPDATE CASCADE);CREATE INDEX "purchaseOrderPayment_invoiceSupplierId_idx" ON "purchaseOrderPayment" ("invoiceSupplierId");@@ -4977,11 +5172,292 @@ CREATE VIEW "parts_view" AS-- 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 "accounts_view" SET (security_invoker = on);+-- ALTER VIEW "account_categories_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);-- ALTER VIEW "purchase_order_suppliers_view" SET (security_invoker = on);-- ALTER VIEW "suppliers_view" SET (security_invoker = on);-- ALTER VIEW "parts_view" SET (security_invoker = on);++```++++## `warehouses`++```sql++++-- inbound warehouse request+-- is created automatically when a source document is released+-- is automatically deleted when the inventory put away gets everything handled+-- has a type+-- has a source document number+++-- warehouse item journal+++-- purchase receipt+-- return receipt+-- transfer receipt++-- part ledger entry pur+-- records the quantity change++-- value entry+-- records the value change+-- has a posting date+-- has an item ledger entry type (e.g. purchase, return, transfer, etc)+-- has an entry type (e.g. direct cost, indirect cost, etc)+-- has an adjustment checkbox+-- has a document type (e.g. purchase receipt, purchase invoice, sales invoice, etc)+-- has a document number+-- has an entry number (serial)+-- has a cost amount actual+-- has a cost amount expected+-- has an actual cost posted to gl+-- has an expected cost posted to gl++-- value entry - gl entry relation+-- has a value entry+-- has a gl entry++-- gl entry+++-- warehouse entry+-- has an entry type (positive or negative)+-- has a part number+-- has a shelf+-- has a qty+++-- inventory put away+-- has a warehouse+-- has a source document (assembly order, purchase order, purchase return order, inbound transfer, outbound transfer, sales order return, etc)+-- has a posting date+++-- inventory put away lines+-- has a part number+-- has a description+-- has a shelf+-- has an order quantity+-- has a qty to handle+-- has a qty handled+-- has a calculated qty outstanding+-- has a uom and due date++++```++++## `ledgers`++```sql+CREATE TYPE "accountDocumentLedgerType" AS ENUM (+ 'Quote',+ 'Order',+ 'Invoice',+ 'Credit Memo',+ 'Blanket Order',+ 'Return Order'+);++CREATE TABLE "generalLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "accountNumber" TEXT NOT NULL,+ "description" TEXT,+ "amount" NUMERIC(19, 4) NOT NULL,+ "documentType" "accountDocumentLedgerType",+ "documentNumber" TEXT,+ "externalDocumentNumber" TEXT,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "generalLedger_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "generalLedger_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account"("number") ON UPDATE CASCADE ON DELETE SET NULL+);++CREATE INDEX "generalLedger_accountNumber_idx" ON "generalLedger" ("accountNumber");+CREATE INDEX "generalLedger_postingDate_idx" ON "generalLedger" ("postingDate");++ALTER TABLE "generalLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view general ledger entries" ON "generalLedger"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert general ledger entries" ON "generalLedger"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++-- delete and update are not availble for general ledger entries++CREATE TYPE "partLedgerType" AS ENUM (+ 'Purchase',+ 'Sale',+ 'Positive Adjmt.',+ 'Negative Adjmt.',+ 'Transfer',+ 'Consumption',+ 'Output',+ 'Assembly Consumption',+ 'Assembly Output'+);++CREATE TYPE "costLedgerType" AS ENUM (+ 'Direct Cost',+ 'Revaluation',+ 'Rounding',+ 'Indirect Cost',+ 'Variance',+ 'Total'+);++CREATE TYPE "partLedgerDocumentType" AS ENUM (+ 'Sales Shipment',+ 'Sales Invoice',+ 'Sales Return Receipt',+ 'Sales Credit Memo',+ 'Purchase Receipt',+ 'Purchase Invoice',+ 'Purchase Return Shipment',+ 'Purchase Credit Memo',+ 'Transfer Shipment',+ 'Transfer Receipt',+ 'Service Shipment',+ 'Service Invoice',+ 'Service Credit Memo',+ 'Posted Assembly',+ 'Inventory Receipt',+ 'Inventory Shipment',+ 'Direct Transfer'+);++CREATE TABLE "valueLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "partLedgerType" "partLedgerType" NOT NULL,+ "costLedgerType" "costLedgerType" NOT NULL,+ "adjustment" BOOLEAN NOT NULL DEFAULT false,+ "documentType" "partLedgerDocumentType",+ "documentNumber" TEXT,+ "costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "expectedCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "valueLedger_pkey" PRIMARY KEY ("id")+);++ALTER TABLE "valueLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view the value ledger" ON "valueLedger"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "valueLedgerAccountLedgerRelation" (+ "valueLedgerId" TEXT NOT NULL,+ "generalLedgerId" TEXT NOT NULL,++ CONSTRAINT "valueLedgerAccountLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),+ CONSTRAINT "valueLedgerAccountLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),+ CONSTRAINT "valueLedgerAccountLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")+);++ALTER TABLE "valueLedgerAccountLedgerRelation" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view the value ledger account relations" ON "valueLedgerAccountLedgerRelation"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "entryType" "partLedgerType" NOT NULL,+ "documentType" "partLedgerDocumentType",+ "documentNumber" TEXT,+ "partId" TEXT NOT NULL,+ "locationId" TEXT,+ "shelfId" TEXT,+ "quantity" NUMERIC(12, 4) NOT NULL,+ "invoicedQuantity" NUMERIC(12, 4) NOT NULL,+ "remainingQuantity" NUMERIC(12, 4) NOT NULL,+ "salesAmount" NUMERIC(12, 4) NOT NULL,+ "costAmount" NUMERIC(12, 4) NOT NULL,+ "open" BOOLEAN NOT NULL DEFAULT true,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "partLedger_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON UPDATE CASCADE ON DELETE CASCADE,+ CONSTRAINT "partLedger_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON UPDATE CASCADE ON DELETE SET NULL+);++ALTER TABLE "partLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++++CREATE OR REPLACE FUNCTION gl_transactions_by_account_number(+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),+ to_date DATE DEFAULT now()+)+RETURNS TABLE (+ "number" TEXT,+ "balance" NUMERIC(19, 4),+ "balanceAtDate" NUMERIC(19, 4),+ "netChange" NUMERIC(19, 4)+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public+AS $$+ BEGIN+ RETURN QUERY+ SELECT+ a."number",+ SUM(g."amount") AS "balance",+ SUM(CASE WHEN g."postingDate" <= to_date THEN g."amount" ELSE 0 END) AS "balanceAtDate",+ SUM(CASE WHEN g."postingDate" >= from_date AND g."postingDate" <= to_date THEN g."amount" ELSE 0 END) AS "netChange"+ FROM "account" a+ LEFT JOIN "generalLedger" g ON g."accountNumber" = a."number"+ GROUP BY a."number";+ END;+$$;+++```diff --git a/apps/carbon/app/components/Form/Account.tsx b/apps/carbon/app/components/Form/Account.tsxindex a0390473bc..6c917b1f67 100644--- a/apps/carbon/app/components/Form/Account.tsx+++ b/apps/carbon/app/components/Form/Account.tsx@@ -33,7 +33,7 @@ const Account = ({useFetcher<Awaited<ReturnType<typeof getAccountsList>>>();useEffect(() => {- accountFetcher.load("/api/accounting/accounts");+ accountFetcher.load("/api/accounting/accounts?type=Posting");// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -42,7 +42,7 @@ const Account = ({accountFetcher.data?.data? accountFetcher.data?.data.map((c) => ({value: c.number,- label: c.name,+ label: `${c.number} - ${c.name}`,})): [],[accountFetcher.data]diff --git a/apps/carbon/app/components/Form/AccountCategory.tsx b/apps/carbon/app/components/Form/AccountCategory.tsxnew file mode 100644index 0000000000..d2158e4e33--- /dev/null+++ b/apps/carbon/app/components/Form/AccountCategory.tsx@@ -0,0 +1,117 @@+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 { AccountCategory as AccountCategoryType } from "~/modules/accounting";+import type { getAccountCategoriesList } from "~/modules/accounting";+import { mapRowsToOptions } from "~/utils/form";+import type { SelectProps } from "./Select";++type AccountCategorySelectProps = Omit<SelectProps, "options" | "onChange"> & {+ onChange?: (accountCategory: AccountCategoryType | undefined) => void;+};++const AccountCategory = ({+ name,+ label = "Account Category",+ helperText,+ isLoading,+ isReadOnly,+ placeholder = "Select Account Category",+ onChange,+ ...props+}: AccountCategorySelectProps) => {+ const { getInputProps, error, defaultValue } = useField(name);+ const [value, setValue] = useControlField<string | undefined>(name);++ const accountCategoryFetcher =+ useFetcher<Awaited<ReturnType<typeof getAccountCategoriesList>>>();++ useEffect(() => {+ if (accountCategoryFetcher.type === "init") {+ accountCategoryFetcher.load("/api/accounting/categories");+ }+ }, [accountCategoryFetcher]);++ const options = useMemo(+ () =>+ mapRowsToOptions({+ data: accountCategoryFetcher.data?.data,+ value: "id",+ label: "category",+ }),+ [accountCategoryFetcher.data]+ );++ const handleChange = (selection: {+ value: string | number;+ label: string;+ }) => {+ const newValue = (selection.value as string) || undefined;+ setValue(newValue);++ if (onChange && typeof onChange === "function") {+ const categories = accountCategoryFetcher.data?.data;+ if (!categories) {+ onChange(undefined);+ return;+ }++ const category = categories.find(+ (category) => category.id === selection.value+ );++ onChange(category as AccountCategoryType | undefined);+ }+ };++ 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>+ );+};++AccountCategory.displayName = "AccountCategory";++export default AccountCategory;diff --git a/apps/carbon/app/components/Form/AccountSubcategory.tsx b/apps/carbon/app/components/Form/AccountSubcategory.tsxnew file mode 100644index 0000000000..fe82693ebe--- /dev/null+++ b/apps/carbon/app/components/Form/AccountSubcategory.tsx@@ -0,0 +1,115 @@+import { Select } from "@carbon/react";+import {+ FormControl,+ FormLabel,+ FormErrorMessage,+ FormHelperText,+} from "@chakra-ui/react";+import { useFetcher } from "@remix-run/react";+import { useEffect, useMemo } from "react";+import { useField, useControlField } from "remix-validated-form";+import type { AccountSubcategory as AccountSubcategoryType } from "~/modules/accounting";+import type { getAccountSubcategoriesByCategory } from "~/modules/accounting";+import { mapRowsToOptions } from "~/utils/form";++const AccountSubcategory = ({+ name,+ label = "Account Subcategory",+ accountCategoryId,+ helperText,+ isReadOnly = false,+ placeholder = "Select Account Subcategory",+ onChange,+}: {+ name: string;+ label?: string;+ accountCategoryId?: string;+ placeholder?: string;+ helperText?: string;+ isReadOnly?: boolean;+ onChange?: (newValue?: AccountSubcategoryType) => void;+}) => {+ const { error, getInputProps, defaultValue } = useField(name);++ const [accountSubcategory, setAccountSubcategory] = useControlField<{+ value: string | number;+ label: string;+ } | null>(name);++ const accountSubcategoriesFetcher =+ useFetcher<Awaited<ReturnType<typeof getAccountSubcategoriesByCategory>>>();++ useEffect(() => {+ if (accountCategoryId) {+ accountSubcategoriesFetcher.load(+ `/api/accounting/subcategories?accountCategoryId=${accountCategoryId}`+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [accountCategoryId]);++ const accountSubcategories = useMemo(+ () =>+ mapRowsToOptions({+ data: accountSubcategoriesFetcher.data?.data ?? [],+ value: "id",+ label: "name",+ }),+ [accountSubcategoriesFetcher.data]+ );++ useEffect(() => {+ // if the initial value is in the options, set it, otherwise set to null+ if (accountSubcategories) {+ setAccountSubcategory(+ accountSubcategories.find((s) => s.value === defaultValue) ?? null+ );++ if (onChange) {+ const subcategory = accountSubcategoriesFetcher.data?.data?.find(+ (c) => c.id === defaultValue+ );++ onChange(subcategory);+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [accountSubcategories, defaultValue]);++ const handleChange = (newValue?: { label: string; value: string }) => {+ setAccountSubcategory(newValue ?? null);+ if (onChange) {+ const subcategory = accountSubcategoriesFetcher.data?.data?.find(+ (c) => c.id === newValue?.value+ );++ onChange(subcategory);+ }+ };++ return (+ <FormControl isInvalid={!!error}>+ <FormLabel htmlFor={name}>{label}</FormLabel>+ <Select+ {...getInputProps({+ // @ts-ignore+ id: name,+ })}+ placeholder={placeholder}+ options={accountSubcategories}+ value={accountSubcategory}+ onChange={handleChange}+ // @ts-ignore+ isReadOnly={isReadOnly}+ w="full"+ />+ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}+ </FormControl>+ );+};++export default AccountSubcategory;diff --git a/apps/carbon/app/components/Form/Boolean.tsx b/apps/carbon/app/components/Form/Boolean.tsxindex 2f353a552f..4a079610d1 100644--- a/apps/carbon/app/components/Form/Boolean.tsx+++ b/apps/carbon/app/components/Form/Boolean.tsx@@ -4,6 +4,7 @@ import { HStack } from "@chakra-ui/react";import {FormControl,FormErrorMessage,+ FormHelperText,FormLabel,Text,chakra,@@ -17,12 +18,13 @@ import { useControlField, useField } from "remix-validated-form";type FormBooleanProps = Omit<SwitchProps, "onChange"> & {name: string;label?: string;+ helperText?: string;description?: string;onChange?: (value: boolean) => void;};const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(- ({ name, label, description, onChange, ...props }, ref) => {+ ({ name, label, description, helperText, onChange, ...props }, ref) => {const { getInputProps, error } = useField(name);const [value, setValue] = useControlField<boolean>(name);@@ -100,8 +102,11 @@ const Boolean = forwardRef<HTMLInputElement, FormBooleanProps>(</HStack></chakra.label></HStack>-- {error && <FormErrorMessage>{error}</FormErrorMessage>}+ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}</FormControl>);}diff --git a/apps/carbon/app/components/Form/SelectControlled.tsx b/apps/carbon/app/components/Form/SelectControlled.tsxnew file mode 100644index 0000000000..835611d0d4--- /dev/null+++ b/apps/carbon/app/components/Form/SelectControlled.tsx@@ -0,0 +1,91 @@+import { Select } from "@carbon/react";+import {+ FormControl,+ FormErrorMessage,+ FormHelperText,+ FormLabel,+} from "@chakra-ui/react";+import { useEffect } from "react";+import { useControlField, useField } from "remix-validated-form";++export type SelectControlledProps = {+ name: string;+ label?: string;+ options: { value: string | number; label: string }[];+ helperText?: string;+ isReadOnly?: boolean;+ isLoading?: boolean;+ placeholder?: string;+ value: string | undefined;+ onChange: (newValue: string | number | undefined) => void;+};++const SelectControlled = ({+ name,+ label,+ options,+ helperText,+ isLoading,+ isReadOnly,+ placeholder,+ value,+ onChange,+ ...props+}: SelectControlledProps) => {+ const { getInputProps, error } = useField(name);+ const [controlValue, setControlValue] = useControlField(name);++ useEffect(() => {+ setControlValue(value);+ }, [setControlValue, value]);++ const handleChange = (+ selection: { value: string | number; label: string } | undefined+ ) => {+ setControlValue(selection?.value || undefined);+ if (onChange && typeof onChange === "function") {+ onChange(selection?.value);+ }+ };++ return (+ <FormControl isInvalid={!!error}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ {options.length > 0 ? (+ <Select+ {...getInputProps({+ // @ts-ignore+ id: name,+ })}+ {...props}+ // @ts-ignore+ isReadOnly={isReadOnly}+ isLoading={isLoading}+ options={options}+ placeholder={placeholder}+ // @ts-ignore+ w="full"+ value={options.find((option) => option.value === controlValue)}+ onChange={handleChange}+ />+ ) : (+ <Select+ isLoading={isLoading}+ options={[]}+ // @ts-ignore+ w="full"+ />+ )}++ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}+ </FormControl>+ );+};++SelectControlled.displayName = "SelectControlled";++export default SelectControlled;diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.tsindex dfc476b309..7c887d297d 100644--- a/apps/carbon/app/components/Form/index.ts+++ b/apps/carbon/app/components/Form/index.ts@@ -1,6 +1,8 @@import Abilities from "./Abilities";import Ability from "./Ability";import Account from "./Account";+import AccountCategory from "./AccountCategory";+import AccountSubcategory from "./AccountSubcategory";import Array from "./Array";import Boolean from "./Boolean";import Color from "./Color";@@ -24,6 +26,7 @@ import Phone from "./Phone";import Radios from "./Radios";import RichText from "./RichText";import Select from "./Select";+import SelectControlled from "./SelectControlled";import Slider from "./Slider";import Submit from "./Submit";import Supplier from "./Supplier";@@ -39,6 +42,8 @@ export {Abilities,Ability,Account,+ AccountCategory,+ AccountSubcategory,Array,Boolean,Color,@@ -62,6 +67,7 @@ export {Radios,RichText,Select,+ SelectControlled,Slider,Submit,Supplier,diff --git a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsxindex 6311e4ff52..858ed844ac 100644--- a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx+++ b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx@@ -9,8 +9,8 @@ import {BsShieldLock,} from "react-icons/bs";import { CgProfile } from "react-icons/cg";-import { GoSettings } from "react-icons/go";import { HiOutlineCube, HiOutlineDocumentDuplicate } from "react-icons/hi";+import { LuSettings2 } from "react-icons/lu";import { TbPigMoney } from "react-icons/tb";import { usePermissions } from "~/hooks";@@ -94,7 +94,7 @@ export function useSidebar() {permission: "settings",name: "Settings",to: "/x/settings",- icon: <GoSettings />,+ icon: <LuSettings2 />,},{name: "My Account",diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsxindex a3f345e0da..5f6aa30ab5 100644--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx@@ -47,11 +47,41 @@ export default function useBreadcrumbs(): Route[] {name: "Accounting",to: match.pathname,});+ case "routes/x+/accounting+/charts":+ return acc.concat({+ name: "Chart of Acounts",+ to: match.pathname,+ });+ case "routes/x+/accounting+/categories":+ return acc.concat({+ name: "Categories",+ to: match.pathname,+ });+ case "routes/x+/accounting+/currencies":+ return acc.concat({+ name: "Currencies",+ to: match.pathname,+ });+ case "routes/x+/accounting+/payment-terms":+ return acc.concat({+ name: "Payment Terms",+ to: match.pathname,+ });case "routes/x+/documents+/_layout":return acc.concat({name: "Documents",to: match.pathname,});+ case "routes/x+/inventory+/_layout":+ return acc.concat({+ name: "Inventory",+ to: match.pathname,+ });+ case "routes/x+/inventory+/shipping-methods":+ return acc.concat({+ name: "Shipping Methods",+ to: match.pathname,+ });case "routes/x+/parts+/index":return acc.concat({name: "Parts",diff --git a/apps/carbon/app/components/Search/Search/Search.tsx b/apps/carbon/app/components/Search/Search/Search.tsxindex 6e116edec4..7505d96bbf 100644--- a/apps/carbon/app/components/Search/Search/Search.tsx+++ b/apps/carbon/app/components/Search/Search/Search.tsx@@ -179,7 +179,7 @@ const SearchModal = ({}}><ModalOverlay />- <ModalContent>+ <ModalContent borderRadius="lg"><ModalBody p={0}><InputGroup size="lg"><InputLeftElement@@ -202,7 +202,7 @@ const SearchModal = ({<Boxbg="white"- borderBottomRadius="lg"+ borderRadius="lg"boxShadow="lg"maxH="66vh"overflowY="scroll"diff --git a/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx b/apps/carbon/app/components/Table/components/Pagination/Pagination.tsxindex 111f20cbdd..4c4777f66d 100644--- a/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx+++ b/apps/carbon/app/components/Table/components/Pagination/Pagination.tsx@@ -53,25 +53,23 @@ const Pagination = (props: PaginationProps) => {w="full"zIndex={1}>- <HStack spacing={2}>- <Menu>- <MenuButton as={Button} variant="ghost">- {pageSize} {pageSizeLabel}- </MenuButton>- <MenuList fontSize="sm" boxShadow="xl" minW={48}>- {pageSizes.map((size) => (- <MenuItem- key={`${size}`}- onClick={() => {- setPageSize(size);- }}- >- {size} {pageSizeLabel}- </MenuItem>- ))}- </MenuList>- </Menu>- </HStack>+ <Menu>+ <MenuButton as={Button} variant="ghost">+ {pageSize} {pageSizeLabel}+ </MenuButton>+ <MenuList fontSize="sm" boxShadow="xl" minW={48}>+ {pageSizes.map((size) => (+ <MenuItem+ key={`${size}`}+ onClick={() => {+ setPageSize(size);+ }}+ >+ {size} {pageSizeLabel}+ </MenuItem>+ ))}+ </MenuList>+ </Menu><HStack spacing={2}><PaginationButtons {...props} /></HStack>diff --git a/apps/carbon/app/lib/bullmq/bullmq.server.ts b/apps/carbon/app/lib/bullmq/bullmq.server.tsindex a6b62f2352..3b0a2010f9 100644--- a/apps/carbon/app/lib/bullmq/bullmq.server.ts+++ b/apps/carbon/app/lib/bullmq/bullmq.server.ts@@ -24,7 +24,6 @@ export const Queue = <Payload>(name: string,handler: Processor<Payload>): BullQueue<Payload> => {- // if (isVercel()) return mockQueue as any;if (registeredQueues[name]) {return registeredQueues[name].queue;}diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsxnew file mode 100644index 0000000000..67ef0e3008--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx@@ -0,0 +1,180 @@+import {+ Badge,+ Button,+ ButtonGroup,+ IconButton,+ MenuItem,+ useDisclosure,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo, useState } from "react";+import { BiAddToQueue } from "react-icons/bi";+import { BsPencilSquare, BsListUl, BsPlus } from "react-icons/bs";+import { IoMdTrash } from "react-icons/io";+import { Table } from "~/components";+import { ConfirmDelete } from "~/components/Modals";+import { usePermissions, useUrlParams } from "~/hooks";+import type { AccountCategory } from "~/modules/accounting";++type AccountCategoriesTableProps = {+ data: AccountCategory[];+ count: number;+};++const AccountCategoriesTable = memo(+ ({ data, count }: AccountCategoriesTableProps) => {+ const navigate = useNavigate();+ const [params] = useUrlParams();+ const permissions = usePermissions();+ const deleteModal = useDisclosure();+ const [selectedCategory, setSelectedCategory] = useState<+ AccountCategory | undefined+ >();++ const onDelete = (data: AccountCategory) => {+ setSelectedCategory(data);+ deleteModal.onOpen();+ };++ const onDeleteCancel = () => {+ setSelectedCategory(undefined);+ deleteModal.onClose();+ };++ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {+ return [+ {+ accessorKey: "category",+ header: "Category",+ cell: (item) => item.getValue(),+ },+ {+ header: "Income/Balance",+ accessorKey: "incomeBalance",+ cell: (item) => item.getValue(),+ },+ {+ header: "Debit/Credit",+ accessorKey: "normalBalance",+ cell: (item) => {+ const isDebit = item.getValue<string>() === "Debit";+ const isCredit = item.getValue<string>() === "Credit";+ return (+ <Badge+ size="sm"+ variant="outline"+ colorScheme={isDebit ? "green" : isCredit ? "red" : "gray"}+ >+ {item.getValue<string>()}+ </Badge>+ );+ },+ },++ {+ header: "Subcategories",+ cell: ({ row }) => (+ <ButtonGroup size="sm" isAttached variant="outline">+ <Button+ onClick={() => {+ navigate(+ `/x/accounting/categories/list/${+ row.original.id+ }?${params?.toString()}`+ );+ }}+ >+ {row.original.subCategoriesCount ?? 0} Subcategories+ </Button>+ <IconButton+ aria-label="Add subcategory"+ icon={<BsPlus />}+ onClick={() => {+ navigate(+ `/x/accounting/categories/list/${+ row.original.id+ }/new?${params?.toString()}`+ );+ }}+ />+ </ButtonGroup>+ ),+ },+ ];+ }, [navigate, params]);++ const renderContextMenu = useCallback(+ (row: typeof data[number]) => {+ return (+ <>+ <MenuItem+ icon={<BiAddToQueue />}+ onClick={() => {+ navigate(+ `/x/accounting/categories/list/${+ row.id+ }/new?${params?.toString()}`+ );+ }}+ >+ New Subcategory+ </MenuItem>+ <MenuItem+ icon={<BsListUl />}+ onClick={() => {+ navigate(+ `/x/accounting/categories/list/${+ row.id+ }?${params?.toString()}`+ );+ }}+ >+ View Subcategories+ </MenuItem>+ <MenuItem+ icon={<BsPencilSquare />}+ onClick={() => {+ navigate(`/x/accounting/categories/${row.id}`);+ }}+ >+ Edit Account Category+ </MenuItem>+ <MenuItem+ isDisabled={!permissions.can("delete", "users")}+ icon={<IoMdTrash />}+ onClick={() => onDelete(row)}+ >+ Delete Account Category+ </MenuItem>+ </>+ );+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [navigate, params, permissions]+ );++ return (+ <>+ <Table<AccountCategory>+ data={data}+ columns={columns}+ count={count ?? 0}+ renderContextMenu={renderContextMenu}+ />++ <ConfirmDelete+ action={`/x/accounting/categories/delete/${selectedCategory?.id}`}+ name={selectedCategory?.category ?? ""}+ text={`Are you sure you want to deactivate the ${selectedCategory?.category} account category?`}+ isOpen={deleteModal.isOpen}+ onCancel={onDeleteCancel}+ onSubmit={onDeleteCancel}+ />+ </>+ );+ }+);++AccountCategoriesTable.displayName = "AccountCategoriesTable";+export default AccountCategoriesTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/index.tsnew file mode 100644index 0000000000..0e087d263b--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTable/index.ts@@ -0,0 +1,3 @@+import AccountCategoriesTable from "./AccountCategoriesTable";++export default AccountCategoriesTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsxnew file mode 100644index 0000000000..4ac1f8467f--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx@@ -0,0 +1,88 @@+import { Select, useColor } from "@carbon/react";+import { Button, HStack } from "@chakra-ui/react";+import { Link } from "@remix-run/react";+import { IoMdAdd } from "react-icons/io";+import { DebouncedInput } from "~/components/Search";+import { usePermissions, useUrlParams } from "~/hooks";+import { incomeBalanceTypes, normalBalanceTypes } from "~/modules/accounting";++const AttributeCategoriesTableFilters = () => {+ const permissions = usePermissions();+ const [params, setParams] = useUrlParams();+ const borderColor = useColor("gray.200");++ return (+ <HStack+ px={4}+ py={3}+ justifyContent="space-between"+ borderBottomColor={borderColor}+ borderBottomStyle="solid"+ borderBottomWidth={1}+ w="full"+ >+ <HStack spacing={2}>+ <DebouncedInput+ param="name"+ size="sm"+ minW={180}+ placeholder="Filter by name"+ />+ <Select+ // @ts-ignore+ size="sm"+ minW={180}+ placeholder="Income Balance"+ value={incomeBalanceTypes+ .map((incomeBalance) => ({+ value: incomeBalance,+ label: incomeBalance,+ }))+ .filter((type) => type.value === params.get("incomeBalance"))}+ isClearable+ options={incomeBalanceTypes.map((incomeBalance) => ({+ value: incomeBalance,+ label: incomeBalance,+ }))}+ onChange={(selected) => {+ setParams({ incomeBalance: selected?.value });+ }}+ />+ <Select+ // @ts-ignore+ size="sm"+ minW={180}+ placeholder="Normal Balance"+ value={normalBalanceTypes+ .map((normalBalance) => ({+ value: normalBalance,+ label: normalBalance,+ }))+ .filter((type) => type.value === params.get("normalBalance"))}+ isClearable+ options={normalBalanceTypes.map((normalBalance) => ({+ value: normalBalance,+ label: normalBalance,+ }))}+ onChange={(selected) => {+ setParams({ normalBalance: selected?.value });+ }}+ />+ </HStack>+ <HStack spacing={2}>+ {permissions.can("update", "resources") && (+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Account Category+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default AttributeCategoriesTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/index.tsnew file mode 100644index 0000000000..ecbe6c620a--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoriesTableFilters/index.ts@@ -0,0 +1,3 @@+import AccountCategoriesTableFilters from "./AccountCategoriesTableFilters";++export default AccountCategoriesTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/AccountCategoryDetail.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/AccountCategoryDetail.tsxnew file mode 100644index 0000000000..569e445b75--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/AccountCategoryDetail.tsx@@ -0,0 +1,135 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ IconButton,+ List,+ ListItem,+ Tag,+ TagLabel,+ Text,+ VStack,+ useDisclosure,+} from "@chakra-ui/react";+import { Link } from "@remix-run/react";+import { useState } from "react";+import { BsPencilSquare } from "react-icons/bs";+import { IoMdTrash } from "react-icons/io";+import { ConfirmDelete } from "~/components/Modals";++import { useUrlParams } from "~/hooks";+import type { AccountCategory, AccountSubcategory } from "~/modules/accounting";++type AccountCategoryDetailProps = {+ accountCategory: AccountCategory;+ accountSubcategories: AccountSubcategory[];+ onClose: () => void;+};++const AccountCategoryDetail = ({+ accountCategory,+ accountSubcategories,+ onClose,+}: AccountCategoryDetailProps) => {+ const [params] = useUrlParams();++ const deleteModal = useDisclosure();+ const [selectedAccountSubcategory, setSelectedAccountSubcategory] =+ useState<AccountSubcategory | null>(null);++ const onDelete = (data?: AccountSubcategory) => {+ if (!data) return;+ setSelectedAccountSubcategory(data);+ deleteModal.onOpen();+ };++ const onDeleteCancel = () => {+ setSelectedAccountSubcategory(null);+ deleteModal.onClose();+ };++ return (+ <>+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ <VStack spacing={2} w="full" alignItems="start">+ <HStack justifyContent="space-between" w="full" pr={8}>+ <span>{accountCategory.category}</span>+ <Tag+ borderRadius="full"+ variant="outline"+ colorScheme={+ accountCategory.incomeBalance === "Income Statement"+ ? "green"+ : "gray"+ }+ >+ <TagLabel>{accountCategory.incomeBalance}</TagLabel>+ </Tag>+ </HStack>+ <Text fontSize="sm" fontWeight="normal" color="gray.500">+ A list of subcategories in the {accountCategory.category}{" "}+ category.+ </Text>+ </VStack>+ </DrawerHeader>+ <DrawerBody>+ <List spacing={2}>+ {accountSubcategories.map((subcategory) => {+ return (+ <ListItem key={subcategory.id} rounded="lg">+ <HStack>+ <Text flexGrow={1}>{subcategory.name}</Text>++ <IconButton+ as={Link}+ to={subcategory.id}+ aria-label="Edit"+ icon={<BsPencilSquare />}+ variant="outline"+ />+ <IconButton+ aria-label="Delete"+ icon={<IoMdTrash />}+ variant="outline"+ onClick={() => onDelete(subcategory)}+ />+ </HStack>+ </ListItem>+ );+ })}+ </List>+ </DrawerBody>+ <DrawerFooter>+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ size="md"+ >+ New Subcategory+ </Button>+ </DrawerFooter>+ </DrawerContent>+ </Drawer>+ <ConfirmDelete+ isOpen={deleteModal.isOpen}+ action={`/x/accounting/subcategory/delete/${selectedAccountSubcategory?.id}`}+ name={selectedAccountSubcategory?.name ?? ""}+ text={`Are you sure you want to deactivate the ${selectedAccountSubcategory?.name} subcategory?`}+ onCancel={onDeleteCancel}+ />+ </>+ );+};++export default AccountCategoryDetail;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/index.tsnew file mode 100644index 0000000000..4fdadeda2c--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryDetail/index.ts@@ -0,0 +1,3 @@+import AccountCategoryDetail from "./AccountCategoryDetail";++export default AccountCategoryDetail;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsxnew file mode 100644index 0000000000..adaf7f140e--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx@@ -0,0 +1,98 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Input, Hidden, Submit, Select } from "~/components/Form";+import { usePermissions } from "~/hooks";+import {+ accountCategoryValidator,+ incomeBalanceTypes,+ normalBalanceTypes,+} from "~/modules/accounting";+import type { TypeOfValidator } from "~/types/validators";++type AccountCategoryFormProps = {+ initialValues: TypeOfValidator<typeof accountCategoryValidator>;+ onClose: () => void;+};++const AccountCategoryForm = ({+ initialValues,+ onClose,+}: AccountCategoryFormProps) => {+ const permissions = usePermissions();++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "accounting")+ : !permissions.can("create", "accounting");++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={accountCategoryValidator}+ method="post"+ action={+ isEditing+ ? `/x/accounting/categories/${initialValues.id}`+ : "/x/accounting/categories/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ {isEditing ? "Edit" : "New"} Account Category+ </DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <VStack spacing={2} alignItems="start">+ <Input name="category" label="Category" />+ <Select+ name="incomeBalance"+ label="Income Balance"+ options={incomeBalanceTypes.map((incomeBalance) => ({+ value: incomeBalance,+ label: incomeBalance,+ }))}+ />+ <Select+ name="normalBalance"+ label="Normal Balance"+ options={normalBalanceTypes.map((normalBalance) => ({+ value: normalBalance,+ label: normalBalance,+ }))}+ />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack spacing={2}>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button+ size="md"+ colorScheme="gray"+ variant="solid"+ onClick={onClose}+ >+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default AccountCategoryForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/index.tsnew file mode 100644index 0000000000..0ae0b2d464--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountCategoryForm/index.ts@@ -0,0 +1,3 @@+import AccountCategoryForm from "./AccountCategoryForm";++export default AccountCategoryForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/AccountSubcategoryForm.tsx b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/AccountSubcategoryForm.tsxnew file mode 100644index 0000000000..f15b263e0c--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/AccountSubcategoryForm.tsx@@ -0,0 +1,98 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ FormControl,+ FormLabel,+ HStack,+ Input as ChakraInput,+ VStack,+} from "@chakra-ui/react";+import { useParams } from "@remix-run/react";+import { ValidatedForm } from "remix-validated-form";+import { Input, Hidden, Submit } from "~/components/Form";+import { usePermissions, useRouteData } from "~/hooks";+import type { AccountCategory } from "~/modules/accounting";+import { accountSubcategoryValidator } from "~/modules/accounting";+import type { TypeOfValidator } from "~/types/validators";++type AccountSubcategoryFormProps = {+ initialValues: TypeOfValidator<typeof accountSubcategoryValidator>;+ onClose: () => void;+};++const AccountSubcategoryForm = ({+ initialValues,+ onClose,+}: AccountSubcategoryFormProps) => {+ const params = useParams();+ const permissions = usePermissions();++ const { categoryId } = params;+ if (!categoryId) throw new Error("categoryId is not found");++ const routeData = useRouteData<{+ accountCategory: AccountCategory;+ }>(`/x/accounting/categories/list/${categoryId}`);++ const category = routeData?.accountCategory.category ?? "";++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "accounting")+ : !permissions.can("create", "accounting");++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={accountSubcategoryValidator}+ method="post"+ action={+ isEditing+ ? `/x/accounting/subcategory/${initialValues.id}`+ : "/x/accounting/subcategory/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ {isEditing ? "Edit" : "New"} Account Subcategory+ </DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <Hidden name="accountCategoryId" />+ <VStack spacing={2} alignItems="start">+ <FormControl>+ <FormLabel>Category</FormLabel>+ <ChakraInput value={category} isReadOnly />+ </FormControl>+ <Input name="name" label="Name" />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack spacing={2}>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button+ size="md"+ colorScheme="gray"+ variant="solid"+ onClick={onClose}+ >+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default AccountSubcategoryForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/index.tsnew file mode 100644index 0000000000..b4eb36a9c4--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/AccountSubcategoryForm/index.ts@@ -0,0 +1,3 @@+import AccountSubcategoryForm from "./AccountSubcategoryForm";++export default AccountSubcategoryForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/AccountCategories/index.ts b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/index.tsnew file mode 100644index 0000000000..90be7b48b0--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/AccountCategories/index.ts@@ -0,0 +1,13 @@+import AccountCategoriesTable from "./AccountCategoriesTable";+import AccountCategoriesTableFilters from "./AccountCategoriesTableFilters";+import AccountCategoryForm from "./AccountCategoryForm";+import AccountSubcategoryForm from "./AccountSubcategoryForm";+import AccountCategoryDetail from "./AccountCategoryDetail";++export {+ AccountCategoriesTable,+ AccountCategoriesTableFilters,+ AccountCategoryForm,+ AccountSubcategoryForm,+ AccountCategoryDetail,+};diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsxnew file mode 100644index 0000000000..1425af307d--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx@@ -0,0 +1,187 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ Grid,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import { useState } from "react";++import { ValidatedForm } from "remix-validated-form";+import {+ AccountCategory,+ AccountSubcategory,+ Boolean,+ Hidden,+ Input,+ Number,+ Select,+ SelectControlled,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import type {+ AccountCategory as AccountCategoryType,+ AccountIncomeBalance,+ AccountNormalBalance,+} from "~/modules/accounting";+import {+ accountTypes,+ accountValidator,+ consolidatedRateTypes,+ incomeBalanceTypes,+ normalBalanceTypes,+} from "~/modules/accounting";+import type { TypeOfValidator } from "~/types/validators";++type ChartOfAccountFormProps = {+ initialValues: TypeOfValidator<typeof accountValidator>;+};++const ChartOfAccountForm = ({ initialValues }: ChartOfAccountFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const [accountCategoryId, setAccountCategoryId] = useState<string>(+ initialValues.accountCategoryId ?? ""+ );+ const [incomeBalance, setIncomeBalance] = useState<+ "Balance Sheet" | "Income Statement"+ >(initialValues.incomeBalance);+ const [normalBalance, setNormalBalance] = useState<+ "Debit" | "Credit" | "Both"+ >(initialValues.normalBalance);++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "accounting")+ : !permissions.can("create", "accounting");++ const onAccountCategoryChange = (category?: AccountCategoryType) => {+ if (category) {+ setAccountCategoryId(category.id ?? "");+ setIncomeBalance(category.incomeBalance ?? "Income Statement");+ setNormalBalance(category.normalBalance ?? "Debit");+ }+ };++ return (+ <Drawer onClose={onClose} isOpen={true} size="full">+ <ValidatedForm+ validator={accountValidator}+ method="post"+ action={+ isEditing+ ? `/x/accounting/charts/${initialValues.id}`+ : "/x/accounting/charts/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ {isEditing+ ? `${initialValues.number} - ${initialValues.name}`+ : "New Account"}+ </DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />++ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack spacing={4} alignItems="start">+ <Number name="number" label="Number" />+ <Input name="name" label="Name" />+ <Select+ name="type"+ label="Type"+ options={accountTypes.map((accountType) => ({+ label: accountType,+ value: accountType,+ }))}+ />+ </VStack>+ <VStack spacing={4} alignItems="start">+ <AccountCategory+ name="accountCategoryId"+ onChange={onAccountCategoryChange}+ />+ <AccountSubcategory+ name="accountSubcategoryId"+ accountCategoryId={accountCategoryId}+ />+ <SelectControlled+ name="incomeBalance"+ label="Income/Balance"+ options={incomeBalanceTypes.map((incomeBalance) => ({+ label: incomeBalance,+ value: incomeBalance,+ }))}+ value={incomeBalance}+ onChange={(newValue) => {+ if (newValue)+ setIncomeBalance(newValue as AccountIncomeBalance);+ }}+ />+ </VStack>+ <VStack spacing={4} alignItems="start">+ <SelectControlled+ name="normalBalance"+ label="Normal Balance"+ options={normalBalanceTypes.map((normalBalance) => ({+ label: normalBalance,+ value: normalBalance,+ }))}+ value={normalBalance}+ onChange={(newValue) => {+ if (newValue)+ setNormalBalance(newValue as AccountNormalBalance);+ }}+ />+ <Select+ name="consolidatedRate"+ label="Consolidated Rate"+ options={consolidatedRateTypes.map(+ (consolidatedRateType) => ({+ label: consolidatedRateType,+ value: consolidatedRateType,+ })+ )}+ />+ <Boolean name="directPosting" label="Direct Posting" />+ </VStack>+ </Grid>+ </DrawerBody>+ <DrawerFooter>+ <HStack spacing={2}>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button+ size="md"+ colorScheme="gray"+ variant="solid"+ onClick={onClose}+ >+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default ChartOfAccountForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/index.ts b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/index.tsnew file mode 100644index 0000000000..4e0b9cefae--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountForm/index.ts@@ -0,0 +1,3 @@+import ChartOfAccountForm from "./ChartOfAccountForm";++export default ChartOfAccountForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsxnew file mode 100644index 0000000000..11b9ceac87--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/ChartOfAccountsTable.tsx@@ -0,0 +1,114 @@+import { DataTable, DataTableColumnHeader } from "@carbon/react";+import { Box, Checkbox, HStack, IconButton, Text } from "@chakra-ui/react";+import { Link } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useMemo } from "react";+import { MdMoreHoriz } from "react-icons/md";+import type { Chart } from "~/modules/accounting";++type ChartOfAccountsTableProps = {+ data: Chart[];+};++const ChartOfAccountsTable = memo(({ data }: ChartOfAccountsTableProps) => {+ const columns = useMemo<ColumnDef<Chart>[]>(() => {+ return [+ {+ accessorKey: "number",+ header: ({ column }) => (+ <DataTableColumnHeader column={column} title="No." />+ ),+ cell: ({ row }) => {+ const isPosting = row.original.type === "Posting";++ return (+ <HStack>+ <Text fontWeight={isPosting ? "normal" : "bold"}>+ {row.original.number}+ </Text>+ <Box position="relative" w={6} h={6}>+ <IconButton+ aria-label="Edit account"+ 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: "name",+ header: "Name",+ cell: ({ row }) => {+ const isPosting = row.original.type === "Posting";+ return (+ <Text+ fontWeight={isPosting ? "normal" : "bold"}+ pl={`calc(${0.75 * row.original.level}rem)`}+ >+ {row.original.name}+ </Text>+ );+ },+ },+ {+ accessorKey: "netChange",+ header: "Net Change",+ cell: ({ row }) => (row.original.netChange ?? 0).toFixed(2),+ },+ {+ accessorKey: "balanceAtDate",+ header: "Balance at Date",+ cell: ({ row }) => (row.original.balanceAtDate ?? 0).toFixed(2),+ },+ {+ accessorKey: "balance",+ header: "Balance",+ cell: ({ row }) => (row.original.balance ?? 0).toFixed(2),+ },+ {+ accessorKey: "incomeBalance",+ header: "Income/Balance",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "type",+ header: "Account Type",+ cell: (item) => item.getValue(),+ },+ {+ acessorKey: "totaling",+ header: "Totaling",+ cell: ({ row }) => row.original.totaling ?? "",+ },+ {+ accessorKey: "accountCategory",+ header: "Account Category",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "accountSubCategory",+ header: "Account Subcategory",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "directPosting",+ header: "Direct Posting",+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,+ },+ ];+ }, []);++ return <DataTable data={data} columns={columns} />;+});++ChartOfAccountsTable.displayName = "ChartOfAccountsTable";+export default ChartOfAccountsTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/index.ts b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/index.tsnew file mode 100644index 0000000000..9cfeb995cc--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTable/index.ts@@ -0,0 +1,3 @@+import ChartOfAccountsTable from "./ChartOfAccountsTable";++export default ChartOfAccountsTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/ChartOfAccountsTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/ChartOfAccountsTableFilters.tsxnew file mode 100644index 0000000000..4cbe2ef933--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/ChartOfAccountsTableFilters.tsx@@ -0,0 +1,128 @@+import { DatePicker, Select, useColor } from "@carbon/react";+import {+ Button,+ Grid,+ HStack,+ Popover,+ PopoverArrow,+ PopoverBody,+ PopoverContent,+ PopoverHeader,+ PopoverTrigger,+ Text,+} from "@chakra-ui/react";+import { parseDate } from "@internationalized/date";+import { Link } from "@remix-run/react";+import { IoMdAdd } from "react-icons/io";+import { MdCalendarMonth, MdClose } from "react-icons/md";+import { usePermissions, useUrlParams } from "~/hooks";+import { incomeBalanceTypes } from "~/modules/accounting/services";++const CurrenciesTableFilters = () => {+ const [params, setParams] = useUrlParams();+ const permissions = usePermissions();+ const borderColor = useColor("gray.200");++ const startDate = params.get("startDate");+ const endDate = params.get("endDate");++ const incomeBalanceOptions = incomeBalanceTypes.map((type) => ({+ label: type,+ value: type,+ }));++ return (+ <HStack+ px={4}+ py={3}+ justifyContent="space-between"+ borderBottomColor={borderColor}+ borderBottomStyle="solid"+ borderBottomWidth={1}+ w="full"+ >+ <HStack spacing={2}>+ <Select+ // @ts-ignore+ minW={200}+ placeholder="Income/Balance Sheet"+ options={incomeBalanceOptions}+ size="sm"+ isClearable+ onChange={(newValue) => setParams({ incomeBalance: newValue?.value })}+ />+ <Popover placement="bottom" closeOnBlur>+ <PopoverTrigger>+ <Button variant="solid" leftIcon={<MdCalendarMonth />}>+ Date Range+ </Button>+ </PopoverTrigger>+ <PopoverContent w={360} boxShadow="xl">+ <PopoverHeader>+ <Text fontSize="sm">Edit date range</Text>+ <Text fontSize="xs" color="gray.500">+ Select date range to filter net change and balance at date+ </Text>+ </PopoverHeader>+ <PopoverArrow />+ <PopoverBody maxH="50vh">+ <Grid+ gridTemplateColumns={"1fr 3fr"}+ gridRowGap={2}+ alignItems="center"+ >+ <Text fontSize="sm" color="gray.500">+ Start Date+ </Text>+ <DatePicker+ // @ts-ignore+ value={startDate ? parseDate(startDate) : null}+ onChange={(value) =>+ setParams({ startDate: value.toString() })+ }+ />+ <Text fontSize="sm" color="gray.500">+ End Date+ </Text>+ <DatePicker+ // @ts-ignore+ value={endDate ? parseDate(endDate) : null}+ onChange={(value) => setParams({ endDate: value.toString() })}+ />+ </Grid>+ </PopoverBody>+ </PopoverContent>+ </Popover>+ {[...params.entries()].length > 0 && (+ <Button+ size="sm"+ rightIcon={<MdClose />}+ onClick={() =>+ setParams({+ incomeBalance: undefined,+ startDate: undefined,+ endDate: undefined,+ })+ }+ >+ Reset+ </Button>+ )}+ </HStack>+ <HStack spacing={2}>+ {permissions.can("create", "accounting") && (+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Account+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default CurrenciesTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/index.ts b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/index.tsnew file mode 100644index 0000000000..4bcae33ff2--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters/index.ts@@ -0,0 +1,3 @@+import ChartOfAccountsTableFilters from "./ChartOfAccountsTableFilters";++export default ChartOfAccountsTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/index.ts b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/index.tsnew file mode 100644index 0000000000..5ec52081b5--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/ChartOfAccounts/index.ts@@ -0,0 +1,4 @@+import ChartOfAccountForm from "./ChartOfAccountForm";+import ChartOfAccountsTable from "./ChartOfAccountsTable";++export { ChartOfAccountForm, ChartOfAccountsTable };diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsxnew file mode 100644index 0000000000..642fb16fe9--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/CurrenciesTable.tsx@@ -0,0 +1,96 @@+import { Checkbox, MenuItem } from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo } from "react";+import { BsPencilSquare } from "react-icons/bs";+import { IoMdTrash } from "react-icons/io";+import { Table } from "~/components";+import { usePermissions, useUrlParams } from "~/hooks";+import type { Currency } from "~/modules/accounting";++type CurrenciesTableProps = {+ data: Currency[];+ count: number;+};++const CurrenciesTable = memo(({ data, count }: CurrenciesTableProps) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const permissions = usePermissions();++ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {+ return [+ {+ accessorKey: "name",+ header: "Name",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "code",+ header: "Code",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "symbol",+ header: "Symbol",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "exchangeRate",+ header: "Exchange Rate",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "isBaseCurrency",+ header: "Default Currency",+ cell: ({ row }) => (+ <Checkbox isChecked={row.original.isBaseCurrency} isReadOnly />+ ),+ },+ ];+ }, []);++ const renderContextMenu = useCallback(+ (row: typeof data[number]) => {+ return (+ <>+ <MenuItem+ isDisabled={!permissions.can("update", "accounting")}+ icon={<BsPencilSquare />}+ onClick={() => {+ navigate(+ `/x/accounting/currencies/${row.id}?${params.toString()}`+ );+ }}+ >+ Edit Currency+ </MenuItem>+ <MenuItem+ isDisabled={!permissions.can("delete", "accounting")}+ icon={<IoMdTrash />}+ onClick={() => {+ navigate(+ `/x/accounting/currencies/delete/${row.id}?${params.toString()}`+ );+ }}+ >+ Delete Currency+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions]+ );++ return (+ <Table<typeof data[number]>+ data={data}+ columns={columns}+ count={count}+ renderContextMenu={renderContextMenu}+ />+ );+});++CurrenciesTable.displayName = "CurrenciesTable";+export default CurrenciesTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/index.ts b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/index.tsnew file mode 100644index 0000000000..2a12fc59c0--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTable/index.ts@@ -0,0 +1,3 @@+import CurrenciesTable from "./CurrenciesTable";++export default CurrenciesTable;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsxnew file mode 100644index 0000000000..30a28df5a6--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/CurrenciesTableFilters.tsx@@ -0,0 +1,46 @@+import { useColor } from "@carbon/react";+import { Button, HStack } from "@chakra-ui/react";+import { Link } from "@remix-run/react";+import { IoMdAdd } from "react-icons/io";+import { DebouncedInput } from "~/components/Search";+import { usePermissions, useUrlParams } from "~/hooks";++const CurrenciesTableFilters = () => {+ const [params] = useUrlParams();+ const permissions = usePermissions();+ const borderColor = useColor("gray.200");+ return (+ <HStack+ px={4}+ py={3}+ justifyContent="space-between"+ borderBottomColor={borderColor}+ borderBottomStyle="solid"+ borderBottomWidth={1}+ w="full"+ >+ <HStack spacing={2}>+ <DebouncedInput+ param="name"+ size="sm"+ minW={180}+ placeholder="Filter by name"+ />+ </HStack>+ <HStack spacing={2}>+ {permissions.can("create", "accounting") && (+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Currency+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default CurrenciesTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/index.ts b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/index.tsnew file mode 100644index 0000000000..78ff070a32--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrenciesTableFilters/index.ts@@ -0,0 +1,3 @@+import CurrenciesTableFilters from "./CurrenciesTableFilters";++export default CurrenciesTableFilters;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/CurrencyForm.tsx b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/CurrencyForm.tsxnew file mode 100644index 0000000000..12b4eaae06--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/CurrencyForm.tsx@@ -0,0 +1,99 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import { useState } from "react";++import { ValidatedForm } from "remix-validated-form";+import { Boolean, Hidden, Input, Number, Submit } from "~/components/Form";+import { usePermissions, useRouteData } from "~/hooks";+import type { Currency } from "~/modules/accounting";+import { currencyValidator } from "~/modules/accounting";+import type { TypeOfValidator } from "~/types/validators";++type CurrencyFormProps = {+ initialValues: TypeOfValidator<typeof currencyValidator>;+};++const CurrencyForm = ({ initialValues }: CurrencyFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const routeData = useRouteData<{ baseCurrency: Currency }>("/x/accounting");+ const [name, setName] = useState(initialValues.name);++ const isBaseCurrency = routeData?.baseCurrency.id === initialValues.id;+ const exchnageRateHelperText = isBaseCurrency+ ? "This is the base currency. Exchange rate is always 1."+ : `One ${name} is equal to how many ${routeData?.baseCurrency.name}?`;++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "accounting")+ : !permissions.can("create", "accounting");+ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={currencyValidator}+ method="post"+ action={+ isEditing+ ? `/x/accounting/currencies/${initialValues.id}`+ : "/x/accounting/currencies/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>{isEditing ? "Edit" : "New"} Currency</DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <VStack spacing={4} alignItems="start">+ <Input+ name="name"+ label="Name"+ onChange={(e) => setName(e.target.value)}+ />+ <Input name="code" label="Code" />+ <Input name="symbol" label="Symbol" />+ <Number+ name="exchangeRate"+ label="Exchange Rate"+ isDisabled={isBaseCurrency}+ min={0}+ helperText={exchnageRateHelperText}+ />+ <Boolean name="isBaseCurrency" label="Base Currency" />+ </VStack>+ </DrawerBody>+ <DrawerFooter>+ <HStack spacing={2}>+ <Submit isDisabled={isDisabled}>Save</Submit>+ <Button+ size="md"+ colorScheme="gray"+ variant="solid"+ onClick={onClose}+ >+ Cancel+ </Button>+ </HStack>+ </DrawerFooter>+ </DrawerContent>+ </ValidatedForm>+ </Drawer>+ );+};++export default CurrencyForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/index.ts b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/index.tsnew file mode 100644index 0000000000..dcb693fca3--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/CurrencyForm/index.ts@@ -0,0 +1,3 @@+import CurrencyForm from "./CurrencyForm";++export default CurrencyForm;diff --git a/apps/carbon/app/modules/accounting/interfaces/Currencies/index.ts b/apps/carbon/app/modules/accounting/interfaces/Currencies/index.tsnew file mode 100644index 0000000000..fc5178a429--- /dev/null+++ b/apps/carbon/app/modules/accounting/interfaces/Currencies/index.ts@@ -0,0 +1,5 @@+import CurrencyForm from "./CurrencyForm";+import CurrenciesTable from "./CurrenciesTable";+import CurrenciesTableFilters from "./CurrenciesTableFilters";++export { CurrencyForm, CurrenciesTable, CurrenciesTableFilters };diff --git a/apps/carbon/app/modules/accounting/interfaces/index.ts b/apps/carbon/app/modules/accounting/interfaces/index.tsindex 40f4971e43..389a6af6ca 100644--- a/apps/carbon/app/modules/accounting/interfaces/index.ts+++ b/apps/carbon/app/modules/accounting/interfaces/index.ts@@ -1,4 +1,7 @@import useAccountingSidebar from "./useAccountingSidebar";export { useAccountingSidebar };+export * from "./AccountCategories";+export * from "./ChartOfAccounts";+export * from "./Currencies";export * from "./PaymentTerms";diff --git a/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx b/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsxindex 4ef8a30520..ad1539063c 100644--- a/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx+++ b/apps/carbon/app/modules/accounting/interfaces/useAccountingSidebar.tsx@@ -2,9 +2,29 @@ import { usePermissions } from "~/hooks";import type { AuthenticatedRouteGroup } from "~/types";const accountingRoutes: AuthenticatedRouteGroup[] = [+ {+ name: "Manage",+ routes: [+ {+ name: "Chart of Accounts",+ to: "/x/accounting/charts",+ role: "employee",+ },+ ],+ },{name: "Configure",routes: [+ {+ name: "Currencies",+ to: "/x/accounting/currencies",+ role: "employee",+ },+ {+ name: "G/L Categories",+ to: "/x/accounting/categories",+ role: "employee",+ },{name: "Payment Terms",to: "/x/accounting/payment-terms",diff --git a/apps/carbon/app/modules/accounting/services/accounting.form.ts b/apps/carbon/app/modules/accounting/services/accounting.form.tsindex bb6a6cd9fe..645b1e6bc6 100644--- a/apps/carbon/app/modules/accounting/services/accounting.form.ts+++ b/apps/carbon/app/modules/accounting/services/accounting.form.ts@@ -2,6 +2,184 @@ import { withZod } from "@remix-validated-form/with-zod";import { z } from "zod";import { zfd } from "zod-form-data";+export const accountDocumentLedgerType = [+ "Quote",+ "Order",+ "Invoice",+ "Credit Memo",+ "Blanket Order",+ "Return Order",+] as const;++export const accountTypes = [+ "Posting",+ "Heading",+ // "Total",+ "Begin Total",+ "End Total",+] as const;++export const consolidatedRateTypes = [+ "Average",+ "Current",+ "Historical",+] as const;++const costLedgerTypes = [+ "Direct Cost",+ "Revaluation",+ "Rounding",+ "Indirect Cost",+ "Variance",+ "Total",+] as const;++const partLedgerTypes = [+ "Purchase",+ "Sale",+ "Positive Adjmt.",+ "Negative Adjmt.",+ "Transfer",+ "Consumption",+ "Output",+ "Assembly Consumption",+ "Assembly Output",+] as const;++const partLedgerDocumentTypes = [+ "Sales Shipment",+ "Sales Invoice",+ "Sales Return Receipt",+ "Sales Credit Memo",+ "Purchase Receipt",+ "Purchase Invoice",+ "Purchase Return Shipment",+ "Purchase Credit Memo",+ "Transfer Shipment",+ "Transfer Receipt",+ "Service Shipment",+ "Service Invoice",+ "Service Credit Memo",+ "Posted Assembly",+ "Inventory Receipt",+ "Inventory Shipment",+ "Direct Transfer",+] as const;++export const incomeBalanceTypes = [+ "Balance Sheet",+ "Income Statement",+] as const;+export const normalBalanceTypes = ["Debit", "Credit", "Both"] as const;++export const accountValidator = withZod(+ z+ .object({+ id: zfd.text(z.string().optional()),+ number: z.string().min(1, { message: "Number is required" }),+ name: z.string().min(1, { message: "Name is required" }),+ type: z.enum(accountTypes, {+ errorMap: (issue, ctx) => ({+ message: "Type is required",+ }),+ }),+ accountCategoryId: zfd.text(z.string().optional()),+ accountSubcategoryId: zfd.text(z.string().optional()),+ incomeBalance: z.enum(incomeBalanceTypes, {+ errorMap: (issue, ctx) => ({+ message: "Income balance is required",+ }),+ }),+ normalBalance: z.enum(normalBalanceTypes, {+ errorMap: (issue, ctx) => ({+ message: "Normal balance is required",+ }),+ }),+ consolidatedRate: z.enum(consolidatedRateTypes),+ directPosting: zfd.checkbox(),+ })+ .refine(+ (data) => {+ if (data.type !== "Heading") {+ return !!data.accountCategoryId;+ }+ return true;+ },+ { message: "Account category is required", path: ["accountCategoryId"] }+ )+);++export const accountCategoryValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ category: z.string().min(1, { message: "Category is required" }),+ incomeBalance: z.enum(incomeBalanceTypes, {+ errorMap: (issue, ctx) => ({+ message: "Income balance is required",+ }),+ }),+ normalBalance: z.enum(normalBalanceTypes, {+ errorMap: (issue, ctx) => ({+ message: "Normal balance is required",+ }),+ }),+ })+);++export const accountLedgerValidator = withZod(+ z.object({+ postingDate: z.string().min(1, { message: "Posting date is required" }),+ accountNumber: z.string().min(1, { message: "Account is required" }),+ description: z.string().optional(),+ amount: z.number(),+ documentType: z.union([z.enum(accountDocumentLedgerType), z.undefined()]),+ documentNumber: z.string().optional(),+ externalDocumentNumber: z.string().optional(),+ })+);++export const accountSubcategoryValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+ accountCategoryId: z.string().min(20, { message: "Category is required" }),+ })+);++export const currencyValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }),+ code: z.string().min(1, { message: "Code is required" }),+ symbol: zfd.text(+ z+ .string()+ .max(1, { message: "Symbol can only be one character" })+ .optional()+ ),+ exchangeRate: zfd.numeric(),+ isBaseCurrency: zfd.checkbox(),+ })+);++export const partLedgerValidator = withZod(+ z.object({+ postingDate: z.string().min(1, { message: "Posting date is required" }),+ entryType: z.enum(partLedgerTypes),+ documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),+ documentNumber: z.string().optional(),+ partId: z.string().min(1, { message: "Part is required" }),+ locationId: z.string().optional(),+ shelfId: z.string().optional(),+ quantity: z.number(),+ invoicedQuantity: z.number(),+ remainingQuantity: z.number(),+ salesAmount: z.number(),+ costAmount: z.number(),+ open: z.boolean(),+ })+);+export const paymentTermValidator = withZod(z.object({id: zfd.text(z.string().optional()),@@ -33,3 +211,18 @@ export const paymentTermValidator = withZod(}),}));++export const valueLedgerValidator = withZod(+ z.object({+ postingDate: z.string(),+ partLedgerType: z.enum(partLedgerTypes),+ costLedgerType: z.enum(costLedgerTypes),+ adjustment: z.boolean(),+ documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),+ documentNumber: z.string().optional(),+ costAmountActual: z.number(),+ costAmountExpected: z.number(),+ actualCostPostedToGl: z.number(),+ expectedCostPostedToGl: z.number(),+ })+);diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.tsindex 1619316159..48e3b4043d 100644--- a/apps/carbon/app/modules/accounting/services/accounting.server.ts+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts@@ -1,10 +1,100 @@import type { Database } from "@carbon/database";+import { getDateNYearsAgo } from "@carbon/utils";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";+import type { Account, Transaction } from "../types";+import type {+ accountCategoryValidator,+ accountLedgerValidator,+ accountSubcategoryValidator,+ accountValidator,+ currencyValidator,+ partLedgerValidator,+ paymentTermValidator,+ valueLedgerValidator,+} from "./accounting.form";++type AccountWithTotals = Account & { level: number; totaling: string };++function addLevelsAndTotalsToAccounts(+ accounts: Account[]+): AccountWithTotals[] {+ let result: AccountWithTotals[] = [];+ let beginTotalAccounts: string[] = [];+ let endTotalAccounts: string[] = [];+ let hasHeading = false;++ accounts.forEach((account) => {+ if (account.type === "End Total") {+ endTotalAccounts.push(account.number);+ }++ let level =+ beginTotalAccounts.length -+ endTotalAccounts.length ++ (hasHeading ? 1 : 0);++ if (account.type === "Begin Total") {+ beginTotalAccounts.push(account.number);+ }++ if (account.type === "Heading") {+ level = 0;+ hasHeading = true;+ }++ let totaling = "";++ if (account.type === "End Total") {+ let startAccount = beginTotalAccounts.pop();+ let endAccount = endTotalAccounts.pop();++ totaling = `${startAccount}..${endAccount}`;+ }++ result.push({+ ...account,+ level,+ totaling,+ });+ });++ return result;+}++export async function deleteAccount(+ client: SupabaseClient<Database>,+ accountId: string+) {+ return client.from("account").delete().eq("id", accountId);+}++export async function deleteAccountCategory(+ client: SupabaseClient<Database>,+ accountSubcategoryId: string+) {+ return client.from("accountCategory").delete().eq("id", accountSubcategoryId);+}++export async function deleteAccountSubcategory(+ client: SupabaseClient<Database>,+ accountSubcategoryId: string+) {+ return client+ .from("accountSubcategory")+ .update({ active: false })+ .eq("id", accountSubcategoryId);+}++export async function deleteCurrency(+ client: SupabaseClient<Database>,+ currencyId: string+) {+ return client.from("currency").update({ active: false }).eq("id", currencyId);+}export async function deletePaymentTerm(client: SupabaseClient<Database>,@@ -16,12 +106,267 @@ export async function deletePaymentTerm(.eq("id", paymentTermId);}-export async function getAccountsList(client: SupabaseClient<Database>) {- return client+export async function getAccount(+ client: SupabaseClient<Database>,+ accountId: string+) {+ return client.from("account").select("*").eq("id", accountId).single();+}++export async function getAccounts(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ search: string | null;+ }+) {+ let query = client.from("account")- .select("number, name")- .eq("active", true)- .order("name", { ascending: true });+ .select("*", {+ count: "exact",+ })+ .eq("active", true);++ if (args.search) {+ query = query.ilike("name", `%${args.search}%`);+ }++ query = setGenericQueryFilters(query, args, "name");+ return query;+}++export async function getAccountsList(+ client: SupabaseClient<Database>,+ type: string | null+) {+ let query = client.from("account").select("number, name").eq("active", true);++ if (type) {+ query = query.eq("type", type);+ }++ query = query.order("name", { ascending: true });++ return query;+}++export async function getAccountCategories(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ name: string | null;+ normalBalance: string | null;+ incomeBalance: string | null;+ }+) {+ let query = client.from("account_categories_view").select("*", {+ count: "exact",+ });++ if (args.name) {+ query = query.ilike("category", `%${args.name}%`);+ }++ if (args.normalBalance) {+ query = query.eq("normalBalance", args.normalBalance);+ }++ if (args.incomeBalance) {+ query = query.eq("incomeBalance", args.incomeBalance);+ }++ query = setGenericQueryFilters(query, args, "category");+ return query;+}++export async function getAccountCategoriesList(+ client: SupabaseClient<Database>+) {+ return client+ .from("accountCategory")+ .select("*")+ .order("category", { ascending: true });+}++export async function getAccountCategory(+ client: SupabaseClient<Database>,+ accountCategoryId: string+) {+ return client+ .from("accountCategory")+ .select("*")+ .eq("id", accountCategoryId)+ .single();+}++export async function getAccountSubcategories(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ name: string | null;+ }+) {+ let query = client+ .from("accountSubcategory")+ .select("*", {+ count: "exact",+ })+ .eq("active", true);++ if (args.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ query = setGenericQueryFilters(query, args, "name");+ return query;+}++export async function getAccountSubcategoriesByCategory(+ client: SupabaseClient<Database>,+ accountCategoryId: string+) {+ return client+ .from("accountSubcategory")+ .select("*")+ .eq("accountCategoryId", accountCategoryId)+ .eq("active", true);+}++export async function getAccountSubcategory(+ client: SupabaseClient<Database>,+ accountSubcategoryId: string+) {+ return client+ .from("accountSubcategory")+ .select("*")+ .eq("id", accountSubcategoryId)+ .single();+}++function getAccountTotal(+ accounts: Account[],+ account: AccountWithTotals,+ type: "netChange" | "balance" | "balanceAtDate",+ transactionsByAccount: Record<string, Transaction>+) {+ if (!account.totaling)+ return transactionsByAccount[account.number][type] ?? 0;++ let total = 0;+ const [start, end] = account.totaling.split("..");+ if (!start || !end) throw new Error("Invalid totaling");++ accounts.forEach((account) => {+ if (account.number >= start && account.number <= end) {+ total += transactionsByAccount[account.number][type] ?? 0;+ }+ });++ return total;+}++export async function getBaseCurrency(client: SupabaseClient<Database>) {+ return client+ .from("currency")+ .select("*")+ .eq("isBaseCurrency", true)+ .single();+}++export async function getChartOfAccounts(+ client: SupabaseClient<Database>,+ args: Omit<GenericQueryFilters, "limit" | "offset"> & {+ name: string | null;+ incomeBalance: string | null;+ startDate: string | null;+ endDate: string | null;+ }+) {+ let accountsQuery = client+ .from("accounts_view")+ .select("*")+ .eq("active", true);++ if (args.incomeBalance) {+ accountsQuery = accountsQuery.eq("incomeBalance", args.incomeBalance);+ }++ accountsQuery = setGenericQueryFilters(accountsQuery, args, "number");++ let transactionsQuery = client.rpc("gl_transactions_by_account_number", {+ from_date:+ args.startDate ?? getDateNYearsAgo(50).toISOString().split("T")[0],+ to_date: args.endDate ?? new Date().toISOString().split("T")[0],+ });++ const [accountsResponse, transactionsResponse] = await Promise.all([+ accountsQuery,+ transactionsQuery,+ ]);++ if (transactionsResponse.error) return transactionsResponse;+ if (accountsResponse.error) return accountsResponse;++ const transactionsByAccount = (+ transactionsResponse.data as unknown as Transaction[]+ ).reduce<Record<string, Transaction>>((acc, transaction: Transaction) => {+ acc[transaction.number] = transaction;+ return acc;+ }, {});++ const accounts: Account[] = accountsResponse.data as Account[];++ return {+ data: addLevelsAndTotalsToAccounts(accounts).map((account) => ({+ ...account,+ netChange: getAccountTotal(+ accounts,+ account,+ "netChange",+ transactionsByAccount+ ),++ balance: getAccountTotal(+ accounts,+ account,+ "balance",+ transactionsByAccount+ ),++ balanceAtDate: getAccountTotal(+ accounts,+ account,+ "balanceAtDate",+ transactionsByAccount+ ),+ })),+ error: null,+ };+}++export async function getCurrency(+ client: SupabaseClient<Database>,+ currencyId: string+) {+ return client.from("currency").select("*").eq("id", currencyId).single();+}++export async function getCurrencies(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ name: string | null;+ }+) {+ let query = client+ .from("currency")+ .select("*", {+ count: "exact",+ })+ .eq("active", true);++ if (args.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ query = setGenericQueryFilters(query, args, "name");+ return query;}export async function getCurrenciesList(client: SupabaseClient<Database>) {@@ -71,6 +416,142 @@ export async function getPaymentTermsList(client: SupabaseClient<Database>) {.order("name", { ascending: true });}+export async function insertAccountEntries(+ client: SupabaseClient<Database>,+ accountEntries: TypeOfValidator<typeof accountLedgerValidator>[]+) {+ return client.from("accountLedger").insert(accountEntries).select("id");+}++export async function insertAccountLedger(+ client: SupabaseClient<Database>,+ accountEntry: TypeOfValidator<typeof accountLedgerValidator>+) {+ return client.from("accountLedger").insert([accountEntry]).select("id");+}++export async function insertPartEntries(+ client: SupabaseClient<Database>,+ partEntries: TypeOfValidator<typeof partLedgerValidator>[]+) {+ return client.from("partLedger").insert(partEntries).select("id");+}++export async function insertPartLedger(+ client: SupabaseClient<Database>,+ partEntry: TypeOfValidator<typeof partLedgerValidator>+) {+ return client.from("partLedger").insert([partEntry]).select("id");+}++export async function insertValueEntries(+ client: SupabaseClient<Database>,+ valueEntries: TypeOfValidator<typeof valueLedgerValidator>[]+) {+ return client.from("valueLedger").insert(valueEntries).select("id");+}++export async function insertValueLedger(+ client: SupabaseClient<Database>,+ valueEntry: TypeOfValidator<typeof valueLedgerValidator>+) {+ return client.from("valueLedger").insert([valueEntry]).select("id");+}++export async function upsertAccount(+ client: SupabaseClient<Database>,+ account:+ | (Omit<TypeOfValidator<typeof accountValidator>, "id"> & {+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof accountValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in account) {+ return client.from("account").insert([account]).select("id");+ }+ return client+ .from("account")+ .update(sanitize(account))+ .eq("id", account.id)+ .select("id");+}++export async function upsertAccountCategory(+ client: SupabaseClient<Database>,+ accountCategory:+ | (Omit<TypeOfValidator<typeof accountCategoryValidator>, "id"> & {+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof accountCategoryValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in accountCategory) {+ return client+ .from("accountCategory")+ .insert([accountCategory])+ .select("id");+ }+ return client+ .from("accountCategory")+ .update(sanitize(accountCategory))+ .eq("id", accountCategory.id)+ .select("id");+}++export async function upsertAccountSubcategory(+ client: SupabaseClient<Database>,+ accountSubcategory:+ | (Omit<TypeOfValidator<typeof accountSubcategoryValidator>, "id"> & {+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof accountSubcategoryValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if ("createdBy" in accountSubcategory) {+ return client+ .from("accountSubcategory")+ .insert([accountSubcategory])+ .select("id");+ }+ return client+ .from("accountSubcategory")+ .update(sanitize(accountSubcategory))+ .eq("id", accountSubcategory.id)+ .select("id");+}++export async function upsertCurrency(+ client: SupabaseClient<Database>,+ currency:+ | (Omit<TypeOfValidator<typeof currencyValidator>, "id"> & {+ createdBy: string;+ })+ | (Omit<TypeOfValidator<typeof currencyValidator>, "id"> & {+ id: string;+ updatedBy: string;+ })+) {+ if (currency.isBaseCurrency) {+ await client.from("currency").update({ isBaseCurrency: false });+ }++ if ("createdBy" in currency) {+ return client.from("currency").insert([currency]).select("id");+ }+ return client+ .from("currency")+ .update(sanitize(currency))+ .eq("id", currency.id)+ .select("id");+}+export async function upsertPaymentTerm(client: SupabaseClient<Database>,paymentTerm:diff --git a/apps/carbon/app/modules/accounting/types.ts b/apps/carbon/app/modules/accounting/types.tsindex 3ebebc68f4..0777c33b17 100644--- a/apps/carbon/app/modules/accounting/types.ts+++ b/apps/carbon/app/modules/accounting/types.ts@@ -1,5 +1,44 @@import type { Database } from "@carbon/database";-import type { getPaymentTerms } from "./services";+import type {+ getAccount,+ getAccountCategories,+ getAccountSubcategories,+ getCurrencies,+ getPaymentTerms,+} from "./services";++export type Account = NonNullable<+ Awaited<ReturnType<typeof getAccount>>["data"]+>;++export type AccountCategory = NonNullable<+ Awaited<ReturnType<typeof getAccountCategories>>["data"]+>[number];++export type AccountConsolidatedRate =+ Database["public"]["Enums"]["glConsolidatedRate"];++export type AccountSubcategory = NonNullable<+ Awaited<ReturnType<typeof getAccountSubcategories>>["data"]+>[number];++export type AccountIncomeBalance =+ Database["public"]["Enums"]["glIncomeBalance"];++export type AccountNormalBalance =+ Database["public"]["Enums"]["glNormalBalance"];++export type AccountType = Database["public"]["Enums"]["glAccountType"];++export type Chart = Account &+ Transaction & {+ level: number;+ totaling: string;+ };++export type Currency = NonNullable<+ Awaited<ReturnType<typeof getCurrencies>>["data"]+>[number];export type PaymentTermCalculationMethod =Database["public"]["Enums"]["paymentTermCalculationMethod"];@@ -7,3 +46,10 @@ export type PaymentTermCalculationMethod =export type PaymentTerm = NonNullable<Awaited<ReturnType<typeof getPaymentTerms>>["data"]>[number];++export type Transaction = {+ number: string;+ netChange: number;+ balanceAtDate: number;+ balance: number;+};diff --git a/apps/carbon/app/modules/parts/services/parts.form.ts b/apps/carbon/app/modules/parts/services/parts.form.tsindex 7b4a0b08fe..a4fc99e78d 100644--- a/apps/carbon/app/modules/parts/services/parts.form.ts+++ b/apps/carbon/app/modules/parts/services/parts.form.ts@@ -14,7 +14,7 @@ export const partValidator = withZod(message: "Replenishment system is required",}),}),- partGroupId: z.string().min(1, { message: "Part Group is required" }),+ partGroupId: z.string().optional(),partType: z.enum(["Inventory", "Non-Inventory", "Service"], {errorMap: (issue, ctx) => ({message: "Part type is required",diff --git a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsxindex 76ccb8f239..a36a84e2ea 100644--- a/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx+++ b/apps/carbon/app/modules/purchasing/interfaces/PurchaseOrder/PurchaseOrderLines/usePurchaseOrderLines.tsx@@ -25,7 +25,7 @@ export default function usePurchaseOrderLines() {useEffect(() => {if (accountsFetcher.type === "init") {- accountsFetcher.load("/api/accounting/accounts");+ accountsFetcher.load("/api/accounting/accounts?type=Posting");}}, [accountsFetcher]);diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.tsindex eeb5a8b5db..90c4e91b80 100644--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts@@ -324,9 +324,7 @@ export async function getSupplierTypes(export async function insertSupplier(client: SupabaseClient<Database>,- supplier: TypeOfValidator<typeof supplierValidator> & {- createdBy: string;- }+ supplier: TypeOfValidator<typeof supplierValidator> & {}) {return client.from("supplier").insert([supplier]).select("id");}diff --git a/apps/carbon/app/routes/api+/accounting.accounts.tsx b/apps/carbon/app/routes/api+/accounting.accounts.tsxindex 2ce8182797..d6ff461d49 100644--- a/apps/carbon/app/routes/api+/accounting.accounts.tsx+++ b/apps/carbon/app/routes/api+/accounting.accounts.tsx@@ -6,5 +6,9 @@ import { requirePermissions } from "~/services/auth";export async function loader({ request }: LoaderArgs) {const authorized = await requirePermissions(request, {});- return json(await getAccountsList(authorized.client));+ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const type = searchParams.get("type");++ return json(await getAccountsList(authorized.client, type));}diff --git a/apps/carbon/app/routes/api+/accounting.categories.tsx b/apps/carbon/app/routes/api+/accounting.categories.tsxnew file mode 100644index 0000000000..6845a1768d--- /dev/null+++ b/apps/carbon/app/routes/api+/accounting.categories.tsx@@ -0,0 +1,10 @@+import type { LoaderArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { getAccountCategoriesList } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";++export async function loader({ request }: LoaderArgs) {+ const authorized = await requirePermissions(request, {});++ return json(await getAccountCategoriesList(authorized.client));+}diff --git a/apps/carbon/app/routes/api+/accounting.subcategories.tsx b/apps/carbon/app/routes/api+/accounting.subcategories.tsxnew file mode 100644index 0000000000..150300ec6f--- /dev/null+++ b/apps/carbon/app/routes/api+/accounting.subcategories.tsx@@ -0,0 +1,37 @@+import type { LoaderArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { getAccountSubcategoriesByCategory } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const authorized = await requirePermissions(request, {+ view: "accounting",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const accountCategoryId = searchParams.get("accountCategoryId") as string;++ if (!accountCategoryId || accountCategoryId === "undefined")+ return json({+ data: [],+ });++ const subcategories = await getAccountSubcategoriesByCategory(+ authorized.client,+ accountCategoryId+ );+ if (subcategories.error) {+ return json(+ subcategories,+ await flash(+ request,+ error(subcategories.error, "Failed to get account subcategories")+ )+ );+ }++ return json(subcategories);+}diff --git a/apps/carbon/app/routes/x+/accounting+/_layout.tsx b/apps/carbon/app/routes/x+/accounting+/_layout.tsxindex 01b0029cfb..c01b663751 100644--- a/apps/carbon/app/routes/x+/accounting+/_layout.tsx+++ b/apps/carbon/app/routes/x+/accounting+/_layout.tsx@@ -1,13 +1,27 @@import { Grid, VStack } from "@chakra-ui/react";-import type { MetaFunction } from "@remix-run/node";+import type { LoaderArgs, MetaFunction } from "@remix-run/node";+import { json } from "@remix-run/node";import { Outlet } from "@remix-run/react";import { GroupedContentSidebar } from "~/components/Layout/Sidebar";-import { useAccountingSidebar } from "~/modules/accounting";+import { getBaseCurrency, useAccountingSidebar } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";export const meta: MetaFunction = () => ({title: "Carbon | Accounting",});+export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ });++ const [baseCurrency] = await Promise.all([getBaseCurrency(client)]);++ return json({+ baseCurrency: baseCurrency.data,+ });+}+export default function UsersRoute() {const { groups } = useAccountingSidebar();diff --git a/apps/carbon/app/routes/x+/accounting+/categories.$categoryId.tsx b/apps/carbon/app/routes/x+/accounting+/categories.$categoryId.tsxnew file mode 100644index 0000000000..0201c76173--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.$categoryId.tsx@@ -0,0 +1,89 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect, json } from "@remix-run/node";+import { useLoaderData, useNavigate } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import {+ AccountCategoryForm,+ accountCategoryValidator,+ getAccountCategory,+ upsertAccountCategory,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const { categoryId } = params;+ if (!categoryId) throw notFound("Invalid categoryId");++ const accountCategory = await getAccountCategory(client, categoryId);+ if (accountCategory.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(accountCategory.error, "Failed to fetch G/L account category")+ )+ );+ }++ return json({ accountCategory: accountCategory.data });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "accounting",+ });++ const validation = await accountCategoryValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;+ if (!id) throw new Error("ID is was not found");++ const updateCategory = await upsertAccountCategory(client, {+ id,+ ...data,+ updatedBy: userId,+ });+ if (updateCategory.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(updateCategory.error, "Failed to update G/L account category")+ )+ );+ }++ return redirect(+ "/x/accounting/categories",+ await flash(request, success("Updated G/L account category "))+ );+}++export default function EditAccountCategoryRoute() {+ const { accountCategory } = useLoaderData<typeof loader>();+ const navigate = useNavigate();+ const onClose = () => navigate("/x/accounting/categories/");++ const initialValues = {+ ...accountCategory,+ };++ return (+ <AccountCategoryForm onClose={onClose} initialValues={initialValues} />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.delete.$categoryId.tsx b/apps/carbon/app/routes/x+/accounting+/categories.delete.$categoryId.tsxnew file mode 100644index 0000000000..942ab9a668--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.delete.$categoryId.tsx@@ -0,0 +1,42 @@+import type { LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { deleteAccountCategory } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error, success } from "~/utils/result";++export async function action({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ update: "accounting",+ });++ const { categoryId } = params;+ if (!categoryId) {+ return redirect(+ "/x/accounting/categories",+ await flash(request, error(params, "Failed to get a category id"))+ );+ }++ const deactivateAttribute = await deleteAccountCategory(client, categoryId);+ if (deactivateAttribute.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(+ deactivateAttribute.error,+ "Failed to deactivate G/L account category"+ )+ )+ );+ }++ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ success("Successfully deactivated G/L account category")+ )+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.$subcategoryId.tsx b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.$subcategoryId.tsxnew file mode 100644index 0000000000..b16f982522--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.$subcategoryId.tsx@@ -0,0 +1,54 @@+import type { LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";+import {+ AccountSubcategoryForm,+ getAccountSubcategory,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { notFound } from "~/utils/http";+import { error } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const { categoryId, subcategoryId } = params;+ if (!subcategoryId) throw notFound("subcategoryId not found");++ const subcategory = await getAccountSubcategory(client, subcategoryId);+ if (subcategory.error) {+ return redirect(+ `/x/accounting/categories/list/${categoryId}`,+ await flash(+ request,+ error(subcategory.error, "Failed to fetch G/L account subcategory")+ )+ );+ }++ return json({+ subcategory: subcategory.data,+ });+}++export default function EditAccountSubcategoryRoute() {+ const { subcategory } = useLoaderData<typeof loader>();+ const { categoryId } = useParams();+ if (!categoryId) throw notFound("categoryId not found");++ const navigate = useNavigate();+ const onClose = () => navigate(`/x/accounting/categories/list/${categoryId}`);++ const initialValues = {+ ...subcategory,+ };++ return (+ <AccountSubcategoryForm initialValues={initialValues} onClose={onClose} />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.new.tsx b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.new.tsxnew file mode 100644index 0000000000..b7ee2db13f--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.new.tsx@@ -0,0 +1,19 @@+import { useNavigate, useParams } from "@remix-run/react";+import { AccountSubcategoryForm } from "~/modules/accounting";++export default function NewAccountSubcategoryRoute() {+ const { categoryId } = useParams();+ if (!categoryId) throw new Error("categoryId is not found");++ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const initialValues = {+ name: "",+ accountCategoryId: categoryId,+ };++ return (+ <AccountSubcategoryForm initialValues={initialValues} onClose={onClose} />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.tsx b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.tsxnew file mode 100644index 0000000000..9f1656c7d5--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.list.$categoryId.tsx@@ -0,0 +1,76 @@+import type { LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet, useLoaderData, useNavigate } from "@remix-run/react";+import { useUrlParams } from "~/hooks";+import {+ AccountCategoryDetail,+ getAccountCategory,+ getAccountSubcategoriesByCategory,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { notFound } from "~/utils/http";+import { error } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const { categoryId } = params;+ if (!categoryId) throw notFound("Invalid categoryId");++ const [accountCategory, accountSubcategories] = await Promise.all([+ getAccountCategory(client, categoryId),+ getAccountSubcategoriesByCategory(client, categoryId),+ ]);+ if (accountCategory.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(accountCategory.error, "Failed to fetch account category")+ )+ );+ }++ if (accountSubcategories.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(+ accountSubcategories.error,+ "Failed to fetch account subcategories"+ )+ )+ );+ }++ return json({+ accountCategory: accountCategory.data,+ accountSubcategories: accountSubcategories.data ?? [],+ });+}++export default function AccountCategoryListRoute() {+ const { accountCategory, accountSubcategories } =+ useLoaderData<typeof loader>();+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const onClose = () =>+ navigate(`/x/accounting/categories?${params.toString()}`);++ return (+ <>+ <AccountCategoryDetail+ // @ts-expect-error+ accountCategory={accountCategory}+ accountSubcategories={accountSubcategories}+ onClose={onClose}+ />+ <Outlet />+ </>+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.new.tsx b/apps/carbon/app/routes/x+/accounting+/categories.new.tsxnew file mode 100644index 0000000000..baead9c017--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.new.tsx@@ -0,0 +1,71 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useNavigate } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import type {+ AccountIncomeBalance,+ AccountNormalBalance,+} from "~/modules/accounting";+import {+ AccountCategoryForm,+ accountCategoryValidator,+ upsertAccountCategory,+} from "~/modules/accounting";+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 }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "accounting",+ });++ const validation = await accountCategoryValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const createAccountCategory = await upsertAccountCategory(client, {+ ...data,+ createdBy: userId,+ });+ if (createAccountCategory.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(+ createAccountCategory.error,+ "Failed to create G/L account category"+ )+ )+ );+ }++ return redirect(+ "/x/accounting/categories",+ await flash(request, success("Created G/L account category "))+ );+}++export default function NewAccountCategoryRoute() {+ const navigate = useNavigate();+ const onClose = () => navigate("/x/accounting/categories");++ const initialValues = {+ category: "",+ incomeBalance: "" as AccountIncomeBalance,+ normalBalance: "" as AccountNormalBalance,+ };++ return (+ <AccountCategoryForm onClose={onClose} initialValues={initialValues} />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/categories.tsx b/apps/carbon/app/routes/x+/accounting+/categories.tsxnew file mode 100644index 0000000000..0c6294ff16--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/categories.tsx@@ -0,0 +1,65 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import { requirePermissions } from "~/services/auth";+import {+ AccountCategoriesTable,+ AccountCategoriesTableFilters,+ getAccountCategories,+} from "~/modules/accounting";+import { flash } from "~/services/session";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const name = searchParams.get("name");+ const incomeBalance = searchParams.get("incomeBalance");+ const normalBalance = searchParams.get("normalBalance");+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);++ const [categories] = await Promise.all([+ getAccountCategories(client, {+ name,+ normalBalance,+ incomeBalance,+ limit,+ offset,+ sorts,+ }),+ ]);++ if (categories.error) {+ redirect(+ "/x",+ await flash(+ request,+ error(categories.error, "Failed to fetch account categories")+ )+ );+ }++ return json({+ count: categories.count ?? 0,+ categories: categories.data ?? [],+ });+}++export default function GlAccountCategoriesRoute() {+ const { count, categories } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <AccountCategoriesTableFilters />+ <AccountCategoriesTable data={categories} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx b/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsxnew file mode 100644index 0000000000..39aa2d206a--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx@@ -0,0 +1,88 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";++import {+ ChartOfAccountForm,+ accountValidator,+ getAccount,+ upsertAccount,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const { accountId } = params;+ if (!accountId) throw notFound("accountId not found");++ const account = await getAccount(client, accountId);++ return json({+ account: account?.data ?? null,+ });+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "accounting",+ });++ const validation = await accountValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;+ if (!id) throw new Error("id not found");++ const updateAccount = await upsertAccount(client, {+ id,+ ...data,+ updatedBy: userId,+ });++ if (updateAccount.error) {+ return json(+ {},+ await flash(+ request,+ error(updateAccount.error, "Failed to update account")+ )+ );+ }++ return redirect(+ "/x/accounting/charts",+ await flash(request, success("Updated account"))+ );+}++export default function EditChartOfAccountsRoute() {+ const { account } = useLoaderData<typeof loader>();++ const initialValues = {+ id: account?.id ?? undefined,+ number: account?.number ?? "",+ name: account?.name ?? "",+ type: account?.type ?? "Posting",+ accountCategoryId: account?.accountCategoryId ?? undefined,+ accountSubcategoryId: account?.accountSubcategoryId ?? undefined,+ normalBalance: account?.normalBalance ?? "Debit",+ incomeBalance: account?.incomeBalance ?? "Balance Sheet",+ consolidatedRate: account?.consolidatedRate ?? "Average",+ directPosting: account?.directPosting ?? false,+ };++ return <ChartOfAccountForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/accounting+/charts.delete.$accountId.tsx b/apps/carbon/app/routes/x+/accounting+/charts.delete.$accountId.tsxnew file mode 100644index 0000000000..5f425bf71a--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/charts.delete.$accountId.tsx@@ -0,0 +1,73 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";+import { ConfirmDelete } from "~/components/Modals";+import { deleteAccount, getAccount } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error, success } from "~/utils/result";+import { notFound } from "~/utils/http";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ });+ const { accountId } = params;+ if (!accountId) throw notFound("accountId not found");++ const account = await getAccount(client, accountId);+ if (account.error) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(account.error, "Failed to get account"))+ );+ }++ return json({ account: account.data });+}++export async function action({ request, params }: ActionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "accounting",+ });++ const { accountId } = params;+ if (!accountId) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(params, "Failed to get an account id"))+ );+ }++ const { error: deleteTypeError } = await deleteAccount(client, accountId);+ if (deleteTypeError) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(deleteTypeError, "Failed to delete account"))+ );+ }++ return redirect(+ "/x/accounting/currencies",+ await flash(request, success("Successfully deleted account"))+ );+}++export default function DeleteAccountRoute() {+ const { accountId } = useParams();+ const { account } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ if (!accountId || !account) return null; // TODO - handle this better (404?)++ const onCancel = () => navigate("/x/accounting/currencies");++ return (+ <ConfirmDelete+ action={`/x/accounting/currencies/delete/${accountId}`}+ name={account.name}+ text={`Are you sure you want to delete the account: ${account.name} (${account.number})? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/charts.new.tsx b/apps/carbon/app/routes/x+/accounting+/charts.new.tsxnew file mode 100644index 0000000000..189da3ee9f--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/charts.new.tsx@@ -0,0 +1,84 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import type {+ AccountType,+ AccountIncomeBalance,+ AccountNormalBalance,+ AccountConsolidatedRate,+} from "~/modules/accounting";+import {+ ChartOfAccountForm,+ accountValidator,+ upsertAccount,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ await requirePermissions(request, {+ create: "accounting",+ });++ return null;+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "accounting",+ });++ const validation = await accountValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const insertAccount = await upsertAccount(client, {+ ...data,+ createdBy: userId,+ });+ if (insertAccount.error) {+ return json(+ {},+ await flash(+ request,+ error(insertAccount.error, "Failed to insert account")+ )+ );+ }++ const accountNumber = insertAccount.data[0]?.id;+ if (!accountNumber) {+ return json(+ {},+ await flash(request, error(insertAccount, "Failed to insert account"))+ );+ }++ return redirect(+ "/x/accounting/charts",+ await flash(request, success("Account created"))+ );+}++export default function NewAccountRoute() {+ const initialValues = {+ name: "",+ number: "",+ type: "Posting" as AccountType,+ accountCategoryId: "",+ incomeBalance: "Balance Sheet" as AccountIncomeBalance,+ normalBalance: "Debit" as AccountNormalBalance,+ consolidatedRate: "Average" as AccountConsolidatedRate,+ directPosting: false,+ };++ return <ChartOfAccountForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/accounting+/charts.tsx b/apps/carbon/app/routes/x+/accounting+/charts.tsxnew file mode 100644index 0000000000..af10592e8a--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/charts.tsx@@ -0,0 +1,57 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import { ChartOfAccountsTable, getChartOfAccounts } from "~/modules/accounting";+import ChartOfAccountsTableFilters from "~/modules/accounting/interfaces/ChartOfAccounts/ChartOfAccountsTableFilters";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const name = searchParams.get("name");+ const incomeBalance = searchParams.get("incomeBalance");+ const startDate = searchParams.get("startDate");+ const endDate = searchParams.get("endDate");++ const chartOfAccounts = await getChartOfAccounts(client, {+ name,+ incomeBalance,+ startDate,+ endDate,+ });++ if (chartOfAccounts.error) {+ return redirect(+ "/x/accounting",+ await flash(+ request,+ error(chartOfAccounts.error, "Failed to get chart of accounts")+ )+ );+ }++ return json({+ chartOfAccounts: chartOfAccounts.data ?? [],+ });+}++export default function ChartOfAccountsRoute() {+ const { chartOfAccounts } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <ChartOfAccountsTableFilters />+ <ChartOfAccountsTable data={chartOfAccounts} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/currencies.$currencyId.tsx b/apps/carbon/app/routes/x+/accounting+/currencies.$currencyId.tsxnew file mode 100644index 0000000000..4366fdcc9f--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/currencies.$currencyId.tsx@@ -0,0 +1,84 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";++import {+ CurrencyForm,+ currencyValidator,+ getCurrency,+ upsertCurrency,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost, notFound } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const { currencyId } = params;+ if (!currencyId) throw notFound("currencyId not found");++ const currency = await getCurrency(client, currencyId);++ return json({+ currency: currency?.data ?? null,+ });+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "accounting",+ });++ const validation = await currencyValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;+ if (!id) throw new Error("id not found");++ const updateCurrency = await upsertCurrency(client, {+ id,+ ...data,+ updatedBy: userId,+ });++ if (updateCurrency.error) {+ return json(+ {},+ await flash(+ request,+ error(updateCurrency.error, "Failed to update currency")+ )+ );+ }++ return redirect(+ "/x/accounting/currencies",+ await flash(request, success("Updated currency"))+ );+}++export default function EditCurrencysRoute() {+ const { currency } = useLoaderData<typeof loader>();++ const initialValues = {+ id: currency?.id ?? undefined,+ name: currency?.name ?? "",+ code: currency?.code ?? "",+ symbol: currency?.symbol ?? "",+ exchangeRate: currency?.exchangeRate ?? 1,+ isBaseCurrency: currency?.isBaseCurrency ?? false,+ };++ return <CurrencyForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/accounting+/currencies.delete.$currencyId.tsx b/apps/carbon/app/routes/x+/accounting+/currencies.delete.$currencyId.tsxnew file mode 100644index 0000000000..cbeb0fa8e4--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/currencies.delete.$currencyId.tsx@@ -0,0 +1,73 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";+import { ConfirmDelete } from "~/components/Modals";+import { deleteCurrency, getCurrency } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error, success } from "~/utils/result";+import { notFound } from "~/utils/http";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ });+ const { currencyId } = params;+ if (!currencyId) throw notFound("currencyId not found");++ const currency = await getCurrency(client, currencyId);+ if (currency.error) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(currency.error, "Failed to get currency"))+ );+ }++ return json({ currency: currency.data });+}++export async function action({ request, params }: ActionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "accounting",+ });++ const { currencyId } = params;+ if (!currencyId) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(params, "Failed to get an currency id"))+ );+ }++ const { error: deleteTypeError } = await deleteCurrency(client, currencyId);+ if (deleteTypeError) {+ return redirect(+ "/x/accounting/currencies",+ await flash(request, error(deleteTypeError, "Failed to delete currency"))+ );+ }++ return redirect(+ "/x/accounting/currencies",+ await flash(request, success("Successfully deleted currency"))+ );+}++export default function DeleteCurrencyRoute() {+ const { currencyId } = useParams();+ const { currency } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ if (!currencyId || !currency) return null; // TODO - handle this better (404?)++ const onCancel = () => navigate("/x/accounting/currencies");++ return (+ <ConfirmDelete+ action={`/x/accounting/currencies/delete/${currencyId}`}+ name={currency.name}+ text={`Are you sure you want to delete the currency: ${currency.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx b/apps/carbon/app/routes/x+/accounting+/currencies.new.tsxnew file mode 100644index 0000000000..9348fbddf3--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/currencies.new.tsx@@ -0,0 +1,75 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { json } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import {+ CurrencyForm,+ currencyValidator,+ upsertCurrency,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ await requirePermissions(request, {+ create: "accounting",+ });++ return null;+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "accounting",+ });++ const validation = await currencyValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const insertCurrency = await upsertCurrency(client, {+ ...data,+ createdBy: userId,+ });+ if (insertCurrency.error) {+ return json(+ {},+ await flash(+ request,+ error(insertCurrency.error, "Failed to insert currency")+ )+ );+ }++ const currencyId = insertCurrency.data[0]?.id;+ if (!currencyId) {+ return json(+ {},+ await flash(request, error(insertCurrency, "Failed to insert currency"))+ );+ }++ return redirect(+ "/x/accounting/currencies",+ await flash(request, success("Currency created"))+ );+}++export default function NewCurrencysRoute() {+ const initialValues = {+ name: "",+ code: "",+ symbol: "",+ exchangeRate: 1,+ isBaseCurrency: false,+ };++ return <CurrencyForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/accounting+/currencies.tsx b/apps/carbon/app/routes/x+/accounting+/currencies.tsxnew file mode 100644index 0000000000..556bfc1855--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/currencies.tsx@@ -0,0 +1,37 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { Outlet, useLoaderData } from "@remix-run/react";+import {+ CurrenciesTable,+ CurrenciesTableFilters,+ getCurrencies,+} from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { getGenericQueryFilters } from "~/utils/query";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "accounting",+ role: "employee",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const name = searchParams.get("name");+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);++ return json(await getCurrencies(client, { name, limit, offset, sorts }));+}++export default function CurrenciesRoute() {+ const { data, count } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <CurrenciesTableFilters />+ <CurrenciesTable data={data ?? []} count={count ?? 0} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/index.tsx b/apps/carbon/app/routes/x+/accounting+/index.tsxindex cbc3904f5d..16a3a70865 100644--- a/apps/carbon/app/routes/x+/accounting+/index.tsx+++ b/apps/carbon/app/routes/x+/accounting+/index.tsx@@ -1,5 +1,5 @@import { redirect } from "@remix-run/node";export async function loader() {- return redirect("/x/accounting/payment-terms");+ return redirect("/x/accounting/charts");}diff --git a/apps/carbon/app/routes/x+/accounting+/subcategory.$subcategoryId.tsx b/apps/carbon/app/routes/x+/accounting+/subcategory.$subcategoryId.tsxnew file mode 100644index 0000000000..2104a0111e--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/subcategory.$subcategoryId.tsx@@ -0,0 +1,50 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import {+ accountSubcategoryValidator,+ upsertAccountSubcategory,+} from "~/modules/accounting";+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: "accounting",+ });++ const { subcategoryId } = params;+ if (!subcategoryId) throw new Error("subcategoryId not found");++ const validation = await accountSubcategoryValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const update = await upsertAccountSubcategory(client, {+ id: subcategoryId,+ ...data,+ updatedBy: userId,+ });+ if (update.error)+ redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(update.error, "Failed to update G/L subcategory")+ )+ );++ return redirect(+ "/x/accounting/categories",+ await flash(request, success("Successfully updated G/L subcategory"))+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/subcategory.delete.$subcategoryId.tsx b/apps/carbon/app/routes/x+/accounting+/subcategory.delete.$subcategoryId.tsxnew file mode 100644index 0000000000..d927317cc9--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/subcategory.delete.$subcategoryId.tsx@@ -0,0 +1,48 @@+import type { LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { deleteAccountSubcategory } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error, success } from "~/utils/result";++export async function action({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ delete: "accounting",+ });++ const { subcategoryId } = params;+ if (!subcategoryId) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(params, "Failed to get a G/L account subcategory id")+ )+ );+ }++ const deactivateSubcategory = await deleteAccountSubcategory(+ client,+ subcategoryId+ );+ if (deactivateSubcategory.error) {+ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ error(+ deactivateSubcategory.error,+ "Failed to deactivate G/L account subcategory"+ )+ )+ );+ }++ return redirect(+ "/x/accounting/categories",+ await flash(+ request,+ success("Successfully deactivated G/L account subcategory")+ )+ );+}diff --git a/apps/carbon/app/routes/x+/accounting+/subcategory.new.tsx b/apps/carbon/app/routes/x+/accounting+/subcategory.new.tsxnew file mode 100644index 0000000000..a18f398dec--- /dev/null+++ b/apps/carbon/app/routes/x+/accounting+/subcategory.new.tsx@@ -0,0 +1,51 @@+import type { ActionArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import {+ accountSubcategoryValidator,+ upsertAccountSubcategory,+} from "~/modules/accounting";+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 }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "accounting",+ });++ const validation = await accountSubcategoryValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const createSubcategory = await upsertAccountSubcategory(client, {+ ...data,+ createdBy: userId,+ });+ if (createSubcategory.error) {+ return json(+ {},+ await flash(+ request,+ error(+ createSubcategory.error,+ "Failed to create G/L account subcategory"+ )+ )+ );+ }++ return redirect(+ `/x/accounting/categories`,+ await flash(request, success("Created G/L account subcategory"))+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$partId.tsxindex 4346854d77..9d19bc6b51 100644--- a/apps/carbon/app/routes/x+/part+/$partId.tsx+++ b/apps/carbon/app/routes/x+/part+/$partId.tsx@@ -34,7 +34,7 @@ export default function PartRoute() {<><PartPreview /><Grid- gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}+ gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}gridColumnGap={4}w="full">diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsxindex 704884b3c3..1ba53f192e 100644--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.tsx@@ -50,7 +50,7 @@ export default function PurchaseOrderRoute() {<><PurchaseOrderHeader /><Grid- gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}+ gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}gridColumnGap={4}w="full">diff --git a/apps/carbon/app/utils/query.ts b/apps/carbon/app/utils/query.tsindex a07f044e01..55608ce5cf 100644--- a/apps/carbon/app/utils/query.ts+++ b/apps/carbon/app/utils/query.ts@@ -96,7 +96,7 @@ export function setGenericQueryFilters<V>(query: PostgrestFilterBuilder<T, U, V>,- args: GenericQueryFilters,+ args: Partial<GenericQueryFilters>,defaultSort?: string,defaultAsc = true): PostgrestFilterBuilder<T, U, V> {@@ -127,7 +127,11 @@ export function setGenericQueryFilters<});}- return query.range(args.offset, args.offset + args.limit - 1);+ if (args.offset && args.limit) {+ query = query.range(args.offset, args.offset + args.limit - 1);+ }++ return query;}const getSafeNumber = (value: string) => {diff --git a/apps/carbon/package.json b/apps/carbon/package.jsonindex 70fd207c81..76a5194e26 100644--- a/apps/carbon/package.json+++ b/apps/carbon/package.json@@ -28,7 +28,7 @@"@remix-run/vercel": "1.13.0","@remix-validated-form/with-zod": "^2.0.5","@supabase/supabase-js": "^2.10.0",- "@tanstack/react-table": "^8.7.3",+ "@tanstack/react-table": "^8.9.3","@vercel/node": "^2.9.6","@visx/axis": "^2.18.0","@visx/curve": "^2.17.0",@@ -49,7 +49,7 @@"performant-array-to-tree": "1.11.0","react": "^18.2.0","react-dom": "^18.2.0",- "react-icons": "^4.8.0",+ "react-icons": "^4.10.1","react-virtual": "2.10.4","reactflow": "^11.5.6","remix-flat-routes": "^0.5.7",diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.tsindex a51084f63a..a846c3817c 100644--- a/packages/carbon-database/src/types.ts+++ b/packages/carbon-database/src/types.ts@@ -48,62 +48,65 @@ export interface Database {Row: {number: string;name: string;- description: string | null;+ type: Database["public"]["Enums"]["glAccountType"];accountCategoryId: string | null;+ accountSubcategoryId: string | null;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"];+ normalBalance: Database["public"]["Enums"]["glNormalBalance"];consolidatedRate:- | Database["public"]["Enums"]["consolidatedRate"]+ | Database["public"]["Enums"]["glConsolidatedRate"]| null;- currencyCode: string | null;- parentAccountNumber: string | null;createdBy: string;updatedBy: string | null;updatedAt: string | null;- controlAccount: boolean;- cashAccount: boolean;+ id: string;+ directPosting: boolean;active: boolean;createdAt: string;};Insert: {number: string;name: string;- description?: string | null;+ type: Database["public"]["Enums"]["glAccountType"];accountCategoryId?: string | null;+ accountSubcategoryId?: string | null;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"];+ normalBalance: Database["public"]["Enums"]["glNormalBalance"];consolidatedRate?:- | Database["public"]["Enums"]["consolidatedRate"]+ | Database["public"]["Enums"]["glConsolidatedRate"]| null;- currencyCode?: string | null;- parentAccountNumber?: string | null;createdBy: string;updatedBy?: string | null;updatedAt?: string | null;- controlAccount?: boolean;- cashAccount?: boolean;+ id?: string;+ directPosting?: boolean;active?: boolean;createdAt?: string;};Update: {number?: string;name?: string;- description?: string | null;+ type?: Database["public"]["Enums"]["glAccountType"];accountCategoryId?: string | null;+ accountSubcategoryId?: string | null;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"];+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"];consolidatedRate?:- | Database["public"]["Enums"]["consolidatedRate"]+ | Database["public"]["Enums"]["glConsolidatedRate"]| null;- currencyCode?: string | null;- parentAccountNumber?: string | null;createdBy?: string;updatedBy?: string | null;updatedAt?: string | null;- controlAccount?: boolean;- cashAccount?: boolean;+ id?: string;+ directPosting?: boolean;active?: boolean;createdAt?: string;};};accountCategory: {Row: {- category: Database["public"]["Enums"]["glAccountCategory"];- type: Database["public"]["Enums"]["glAccountType"];+ category: string;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"];normalBalance: Database["public"]["Enums"]["glNormalBalance"];createdBy: string;updatedBy: string | null;@@ -112,8 +115,8 @@ export interface Database {createdAt: string;};Insert: {- category: Database["public"]["Enums"]["glAccountCategory"];- type: Database["public"]["Enums"]["glAccountType"];+ category: string;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"];normalBalance: Database["public"]["Enums"]["glNormalBalance"];createdBy: string;updatedBy?: string | null;@@ -122,8 +125,8 @@ export interface Database {createdAt?: string;};Update: {- category?: Database["public"]["Enums"]["glAccountCategory"];- type?: Database["public"]["Enums"]["glAccountType"];+ category?: string;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"];normalBalance?: Database["public"]["Enums"]["glNormalBalance"];createdBy?: string;updatedBy?: string | null;@@ -132,6 +135,38 @@ export interface Database {createdAt?: string;};};+ accountSubcategory: {+ Row: {+ name: string;+ accountCategoryId: string;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ name: string;+ accountCategoryId: string;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ name?: string;+ accountCategoryId?: string;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ };address: {Row: {addressLine1: string | null;@@ -379,10 +414,9 @@ export interface Database {updatedBy: string | null;updatedAt: string | null;id: string;- symbolPlacementBefore: boolean;exchangeRate: number;- currencyPrecision: number;isBaseCurrency: boolean;+ active: boolean;createdAt: string;};Insert: {@@ -393,10 +427,9 @@ export interface Database {updatedBy?: string | null;updatedAt?: string | null;id?: string;- symbolPlacementBefore?: boolean;exchangeRate?: number;- currencyPrecision?: number;isBaseCurrency?: boolean;+ active?: boolean;createdAt?: string;};Update: {@@ -407,10 +440,9 @@ export interface Database {updatedBy?: string | null;updatedAt?: string | null;id?: string;- symbolPlacementBefore?: boolean;exchangeRate?: number;- currencyPrecision?: number;isBaseCurrency?: boolean;+ active?: boolean;createdAt?: string;};};@@ -946,6 +978,50 @@ export interface Database {createdAt?: string;};};+ generalLedger: {+ Row: {+ postingDate: string;+ accountNumber: string;+ description: string | null;+ amount: number;+ documentType:+ | Database["public"]["Enums"]["accountDocumentLedgerType"]+ | null;+ documentNumber: string | null;+ externalDocumentNumber: string | null;+ id: string;+ entryNumber: number;+ createdAt: string;+ };+ Insert: {+ postingDate: string;+ accountNumber: string;+ description?: string | null;+ amount: number;+ documentType?:+ | Database["public"]["Enums"]["accountDocumentLedgerType"]+ | null;+ documentNumber?: string | null;+ externalDocumentNumber?: string | null;+ id?: string;+ entryNumber?: number;+ createdAt?: string;+ };+ Update: {+ postingDate?: string;+ accountNumber?: string;+ description?: string | null;+ amount?: number;+ documentType?:+ | Database["public"]["Enums"]["accountDocumentLedgerType"]+ | null;+ documentNumber?: string | null;+ externalDocumentNumber?: string | null;+ id?: string;+ entryNumber?: number;+ createdAt?: string;+ };+ };group: {Row: {name: string;@@ -1095,7 +1171,7 @@ export interface Database {name: string;description: string | null;replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"];- partGroupId: string;+ partGroupId: string | null;partType: Database["public"]["Enums"]["partType"];manufacturerPartNumber: string | null;unitOfMeasureCode: string;@@ -1115,7 +1191,7 @@ export interface Database {name: string;description?: string | null;replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"];- partGroupId: string;+ partGroupId?: string | null;partType: Database["public"]["Enums"]["partType"];manufacturerPartNumber?: string | null;unitOfMeasureCode: string;@@ -1135,7 +1211,7 @@ export interface Database {name?: string;description?: string | null;replenishmentSystem?: Database["public"]["Enums"]["partReplenishmentSystem"];- partGroupId?: string;+ partGroupId?: string | null;partType?: Database["public"]["Enums"]["partType"];manufacturerPartNumber?: string | null;unitOfMeasureCode?: string;@@ -1283,6 +1359,68 @@ export interface Database {createdAt?: string;};};+ partLedger: {+ Row: {+ postingDate: string;+ entryType: Database["public"]["Enums"]["partLedgerType"];+ documentType:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber: string | null;+ partId: string;+ locationId: string | null;+ shelfId: string | null;+ quantity: number;+ invoicedQuantity: number;+ remainingQuantity: number;+ salesAmount: number;+ costAmount: number;+ id: string;+ entryNumber: number;+ open: boolean;+ createdAt: string;+ };+ Insert: {+ postingDate: string;+ entryType: Database["public"]["Enums"]["partLedgerType"];+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber?: string | null;+ partId: string;+ locationId?: string | null;+ shelfId?: string | null;+ quantity: number;+ invoicedQuantity: number;+ remainingQuantity: number;+ salesAmount: number;+ costAmount: number;+ id?: string;+ entryNumber?: number;+ open?: boolean;+ createdAt?: string;+ };+ Update: {+ postingDate?: string;+ entryType?: Database["public"]["Enums"]["partLedgerType"];+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber?: string | null;+ partId?: string;+ locationId?: string | null;+ shelfId?: string | null;+ quantity?: number;+ invoicedQuantity?: number;+ remainingQuantity?: number;+ salesAmount?: number;+ costAmount?: number;+ id?: string;+ entryNumber?: number;+ open?: boolean;+ createdAt?: string;+ };+ };partner: {Row: {id: string;@@ -1893,6 +2031,7 @@ export interface Database {Row: {id: string;locationId: string | null;+ warehouseId: string | null;createdBy: string;updatedBy: string | null;updatedAt: string | null;@@ -1902,6 +2041,7 @@ export interface Database {Insert: {id: string;locationId?: string | null;+ warehouseId?: string | null;createdBy: string;updatedBy?: string | null;updatedAt?: string | null;@@ -1911,6 +2051,7 @@ export interface Database {Update: {id?: string;locationId?: string | null;+ warehouseId?: string | null;createdBy?: string;updatedBy?: string | null;updatedAt?: string | null;@@ -2413,6 +2554,120 @@ export interface Database {createdAt?: string;};};+ valueLedger: {+ Row: {+ postingDate: string;+ partLedgerType: Database["public"]["Enums"]["partLedgerType"];+ costLedgerType: Database["public"]["Enums"]["costLedgerType"];+ documentType:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber: string | null;+ id: string;+ entryNumber: number;+ adjustment: boolean;+ costAmountActual: number;+ costAmountExpected: number;+ actualCostPostedToGl: number;+ expectedCostPostedToGl: number;+ createdAt: string;+ };+ Insert: {+ postingDate: string;+ partLedgerType: Database["public"]["Enums"]["partLedgerType"];+ costLedgerType: Database["public"]["Enums"]["costLedgerType"];+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber?: string | null;+ id?: string;+ entryNumber?: number;+ adjustment?: boolean;+ costAmountActual?: number;+ costAmountExpected?: number;+ actualCostPostedToGl?: number;+ expectedCostPostedToGl?: number;+ createdAt?: string;+ };+ Update: {+ postingDate?: string;+ partLedgerType?: Database["public"]["Enums"]["partLedgerType"];+ costLedgerType?: Database["public"]["Enums"]["costLedgerType"];+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null;+ documentNumber?: string | null;+ id?: string;+ entryNumber?: number;+ adjustment?: boolean;+ costAmountActual?: number;+ costAmountExpected?: number;+ actualCostPostedToGl?: number;+ expectedCostPostedToGl?: number;+ createdAt?: string;+ };+ };+ valueLedgerAccountLedgerRelation: {+ Row: {+ valueLedgerId: string;+ generalLedgerId: string;+ };+ Insert: {+ valueLedgerId: string;+ generalLedgerId: string;+ };+ Update: {+ valueLedgerId?: string;+ generalLedgerId?: string;+ };+ };+ warehouse: {+ Row: {+ name: string;+ locationId: string;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ requiresPick: boolean;+ requiresPutAway: boolean;+ requiresBin: boolean;+ requiresReceive: boolean;+ requiresShipment: boolean;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ name: string;+ locationId: string;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ requiresPick?: boolean;+ requiresPutAway?: boolean;+ requiresBin?: boolean;+ requiresReceive?: boolean;+ requiresShipment?: boolean;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ name?: string;+ locationId?: string;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ requiresPick?: boolean;+ requiresPutAway?: boolean;+ requiresBin?: boolean;+ requiresReceive?: boolean;+ requiresShipment?: boolean;+ active?: boolean;+ createdAt?: string;+ };+ };workCell: {Row: {name: string;@@ -2500,6 +2755,106 @@ export interface Database {};};Views: {+ account_categories_view: {+ Row: {+ id: string | null;+ category: string | null;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance: Database["public"]["Enums"]["glNormalBalance"] | null;+ createdBy: string | null;+ createdAt: string | null;+ updatedBy: string | null;+ updatedAt: string | null;+ subCategoriesCount: number | null;+ };+ Insert: {+ id?: string | null;+ category?: string | null;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null;+ createdBy?: string | null;+ createdAt?: string | null;+ updatedBy?: string | null;+ updatedAt?: string | null;+ subCategoriesCount?: never;+ };+ Update: {+ id?: string | null;+ category?: string | null;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null;+ createdBy?: string | null;+ createdAt?: string | null;+ updatedBy?: string | null;+ updatedAt?: string | null;+ subCategoriesCount?: never;+ };+ };+ accounts_view: {+ Row: {+ id: string | null;+ number: string | null;+ name: string | null;+ type: Database["public"]["Enums"]["glAccountType"] | null;+ accountCategoryId: string | null;+ accountCategory: string | null;+ accountSubcategoryId: string | null;+ accountSubCategory: string | null;+ incomeBalance: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance: Database["public"]["Enums"]["glNormalBalance"] | null;+ consolidatedRate:+ | Database["public"]["Enums"]["glConsolidatedRate"]+ | null;+ directPosting: boolean | null;+ active: boolean | null;+ createdBy: string | null;+ createdAt: string | null;+ updatedBy: string | null;+ updatedAt: string | null;+ };+ Insert: {+ id?: string | null;+ number?: string | null;+ name?: string | null;+ type?: Database["public"]["Enums"]["glAccountType"] | null;+ accountCategoryId?: string | null;+ accountCategory?: never;+ accountSubcategoryId?: string | null;+ accountSubCategory?: never;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null;+ consolidatedRate?:+ | Database["public"]["Enums"]["glConsolidatedRate"]+ | null;+ directPosting?: boolean | null;+ active?: boolean | null;+ createdBy?: string | null;+ createdAt?: string | null;+ updatedBy?: string | null;+ updatedAt?: string | null;+ };+ Update: {+ id?: string | null;+ number?: string | null;+ name?: string | null;+ type?: Database["public"]["Enums"]["glAccountType"] | null;+ accountCategoryId?: string | null;+ accountCategory?: never;+ accountSubcategoryId?: string | null;+ accountSubCategory?: never;+ incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null;+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null;+ consolidatedRate?:+ | Database["public"]["Enums"]["glConsolidatedRate"]+ | null;+ directPosting?: boolean | null;+ active?: boolean | null;+ createdBy?: string | null;+ createdAt?: string | null;+ updatedBy?: string | null;+ updatedAt?: string | null;+ };+ };contractors_view: {Row: {supplierContactId: string | null;@@ -2696,6 +3051,15 @@ export interface Database {Args: Record<PropertyKey, never>;Returns: Json;};+ gl_transactions_by_account_number: {+ Args: { from_date: string; to_date: string };+ Returns: {+ number: string;+ balance: number;+ balanceAtDate: number;+ netChange: number;+ }[];+ };groups_for_user: {Args: { uid: string };Returns: string[];@@ -2756,7 +3120,20 @@ export interface Database {};};Enums: {- consolidatedRate: "Average" | "Current" | "Historical";+ accountDocumentLedgerType:+ | "Quote"+ | "Order"+ | "Invoice"+ | "Credit Memo"+ | "Blanket Order"+ | "Return Order";+ costLedgerType:+ | "Direct Cost"+ | "Revaluation"+ | "Rounding"+ | "Indirect Cost"+ | "Variance"+ | "Total";documentTransactionType:| "Download"| "Edit"@@ -2795,9 +3172,39 @@ export interface Database {| "Expense"| "Other Income"| "Other Expense";- glAccountType: "Balance Sheet" | "Income Statement";- glNormalBalance: "Debit" | "Credit";+ glAccountType: "Posting" | "Heading" | "Begin Total" | "End Total";+ glConsolidatedRate: "Average" | "Current" | "Historical";+ glIncomeBalance: "Balance Sheet" | "Income Statement";+ glNormalBalance: "Debit" | "Credit" | "Both";partCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO";+ partLedgerDocumentType:+ | "Sales Shipment"+ | "Sales Invoice"+ | "Sales Return Receipt"+ | "Sales Credit Memo"+ | "Purchase Receipt"+ | "Purchase Invoice"+ | "Purchase Return Shipment"+ | "Purchase Credit Memo"+ | "Transfer Shipment"+ | "Transfer Receipt"+ | "Service Shipment"+ | "Service Invoice"+ | "Service Credit Memo"+ | "Posted Assembly"+ | "Inventory Receipt"+ | "Inventory Shipment"+ | "Direct Transfer";+ partLedgerType:+ | "Purchase"+ | "Sale"+ | "Positive Adjmt."+ | "Negative Adjmt."+ | "Transfer"+ | "Consumption"+ | "Output"+ | "Assembly Consumption"+ | "Assembly Output";partManufacturingPolicy: "Make to Order" | "Make to Stock";partReorderingPolicy:| "Manual Reorder"diff --git a/packages/carbon-database/supabase/migrations/20230123004536_attributes.sql b/packages/carbon-database/supabase/migrations/20230123004536_attributes.sqlindex d815d41bf1..917c3975a0 100644--- a/packages/carbon-database/supabase/migrations/20230123004536_attributes.sql+++ b/packages/carbon-database/supabase/migrations/20230123004536_attributes.sql@@ -11,8 +11,8 @@ CREATE TABLE "userAttributeCategory" ("updatedBy" TEXT,CONSTRAINT "userAttributeCategory_pkey" PRIMARY KEY ("id"),- CONSTRAINT "userAttributeCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),- CONSTRAINT "userAttributeCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+ CONSTRAINT "userAttributeCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "userAttributeCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE);-- ALTER TABLE "userAttributeCategory" ENABLE ROW LEVEL SECURITY;@@ -109,8 +109,8 @@ CREATE TABLE "userAttribute" (CONSTRAINT "userAttribute_pkey" PRIMARY KEY ("id"),CONSTRAINT "userAttribute_userAttributeCategoryId_fkey" FOREIGN KEY ("userAttributeCategoryId") REFERENCES "userAttributeCategory"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "userAttribute_attributeDataTypeId_fkey" FOREIGN KEY ("attributeDataTypeId") REFERENCES "attributeDataType"("id") ON DELETE CASCADE ON UPDATE CASCADE,- CONSTRAINT "userAttribute_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),- CONSTRAINT "userAttribute_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+ CONSTRAINT "userAttribute_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "userAttribute_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE);diff --git a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sqlindex 379d688c45..122b497812 100644--- a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql+++ b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql@@ -83,8 +83,8 @@ CREATE TABLE "supplier" (CONSTRAINT "supplier_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_supplierStatusId_fkey" FOREIGN KEY ("supplierStatusId") REFERENCES "supplierStatus"("id") ON UPDATE CASCADE ON DELETE SET NULL,CONSTRAINT "supplier_accountManagerId_fkey" FOREIGN KEY ("accountManagerId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,- CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "supplier_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,+ CONSTRAINT "supplier_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE,CONSTRAINT "supplier_name_unique" UNIQUE ("name"));diff --git a/packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sql b/packages/carbon-database/supabase/migrations/20230330024715_accounts.sqlsimilarity index 61%rename from packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sqlrename to packages/carbon-database/supabase/migrations/20230330024715_accounts.sqlindex 90ad639696..42ac4f239e 100644--- a/packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sql+++ b/packages/carbon-database/supabase/migrations/20230330024715_accounts.sql@@ -3,10 +3,9 @@ CREATE TABLE "currency" ("name" TEXT NOT NULL,"code" TEXT NOT NULL,"symbol" TEXT,- "symbolPlacementBefore" BOOLEAN NOT NULL DEFAULT true,"exchangeRate" NUMERIC(10,4) NOT NULL DEFAULT 1.0000,- "currencyPrecision" INTEGER NOT NULL DEFAULT 2,"isBaseCurrency" BOOLEAN NOT NULL DEFAULT false,+ "active" BOOLEAN NOT NULL DEFAULT true,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"updatedBy" TEXT,@@ -14,12 +13,13 @@ CREATE TABLE "currency" (CONSTRAINT "currency_pkey" PRIMARY KEY ("id"),CONSTRAINT "currency_code_key" UNIQUE ("code"),+ CONSTRAINT "currency_exchangeRate_check" CHECK ("exchangeRate" > 0),CONSTRAINT "currency_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "currency_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "currency" ("name", "code", "symbol", "symbolPlacementBefore", "exchangeRate", "currencyPrecision", "isBaseCurrency", "createdBy")-VALUES ('US Dollar', 'USD', '$', true, 1.0000, 2, true, 'system');+INSERT INTO "currency" ("name", "code", "symbol", "exchangeRate", "isBaseCurrency", "createdBy")+VALUES ('US Dollar', 'USD', '$', 1.0000, true, 'system');CREATE INDEX "currency_code_index" ON "currency" ("code");@@ -73,20 +73,29 @@ CREATE TYPE "glAccountCategory" AS ENUM ('Other Expense');-CREATE TYPE "glAccountType" AS ENUM (+CREATE TYPE "glIncomeBalance" AS ENUM ('Balance Sheet','Income Statement');CREATE TYPE "glNormalBalance" AS ENUM ('Debit',- 'Credit'+ 'Credit',+ 'Both'+);++CREATE TYPE "glAccountType" AS ENUM (+ 'Posting',+ 'Heading',+ -- 'Total',+ 'Begin Total',+ 'End Total');CREATE TABLE "accountCategory" ("id" TEXT NOT NULL DEFAULT xid(),- "category" "glAccountCategory" NOT NULL,- "type" "glAccountType" NOT NULL,+ "category" TEXT NOT NULL,+ "incomeBalance" "glIncomeBalance" NOT NULL,"normalBalance" "glNormalBalance" NOT NULL,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),@@ -94,12 +103,12 @@ CREATE TABLE "accountCategory" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "accountCategory_pkey" PRIMARY KEY ("id"),- CONSTRAINT "accountCategory_category_type_key" UNIQUE ("category"),+ CONSTRAINT "accountCategory_unique_category" UNIQUE ("category"),CONSTRAINT "accountCategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "accountCategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "accountCategory" ("category", "type", "normalBalance", "createdBy")+INSERT INTO "accountCategory" ("category", "incomeBalance", "normalBalance", "createdBy")VALUES('Bank', 'Balance Sheet', 'Credit', 'system'),('Accounts Receivable', 'Balance Sheet', 'Credit', 'system'),@@ -151,39 +160,93 @@ CREATE POLICY "Employees with accounting_delete can delete account categories" OAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE TYPE "consolidatedRate" AS ENUM (+CREATE TYPE "glConsolidatedRate" AS ENUM ('Average','Current','Historical');+CREATE TABLE "accountSubcategory" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "accountCategoryId" TEXT NOT NULL,+ "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 "accountSubcategory_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "accountSubcategory_name_key" UNIQUE ("name"),+ CONSTRAINT "accountSubcategory_accountCategoryId_fkey" FOREIGN KEY ("accountCategoryId") REFERENCES "accountCategory"("id"),+ CONSTRAINT "accountSubcategory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "accountSubcategory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "accountSubcategory_accountCategoryId_idx" ON "accountSubcategory" ("accountCategoryId");++ALTER TABLE "accountSubcategory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view account subcategories" ON "accountSubcategory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert account subcategories" ON "accountSubcategory"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with accounting_update can update account subcategories" ON "accountSubcategory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('accounting_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with accounting_delete can delete account subcategories" ON "accountSubcategory"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "account" (+ "id" TEXT NOT NULL DEFAULT xid(),"number" TEXT NOT NULL,"name" TEXT NOT NULL,- "description" TEXT,+ "type" "glAccountType" NOT NULL,"accountCategoryId" TEXT,- "controlAccount" BOOLEAN NOT NULL DEFAULT false,- "cashAccount" BOOLEAN NOT NULL DEFAULT false,- "consolidatedRate" "consolidatedRate",- "currencyCode" TEXT,- "parentAccountNumber" TEXT,+ "accountSubcategoryId" TEXT,+ "incomeBalance" "glIncomeBalance" NOT NULL,+ "normalBalance" "glNormalBalance" NOT NULL,+ "consolidatedRate" "glConsolidatedRate",+ "directPosting" BOOLEAN NOT NULL DEFAULT false,"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 "account_pkey" PRIMARY KEY ("number"),+ CONSTRAINT "account_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "account_number_key" UNIQUE ("number"),CONSTRAINT "account_name_key" UNIQUE ("name"),CONSTRAINT "account_accountCategoryId_fkey" FOREIGN KEY ("accountCategoryId") REFERENCES "accountCategory"("id"),- CONSTRAINT "account_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL,- CONSTRAINT "account_parentAccountNumber_fkey" FOREIGN KEY ("parentAccountNumber") REFERENCES "account"("number"),CONSTRAINT "account_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "account_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));-INSERT INTO "account" ("number", "name", "consolidatedRate", "currencyCode", "createdBy")-VALUES ('999999', 'Unassigned', 'Average', 'USD', 'system');+CREATE INDEX "account_number_idx" ON "account" ("number");+CREATE INDEX "account_type_idx" ON "account" ("type");+CREATE INDEX "account_incomeBalance_idx" ON "account" ("incomeBalance");+CREATE INDEX "account_accountCategoryId_idx" ON "account" ("accountCategoryId");+CREATE INDEX "account_accountSubcategoryId_idx" ON "account" ("accountSubcategoryId");+ALTER TABLE "account" ENABLE ROW LEVEL SECURITY;@@ -220,4 +283,40 @@ CREATE POLICY "Employees with accounting_delete can delete accounts" ON "accountUSING (coalesce(get_my_claim('accounting_delete')::boolean, false) = trueAND (get_my_claim('role'::text)) = '"employee"'::jsonb- );\ No newline at end of file+ );++CREATE VIEW "account_categories_view" AS+ SELECT+ "id",+ "category",+ "incomeBalance",+ "normalBalance",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt",+ (SELECT count(*) FROM "accountSubcategory" WHERE "accountSubcategory"."accountCategoryId" = "accountCategory"."id" AND "accountSubcategory"."active" = true) AS "subCategoriesCount"+ FROM "accountCategory"+;++CREATE VIEW "accounts_view" AS+ SELECT+ "id",+ "number",+ "name",+ "type",+ "accountCategoryId",+ (SELECT "category" FROM "accountCategory" WHERE "accountCategory"."id" = "account"."accountCategoryId") AS "accountCategory",+ "accountSubcategoryId",+ (SELECT "name" FROM "accountSubcategory" WHERE "accountSubcategory"."id" = "account"."accountSubcategoryId") AS "accountSubCategory",+ "incomeBalance",+ "normalBalance",+ "consolidatedRate",+ "directPosting",+ "active",+ "createdBy",+ "createdAt",+ "updatedBy",+ "updatedAt"+ FROM "account"+;\ No newline at end of filediff --git a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql b/packages/carbon-database/supabase/migrations/20230330024716_parts.sqlindex e2ef9b55d7..5e714d1d3b 100644--- a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql+++ b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql@@ -17,13 +17,13 @@ CREATE TABLE "partGroup" (CONSTRAINT "partGroup_pkey" PRIMARY KEY ("id"),CONSTRAINT "partGroup_name_key" UNIQUE ("name"),- CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldLaborAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldLaborAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldMaterialAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldMaterialAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldOverheadAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldOverheadAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_costOfGoodsSoldSubcontractorAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldSubcontractorAccountId") REFERENCES "account"("number") ON DELETE CASCADE,+ CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldLaborAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldLaborAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldMaterialAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldMaterialAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldOverheadAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldOverheadAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_costOfGoodsSoldSubcontractorAccountId_fkey" FOREIGN KEY ("costOfGoodsSoldSubcontractorAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -152,7 +152,7 @@ CREATE TABLE "part" ("description" TEXT,"blocked" BOOLEAN NOT NULL DEFAULT false,"replenishmentSystem" "partReplenishmentSystem" NOT NULL,- "partGroupId" TEXT NOT NULL,+ "partGroupId" TEXT,"partType" "partType" NOT NULL,"manufacturerPartNumber" TEXT,"unitOfMeasureCode" TEXT NOT NULL,@@ -167,7 +167,7 @@ CREATE TABLE "part" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "part_pkey" PRIMARY KEY ("id"),- CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,+ CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id") ON DELETE SET NULL,CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),CONSTRAINT "part_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),@@ -279,10 +279,10 @@ CREATE TABLE "partCost" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partCost_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,- CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE,- CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE,+ CONSTRAINT "partCost_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_salesAccountId_fkey" FOREIGN KEY ("salesAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_discountAccountId_fkey" FOREIGN KEY ("discountAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partGroup_inventoryAccountId_fkey" FOREIGN KEY ("inventoryAccountId") REFERENCES "account"("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -318,8 +318,8 @@ CREATE TABLE "partUnitSalePrice" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partUnitSalePrice_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,- CONSTRAINT "partUnitSalePrice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL,+ CONSTRAINT "partUnitSalePrice_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "partUnitSalePrice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "partUnitSalePrice_salesUnitOfMeasureId_fkey" FOREIGN KEY ("salesUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,CONSTRAINT "partUnitSalePrice_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partUnitSalePrice_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")@@ -358,7 +358,7 @@ CREATE TABLE "partSupplier" ("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_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE 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"),@@ -445,9 +445,9 @@ CREATE TABLE "partReplenishment" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,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_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -586,9 +586,32 @@ CREATE POLICY "Suppliers with parts_update can update parts replenishments that));+CREATE TABLE "warehouse" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "locationId" TEXT NOT NULL,+ "requiresPick" BOOLEAN NOT NULL DEFAULT false,+ "requiresPutAway" BOOLEAN NOT NULL DEFAULT false,+ "requiresBin" BOOLEAN NOT NULL DEFAULT false,+ "requiresReceive" BOOLEAN NOT NULL DEFAULT false,+ "requiresShipment" BOOLEAN NOT NULL DEFAULT false,+ "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 "warehouse_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "warehouse_name_key" UNIQUE ("name"),+ CONSTRAINT "warehouse_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id"),+ CONSTRAINT "warehouse_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "warehouse_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);+CREATE TABLE "shelf" ("id" TEXT NOT NULL,"locationId" TEXT,+ "warehouseId" TEXT,"active" BOOLEAN NOT NULL DEFAULT true,"createdBy" TEXT NOT NULL,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),@@ -597,11 +620,13 @@ CREATE TABLE "shelf" (CONSTRAINT "shelf_pkey" PRIMARY KEY ("id"),CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,+ CONSTRAINT "shelf_warehouseId_fkey" FOREIGN KEY ("warehouseId") REFERENCES "warehouse"("id") ON DELETE CASCADE,CONSTRAINT "shelf_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "shelf_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));CREATE INDEX "shelf_locationId_index" ON "shelf" ("locationId");+CREATE INDEX "shelf_warehouseId_index" ON "shelf" ("warehouseId");ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;@@ -656,7 +681,7 @@ CREATE TABLE "partPlanning" ("updatedBy" TEXT,"updatedAt" TIMESTAMP WITH TIME ZONE,- CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));@@ -691,7 +716,7 @@ CREATE TABLE "partInventory" ("updatedAt" TIMESTAMP WITH TIME ZONE,CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),- CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "partInventory_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON DELETE SET NULL,CONSTRAINT "partInventory_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),CONSTRAINT "partInventory_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")diff --git a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sqlindex 9f2ce556ce..c8b03f5101 100644--- a/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql+++ b/packages/carbon-database/supabase/migrations/20230510035345_purchasing.sql@@ -34,6 +34,43 @@ VALUES('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),('Due on Receipt', 0, 'Net', 0, 0, 'system'),('Net EOM 10', 10, 'End of Month', 0, 0, 'system');++ALTER TABLE "paymentTerm" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true OR+ coalesce(get_my_claim('resources_view')::boolean, false) = true OR+ coalesce(get_my_claim('sales_view')::boolean, false) = true OR+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert payment terms" ON "paymentTerm"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with accounting_update can update payment terms" ON "paymentTerm"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('accounting_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with accounting_delete can delete payment terms" ON "paymentTerm"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );CREATE TYPE "shippingCarrier" AS ENUM (@@ -58,13 +95,49 @@ CREATE TABLE "shippingMethod" (CONSTRAINT "shippingMethod_pkey" PRIMARY KEY ("id"),CONSTRAINT "shippingMethod_name_key" UNIQUE ("name"),- CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE,+ CONSTRAINT "shippingMethod_carrierAccountId_fkey" FOREIGN KEY ("carrierAccountId") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "shippingMethod_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,CONSTRAINT "shippingMethod_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE);CREATE INDEX "shippingMethod_name_idx" ON "shippingMethod" ("name");++CREATE POLICY "Certain employees can view shipping methods" ON "shippingMethod"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('inventory_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true OR+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true OR+ coalesce(get_my_claim('sales_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with inventory_create can insert shipping methods" ON "shippingMethod"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('inventory_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with inventory_update can update shipping methods" ON "shippingMethod"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('inventory_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with inventory_delete can delete shipping methods" ON "shippingMethod"+ FOR DELETE+ USING (+ coalesce(get_my_claim('inventory_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "shippingTerm" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -186,11 +259,11 @@ CREATE TABLE "purchaseOrderLine" (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,+ CONSTRAINT "purchaseOrderLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,-- TODO: Add assetId foreign keyCONSTRAINT "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_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "purchaseOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE CASCADE,CONSTRAINT "purchaseOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE CASCADE);@@ -212,7 +285,7 @@ CREATE TABLE "purchaseOrderPayment" (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+ CONSTRAINT "purchaseOrderPayment_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON DELETE CASCADE ON UPDATE CASCADE);CREATE INDEX "purchaseOrderPayment_invoiceSupplierId_idx" ON "purchaseOrderPayment" ("invoiceSupplierId");diff --git a/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql b/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sqlindex e0f5b063be..b82c09871d 100644--- a/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql+++ b/packages/carbon-database/supabase/migrations/20230704175831_view-rls.sql@@ -1,9 +1,11 @@-- 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 "accounts_view" SET (security_invoker = on);+-- ALTER VIEW "account_categories_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);-- ALTER VIEW "purchase_order_suppliers_view" SET (security_invoker = on);-- ALTER VIEW "suppliers_view" SET (security_invoker = on);--- ALTER VIEW "parts_view" SET (security_invoker = on);\ No newline at end of file+-- ALTER VIEW "parts_view" SET (security_invoker = on);diff --git a/packages/carbon-database/supabase/migrations/20230705033431_warehouses.sql b/packages/carbon-database/supabase/migrations/20230705033431_warehouses.sqlnew file mode 100644index 0000000000..f1a3a5d5ad--- /dev/null+++ b/packages/carbon-database/supabase/migrations/20230705033431_warehouses.sql@@ -0,0 +1,65 @@++++-- inbound warehouse request+-- is created automatically when a source document is released+-- is automatically deleted when the inventory put away gets everything handled+-- has a type+-- has a source document number+++-- warehouse item journal+++-- purchase receipt+-- return receipt+-- transfer receipt++-- part ledger entry pur+-- records the quantity change++-- value entry+-- records the value change+-- has a posting date+-- has an item ledger entry type (e.g. purchase, return, transfer, etc)+-- has an entry type (e.g. direct cost, indirect cost, etc)+-- has an adjustment checkbox+-- has a document type (e.g. purchase receipt, purchase invoice, sales invoice, etc)+-- has a document number+-- has an entry number (serial)+-- has a cost amount actual+-- has a cost amount expected+-- has an actual cost posted to gl+-- has an expected cost posted to gl++-- value entry - gl entry relation+-- has a value entry+-- has a gl entry++-- gl entry+++-- warehouse entry+-- has an entry type (positive or negative)+-- has a part number+-- has a shelf+-- has a qty+++-- inventory put away+-- has a warehouse+-- has a source document (assembly order, purchase order, purchase return order, inbound transfer, outbound transfer, sales order return, etc)+-- has a posting date+++-- inventory put away lines+-- has a part number+-- has a description+-- has a shelf+-- has an order quantity+-- has a qty to handle+-- has a qty handled+-- has a calculated qty outstanding+-- has a uom and due date++diff --git a/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql b/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sqlnew file mode 100644index 0000000000..a1fda2f6d3--- /dev/null+++ b/packages/carbon-database/supabase/migrations/20230705033432_ledgers.sql@@ -0,0 +1,197 @@+CREATE TYPE "accountDocumentLedgerType" AS ENUM (+ 'Quote',+ 'Order',+ 'Invoice',+ 'Credit Memo',+ 'Blanket Order',+ 'Return Order'+);++CREATE TABLE "generalLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "accountNumber" TEXT NOT NULL,+ "description" TEXT,+ "amount" NUMERIC(19, 4) NOT NULL,+ "documentType" "accountDocumentLedgerType",+ "documentNumber" TEXT,+ "externalDocumentNumber" TEXT,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "generalLedger_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "generalLedger_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account"("number") ON UPDATE CASCADE ON DELETE SET NULL+);++CREATE INDEX "generalLedger_accountNumber_idx" ON "generalLedger" ("accountNumber");+CREATE INDEX "generalLedger_postingDate_idx" ON "generalLedger" ("postingDate");++ALTER TABLE "generalLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view general ledger entries" ON "generalLedger"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with accounting_create can insert general ledger entries" ON "generalLedger"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('accounting_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++-- delete and update are not availble for general ledger entries++CREATE TYPE "partLedgerType" AS ENUM (+ 'Purchase',+ 'Sale',+ 'Positive Adjmt.',+ 'Negative Adjmt.',+ 'Transfer',+ 'Consumption',+ 'Output',+ 'Assembly Consumption',+ 'Assembly Output'+);++CREATE TYPE "costLedgerType" AS ENUM (+ 'Direct Cost',+ 'Revaluation',+ 'Rounding',+ 'Indirect Cost',+ 'Variance',+ 'Total'+);++CREATE TYPE "partLedgerDocumentType" AS ENUM (+ 'Sales Shipment',+ 'Sales Invoice',+ 'Sales Return Receipt',+ 'Sales Credit Memo',+ 'Purchase Receipt',+ 'Purchase Invoice',+ 'Purchase Return Shipment',+ 'Purchase Credit Memo',+ 'Transfer Shipment',+ 'Transfer Receipt',+ 'Service Shipment',+ 'Service Invoice',+ 'Service Credit Memo',+ 'Posted Assembly',+ 'Inventory Receipt',+ 'Inventory Shipment',+ 'Direct Transfer'+);++CREATE TABLE "valueLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "partLedgerType" "partLedgerType" NOT NULL,+ "costLedgerType" "costLedgerType" NOT NULL,+ "adjustment" BOOLEAN NOT NULL DEFAULT false,+ "documentType" "partLedgerDocumentType",+ "documentNumber" TEXT,+ "costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "expectedCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "valueLedger_pkey" PRIMARY KEY ("id")+);++ALTER TABLE "valueLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view the value ledger" ON "valueLedger"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "valueLedgerAccountLedgerRelation" (+ "valueLedgerId" TEXT NOT NULL,+ "generalLedgerId" TEXT NOT NULL,++ CONSTRAINT "valueLedgerAccountLedgerRelation_pkey" PRIMARY KEY ("valueLedgerId", "generalLedgerId"),+ CONSTRAINT "valueLedgerAccountLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),+ CONSTRAINT "valueLedgerAccountLedgerRelation_generalLedgerId_fkey" FOREIGN KEY ("generalLedgerId") REFERENCES "generalLedger"("id")+);++ALTER TABLE "valueLedgerAccountLedgerRelation" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view the value ledger account relations" ON "valueLedgerAccountLedgerRelation"+ FOR SELECT+ USING (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true AND+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partLedger" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "entryNumber" SERIAL,+ "postingDate" DATE NOT NULL,+ "entryType" "partLedgerType" NOT NULL,+ "documentType" "partLedgerDocumentType",+ "documentNumber" TEXT,+ "partId" TEXT NOT NULL,+ "locationId" TEXT,+ "shelfId" TEXT,+ "quantity" NUMERIC(12, 4) NOT NULL,+ "invoicedQuantity" NUMERIC(12, 4) NOT NULL,+ "remainingQuantity" NUMERIC(12, 4) NOT NULL,+ "salesAmount" NUMERIC(12, 4) NOT NULL,+ "costAmount" NUMERIC(12, 4) NOT NULL,+ "open" BOOLEAN NOT NULL DEFAULT true,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),++ CONSTRAINT "partLedger_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "partLedger_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON UPDATE CASCADE ON DELETE CASCADE,+ CONSTRAINT "partLedger_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,+ CONSTRAINT "partLedger_shelfId_fkey" FOREIGN KEY ("shelfId") REFERENCES "shelf"("id") ON UPDATE CASCADE ON DELETE SET NULL+);++ALTER TABLE "partLedger" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger"+ FOR SELECT+ USING (+ (+ coalesce(get_my_claim('accounting_view')::boolean, false) = true OR+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ )+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++++CREATE OR REPLACE FUNCTION gl_transactions_by_account_number(+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),+ to_date DATE DEFAULT now()+)+RETURNS TABLE (+ "number" TEXT,+ "balance" NUMERIC(19, 4),+ "balanceAtDate" NUMERIC(19, 4),+ "netChange" NUMERIC(19, 4)+) LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public+AS $$+ BEGIN+ RETURN QUERY+ SELECT+ a."number",+ SUM(g."amount") AS "balance",+ SUM(CASE WHEN g."postingDate" <= to_date THEN g."amount" ELSE 0 END) AS "balanceAtDate",+ SUM(CASE WHEN g."postingDate" >= from_date AND g."postingDate" <= to_date THEN g."amount" ELSE 0 END) AS "netChange"+ FROM "account" a+ LEFT JOIN "generalLedger" g ON g."accountNumber" = a."number"+ GROUP BY a."number";+ END;+$$;++diff --git a/packages/carbon-react/package.json b/packages/carbon-react/package.jsonindex 65c8136f61..13a3bf4c3c 100644--- a/packages/carbon-react/package.json+++ b/packages/carbon-react/package.json@@ -33,6 +33,7 @@"@react-types/button": "^3.7.1","@react-types/calendar": "^3.1.0","@react-types/datepicker": "^3.2.0",+ "@tanstack/react-table": "^8.9.3","@tiptap/extension-color": "^2.0.0-beta.220","@tiptap/extension-list-item": "^2.0.0-beta.220","@tiptap/extension-text-style": "^2.0.0-beta.220",@@ -43,7 +44,7 @@"framer-motion": "^10.0.0","is-hotkey": "^0.2.0","react-colorful": "^5.6.1",- "react-icons": "^4.8.0",+ "react-icons": "^4.10.1","react-select": "^5.5.1"},"devDependencies": {diff --git a/packages/carbon-react/src/DataTable/DataTable.tsx b/packages/carbon-react/src/DataTable/DataTable.tsxnew file mode 100644index 0000000000..899bd66b49--- /dev/null+++ b/packages/carbon-react/src/DataTable/DataTable.tsx@@ -0,0 +1,149 @@+import {+ Box,+ Grid,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr,+ VStack,+} from "@chakra-ui/react";+import type {+ ColumnDef,+ ColumnFiltersState,+ SortingState,+ VisibilityState,+} from "@tanstack/react-table";+import {+ flexRender,+ getCoreRowModel,+ getFacetedRowModel,+ getFacetedUniqueValues,+ getFilteredRowModel,+ getPaginationRowModel,+ getSortedRowModel,+ useReactTable,+} from "@tanstack/react-table";+import { useState } from "react";++import { useColor } from "../hooks";+import { DataTablePagination } from "./DataTablePagination";++interface DataTableProps<TData, TValue> {+ columns: ColumnDef<TData, TValue>[];+ data: TData[];+}++const DataTable = <TData, TValue>({+ columns,+ data,+}: DataTableProps<TData, TValue>) => {+ const [rowSelection, setRowSelection] = useState({});+ const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});+ const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);+ const [sorting, setSorting] = useState<SortingState>([]);++ const table = useReactTable({+ data,+ columns,+ state: {+ sorting,+ columnVisibility,+ rowSelection,+ columnFilters,+ },+ initialState: {+ pagination: {+ pageSize: 25,+ },+ },+ enableRowSelection: true,+ onRowSelectionChange: setRowSelection,+ onSortingChange: setSorting,+ onColumnFiltersChange: setColumnFilters,+ onColumnVisibilityChange: setColumnVisibility,+ getCoreRowModel: getCoreRowModel(),+ getFilteredRowModel: getFilteredRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getFacetedRowModel: getFacetedRowModel(),+ getFacetedUniqueValues: getFacetedUniqueValues(),+ });++ return (+ <VStack spacing={0} w="full" h="full">+ <Box+ w="full"+ h="full"+ bg={useColor("white")}+ overflow="scroll"+ style={{ contain: "strict" }}+ >+ <Grid w="full" gridTemplateColumns="1fr">+ <Table>+ <Thead>+ {table.getHeaderGroups().map((headerGroup) => (+ <Tr key={headerGroup.id}>+ {headerGroup.headers.map((header) => {+ return (+ <Th+ key={header.id}+ colSpan={header.colSpan}+ px={4}+ py={2}+ whiteSpace="nowrap"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext()+ )}+ </Th>+ );+ })}+ </Tr>+ ))}+ </Thead>+ <Tbody>+ {table.getRowModel().rows?.length ? (+ table.getRowModel().rows.map((row) => (+ <Tr+ key={row.id}+ data-state={row.getIsSelected() && "selected"}+ >+ {row.getVisibleCells().map((cell) => (+ <Td+ key={cell.id}+ fontSize="sm"+ outline="none"+ px={4}+ py={2}+ whiteSpace="nowrap"+ >+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext()+ )}+ </Td>+ ))}+ </Tr>+ ))+ ) : (+ <Tr>+ <Td colSpan={columns.length} textAlign="center" h={24}>+ No results.+ </Td>+ </Tr>+ )}+ </Tbody>+ </Table>+ </Grid>+ </Box>+ <DataTablePagination table={table} />+ </VStack>+ );+};++export default DataTable;diff --git a/packages/carbon-react/src/DataTable/DataTableColumnHeader.tsx b/packages/carbon-react/src/DataTable/DataTableColumnHeader.tsxnew file mode 100644index 0000000000..1d8e58fce5--- /dev/null+++ b/packages/carbon-react/src/DataTable/DataTableColumnHeader.tsx@@ -0,0 +1,76 @@+import {+ Flex,+ HStack,+ Menu,+ MenuButton,+ MenuItem,+ MenuList,+ chakra,+} from "@chakra-ui/react";+import type { Column } from "@tanstack/react-table";+import { FaSortDown, FaSortUp, FaSort } from "react-icons/fa";+import {+ MdDisabledVisible,+ MdKeyboardArrowUp,+ MdKeyboardArrowDown,+} from "react-icons/md";++interface DataTableColumnHeaderProps<TData, TValue>+ extends React.HTMLAttributes<HTMLDivElement> {+ column: Column<TData, TValue>;+ title: string;+}++export function DataTableColumnHeader<TData, TValue>({+ column,+ title,+}: DataTableColumnHeaderProps<TData, TValue>) {+ if (!column.getCanSort()) {+ return <span>{title}</span>;+ }++ return (+ <Menu>+ <MenuButton as={HStack} cursor="pointer" justifyContent="space-between">+ <Flex+ justify="flex-start"+ align="center"+ fontSize="xs"+ color="gray.500"+ >+ {title}+ <chakra.span pl="4">+ {column.getIsSorted() === "desc" ? (+ <FaSortDown aria-label="sorted descending" />+ ) : column.getIsSorted() === "asc" ? (+ <FaSortUp aria-label="sorted ascending" />+ ) : (+ <FaSort aria-label="sort" />+ )}+ </chakra.span>+ </Flex>+ </MenuButton>+ <MenuList>+ <MenuItem+ icon={<MdKeyboardArrowUp />}+ onClick={() => column.toggleSorting(false)}+ >+ Asc+ </MenuItem>+ <MenuItem+ icon={<MdKeyboardArrowDown />}+ onClick={() => column.toggleSorting(true)}+ >+ Desc+ </MenuItem>+ <MenuItem+ icon={<MdDisabledVisible />}+ disabled={!column.getCanHide()}+ onClick={() => column.toggleVisibility(false)}+ >+ Hide+ </MenuItem>+ </MenuList>+ </Menu>+ );+}diff --git a/packages/carbon-react/src/DataTable/DataTablePagination.tsx b/packages/carbon-react/src/DataTable/DataTablePagination.tsxnew file mode 100644index 0000000000..6874dfb936--- /dev/null+++ b/packages/carbon-react/src/DataTable/DataTablePagination.tsx@@ -0,0 +1,88 @@+import {+ Button,+ Flex,+ HStack,+ Menu,+ MenuButton,+ MenuItem,+ MenuList,+} from "@chakra-ui/react";+import type { Table } from "@tanstack/react-table";+import { BsChevronLeft, BsChevronRight } from "react-icons/bs";+import { useColor } from "../hooks";++interface DataTablePaginationProps<TData> {+ table: Table<TData>;+}++export function DataTablePagination<TData>({+ table,+}: DataTablePaginationProps<TData>) {+ const pageSizes = [15, 25, 50, 100];+ const pageSizeLabel = "results per page";+ const borderColor = useColor("gray.200");++ const scrollToTop = () => {+ window.scrollTo({ top: 0, behavior: "smooth" });+ };++ return (+ <HStack+ align="center"+ bg={useColor("white")}+ borderTopColor={borderColor}+ borderTopWidth={1}+ borderTopStyle="solid"+ justify="space-between"+ px={4}+ py={2}+ spacing="6"+ w="full"+ zIndex={1}+ >+ <Menu>+ <MenuButton as={Button} variant="ghost">+ {table.getState().pagination.pageSize} {pageSizeLabel}+ </MenuButton>+ <MenuList fontSize="sm" boxShadow="xl" minW={48}>+ {pageSizes.map((size) => (+ <MenuItem+ key={`${size}`}+ onClick={() => {+ table.setPageSize(Number(size));+ }}+ >+ {size} {pageSizeLabel}+ </MenuItem>+ ))}+ </MenuList>+ </Menu>+ <HStack spacing={2}>+ <Flex fontSize="sm" h={8} fontWeight="medium" alignItems="center">+ Page {table.getState().pagination.pageIndex + 1} of{" "}+ {table.getPageCount()}+ </Flex>+ <Button+ isDisabled={!table.getCanPreviousPage()}+ onClick={() => {+ table.previousPage();+ scrollToTop();+ }}+ leftIcon={<BsChevronLeft />}+ >+ Previous+ </Button>+ <Button+ isDisabled={!table.getCanNextPage()}+ onClick={() => {+ table.nextPage();+ scrollToTop();+ }}+ rightIcon={<BsChevronRight />}+ >+ Next+ </Button>+ </HStack>+ </HStack>+ );+}diff --git a/packages/carbon-react/src/DataTable/index.ts b/packages/carbon-react/src/DataTable/index.tsnew file mode 100644index 0000000000..b710daa120--- /dev/null+++ b/packages/carbon-react/src/DataTable/index.ts@@ -0,0 +1,5 @@+import DataTable from "./DataTable";+import { DataTableColumnHeader } from "./DataTableColumnHeader";++export default DataTable;+export { DataTableColumnHeader };diff --git a/packages/carbon-react/src/Inputs/Date/DatePicker.tsx b/packages/carbon-react/src/Inputs/Date/DatePicker.tsxindex ae96dfc5d8..2d3c9950f2 100644--- a/packages/carbon-react/src/Inputs/Date/DatePicker.tsx+++ b/packages/carbon-react/src/Inputs/Date/DatePicker.tsx@@ -2,7 +2,13 @@ import { useRef } from "react";import { useDatePickerState } from "@react-stately/datepicker";import { useDatePicker } from "@react-aria/datepicker";import { MdOutlineCalendarToday, MdOutlineDoNotDisturb } from "react-icons/md";-import { Box, Icon, InputGroup, InputRightElement } from "@chakra-ui/react";+import {+ Box,+ Icon,+ InputGroup,+ InputRightElement,+ useOutsideClick,+} from "@chakra-ui/react";import type { DatePickerProps } from "@react-types/datepicker";import type { CalendarDate } from "@internationalized/date";@@ -21,6 +27,11 @@ const DatePicker = (props: DatePickerProps<CalendarDate>) => {const { groupProps, fieldProps, buttonProps, dialogProps, calendarProps } =useDatePicker(props, state, ref);+ useOutsideClick({+ ref,+ handler: () => state.setOpen(false),+ });+return (<Boxposition="relative"diff --git a/packages/carbon-react/src/Theme/theme.ts b/packages/carbon-react/src/Theme/theme.tsindex af7cf9f0a3..cd303914be 100644--- a/packages/carbon-react/src/Theme/theme.ts+++ b/packages/carbon-react/src/Theme/theme.ts@@ -95,6 +95,13 @@ export const theme = {defaultProps: {borderRadius: "md",},+ sizes: {+ sm: {+ field: {+ borderRadius: "md",+ },+ },+ },variants: {outline: focusRingOutlined,filled: focusRingFilled,diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsxindex 2e0f20ffaa..924694c3de 100644--- a/packages/carbon-react/src/index.tsx+++ b/packages/carbon-react/src/index.tsx@@ -1,5 +1,6 @@import Button from "./Button";import Count from "./Count";+import DataTable, { DataTableColumnHeader } from "./DataTable";import Dot from "./Dot";import HTML from "./HTML";import type { OptionBase, OptionProps, GroupBase } from "./Inputs";@@ -38,6 +39,8 @@ export {ContextMenu,Count,CreatableSelect,+ DataTable,+ DataTableColumnHeader,DatePicker,DateTimePicker,DateRangePicker,diff --git a/packages/carbon-utils/src/date.ts b/packages/carbon-utils/src/date.tsindex 81a5fa0e64..788027044c 100644--- a/packages/carbon-utils/src/date.ts+++ b/packages/carbon-utils/src/date.ts@@ -40,3 +40,9 @@ export function formatTimeAgo(isoString: string) {duration /= division.amount;}}++export function getDateNYearsAgo(n: number) {+ const date = new Date();+ date.setFullYear(date.getFullYear() - n);+ return date;+}diff --git a/www/package.json b/www/package.jsonindex 621e5e40d0..843bd16e0c 100644--- a/www/package.json+++ b/www/package.json@@ -15,7 +15,7 @@"nextra-theme-docs": "^2.2.19","react": "^18.2.0","react-dom": "^18.2.0",- "react-icons": "^4.8.0"+ "react-icons": "^4.10.1"},"devDependencies": {"@carbon/tsconfig": "*",diff --git a/yarn.lock b/yarn.lockindex 7fad1c361e..18d0d961b4 100644--- a/yarn.lock+++ b/yarn.lock@@ -3700,17 +3700,17 @@dependencies:defer-to-connect "^2.0.0"-"@tanstack/react-table@^8.7.3":- version "8.7.3"- resolved "https://registry.npmjs.org/@tanstack/react-table/-/react-table-8.7.3.tgz"- integrity sha512-4hUSl10UGEp3DTS0sKe8ZEr0MYKEHXKXzAolzjs+w+vjVIimFICuyIjxisY6rLOvRVNXbwF5Pjyr+1YC6ptpZw==+"@tanstack/react-table@^8.9.3":+ version "8.9.3"+ resolved "https://registry.yarnpkg.com/@tanstack/react-table/-/react-table-8.9.3.tgz#03a52e9e15f65c82a8c697a445c42bfca0c5cfc4"+ integrity sha512-Ng9rdm3JPoSCi6cVZvANsYnF+UoGVRxflMb270tVj0+LjeT/ZtZ9ckxF6oLPLcKesza6VKBqtdF9mQ+vaz24Aw==dependencies:- "@tanstack/table-core" "8.7.3"+ "@tanstack/table-core" "8.9.3"-"@tanstack/[email protected]":- version "8.7.3"- resolved "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.7.3.tgz"- integrity sha512-P+LKZuytLRUEKv0zMKFpYCLb9ZRiZ+kaFXh99HS6gOEX58tq41PltQ2BhTBe2UPlB8O6IQFsilKhx94/6w3ZMg==+"@tanstack/[email protected]":+ version "8.9.3"+ resolved "https://registry.yarnpkg.com/@tanstack/table-core/-/table-core-8.9.3.tgz#991da6b015f6200fdc841c48048bee5e197f6a46"+ integrity sha512-NpHZBoHTfqyJk0m/s/+CSuAiwtebhYK90mDuf5eylTvgViNOujiaOaxNDxJkQQAsVvHWZftUGAx1EfO1rkKtLg=="@testing-library/dom@^8.11.1":version "8.19.0"@@ -12684,6 +12684,11 @@ react-focus-lock@^2.9.2:use-callback-ref "^1.3.0"use-sidecar "^1.1.2"+react-icons@^4.10.1:+ version "4.10.1"+ resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-4.10.1.tgz#3f3b5eec1f63c1796f6a26174a1091ca6437a500"+ integrity sha512-/ngzDP/77tlCfqthiiGNZeYFACw85fUjZtLbedmJ5DTlNDIwETxhwBzdOJ21zj4iJdvc0J3y7yOsX3PpxAJzrw==+react-icons@^4.8.0:version "4.8.0"resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-4.8.0.tgz#621e900caa23b912f737e41be57f27f6b2bff445"