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
Parts (#27)
Brad Barbinf42de5911094
diff --git a/.env.example b/.env.exampleindex 79e3eab06d..4dec003daf 100644--- a/.env.example+++ b/.env.example@@ -1,4 +1,4 @@-REDIS_URL="redis://localhost:6379"+REDIS_URL="redis://localhost:6389"SESSION_SECRET="super-duper-s3cret"SUPABASE_ANON_PUBLIC="************"SUPABASE_SERVICE_ROLE="***********"diff --git a/SCHEMA.md b/SCHEMA.mdindex 3623a48a0b..5038fd47eb 100644--- a/SCHEMA.md+++ b/SCHEMA.md@@ -291,6 +291,9 @@ CREATE TABLE "user" (CONSTRAINT "user_pkey" PRIMARY KEY ("id"));+INSERT INTO "user" ("id", "email", "firstName", "lastName")+VALUES ('system', '[email protected]', 'System', 'Operation');+CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");CREATE INDEX "index_user_fullName" ON "user"("fullName");@@ -784,6 +787,8 @@ CREATE TABLE "supplierContact" (CONSTRAINT "supplierContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "supplierContact_supplierId_index" ON "supplierContact"("supplierId");+CREATE TABLE "supplierAccount" ("id" TEXT NOT NULL,"supplierId" TEXT NOT NULL,@@ -793,6 +798,8 @@ CREATE TABLE "supplierAccount" (CONSTRAINT "supplierAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+CREATE INDEX "supplierAccount_supplierId_index" ON "supplierAccount"("supplierId");+CREATE TABLE "customerStatus" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -863,6 +870,8 @@ CREATE TABLE "customerContact" (CONSTRAINT "customerContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "customerContact_customerId_index" ON "customerContact"("customerId");+CREATE TABLE "customerAccount" ("id" TEXT NOT NULL,"customerId" TEXT NOT NULL,@@ -872,6 +881,8 @@ CREATE TABLE "customerAccount" (CONSTRAINT "customerAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+CREATE INDEX "customerAccount_customerId_index" ON "customerAccount"("customerId");+```@@ -1358,13 +1369,13 @@ NOTIFY pgrst, 'reload schema';```sql-CREATE TYPE search_entity AS enum ('Resource', 'Person', 'Customer', 'Supplier', 'Job', 'Part', 'Purchase Order', 'Sales Order', 'Document');+CREATE TYPE "searchEntity" AS enum ('Resource', 'Person', 'Customer', 'Supplier', 'Job', 'Part', 'Purchase Order', 'Sales Order', 'Document');CREATE TABLE search (id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,name TEXT NOT NULL,description TEXT DEFAULT '',- entity search_entity,+ entity "searchEntity",uuid TEXT,link TEXT NOT NULL);@@ -2324,6 +2335,36 @@ CREATE TABLE "department" (CONSTRAINT "department_parentDepartmentId_fkey" FOREIGN KEY ("parentDepartmentId") REFERENCES "department"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "department" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view departments" ON "department"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert departments" ON "department"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update departments" ON "department"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete departments" ON "department"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "workCellType" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -2343,6 +2384,36 @@ CREATE TABLE "workCellType" (CONSTRAINT "workCellType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "workCellType" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view work cell types" ON "workCellType"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert work cell types" ON "workCellType"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update work cell types" ON "workCellType"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete work cell types" ON "workCellType"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "workCell" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -2365,6 +2436,36 @@ CREATE TABLE "workCell" (CONSTRAINT "uq_workCell_name_departmentId" UNIQUE ("name", "departmentId"));+ALTER TABLE "workCell" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view work cells" ON "workCell"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert work cells" ON "workCell"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update work cells" ON "workCell"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete work cells" ON "workCell"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+ALTER TABLE "employeeJob"ADD COLUMN "departmentId" TEXT REFERENCES "department"("id") ON DELETE CASCADE ON UPDATE CASCADE,ADD COLUMN "workCellId" TEXT REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE;@@ -2383,6 +2484,36 @@ CREATE TABLE "crew" (CONSTRAINT "crew_workCellId_fkey" FOREIGN KEY ("workCellId") REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "crew" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view crews" ON "crew"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert crews" ON "crew"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update crews" ON "crew"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete crews" ON "crew"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "crewAbility" ("id" TEXT NOT NULL DEFAULT xid(),"crewId" TEXT NOT NULL,@@ -2394,6 +2525,37 @@ CREATE TABLE "crewAbility" (CONSTRAINT "crewAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "crewAbility" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view crew abilities" ON "crewAbility"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (get_my_claim('resources_view')::boolean) = true+ );++CREATE POLICY "Employees with resources_create can insert crew abilities" ON "crewAbility"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update crew abilities" ON "crewAbility"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete crew abilities" ON "crewAbility"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "equipmentType" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -2413,6 +2575,36 @@ CREATE TABLE "equipmentType" (CONSTRAINT "equipmentType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "equipmentType" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view equipment types" ON "equipmentType"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert equipment types" ON "equipmentType"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update equipment types" ON "equipmentType"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete equipment types" ON "equipmentType"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "equipment" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -2431,12 +2623,77 @@ CREATE TABLE "equipment" (CONSTRAINT "equipment_pkey" PRIMARY KEY ("id"),CONSTRAINT "equipment_equipmentTypeId_fkey" FOREIGN KEY ("equipmentTypeId") REFERENCES "equipmentType"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "equipment_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_workCellId_fkey" FOREIGN KEY ("workCellId") REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);--- TODO: insert/update search results with triggers+ALTER TABLE "equipment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view equipment" ON "equipment"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert equipment" ON "equipment"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update equipment" ON "equipment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete equipment" ON "equipment"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE FUNCTION public.create_equipment_search_result()+RETURNS TRIGGER AS $$+DECLARE+ equipment_type TEXT;+BEGIN+ equipment_type := (SELECT u."name" FROM public."equipmentType" et WHERE et.id = new."equipmentTypeId");+ INSERT INTO public.search(name, description, entity, uuid, link)+ VALUES (new.name, COALESCE(new.description, '') || ' ' || equipment_type, 'Resource', new.id, '/x/resources/equipment/list/' || new."equipmentTypeId" || '/' || new.id);+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_equipment_search_result+ AFTER INSERT on public.equipment+ FOR EACH ROW EXECUTE PROCEDURE public.create_equipment_search_result();++CREATE FUNCTION public.update_equipment_search_result()+RETURNS TRIGGER AS $$+DECLARE+ equipment_type TEXT;+BEGIN+ IF (old.name <> new.name OR old.description <> new.description OR old."equipmentTypeId" <> new."equipmentTypeId") THEN+ equipment_type := (SELECT u."name" FROM public."equipmentType" et WHERE et.id = new."equipmentTypeId");+ UPDATE public.search SET name = new.name, description = COALESCE(new.description, '') || ' ' || equipment_type+ WHERE entity = 'Resource' AND uuid = new.id;+ END IF;+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER update_equipment_search_result+ AFTER UPDATE on public.equipment+ FOR EACH ROW EXECUTE PROCEDURE public.update_equipment_search_result();++```@@ -2479,6 +2736,36 @@ CREATE TABLE "holiday" ();CREATE VIEW "holiday_years" AS SELECT DISTINCT "year" FROM "holiday";++ALTER TABLE "holiday" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view holidays" ON "holiday"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert holidays" ON "holiday"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update holidays" ON "holiday"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete holidays" ON "holiday"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );```@@ -2557,6 +2844,37 @@ CREATE TABLE "contractor" (CONSTRAINT "contractor_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));+ALTER TABLE "contractor" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view contractors" ON "contractor"+ FOR SELECT+ USING (+ coalesce(get_my_claim('resources_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert contractors" ON "contractor"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update contractors" ON "contractor"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete contractors" ON "contractor"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "contractorAbility" ("contractorId" TEXT NOT NULL,"abilityId" TEXT NOT NULL,@@ -2569,13 +2887,44 @@ CREATE TABLE "contractorAbility" (CONSTRAINT "contractorAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"));-CREATE VIEW "contractors_query" AS- SELECT- p.id AS "supplierContactId",- p."active",- p."hoursPerWeek",- s.id AS "supplierId",- s.name AS "supplierName",+ALTER TABLE "contractorAbility" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view contractorAbilities" ON "contractorAbility"+ FOR SELECT+ USING (+ coalesce(get_my_claim('resources_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert contractorAbilities" ON "contractorAbility"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update contractorAbilities" ON "contractorAbility"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete contractorAbilities" ON "contractorAbility"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE VIEW "contractors_query" AS+ SELECT+ p.id AS "supplierContactId",+ p."active",+ p."hoursPerWeek",+ s.id AS "supplierId",+ s.name AS "supplierName",c."firstName",c."lastName",c."email",@@ -2594,3 +2943,890 @@ CREATE VIEW "contractors_query" AS;```+++## `chart-of-accounts`++```sql+CREATE TABLE "currency" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "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,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "currency_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "currency_code_key" UNIQUE ("code"),+ 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');++CREATE INDEX "currency_code_index" ON "currency" ("code");++ALTER TABLE "currency" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view currencies" ON "currency"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );++CREATE POLICY "Employees with accounting_create can insert currencies" ON "currency"+ 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 currencies" ON "currency"+ 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 currencies" ON "currency"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "glAccountCategory" AS ENUM (+ 'Bank',+ 'Accounts Receivable',+ 'Inventory',+ 'Other Current Asset',+ 'Fixed Asset',+ 'Accumulated Depreciation',+ 'Other Asset',+ 'Accounts Payable',+ 'Other Current Liability',+ 'Long Term Liability',+ 'Equity - No Close',+ 'Equity - Close',+ 'Retained Earnings',+ 'Income',+ 'Cost of Goods Sold',+ 'Expense',+ 'Other Income',+ 'Other Expense'+);++CREATE TYPE "glAccountType" AS ENUM (+ 'Balance Sheet',+ 'Income Statement'+);++CREATE TYPE "glNormalBalance" AS ENUM (+ 'Debit',+ 'Credit'+);++CREATE TABLE "accountCategory" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "category" "glAccountCategory" NOT NULL,+ "type" "glAccountType" NOT NULL,+ "normalBalance" "glNormalBalance" NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "accountCategory_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "accountCategory_category_type_key" 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")+VALUES+ ('Bank', 'Balance Sheet', 'Credit', 'system'),+ ('Accounts Receivable', 'Balance Sheet', 'Credit', 'system'),+ ('Inventory', 'Balance Sheet', 'Debit', 'system'),+ ('Other Current Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Fixed Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Accumulated Depreciation', 'Balance Sheet', 'Credit', 'system'),+ ('Other Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Accounts Payable', 'Balance Sheet', 'Debit', 'system'),+ ('Other Current Liability', 'Balance Sheet', 'Debit', 'system'),+ ('Long Term Liability', 'Balance Sheet', 'Debit', 'system'),+ ('Equity - No Close', 'Balance Sheet', 'Credit', 'system'),+ ('Equity - Close', 'Balance Sheet', 'Credit', 'system'),+ ('Retained Earnings', 'Balance Sheet', 'Credit', 'system'),+ ('Income', 'Income Statement', 'Credit', 'system'),+ ('Cost of Goods Sold', 'Income Statement', 'Debit', 'system'),+ ('Expense', 'Income Statement', 'Debit', 'system'),+ ('Other Income', 'Income Statement', 'Credit', 'system'),+ ('Other Expense', 'Income Statement', 'Debit', 'system');++ALTER TABLE "accountCategory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view account categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "consolidatedRate" AS ENUM (+ 'Average',+ 'Current',+ 'Historical'+);++CREATE TABLE "account" (+ "number" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "accountCategoryId" TEXT,+ "controlAccount" BOOLEAN NOT NULL DEFAULT false,+ "cashAccount" BOOLEAN NOT NULL DEFAULT false,+ "consolidatedRate" "consolidatedRate",+ "currencyCode" TEXT,+ "parentAccountNumber" TEXT,+ "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_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');++ALTER TABLE "account" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view accounts" ON "account"+ 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 accounts" ON "account"+ 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 accounts" ON "account"+ 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 accounts" ON "account"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+```++++## `parts`++```sql+CREATE TABLE "partGroup" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "description" TEXT,+ "salesAccountId" TEXT,+ "discountAccountId" TEXT,+ "inventoryAccountId" TEXT,+ "costOfGoodsSoldLaborAccountId" TEXT,+ "costOfGoodsSoldMaterialAccountId" TEXT,+ "costOfGoodsSoldOverheadAccountId" TEXT,+ "costOfGoodsSoldSubcontractorAccountId" TEXT,+ "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 "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_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++ALTER TABLE "partGroup" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with parts_view can view part groups" ON "partGroup"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with parts_create can insert part groups" ON "partGroup"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update part groups" ON "partGroup"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete part groups" ON "partGroup"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "partType" AS ENUM (+ 'Inventory',+ 'Non-Inventory',+ 'Service'+);++CREATE TYPE "partReplenishmentSystem" AS ENUM (+ 'Buy',+ 'Make',+ 'Buy and Make'+);++CREATE TYPE "partManufacturingPolicy" AS ENUM (+ 'Make to Order',+ 'Make to Stock'+);+++CREATE TYPE "partCostingMethod" AS ENUM (+ 'Standard',+ 'Average',+ 'LIFO',+ 'FIFO'+);++CREATE TYPE "partReorderingPolicy" AS ENUM (+ 'Manual Reorder',+ 'Demand-Based Reorder',+ 'Fixed Reorder Quantity',+ 'Maximum Quantity'+);++CREATE TABLE "unitOfMeasure" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "code" TEXT NOT NULL,+ "name" 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 "unitOfMeasure_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "unitOfMeasure_code_key" UNIQUE ("code"),+ CONSTRAINT "unitOfMeasure_code_check" CHECK (char_length("code") <= 3),+ CONSTRAINT "unitOfMeasure_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "unitOfMeasure_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "unitOfMeasure_code_index" ON "unitOfMeasure"("code");++INSERT INTO "unitOfMeasure" ("code", "name", "createdBy")+VALUES+( 'EA', 'Each', 'system'),+( 'PCS', 'Pieces', 'system');++ALTER TABLE "unitOfMeasure" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );+++CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "part" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "blocked" BOOLEAN NOT NULL DEFAULT false,+ "replenishmentSystem" "partReplenishmentSystem" NOT NULL,+ "partGroupId" TEXT NOT NULL,+ "partType" "partType" NOT NULL,+ "manufacturerPartNumber" TEXT,+ "unitOfMeasureCode" TEXT NOT NULL,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "approved" BOOLEAN NOT NULL DEFAULT false,+ "approvedBy" TEXT,+ "fromDate" DATE,+ "toDate" DATE,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "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_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"),+ CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view parts" ON "part"+ FOR SELECT+ USING (+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_create can insert parts" ON "part"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update parts" ON "part"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete parts" ON "part"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE FUNCTION public.create_part_search_result()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public.search(name, description, entity, uuid, link)+ VALUES (new.id, new.id || ' ' || new.name || ' ' || COALESCE(new.description, ''), 'Part', new.id, '/x/part/' || new.id);+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_part_search_result+ AFTER INSERT on public.part+ FOR EACH ROW EXECUTE PROCEDURE public.create_part_search_result();++CREATE FUNCTION public.create_part_related_records()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."partCost"("partId", "costingMethod", "createdBy")+ VALUES (new.id, 'Standard', new."createdBy");++ INSERT INTO public."partReplenishment"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partPlanning"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partInventory"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")+ -- TODO: get default currency+ VALUES (new.id, 'USD', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_part_related_records+ AFTER INSERT on public.part+ FOR EACH ROW EXECUTE PROCEDURE public.create_part_related_records();++CREATE FUNCTION public.update_part_search_result()+RETURNS TRIGGER AS $$+BEGIN+ IF (old.name <> new.name OR old.description <> new.description) THEN+ UPDATE public.search SET name = new.name, description = new.id || ' ' || new.name || ' ' || COALESCE(new.description, '')+ WHERE entity = 'Part' AND uuid = new.id;+ END IF;+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER update_part_search_result+ AFTER UPDATE on public.customer+ FOR EACH ROW EXECUTE PROCEDURE public.update_part_search_result();+++CREATE TABLE "partCost" (+ "partId" TEXT NOT NULL,+ "costingMethod" "partCostingMethod" NOT NULL,+ "standardCost" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "unitCost" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "salesAccountId" TEXT,+ "discountAccountId" TEXT,+ "inventoryAccountId" TEXT,+ "costIsAdjusted" BOOLEAN NOT NULL DEFAULT false,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "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 "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partCost_partId_index" ON "partCost" ("partId");++ALTER TABLE "partCost" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part costs" ON "partCost"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part costs" ON "partCost"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partUnitSalePrice" (+ "partId" TEXT NOT NULL,+ "unitSalePrice" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "currencyCode" TEXT NOT NULL,+ "salesUnitOfMeasureCode" TEXT,+ "salesBlocked" BOOLEAN NOT NULL DEFAULT false,+ "priceIncludesTax" BOOLEAN NOT NULL DEFAULT false,+ "allowInvoiceDiscount" 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 "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_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")+);++CREATE INDEX "partUnitSalePrice_partId_index" ON "partUnitSalePrice"("partId");++ALTER TABLE "partUnitSalePrice" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part sale prices" ON "partUnitSalePrice"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part sale prices" ON "partUnitSalePrice"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partReplenishment" (+ "partId" TEXT NOT NULL,+ "supplierId" TEXT,+ "supplierPartNumber" TEXT,+ "purchasingLeadTime" INTEGER NOT NULL DEFAULT 0,+ "purchasingUnitOfMeasureCode" TEXT,+ "purchasingBlocked" BOOLEAN NOT NULL DEFAULT false,+ "manufacturingPolicy" "partManufacturingPolicy" NOT NULL DEFAULT 'Make to Stock',+ "manufacturingLeadTime" INTEGER NOT NULL DEFAULT 0,+ "manufacturingBlocked" BOOLEAN NOT NULL DEFAULT false,+ "requiresConfiguration" BOOLEAN NOT NULL DEFAULT false,+ "scrapPercentage" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "lotSize" INTEGER,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partReplenishment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,+ CONSTRAINT "partReplenishment_purchaseUnitOfMeasureId_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,+ CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partReplenishment_partId_index" ON "partReplenishment" ("partId");+CREATE INDEX "partReplenishment_supplierId_index" ON "partReplenishment" ("supplierId");++ALTER TABLE "partReplenishment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part costs" ON "partReplenishment"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part costs" ON "partReplenishment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view parts they created or supply" ON "part"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Supliers with parts_create can insert parts" ON "part"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ );++CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "part"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "part"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "partCost"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update parts costs that they supply" ON "partCost"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_view can view part replenishments they supply" ON "partReplenishment"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update parts replenishments that they supply" ON "partReplenishment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ );++CREATE TABLE "shelf" (+ "id" TEXT NOT NULL,+ "locationId" TEXT,+ "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 "shelf_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("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");++ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view shelves" ON "shelf"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );+++CREATE POLICY "Employees with parts_create can insert shelves" ON "shelf"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update shelves" ON "shelf"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "partPlanning" (+ "partId" TEXT NOT NULL,+ "reorderingPolicy" "partReorderingPolicy" NOT NULL DEFAULT 'Demand-Based Reorder',+ "critical" BOOLEAN NOT NULL DEFAULT false,+ "safetyStockQuantity" INTEGER NOT NULL DEFAULT 0,+ "safetyStockLeadTime" INTEGER NOT NULL DEFAULT 0,+ "demandAccumulationPeriod" INTEGER NOT NULL DEFAULT 0,+ "demandReschedulingPeriod" INTEGER NOT NULL DEFAULT 0,+ "demandAccumulationIncludesInventory" BOOLEAN NOT NULL DEFAULT false,+ "reorderPoint" INTEGER NOT NULL DEFAULT 0,+ "reorderQuantity" INTEGER NOT NULL DEFAULT 0,+ "reorderMaximumInventory" INTEGER NOT NULL DEFAULT 0,+ "reorderOverflowLevel" INTEGER NOT NULL DEFAULT 0,+ "reorderTimeBucket" INTEGER NOT NULL DEFAULT 5,+ "minimumOrderQuantity" INTEGER NOT NULL DEFAULT 0,+ "maximumOrderQuantity" INTEGER NOT NULL DEFAULT 0,+ "orderMultiple" INTEGER NOT NULL DEFAULT 1,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partPlanning_partId_index" ON "partPlanning" ("partId");+ALTER TABLE "partPlanning" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part planning" ON "partPlanning"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "partInventory" (+ "partId" TEXT NOT NULL,+ "shelfId" TEXT,+ "stockoutWarning" BOOLEAN NOT NULL DEFAULT true,+ "unitVolume" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "unitWeight" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),+ CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE 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")+);++CREATE INDEX "partInventory_partId_index" ON "partInventory" ("partId");+CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("shelfId");++ALTER TABLE "partInventory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part planning" ON "partInventory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part planning" ON "partInventory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );+```+diff --git a/apps/carbon/app/components/Form/CreatableSelect.tsx b/apps/carbon/app/components/Form/CreatableSelect.tsxnew file mode 100644index 0000000000..17faa1b813--- /dev/null+++ b/apps/carbon/app/components/Form/CreatableSelect.tsx@@ -0,0 +1,105 @@+import { CreatableSelect } from "@carbon/react";+import {+ Box,+ FormControl,+ FormErrorMessage,+ FormHelperText,+ FormLabel,+} from "@chakra-ui/react";++import { useControlField, useField } from "remix-validated-form";++export type SelectProps = {+ name: string;+ label?: string;+ options: { value: string | number; label: string }[];+ helperText?: string;+ isReadOnly?: boolean;+ isLoading?: boolean;+ placeholder?: string;+ onChange?: (+ newValue: { value: string | number; label: string } | null+ ) => void;+ onUsingCreatedChanged?: (usingCreated: boolean) => void;+};++const Select = ({+ name,+ label,+ options,+ helperText,+ isLoading,+ isReadOnly,+ placeholder,+ onChange,+ onUsingCreatedChanged,+ ...props+}: SelectProps) => {+ const { getInputProps, error } = useField(name);+ const [value, setValue] = useControlField<string>(name);++ const handleChange = (+ newValue: { value: string | number; label: string } | null+ ) => {+ setValue(newValue?.value.toString() ?? "");+ onChange?.(newValue);+ onUsingCreatedChanged?.(false);+ };++ const handleCreate = (inputValue: string) => {+ setValue(inputValue);+ onChange?.({ value: inputValue, label: inputValue });+ onUsingCreatedChanged?.(true);+ };++ const optionsWithCreation = options.find((option) => option.value === value)+ ? options+ : options.concat({ value, label: value });++ const selectedValue = optionsWithCreation.find(+ (option) => option.value === value+ );++ // TODO: hack for default value+ return optionsWithCreation.length > 0 ? (+ <FormControl isInvalid={!!error}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ <CreatableSelect+ {...getInputProps({+ // @ts-ignore+ id: name,+ })}+ {...props}+ value={selectedValue}+ isClearable+ isLoading={isLoading}+ options={options}+ placeholder={placeholder}+ // @ts-ignore+ w="full"+ onCreateOption={handleCreate}+ onChange={handleChange}+ />+ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}+ </FormControl>+ ) : (+ <Box>+ {label && <FormLabel>{label}</FormLabel>}+ <CreatableSelect+ isDisabled+ isLoading={isLoading}+ options={[]}+ // @ts-ignore+ w="full"+ />+ </Box>+ );+};++Select.displayName = "Select";++export default Select;diff --git a/apps/carbon/app/components/Form/Currency.tsx b/apps/carbon/app/components/Form/Currency.tsxnew file mode 100644index 0000000000..e895b5bc57--- /dev/null+++ b/apps/carbon/app/components/Form/Currency.tsx@@ -0,0 +1,112 @@+import { Select } from "@carbon/react";+import {+ Box,+ 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 { getCurrenciesList } from "~/modules/accounting";+import type { SelectProps } from "./Select";++type CurrencySelectProps = Omit<SelectProps, "options"> & {+ currency?: string;+};++const Currency = ({+ name,+ label = "Currency",+ currency,+ helperText,+ isLoading,+ isReadOnly,+ placeholder = "Select Currency",+ onChange,+ ...props+}: CurrencySelectProps) => {+ const { error, defaultValue } = useField(name);+ const [value, setValue] = useControlField<string | undefined>(name);++ const currencyFetcher =+ useFetcher<Awaited<ReturnType<typeof getCurrenciesList>>>();++ useEffect(() => {+ currencyFetcher.load(`/api/accounting/currencies`);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const options = useMemo(+ () =>+ currencyFetcher.data?.data+ ? currencyFetcher.data?.data.map((c) => ({+ value: c.code,+ label: c.name,+ }))+ : [],+ [currencyFetcher.data]+ );++ const handleChange = (selection: {+ value: string | number;+ label: string;+ }) => {+ const newValue = (selection.value as string) || undefined;+ setValue(newValue);+ if (onChange && typeof onChange === "function") {+ onChange(selection);+ }+ };++ const controlledValue = useMemo(+ // @ts-ignore+ () => options.find((option) => option.value === value),+ [value, options]+ );++ // so that we can call onChange on load+ useEffect(() => {+ if (controlledValue && controlledValue.value === defaultValue) {+ handleChange(controlledValue);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [controlledValue?.value]);++ // TODO: hack for default value+ return currencyFetcher.state !== "loading" ? (+ <FormControl isInvalid={!!error}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ <input type="hidden" name={name} id={name} value={value} />+ <Select+ {...props}+ value={controlledValue}+ isLoading={isLoading}+ options={options}+ placeholder={placeholder}+ // @ts-ignore+ onChange={handleChange}+ />+ {error ? (+ <FormErrorMessage>{error}</FormErrorMessage>+ ) : (+ helperText && <FormHelperText>{helperText}</FormHelperText>+ )}+ </FormControl>+ ) : (+ <Box>+ {label && <FormLabel>{label}</FormLabel>}+ <Select+ isDisabled+ isLoading={isLoading}+ options={[]}+ //@ts-ignore+ />+ </Box>+ );+};++Currency.displayName = "Currency";++export default Currency;diff --git a/apps/carbon/app/components/Form/Employees.tsx b/apps/carbon/app/components/Form/Employees.tsxindex 15ee836895..6237ff30ef 100644--- a/apps/carbon/app/components/Form/Employees.tsx+++ b/apps/carbon/app/components/Form/Employees.tsx@@ -8,7 +8,7 @@ import { useState } from "react";import { useField } from "remix-validated-form";import { UserSelect } from "../Selectors";import type {- SelectionItemInterface,+ IndividualOrGroup,UserSelectProps,} from "../Selectors/UserSelect/types";@@ -22,7 +22,7 @@ const Employees = ({ name, label, helperText, ...props }: EmployeesProps) => {const { error, defaultValue, validate } = useField(name);const [selections, setSelections] = useState<string[]>(defaultValue);- const handleChange = (items: SelectionItemInterface[]) => {+ const handleChange = (items: IndividualOrGroup[]) => {setSelections(items.map((item) => item.id));validate();};diff --git a/apps/carbon/app/components/Form/Input.tsx b/apps/carbon/app/components/Form/Input.tsxindex a50c5a2279..02a610d8fb 100644--- a/apps/carbon/app/components/Form/Input.tsx+++ b/apps/carbon/app/components/Form/Input.tsx@@ -1,4 +1,5 @@import type { InputProps } from "@chakra-ui/react";+import { FormHelperText } from "@chakra-ui/react";import {FormControl,FormErrorMessage,@@ -12,10 +13,11 @@ type FormInputProps = InputProps & {name: string;label?: string;isRequired?: boolean;+ helperText?: string;};const Input = forwardRef<HTMLInputElement, FormInputProps>(- ({ name, label, isRequired, ...rest }, ref) => {+ ({ name, label, isRequired, helperText, ...rest }, ref) => {const { getInputProps, error } = useField(name);return (@@ -28,6 +30,7 @@ const Input = forwardRef<HTMLInputElement, FormInputProps>(...rest,})}/>+ {helperText && <FormHelperText>{helperText}</FormHelperText>}{error && <FormErrorMessage>{error}</FormErrorMessage>}</FormControl>);diff --git a/apps/carbon/app/components/Form/Select.tsx b/apps/carbon/app/components/Form/Select.tsxindex 0f77727503..2b3859be86 100644--- a/apps/carbon/app/components/Form/Select.tsx+++ b/apps/carbon/app/components/Form/Select.tsx@@ -33,7 +33,7 @@ const Select = ({}: SelectProps) => {const { getInputProps, error, defaultValue } = useField(name);const initialValue = useMemo(- () => options.filter((option) => option.value === defaultValue),+ () => options.find((option) => option.value === defaultValue),[defaultValue, options]);@@ -53,6 +53,8 @@ const Select = ({options={options}placeholder={placeholder}// @ts-ignore+ w="full"+ // @ts-ignoreonChange={onChange ?? undefined}/>{error ? (@@ -64,7 +66,13 @@ const Select = ({) : (<Box>{label && <FormLabel>{label}</FormLabel>}- <CarbonSelect isDisabled isLoading={isLoading} options={[]} />+ <CarbonSelect+ isDisabled+ isLoading={isLoading}+ options={[]}+ // @ts-ignore+ w="full"+ /></Box>);};diff --git a/apps/carbon/app/components/Form/User.tsx b/apps/carbon/app/components/Form/User.tsxindex 2b6e076961..31a082cefc 100644--- a/apps/carbon/app/components/Form/User.tsx+++ b/apps/carbon/app/components/Form/User.tsx@@ -8,7 +8,7 @@ import { useState } from "react";import { useField } from "remix-validated-form";import { UserSelect } from "../Selectors";import type {- SelectionItemInterface,+ IndividualOrGroup,UserSelectProps,} from "../Selectors/UserSelect/types";@@ -22,7 +22,7 @@ const User = ({ name, label, type, helperText, ...props }: UserProps) => {const { error, defaultValue, validate } = useField(name);const [selection, setSelection] = useState<string>(defaultValue);- const handleChange = (items: SelectionItemInterface[]) => {+ const handleChange = (items: IndividualOrGroup[]) => {if (items.length > 0) {const item = items[0];setSelection(item.id);diff --git a/apps/carbon/app/components/Form/Users.tsx b/apps/carbon/app/components/Form/Users.tsxindex ad2c5eac7e..f286032d14 100644--- a/apps/carbon/app/components/Form/Users.tsx+++ b/apps/carbon/app/components/Form/Users.tsx@@ -8,7 +8,7 @@ import { useState } from "react";import { useField } from "remix-validated-form";import { UserSelect } from "../Selectors";import type {- SelectionItemInterface,+ IndividualOrGroup,UserSelectProps,} from "../Selectors/UserSelect/types";@@ -22,7 +22,7 @@ const Users = ({ name, label, type, helperText, ...props }: UsersProps) => {const { error, defaultValue, validate } = useField(name);const [selections, setSelections] = useState<string[]>(defaultValue);- const handleChange = (items: SelectionItemInterface[]) => {+ const handleChange = (items: IndividualOrGroup[]) => {setSelections(items.map((item) =>"users" in item ? `group_${item.id}` : `user_${item.id}`diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.tsindex 767654b4b9..3564106f2b 100644--- a/apps/carbon/app/components/Form/index.ts+++ b/apps/carbon/app/components/Form/index.ts@@ -3,8 +3,10 @@ import Ability from "./Ability";import Array from "./Array";import Boolean from "./Boolean";import Color from "./Color";+import CreatableSelect from "./CreatableSelect";import Customer from "./Customer";import CustomerContact from "./CustomerContact";+import Currency from "./Currency";import DatePicker from "./DatePicker";import Department from "./Department";import Employee from "./Employee";@@ -34,6 +36,8 @@ export {Array,Boolean,Color,+ CreatableSelect,+ Currency,Customer,CustomerContact,DatePicker,diff --git a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsxindex b3d4e1478e..820d137132 100644--- a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx+++ b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx@@ -14,6 +14,8 @@ const IconSidebar = () => {borderRight={1}borderRightColor={useColor("gray.200")}borderRightStyle="solid"+ background={useColor("white")}+ zIndex={1}><IconButtonaria-label="Home"diff --git a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsxindex ba50183ef0..26f90ecb13 100644--- a/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx+++ b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsx@@ -9,92 +9,100 @@ import {BsShieldLock,} from "react-icons/bs";import { CgProfile } from "react-icons/cg";-import { GoSettings } from "react-icons/go";+// import { GoSettings } from "react-icons/go";import { HiOutlineCube, HiOutlineDocumentDuplicate } from "react-icons/hi";+import { TbPigMoney } from "react-icons/tb";import { usePermissions } from "~/hooks";-const sidebarItems: Authenticated<NavItem>[] = [- {- permission: "parts",- name: "Parts",- to: "/x/parts",- icon: <AiOutlinePartition />,- },- {- permission: "jobs",- name: "Jobs",- to: "/x/jobs",- icon: <BiListCheck />,- },- {- permission: "inventory",- name: "Inventory",- to: "/x/inventory",- icon: <HiOutlineCube />,- },- {- permission: "scheduling",- name: "Scheduling",- to: "/x/scheduling",- icon: <BsCalendar2Week />,- },- {- permission: "timecards",- name: "Timecards",- to: "/x/timecards",- icon: <AiOutlineFieldTime />,- },- {- permission: "sales",- name: "Sales",- to: "/x/sales",- icon: <BsCartPlus />,- },- {- permission: "purchasing",- name: "Purchasing",- to: "/x/purchasing",- icon: <BsCartDash />,- },- {- permission: "documents",- name: "Documents",- to: "/x/documents",- icon: <HiOutlineDocumentDuplicate />,- },- {- permission: "messages",- name: "Messaging",- to: "/x/messaging",- icon: <BiMessage />,- },- {- permission: "resources",- name: "Resources",- to: "/x/resources",- icon: <BsPeopleFill />,- },- {- permission: "users",- name: "Users",- to: "/x/users",- icon: <BsShieldLock />,- },- {- permission: "settings",- name: "Settings",- to: "/x/settings",- icon: <GoSettings />,- },- {- name: "My Account",- to: "/x/account",- icon: <CgProfile />,- },-];-export function useSidebar() {const permissions = usePermissions();++ const sidebarItems: Authenticated<NavItem>[] = [+ {+ permission: "parts",+ name: "Parts",+ to: "/x/parts",+ icon: <AiOutlinePartition />,+ },+ {+ permission: "jobs",+ name: "Jobs",+ to: "/x/jobs",+ icon: <BiListCheck />,+ },+ {+ permission: "inventory",+ name: "Inventory",+ to: "/x/inventory",+ icon: <HiOutlineCube />,+ },+ {+ permission: "scheduling",+ name: "Scheduling",+ to: "/x/scheduling",+ icon: <BsCalendar2Week />,+ },+ {+ permission: "timecards",+ name: "Timecards",+ to: "/x/timecards",+ icon: <AiOutlineFieldTime />,+ },+ {+ permission: "sales",+ name: "Sales",+ to: "/x/sales",+ icon: <BsCartPlus />,+ },+ {+ permission: "purchasing",+ name: "Purchasing",+ to: "/x/purchasing",+ icon: <BsCartDash />,+ },+ {+ permission: "documents",+ name: "Documents",+ to: "/x/documents",+ icon: <HiOutlineDocumentDuplicate />,+ },+ {+ permission: "messages",+ name: "Messaging",+ to: "/x/messaging",+ icon: <BiMessage />,+ },+ {+ permission: "accounting",+ name: "Accounting",+ to: "/x/accounting",+ icon: <TbPigMoney />,+ },+ {+ permission: "resources",+ name: "Resources",+ to: "/x/resources",+ icon: <BsPeopleFill />,+ },+ {+ permission: "users",+ name: "Users",+ to: "/x/users",+ icon: <BsShieldLock />,+ },+ // {+ // permission: "settings",+ // name: "Settings",+ // to: "/x/settings",+ // icon: <GoSettings />,+ // },+ {+ name: "My Account",+ to: "/x/account",+ icon: <CgProfile />,+ },+ ];+return sidebarItems.filter((item) => {if (item.permission) {return permissions.can("view", item.permission);diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsxindex 43a3657e1f..07db4c34ef 100644--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx@@ -42,6 +42,11 @@ export default function useBreadcrumbs(): Route[] {name: "Settings",to: match.pathname,});+ case "routes/x+/accounting+/_layout":+ return acc.concat({+ name: "Accounting",+ to: match.pathname,+ });case "routes/x+/parts+/index":return acc.concat({name: "Parts",@@ -52,7 +57,32 @@ export default function useBreadcrumbs(): Route[] {name: "Resources",to: match.pathname,});-+ case "routes/x+/part+/_layout":+ case "routes/x+/parts+/_layout":+ return acc.concat({+ name: "Parts",+ to: "/x/parts",+ });+ case "routes/x+/part+/$partId":+ return acc.concat({+ name: match.params?.partId ?? "",+ to: match.pathname,+ });+ case "routes/x+/parts+/accounts":+ return acc.concat({+ name: "Accounts",+ to: match.pathname,+ });+ case "routes/x+/parts+/configurator":+ return acc.concat({+ name: "Configurator",+ to: match.pathname,+ });+ case "routes/x+/parts+/groups":+ return acc.concat({+ name: "Groups",+ to: match.pathname,+ });case "routes/x+/resources+/abilities":return acc.concat({name: "Abilities",@@ -68,6 +98,11 @@ export default function useBreadcrumbs(): Route[] {name: "Attributes",to: match.pathname,});+ case "routes/x+/resources+/contractors":+ return acc.concat({+ name: "Contractors",+ to: match.pathname,+ });case "routes/x+/resources+/departments":return acc.concat({name: "Departments",diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsxindex ed0f556ee8..ec70b0c125 100644--- a/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx+++ b/apps/carbon/app/components/Selectors/UserSelect/components/TreeSelect.tsx@@ -2,7 +2,7 @@ import { Loading } from "@carbon/react";import type { IconProps } from "@chakra-ui/react";import { Box, Icon, List, ListItem, MenuIcon, Text } from "@chakra-ui/react";import { FaCheck, FaChevronRight } from "react-icons/fa";-import type { OptionGroup, SelectionItemInterface } from "../types";+import type { OptionGroup, IndividualOrGroup } from "../types";import useUserSelectContext from "../provider";import { useGroupStyles, useOptionStyles } from "./useUserSelectStyles";@@ -121,7 +121,7 @@ const Option = ({onClick,}: {id?: string;- item: SelectionItemInterface;+ item: IndividualOrGroup;isDisabled: boolean;isFocused: boolean;isSelected: boolean;diff --git a/apps/carbon/app/components/Selectors/UserSelect/types.ts b/apps/carbon/app/components/Selectors/UserSelect/types.tsindex 1e794244eb..f1d0fe920e 100644--- a/apps/carbon/app/components/Selectors/UserSelect/types.ts+++ b/apps/carbon/app/components/Selectors/UserSelect/types.ts@@ -37,7 +37,7 @@ export interface UserSelectProps {readOnly?: boolean;renderInput?: ReactNode;resetAfterSelection?: boolean;- selections?: SelectionItemInterface[];+ selections?: IndividualOrGroup[];selectionsMaxHeight?: string | number;testID?: string;type?: "employee" | "supplier" | "customer";@@ -46,16 +46,16 @@ export interface UserSelectProps {width?: number;onBlur?: (e: any) => void;onCancel?: () => void;- onChange?: (selectionsList: SelectionItemInterface[]) => void;+ onChange?: (selectionsList: IndividualOrGroup[]) => void;onCheckedSelectionsChange?: (- checkedSelectionsList: SelectionItemInterface[]+ checkedSelectionsList: IndividualOrGroup[]) => void;}export type OptionGroup = {uid: string;expanded: boolean;- items: SelectionItemInterface[];+ items: IndividualOrGroup[];name: string;};@@ -85,11 +85,9 @@ type SelectionGroupWithOptions = Group["data"] & {children?: Group[];} & SelectionOptions;-export type SelectionItemInterface =- | UserWithOptions- | SelectionGroupWithOptions;+export type IndividualOrGroup = UserWithOptions | SelectionGroupWithOptions;-export type SelectionItemsById = Record<string, SelectionItemInterface>;+export type SelectionItemsById = Record<string, IndividualOrGroup>;export interface SelectInputProps {aria?: Omit<InputHTMLAttributes<HTMLInputElement>, "size">;@@ -114,8 +112,8 @@ export interface UserTreeSelectProps {groupTypeFilter?: string;innerProps: UserSelectProps;instanceId: string;- itemOnSelect?: (selectableItem: SelectionItemInterface) => void;- itemOnStage?: (selectableItem: SelectionItemInterface) => void;+ itemOnSelect?: (selectableItem: IndividualOrGroup) => void;+ itemOnStage?: (selectableItem: IndividualOrGroup) => void;loading: boolean;multi?: boolean;refs: ComboBoxRefs;diff --git a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.tsindex 0f70f5e8a4..c85888713b 100644--- a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts+++ b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts@@ -8,9 +8,9 @@ import { useEffect, useState, useMemo, useCallback, useRef } from "react";import type { Group } from "~/modules/users";import type {+ IndividualOrGroup,OptionGroup,SelectionItemsById,- SelectionItemInterface,UserSelectionGenericQueryFilters,UserSelectProps,TreeNode,@@ -28,7 +28,7 @@ const defaultProps = {queryFilters: {} as UserSelectionGenericQueryFilters,readOnly: false,resetAfterSelection: false,- selections: [] as SelectionItemInterface[],+ selections: [] as IndividualOrGroup[],selectionsMaxHeight: 400,showAvatars: false,testID: "UserSelect",@@ -94,8 +94,8 @@ export default function useUserSelect(props: UserSelectProps) {const makeGroupItems = (group: Group,groupId: string- ): SelectionItemInterface[] => {- const result: SelectionItemInterface[] = [];+ ): IndividualOrGroup[] => {+ const result: IndividualOrGroup[] = [];if (!innerProps.usersOnly) {result.push({@@ -152,12 +152,12 @@ export default function useUserSelect(props: UserSelectProps) {/* Pre-populate controlled component after data loads */useEffect(() => {if (innerProps.value && optionGroups && optionGroups.length > 0) {- const flattened = optionGroups.reduce(+ const flattened = optionGroups.reduce<IndividualOrGroup[]>((acc, group) => acc.concat(group.items),- [] as SelectionItemInterface[]+ []);if (Array.isArray(innerProps.value)) {- const selections = flattened.reduce((acc, item) => {+ const selections = flattened.reduce<SelectionItemsById>((acc, item) => {if (innerProps.value!.includes(item.id)) {return {...acc,@@ -165,7 +165,7 @@ export default function useUserSelect(props: UserSelectProps) {};}return acc;- }, {} as SelectionItemsById);+ }, {});if (Object.keys(selections).length > 0) {setSelectionItemsById(selections);}@@ -417,7 +417,7 @@ export default function useUserSelect(props: UserSelectProps) {}, []);const onChange = useCallback(- (selections: SelectionItemInterface[]) => {+ (selections: IndividualOrGroup[]) => {if (innerProps.onChange && typeof innerProps.onChange === "function") {innerProps.onChange(selections);}@@ -426,7 +426,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onCheckedChange = useCallback(- (selections: SelectionItemInterface[]) => {+ (selections: IndividualOrGroup[]) => {if (innerProps.onCheckedSelectionsChange &&typeof innerProps.onChange === "function"@@ -438,7 +438,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onSelect = useCallback(- (selectionItem?: SelectionItemInterface) => {+ (selectionItem?: IndividualOrGroup) => {if (selectionItem === undefined) return;setSelectionItemsById((previousSelections) => {const nextSelections = innerProps.isMulti@@ -471,7 +471,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onDeselect = useCallback(- (selectionItem: SelectionItemInterface) => {+ (selectionItem: IndividualOrGroup) => {if (selectionItem === undefined) return;const { id } = selectionItem;setSelectionItemsById((previousSelections) => {@@ -489,7 +489,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onToggle = useCallback(- (selectionItem?: SelectionItemInterface) => {+ (selectionItem?: IndividualOrGroup) => {if (selectionItem === undefined) return;if (selectionItem.id in selectionItemsById) {onDeselect(selectionItem);@@ -501,7 +501,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onToggleChecked = useCallback(- (selectionItem?: SelectionItemInterface) => {+ (selectionItem?: IndividualOrGroup) => {if (selectionItem === undefined) return;setSelectionItemsById((previousSelections) => {const nextSelections = {@@ -550,7 +550,7 @@ export default function useUserSelect(props: UserSelectProps) {);const onExplode = useCallback(- (selectionItem: SelectionItemInterface) => {+ (selectionItem: IndividualOrGroup) => {if (!("users" in selectionItem)) return;const { id, users, children } = selectionItem;@@ -778,21 +778,21 @@ function getGroupId(instanceId: string, groupId: string) {return `${instanceId}_${groupId}_group`;}-function checked(item: SelectionItemInterface): SelectionItemInterface {+function checked(item: IndividualOrGroup): IndividualOrGroup {return {...item,isChecked: true,};}-export function isGroup(item: SelectionItemInterface) {+export function isGroup(item: IndividualOrGroup) {return (("users" in item && item.users?.length > 0) ||("children" in item && item?.children?.length));}-function toggleChecked(item: SelectionItemInterface): SelectionItemInterface {+function toggleChecked(item: IndividualOrGroup): IndividualOrGroup {return {...item,isChecked: !item.isChecked || false,@@ -800,7 +800,7 @@ function toggleChecked(item: SelectionItemInterface): SelectionItemInterface {}function makeSelectionItemsById(- input: SelectionItemInterface[],+ input: IndividualOrGroup[],isMulti: boolean): SelectionItemsById {const result: SelectionItemsById = {};diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsxindex 9240fd817c..18b83172ed 100644--- a/apps/carbon/app/components/Table/Table.tsx+++ b/apps/carbon/app/components/Table/Table.tsx@@ -72,12 +72,12 @@ const Table = <T extends object>({actions = [],count = 0,colorScheme = "blackAlpha",- editableComponents = {},- defaultColumnOrder = [],+ editableComponents,+ defaultColumnOrder,defaultColumnPinning = {left: ["Select"],},- defaultColumnVisibility = {},+ defaultColumnVisibility,withFilters = false,withInlineEditing = false,withColumnOrdering = false,@@ -104,12 +104,13 @@ const Table = <T extends object>({/* Column Visibility */const [columnVisibility, setColumnVisibility] = useState(- defaultColumnVisibility+ defaultColumnVisibility ?? {});/* Column Ordering */- const [columnOrder, setColumnOrder] =- useState<ColumnOrderState>(defaultColumnOrder);+ const [columnOrder, setColumnOrder] = useState<ColumnOrderState>(+ defaultColumnOrder ?? []+ );const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(withColumnOrdering ? defaultColumnPinning : {});@@ -231,13 +232,19 @@ const Table = <T extends object>({(selectedColumn: number) => {if (!withInlineEditing) return false;- const columns = table.getVisibleLeafColumns();+ const tableColumns = [+ ...table.getLeftVisibleLeafColumns(),+ ...table.getCenterVisibleLeafColumns(),+ ];+const column =- columns[withSelectableRows ? selectedColumn + 1 : selectedColumn];+ tableColumns[withSelectableRows ? selectedColumn + 1 : selectedColumn];if (!column) return false;const accessorKey = getAccessorKey(column.columnDef);- return accessorKey && accessorKey in editableComponents;+ return (+ accessorKey && editableComponents && accessorKey in editableComponents+ );},[table, editableComponents, withInlineEditing, withSelectableRows]);@@ -274,17 +281,17 @@ const Table = <T extends object>({(event: React.KeyboardEvent<HTMLDivElement>) => {if (!selectedCell) return;- const { code } = event;+ const { code, shiftKey } = event;const commandCodes: {- [key: string]: [0, 1] | [1, 0] | [0, -1] | [-1, 0];+ [key: string]: [number, number];} = {Tab: [0, 1],Enter: [1, 0],};const navigationCodes: {- [key: string]: [0, 1] | [1, 0] | [0, -1] | [-1, 0];+ [key: string]: [number, number];} = {ArrowRight: [0, 1],ArrowLeft: [0, -1],@@ -296,7 +303,10 @@ const Table = <T extends object>({const lastColumn =table.getVisibleLeafColumns().length - 1 - (withSelectableRows ? 1 : 0);- const navigate = (delta: number[], tabWrap = false): number[] => {+ const navigate = (+ delta: [number, number],+ tabWrap = false+ ): [number, number] => {const x0 = selectedCell?.column || 0;const y0 = selectedCell?.row || 0;@@ -304,15 +314,28 @@ const Table = <T extends object>({let y1 = y0 + delta[0];if (tabWrap) {- // wrap to the next row if we're on the last column- if (x1 > lastColumn) {- x1 = 0;- y1++;- }- // don't wrap to the next row if we're on the last row- if (y1 > lastRow) {- x1 = x0;- y1 = y0;+ if (delta[1] > 0) {+ // wrap to the next row if we're on the last column+ if (x1 > lastColumn) {+ x1 = 0;+ y1 += 1;+ }+ // don't wrap to the next row if we're on the last row+ if (y1 > lastRow) {+ x1 = x0;+ y1 = y0;+ }+ } else {+ // reverse tab wrap+ if (x1 < 0) {+ x1 = lastColumn;+ y1 -= 1;+ }++ if (y1 < 0) {+ x1 = x0;+ y1 = y0;+ }}} else {x1 = clip(x1, 0, lastColumn);@@ -324,16 +347,26 @@ const Table = <T extends object>({};if (code in commandCodes) {- // enter and tab work even if we're editingevent.preventDefault();- const [x1, y1] = navigate(commandCodes[code], code === "Tab");++ if (+ !isEditing &&+ code === "Enter" &&+ !shiftKey &&+ isColumnEditable(selectedCell.column)+ ) {+ setIsEditing(true);+ return;+ }++ let direction = commandCodes[code];+ if (shiftKey) direction = [-direction[0], -direction[1]];+ const [x1, y1] = navigate(direction, code === "Tab");setSelectedCell({row: y1,column: x1,});-if (isEditing) {- focusOnSelectedCell();setIsEditing(false);}} else if (code in navigationCodes) {@@ -346,9 +379,10 @@ const Table = <T extends object>({row: y1,column: x1,});- // any other key activates editing+ // any other key (besides shift) activates editing// if the column is editable and a cell is selected} else if (+ !["ShiftLeft", "ShiftRight"].includes(code) &&!isEditing &&selectedCell &&isColumnEditable(selectedCell.column)@@ -357,7 +391,6 @@ const Table = <T extends object>({}},[- focusOnSelectedCell,isColumnEditable,isEditing,selectedCell,@@ -393,7 +426,11 @@ const Table = <T extends object>({return (<VStack w="full" h="full" spacing={0}>- {(withColumnOrdering || withFilters || withSelectableRows) && (+ {(withColumnOrdering ||+ withFilters ||+ withSelectableRows ||+ withInlineEditing ||+ withSimpleSorting) && (<TableHeaderactions={actions}columnAccessors={columnAccessors}@@ -444,7 +481,6 @@ const Table = <T extends object>({const sortable =withSimpleSorting &&accessorKey &&- accessorKey !== "id" &&!accessorKey.endsWith(".id") &&header.column.columnDef.enableSorting !== false;@@ -514,6 +550,10 @@ const Table = <T extends object>({isEditing={isEditing}isEditMode={editMode}isFrozenColumn+ isRowSelected={+ row.index in rowSelection &&+ !!rowSelection[row.index]+ }selectedCell={selectedCell}// @ts-ignorerow={row}@@ -538,6 +578,9 @@ const Table = <T extends object>({isEditing={isEditing}isEditMode={editMode}isFrozenColumn+ isRowSelected={+ row.index in rowSelection && !!rowSelection[row.index]+ }selectedCell={selectedCell}// @ts-ignorerow={row}@@ -571,7 +614,6 @@ const Table = <T extends object>({const sortable =withSimpleSorting &&accessorKey &&- accessorKey !== "id" &&!accessorKey.endsWith(".id") &&header.column.columnDef.enableSorting !== false;const sorted = isSorted(accessorKey ?? "");@@ -647,6 +689,10 @@ const Table = <T extends object>({editableComponents={editableComponents}isEditing={isEditing}isEditMode={editMode}+ isRowSelected={+ row.index in rowSelection &&+ !!rowSelection[row.index]+ }pinnedColumns={columnPinning?.left? columnPinning.left?.length -@@ -678,6 +724,9 @@ const Table = <T extends object>({editableComponents={editableComponents}isEditing={isEditing}isEditMode={editMode}+ isRowSelected={+ row.index in rowSelection && !!rowSelection[row.index]+ }pinnedColumns={columnPinning?.left? columnPinning.left?.length -diff --git a/apps/carbon/app/components/Table/components/Cell/Cell.tsx b/apps/carbon/app/components/Table/components/Cell/Cell.tsxindex cef8dead51..df49abc62c 100644--- a/apps/carbon/app/components/Table/components/Cell/Cell.tsx+++ b/apps/carbon/app/components/Table/components/Cell/Cell.tsx@@ -18,10 +18,11 @@ type CellProps<T> = {borderColor: string;cell: CellType<T, unknown>;columnIndex: number;- editableComponents: Record<string, EditableTableCellComponent<T>>;- isSelected: boolean;+ editableComponents?: Record<string, EditableTableCellComponent<T>>;isEditing: boolean;isEditMode: boolean;+ isRowSelected: boolean;+ isSelected: boolean;onClick?: () => void;onUpdate?: (value: unknown) => void;};@@ -31,9 +32,9 @@ const Cell = <T extends object>({cell,columnIndex,editableComponents,- isSelected,isEditing,isEditMode,+ isSelected,onClick,onUpdate,}: CellProps<T>) => {@@ -41,7 +42,22 @@ const Cell = <T extends object>({const accessorKey = getAccessorKey(cell.column.columnDef);const hasEditableTableCellComponent =- accessorKey !== undefined && accessorKey in editableComponents;+ accessorKey !== undefined &&+ editableComponents &&+ accessorKey in editableComponents;++ const editableCell = hasEditableTableCellComponent+ ? editableComponents[accessorKey]({+ accessorKey,+ value: cell.getValue(),+ row: cell.row.original,+ onUpdate:+ onUpdate ||+ (() => {+ console.error("failed to pass an onUpdate function to the popover");+ }),+ })+ : null;return (<Td@@ -87,18 +103,7 @@ const Cell = <T extends object>({<PopoverContent><PopoverBody>- <HStack spacing={2}>- {editableComponents[accessorKey!]({- accessorKey,- value: cell.getValue(),- row: cell.row.original,- onUpdate: onUpdate- ? onUpdate- : () => {- console.error("failed to pass an onUpdate function");- },- })}- </HStack>+ <HStack spacing={2}>{editableCell}</HStack></PopoverBody></PopoverContent></Popover>@@ -113,9 +118,10 @@ const Cell = <T extends object>({export const MemoizedCell = memo(Cell,(prev, next) =>- next.cell === prev.cell &&+ next.isRowSelected === prev.isRowSelected &&next.isSelected === prev.isSelected &&next.isEditing === prev.isEditing &&next.isEditMode === prev.isEditMode &&- next.cell.column.columnDef.id !== "select"-);+ next.cell.getValue() === prev.cell.getValue() &&+ next.cell.getContext() === prev.cell.getContext()+) as typeof Cell;diff --git a/apps/carbon/app/components/Table/components/Row/Row.tsx b/apps/carbon/app/components/Table/components/Row/Row.tsxindex 3aad03a393..205d533e79 100644--- a/apps/carbon/app/components/Table/components/Row/Row.tsx+++ b/apps/carbon/app/components/Table/components/Row/Row.tsx@@ -1,17 +1,19 @@import type { Row as RowType } from "@tanstack/react-table";+import type { MutableRefObject } from "react";+import { memo } from "react";import { Tr, spring } from "../Animations";import Cell from "../Cell";import type { EditableTableCellComponent, Position } from "../../types";import { useColor } from "@carbon/react";-import type { MutableRefObject } from "react";type RowProps<T> = {borderColor: string;backgroundColor: string;- editableComponents: Record<string, EditableTableCellComponent<T> | object>;+ editableComponents?: Record<string, EditableTableCellComponent<T> | object>;isEditing: boolean;isEditMode: boolean;isFrozenColumn?: boolean;+ isRowSelected?: boolean;pinnedColumns?: number;selectedCell: Position;row: RowType<T>;@@ -30,6 +32,7 @@ const Row = <T extends object>({isEditing,isEditMode,isFrozenColumn = false,+ isRowSelected = false,pinnedColumns = 0,row,rowIsClickable = false,@@ -68,14 +71,14 @@ const Row = <T extends object>({selectedCell?.column === columnIndex + pinnedColumns;return (- <Cell+ <Cell<T>key={cell.id}borderColor={borderColor}- // @ts-ignorecell={cell}columnIndex={columnIndex}// @ts-ignoreeditableComponents={editableComponents}+ isRowSelected={isRowSelected}isSelected={isSelected}isEditing={isEditing}isEditMode={isEditMode}@@ -102,4 +105,15 @@ const Row = <T extends object>({);};-export default Row;+const MemoizedRow = memo(+ Row,+ (prev, next) =>+ next.isRowSelected === prev.isRowSelected &&+ next.selectedCell?.row === prev.row.index &&+ next.row.index === prev.selectedCell?.row &&+ next.selectedCell?.column === prev.selectedCell?.column &&+ next.isEditing === prev.isEditing &&+ next.isEditMode === prev.isEditMode+) as typeof Row;++export default MemoizedRow;diff --git a/apps/carbon/app/components/Table/editable/EditableList.tsx b/apps/carbon/app/components/Table/editable/EditableList.tsxnew file mode 100644index 0000000000..e98b8e7e75--- /dev/null+++ b/apps/carbon/app/components/Table/editable/EditableList.tsx@@ -0,0 +1,45 @@+/* eslint-disable react/display-name */+import { Select } from "@carbon/react";+import type { EditableTableCellComponentProps } from "../types";++const EditableList =+ <T extends object>(+ mutation: (+ accessorKey: string,+ newValue: string | undefined,+ row: T+ ) => void,+ options: { label: string; value: string | number }[]+ ) =>+ ({+ value,+ row,+ accessorKey,+ onUpdate,+ }: EditableTableCellComponentProps<T>) => {+ const updateSelection = (newValue: string | null) => {+ if (newValue === value || (newValue === null && value === undefined))+ return;+ // this is the optimistic update on the FE+ onUpdate(newValue);+ // the is the actual update on the BE+ mutation(accessorKey, newValue ?? undefined, row);+ };++ return (+ <Select+ autoFocus+ bordered={false}+ defaultOpen+ defaultValue={value as string}+ // @ts-ignore+ options={options}+ optionFilterProp="label"+ showSearch+ style={{ margin: "0 -0.75rem", minWidth: 100 }}+ onChange={updateSelection}+ />+ );+ };++export default EditableList;diff --git a/apps/carbon/app/components/Table/editable/EditableText.tsx b/apps/carbon/app/components/Table/editable/EditableText.tsxnew file mode 100644index 0000000000..864e3a649d--- /dev/null+++ b/apps/carbon/app/components/Table/editable/EditableText.tsx@@ -0,0 +1,43 @@+/* eslint-disable react/display-name */+import { Input } from "@chakra-ui/react";+import type { EditableTableCellComponentProps } from "../types";++const EditableText =+ <T extends object>(+ mutation: (accessorKey: string, newValue: string, row: T) => void+ ) =>+ ({+ value,+ row,+ accessorKey,+ onUpdate,+ }: EditableTableCellComponentProps<T>) => {+ const updateText = async (newValue: string) => {+ // this is the optimistic update on the FE+ onUpdate(newValue);+ // the is the actual update on the BE+ mutation(accessorKey, newValue, row);+ };++ const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {+ // only run the update if they click enter+ if (event.key === "Enter" || event.key === "Tab") {+ if (event.currentTarget.value !== value) {+ updateText(event.currentTarget.value);+ }+ }+ };++ // eslint-disable-next-line jsx-a11y/no-autofocus+ return (+ <Input+ border="none"+ autoFocus+ defaultValue={value as string}+ style={{ margin: "0 -0.75rem" }}+ onKeyDown={onKeyDown}+ />+ );+ };++export default EditableText;diff --git a/apps/carbon/app/components/Table/types.ts b/apps/carbon/app/components/Table/types.tsindex b7f4799e5b..460abec7ef 100644--- a/apps/carbon/app/components/Table/types.ts+++ b/apps/carbon/app/components/Table/types.ts@@ -1,4 +1,4 @@-export type EditableTableCellComponent<TData extends unknown> = (props: {+export type EditableTableCellComponent<TData> = (props: {accessorKey: string;row: TData;value: unknown;@@ -13,7 +13,7 @@ export type EditableTableCellComponentProps<T> = {};declare module "@tanstack/react-table" {- interface TableMeta<TData extends unknown> {+ interface TableMeta<TData> {editableComponents?: Record<string, EditableTableCellComponent<TData>>;updateData?: (rowIndex: number, columnId: string, value: unknown) => void;}diff --git a/apps/carbon/app/hooks/usePermissions.tsx b/apps/carbon/app/hooks/usePermissions.tsxindex 021893e2bb..c0e97bd78f 100644--- a/apps/carbon/app/hooks/usePermissions.tsx+++ b/apps/carbon/app/hooks/usePermissions.tsx@@ -24,6 +24,13 @@ export function usePermissions() {[data?.permissions]);+ const has = useCallback(+ (feature: string) => {+ return feature in (data?.permissions as Record<string, Permission>);+ },+ [data?.permissions]+ );+const is = useCallback((role: Role) => {return data?.role === role;@@ -33,6 +40,7 @@ export function usePermissions() {return {can,+ has,is,};}diff --git a/apps/carbon/app/modules/accounting/index.ts b/apps/carbon/app/modules/accounting/index.tsnew file mode 100644index 0000000000..b2221a94a8--- /dev/null+++ b/apps/carbon/app/modules/accounting/index.ts@@ -0,0 +1 @@+export * from "./services";diff --git a/apps/carbon/app/modules/accounting/services/accounting.server.ts b/apps/carbon/app/modules/accounting/services/accounting.server.tsnew file mode 100644index 0000000000..5ad500a6d8--- /dev/null+++ b/apps/carbon/app/modules/accounting/services/accounting.server.ts@@ -0,0 +1,17 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++export async function getAccountsList(client: SupabaseClient<Database>) {+ return client+ .from("account")+ .select("number, name")+ .eq("active", true)+ .order("name", { ascending: true });+}++export async function getCurrenciesList(client: SupabaseClient<Database>) {+ return client+ .from("currency")+ .select("code, name")+ .order("name", { ascending: true });+}diff --git a/apps/carbon/app/modules/accounting/services/index.ts b/apps/carbon/app/modules/accounting/services/index.tsnew file mode 100644index 0000000000..c5fec51e7e--- /dev/null+++ b/apps/carbon/app/modules/accounting/services/index.ts@@ -0,0 +1 @@+export * from "./accounting.server";diff --git a/apps/carbon/app/modules/parts/index.ts b/apps/carbon/app/modules/parts/index.tsindex afccf2b240..684aed031a 100644--- a/apps/carbon/app/modules/parts/index.ts+++ b/apps/carbon/app/modules/parts/index.ts@@ -1,3 +1,3 @@-// export * from "./services";+export * from "./services";export * from "./interfaces";-// export * from "./types";+export * from "./types";diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/PartCostingForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/PartCostingForm.tsxnew file mode 100644index 0000000000..f9fd6dd4e6--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/PartCostingForm.tsx@@ -0,0 +1,115 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Boolean, Hidden, Number, Select, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { PartCostingMethod } from "~/modules/parts";+import { partCostValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";+import { mapRowsToOptions } from "~/utils/form";++type PartCostingFormProps = {+ initialValues: TypeOfValidator<typeof partCostValidator>;+ accounts: { number: string; name: string }[];+ partCostingMethods: PartCostingMethod[];+};++const PartCostingForm = ({+ initialValues,+ accounts,+ partCostingMethods,+}: PartCostingFormProps) => {+ const permissions = usePermissions();++ const accountOptions = mapRowsToOptions({+ data: accounts,+ value: "number",+ label: "name",+ });++ const partCostingMethodOptions = partCostingMethods.map(+ (partCostingMethod) => ({+ label: partCostingMethod,+ value: partCostingMethod,+ })+ );++ return (+ <ValidatedForm+ method="post"+ validator={partCostValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Costing & Posting</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="costingMethod"+ label="Part Costing Method"+ options={partCostingMethodOptions}+ />+ <Number name="standardCost" label="Standard Cost" precision={2} />+ <Number name="unitCost" label="Unit Cost" precision={2} />+ </VStack>+ {permissions.has("accounting") && (+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="salesAccountId"+ label="Sales Account"+ options={accountOptions}+ />+ <Select+ name="inventoryAccountId"+ label="Inventory Account"+ options={accountOptions}+ />+ <Select+ name="discountAccountId"+ label="Discount Account"+ options={accountOptions}+ />+ </VStack>+ )}+ <VStack alignItems="start" spacing={2} w="full">+ <Number+ name="salesHistory"+ label="Sales History"+ precision={2}+ isReadOnly+ />+ <Number+ name="salesHistoryQty"+ label="Sales History Qty"+ precision={2}+ isReadOnly+ />+ <Boolean name="costIsAdjusted" label="Cost Is Adjusted" />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartCostingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/index.tsnew file mode 100644index 0000000000..1a274660db--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartCostingForm/index.ts@@ -0,0 +1,3 @@+import PartCostingForm from "./PartCostingForm";++export default PartCostingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartForm/PartForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartForm/PartForm.tsxnew file mode 100644index 0000000000..a2b3a249b8--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartForm/PartForm.tsx@@ -0,0 +1,148 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ Text,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Boolean, Input, Select, Submit, TextArea } from "~/components/Form";+import { usePermissions } from "~/hooks";+import type {+ PartGroupListItem,+ PartReplenishmentSystem,+ PartType,+ UnitOfMeasureListItem,+} from "~/modules/parts";+import { partValidator } from "~/modules/parts";++type PartFormValues = {+ id?: string;+ name: string;+ description?: string;+ partType?: PartType;+ partGroupId?: string;+ replenishmentSystem?: PartReplenishmentSystem;+ unitOfMeasureCode?: string;+ blocked?: boolean;+ active?: boolean;+};++type PartFormProps = {+ initialValues: PartFormValues;+ partGroups: PartGroupListItem[];+ partTypes: PartType[];+ partReplenishmentSystems: PartReplenishmentSystem[];+ unitOfMeasures: UnitOfMeasureListItem[];+};++const PartForm = ({+ initialValues,+ partGroups,+ partTypes,+ partReplenishmentSystems,+ unitOfMeasures,+}: PartFormProps) => {+ const permissions = usePermissions();+ const isEditing = initialValues.id !== undefined;++ const partGroupOptions = partGroups.map((partGroup) => ({+ label: partGroup.name,+ value: partGroup.id,+ }));++ const partTypeOptions = partTypes.map((partType) => ({+ label: partType,+ value: partType,+ }));++ const partReplenishmentSystemOptions = partReplenishmentSystems.map(+ (partReplenishmentSystem) => ({+ label: partReplenishmentSystem,+ value: partReplenishmentSystem,+ })+ );++ const unitOfMeasureOptions = unitOfMeasures.map((uom) => ({+ label: uom.name,+ value: uom.code,+ }));++ return (+ <ValidatedForm+ method="post"+ validator={partValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">{isEditing ? "Part Basics" : "New Part"}</Heading>+ {!isEditing && (+ <Text color="gray.500">+ A part contains the information about a specific item that can be+ purchased or manufactured.+ </Text>+ )}+ </CardHeader>+ <CardBody>+ <Grid+ gridTemplateColumns={+ isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"+ }+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Input name="id" label="Part ID" isReadOnly={isEditing} />+ <Input name="name" label="Name" />+ <TextArea name="description" label="Description" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="replenishmentSystem"+ label="Replenishment System"+ options={partReplenishmentSystemOptions}+ />+ <Select+ name="partType"+ label="Part Type"+ options={partTypeOptions}+ />+ <Select+ name="unitOfMeasureCode"+ label="Unit of Measure"+ options={unitOfMeasureOptions}+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="partGroupId"+ label="Part Group"+ options={partGroupOptions}+ />+ <Boolean name="blocked" label="Blocked" />+ {isEditing && <Boolean name="active" label="Active" />}+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit+ isDisabled={+ isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts")+ }+ >+ Save+ </Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartForm/index.tsnew file mode 100644index 0000000000..aace59b8a1--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartForm/index.ts@@ -0,0 +1,3 @@+import PartForm from "./PartForm";++export default PartForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsxnew file mode 100644index 0000000000..9118b570d1--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/PartInventoryForm.tsx@@ -0,0 +1,119 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { useState } from "react";+import { ValidatedForm } from "remix-validated-form";+import {+ Boolean,+ CreatableSelect,+ Hidden,+ Number,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import { partInventoryValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type PartInventoryFormProps = {+ initialValues: Omit<+ TypeOfValidator<typeof partInventoryValidator>,+ "hasNewShelf"+ >;+ shelves: string[];+};++const PartInventoryForm = ({+ initialValues,+ shelves,+}: PartInventoryFormProps) => {+ const permissions = usePermissions();+ const [hasNewShelf, setHasNewShelf] = useState(false);+ const shelfOptions = shelves.map((shelf) => ({ value: shelf, label: shelf }));++ return (+ <ValidatedForm+ method="post"+ validator={partInventoryValidator}+ defaultValues={{+ ...initialValues,+ // TODO: Remove these defaults once the API is ready+ // @ts-expect-error+ quantityOnHand: 0,+ quantityAvailable: 0,+ quantityOnPurchaseOrder: 0,+ quantityOnProdOrder: 0,+ quantityOnSalesOrder: 0,+ }}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Inventory</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Hidden name="hasNewShelf" value={hasNewShelf.toString()} />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <CreatableSelect+ options={shelfOptions}+ name="shelfId"+ label="Shelf"+ onUsingCreatedChanged={setHasNewShelf}+ // @ts-ignore+ w="full"+ />+ <Number+ name="quantityOnHand"+ label="Quantity On Hand"+ isReadOnly+ />+ <Number+ name="quantityAvailable"+ label="Quantity Available"+ isReadOnly+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number+ name="quantityOnPurchaseOrder"+ label="Quantity On Purchase Order"+ isReadOnly+ />+ <Number+ name="quantityOnProdOrder"+ label="Quantity On Prod Order"+ isReadOnly+ />+ <Number+ name="quantityOnSalesOrder"+ label="Quantity On Sales Order"+ isReadOnly+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number name="unitVolume" label="Unit Volume" />+ <Number name="unitWeight" label="Unit Weight" />+ <Boolean name="stockoutWarning" label="Stockout Warning" />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartInventoryForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/index.tsnew file mode 100644index 0000000000..85895a2460--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartInventoryForm/index.ts@@ -0,0 +1,3 @@+import PartInventoryForm from "./PartInventoryForm";++export default PartInventoryForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/PartManufacturingForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/PartManufacturingForm.tsxnew file mode 100644index 0000000000..d7119908eb--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/PartManufacturingForm.tsx@@ -0,0 +1,89 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Boolean, Hidden, Number, Select, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { PartManufacturingPolicy } from "~/modules/parts";+import { partManufacturingValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type PartManufacturingFormProps = {+ initialValues: TypeOfValidator<typeof partManufacturingValidator>;+ partManufacturingPolicies: PartManufacturingPolicy[];+};++const PartManufacturingForm = ({+ initialValues,+ partManufacturingPolicies,+}: PartManufacturingFormProps) => {+ const permissions = usePermissions();++ const partManufacturingPolicyOptions =+ partManufacturingPolicies?.map((policy) => ({+ label: policy,+ value: policy,+ })) ?? [];++ return (+ <ValidatedForm+ method="post"+ validator={partManufacturingValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Manufacturing</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="manufacturingPolicy"+ label="Manufacturing Policy"+ options={partManufacturingPolicyOptions}+ />+ <Select+ name="routingId"+ label="Routing ID"+ options={[{ label: "", value: "" }]}+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number name="manufacturingLeadTime" label="Lead Time (Days)" />+ <Number name="scrapPercentage" label="Scrap Percentage" />+ <Number name="lotSize" label="Lot Size" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Boolean+ name="manufacturingBlocked"+ label="Manufacturing Blocked"+ />+ <Boolean+ name="requiresConfiguration"+ label="Requires Configuration"+ />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartManufacturingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/index.tsnew file mode 100644index 0000000000..c030e3a122--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartManufacturingForm/index.ts@@ -0,0 +1,3 @@+import PartManufacturingForm from "./PartManufacturingForm";++export default PartManufacturingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsxnew file mode 100644index 0000000000..ee806dc830--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/PartPlanningForm.tsx@@ -0,0 +1,116 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Boolean, Hidden, Number, Select, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { PartReorderingPolicy } from "~/modules/parts";+import { partPlanningValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type PartPlanningFormProps = {+ initialValues: TypeOfValidator<typeof partPlanningValidator>;+ partReorderingPolicies: PartReorderingPolicy[];+};++const PartPlanningForm = ({+ initialValues,+ partReorderingPolicies,+}: PartPlanningFormProps) => {+ const permissions = usePermissions();++ const partReorderingOptions = partReorderingPolicies.map((policy) => ({+ label: policy,+ value: policy,+ }));++ return (+ <ValidatedForm+ method="post"+ validator={partPlanningValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Planning</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="reorderingPolicy"+ label="Reordering Policy"+ options={partReorderingOptions}+ />+ <Boolean name="critical" label="Critical" />+ <Number+ name="safetyStockQuantity"+ label="Safety Stock Quantity"+ />+ <Number+ name="safetyStockLeadTime"+ label="Safety Stock Lead Time (Days)"+ />+ <Number+ name="minimumOrderQuantity"+ label="Minimum Order Quantity"+ />+ <Number+ name="maximumOrderQuantity"+ label="Maximum Order Quantity"+ />+ <Number name="orderMultiple" label="Order Multiple" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number+ name="demandAccumulationPeriod"+ label="Demand Accumulation Period (Days)"+ />+ <Number+ name="demandReschedulingPeriod"+ label="Rescheduling Period (Days)"+ />+ <Boolean+ name="demandAccumulationIncludesInventory"+ label="Demand Includes Inventory"+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number name="reorderPoint" label="Reorder Point" />+ <Number name="reorderQuantity" label="Reorder Quantity" />+ <Number+ name="reorderMaximumInventory"+ label="Reorder Maximum Inventory"+ />+ <Number+ name="reorderOverflowLevel"+ label="Reorder Overflow Level"+ />+ <Number+ name="reorderTimeBucket"+ label="Reorder Time Bucket (Days)"+ />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartPlanningForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/index.tsnew file mode 100644index 0000000000..76a00061bd--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPlanningForm/index.ts@@ -0,0 +1,3 @@+import PartPlanningForm from "./PartPlanningForm";++export default PartPlanningForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsxnew file mode 100644index 0000000000..d889a8c54c--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/PartPreview.tsx@@ -0,0 +1,74 @@+import {+ Button,+ Card,+ CardBody,+ CardHeader,+ Heading,+ HStack,+ Stack,+ Text,+} from "@chakra-ui/react";+import { useParams } from "@remix-run/react";+import { FaHistory } from "react-icons/fa";+import { useRouteData } from "~/hooks";+import type { PartSummary } from "~/modules/parts";++const PartPreview = () => {+ const { partId } = useParams();+ if (!partId) throw new Error("Could not find partId");+ const routeData = useRouteData<PartSummary>(`/x/part/${partId}`);++ return (+ <Card w="full">+ <CardHeader>+ <HStack justifyContent="space-between" alignItems="start">+ <Stack direction={["column", "column", "row"]} spacing={2}>+ <Heading size="md">{routeData?.id}</Heading>+ <Text color="gray.500">{routeData?.name}</Text>+ </Stack>+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>+ View History+ </Button>+ </HStack>+ </CardHeader>+ <CardBody>+ <Stack direction={["column", "column", "row"]} spacing={8}>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Replenishment System</Text>+ <Text fontWeight="bold">{routeData?.replenishmentSystem}</Text>+ </Stack>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Part Type</Text>+ <Text fontWeight="bold">{routeData?.partType}</Text>+ </Stack>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Unit of Measure</Text>+ <Text fontWeight="bold">{routeData?.unitOfMeasureCode}</Text>+ </Stack>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Location</Text>+ <Text fontWeight="bold">--</Text>+ </Stack>+ </Stack>+ </CardBody>+ </Card>+ );+};++export default PartPreview;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/index.tsnew file mode 100644index 0000000000..98c18c14da--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPreview/index.ts@@ -0,0 +1,3 @@+import PartPreview from "./PartPreview";++export default PartPreview;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsxnew file mode 100644index 0000000000..fd1096b1c5--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/PartPurchasingForm.tsx@@ -0,0 +1,84 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import {+ Boolean,+ Hidden,+ Input,+ Number,+ Select,+ Submit,+ Supplier,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { UnitOfMeasureListItem } from "~/modules/parts";+import { partPurchasingValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type PartPurchasingFormProps = {+ initialValues: TypeOfValidator<typeof partPurchasingValidator>;+ unitOfMeasures: UnitOfMeasureListItem[];+};++const PartPurchasingForm = ({+ initialValues,+ unitOfMeasures,+}: PartPurchasingFormProps) => {+ const permissions = usePermissions();++ const unitOfMeasureOptions = unitOfMeasures.map((unitOfMeasure) => ({+ label: unitOfMeasure.name,+ value: unitOfMeasure.code,+ }));++ return (+ <ValidatedForm+ method="post"+ validator={partPurchasingValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Purchasing</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Supplier name="supplierId" label="Supplier" />+ <Input name="supplierPartNumber" label="Supplier Part Number" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Number name="purchasingLeadTime" label="Lead Time (Days)" />+ <Select+ name="purchasingUnitOfMeasureCode"+ label="Purchasing Unit of Measure"+ options={unitOfMeasureOptions}+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Boolean name="purchasingBlocked" label="Purchasing Blocked" />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartPurchasingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/index.tsnew file mode 100644index 0000000000..e06475c8ec--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartPurchasingForm/index.ts@@ -0,0 +1,3 @@+import PartPurchasingForm from "./PartPurchasingForm";++export default PartPurchasingForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/PartSalePriceForm.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/PartSalePriceForm.tsxnew file mode 100644index 0000000000..9a7cb4fae3--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/PartSalePriceForm.tsx@@ -0,0 +1,87 @@+import {+ Card,+ CardBody,+ CardFooter,+ CardHeader,+ Grid,+ Heading,+ VStack,+} from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import {+ Boolean,+ Currency,+ Hidden,+ Number,+ Select,+ Submit,+} from "~/components/Form";+import { usePermissions } from "~/hooks";+import type { UnitOfMeasureListItem } from "~/modules/parts";+import { partUnitSalePriceValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type PartSalePriceFormProps = {+ initialValues: TypeOfValidator<typeof partUnitSalePriceValidator>;+ unitOfMeasures: UnitOfMeasureListItem[];+};++const PartSalePriceForm = ({+ initialValues,+ unitOfMeasures,+}: PartSalePriceFormProps) => {+ const permissions = usePermissions();++ const unitOfMeasureOptions = unitOfMeasures.map((unitOfMeasure) => ({+ label: unitOfMeasure.name,+ value: unitOfMeasure.code,+ }));++ return (+ <ValidatedForm+ method="post"+ validator={partUnitSalePriceValidator}+ defaultValues={initialValues}+ >+ <Card w="full">+ <CardHeader>+ <Heading size="md">Sale Price</Heading>+ </CardHeader>+ <CardBody>+ <Hidden name="partId" />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr 1fr"]}+ gridColumnGap={8}+ gridRowGap={2}+ w="full"+ >+ <VStack alignItems="start" spacing={2} w="full">+ <Number name="unitSalePrice" label="Unit Sale Price" />+ <Currency name="currencyCode" label="Currency" />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Select+ name="salesUnitOfMeasureCode"+ label="Sales Unit of Measure"+ options={unitOfMeasureOptions}+ />+ </VStack>+ <VStack alignItems="start" spacing={2} w="full">+ <Boolean name="salesBlocked" label="Sales Blocked" />+ <Boolean name="priceIncludesTax" label="Price Includes Tax" />+ <Boolean+ name="allowInvoiceDiscount"+ label="Allow Invoice Discount"+ />+ </VStack>+ </Grid>+ </CardBody>+ <CardFooter>+ <Submit isDisabled={!permissions.can("update", "parts")}>Save</Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ );+};++export default PartSalePriceForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/index.tsnew file mode 100644index 0000000000..029d2459fb--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSalePriceForm/index.ts@@ -0,0 +1,3 @@+import PartSalePriceForm from "./PartSalePriceForm";++export default PartSalePriceForm;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsxnew file mode 100644index 0000000000..d085551aec--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/PartSidebar.tsx@@ -0,0 +1,56 @@+import { Button, Box, VStack } from "@chakra-ui/react";+import { Link, useMatches, useParams } from "@remix-run/react";+import { useRouteData } from "~/hooks";+import type { PartSummary } from "~/modules/parts/types";+import { usePartSidebar } from "./usePartSidebar";++const PartSidebar = () => {+ const { partId } = useParams();+ if (!partId)+ throw new Error(+ "PartSidebar requires a partId and could not find partId in params"+ );++ const routeData = useRouteData<PartSummary>(`/x/part/${partId}`);+ if (!routeData?.replenishmentSystem)+ throw new Error("Could not find replenishmentSystem in routeData");++ const links = usePartSidebar(routeData.replenishmentSystem);+ const matches = useMatches();++ return (+ <VStack h="full" alignItems="start">+ <Box overflowY="auto" w="full" h="full">+ <VStack spacing={2}>+ <VStack spacing={1} alignItems="start" w="full">+ {links.map((route) => {+ const isActive = matches.some(+ (match) =>+ (match.pathname.includes(route.to) && route.to !== "") ||+ (match.id.includes(".index") && route.to === "")+ );++ return (+ <Button+ key={route.name}+ as={Link}+ to={route.to}+ variant={isActive ? "solid" : "ghost"}+ border="none"+ fontWeight={isActive ? "bold" : "normal"}+ justifyContent="start"+ size="md"+ w="full"+ >+ {route.name}+ </Button>+ );+ })}+ </VStack>+ </VStack>+ </Box>+ </VStack>+ );+};++export default PartSidebar;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/index.tsnew file mode 100644index 0000000000..edc2d6c882--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/index.ts@@ -0,0 +1,3 @@+import PartSidebar from "./PartSidebar";++export default PartSidebar;diff --git a/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsxnew file mode 100644index 0000000000..c276a4c0d6--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/PartSidebar/usePartSidebar.tsx@@ -0,0 +1,50 @@+import { usePermissions } from "~/hooks";+import type { PartReplenishmentSystem } from "~/modules/parts/types";+import type { Role } from "~/types";++export function usePartSidebar(replenishment: PartReplenishmentSystem) {+ const permissions = usePermissions();+ return [+ {+ name: "Part Basics",+ to: "",+ },+ {+ name: "Purchasing",+ to: "purchasing",+ isDisabled: replenishment === "Make",+ role: ["employee", "supplier"],+ },+ {+ name: "Manufacturing",+ to: "manufacturing",+ isDisabled: replenishment === "Buy",+ role: ["employee"],+ },+ {+ name: "Costing",+ to: "costing",+ role: ["employee", "supplier"],+ },+ {+ name: "Planning",+ to: "planning",+ role: ["employee"],+ },+ {+ name: "Inventory",+ to: "inventory",+ role: ["employee", "supplier"],+ },+ {+ name: "Sale Price",+ to: "sale-price",+ role: ["employee", "customer"],+ },+ ].filter(+ (item) =>+ !item.isDisabled &&+ (item.role === undefined ||+ item.role.some((role) => permissions.is(role as Role)))+ );+}diff --git a/apps/carbon/app/modules/parts/interfaces/Part/index.ts b/apps/carbon/app/modules/parts/interfaces/Part/index.tsnew file mode 100644index 0000000000..28b261070d--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Part/index.ts@@ -0,0 +1,21 @@+import PartCostingForm from "./PartCostingForm";+import PartForm from "./PartForm";+import PartInventoryForm from "./PartInventoryForm";+import PartManufacturingForm from "./PartManufacturingForm";+import PartPlanningForm from "./PartPlanningForm";+import PartPreview from "./PartPreview";+import PartPurchasingForm from "./PartPurchasingForm";+import PartSalePriceForm from "./PartSalePriceForm";+import PartSidebar from "./PartSidebar";++export {+ PartCostingForm,+ PartForm,+ PartInventoryForm,+ PartPlanningForm,+ PartPreview,+ PartManufacturingForm,+ PartPurchasingForm,+ PartSalePriceForm,+ PartSidebar,+};diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/PartGroupForm.tsx b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/PartGroupForm.tsxnew file mode 100644index 0000000000..ab5d743566--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/PartGroupForm.tsx@@ -0,0 +1,106 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import { ValidatedForm } from "remix-validated-form";+import { Hidden, Input, Select, Submit, TextArea } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { partGroupValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";+import { mapRowsToOptions } from "~/utils/form";++type PartGroupFormProps = {+ initialValues: TypeOfValidator<typeof partGroupValidator>;+ accounts: {+ number: string;+ name: string;+ }[];+};++const PartGroupForm = ({ accounts, initialValues }: PartGroupFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts");++ const accountOptions = mapRowsToOptions({+ data: accounts,+ value: "number",+ label: "name",+ });++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={partGroupValidator}+ method="post"+ action={+ isEditing+ ? `/x/parts/groups/${initialValues.id}`+ : "/x/parts/groups/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>{isEditing ? "Edit" : "New"} Part Group</DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <VStack spacing={4} alignItems="start">+ <Input name="name" label="Part Group" />+ <TextArea name="description" label="Description" />+ {permissions.has("accounting") && (+ <>+ <Select+ name="salesAccountId"+ label="Sales Account"+ options={accountOptions}+ />+ <Select+ name="discountAccountId"+ label="Discount Account"+ options={accountOptions}+ />+ <Select+ name="inventoryAccountId"+ label="Inventory Account"+ options={accountOptions}+ />+ </>+ )}+ </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 PartGroupForm;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/index.ts b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/index.tsnew file mode 100644index 0000000000..4f38fd77ed--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupForm/index.ts@@ -0,0 +1,3 @@+import PartGroupForm from "./PartGroupForm";++export default PartGroupForm;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsxnew file mode 100644index 0000000000..539b970d63--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/PartGroupsTable.tsx@@ -0,0 +1,99 @@+import { 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 { PartGroup } from "~/modules/parts";++type PartGroupsTableProps = {+ data: PartGroup[];+ count: number;+};++const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const permissions = usePermissions();+ const hasAccounting =+ permissions.has("accounting") && permissions.can("view", "accounting");++ const rows = useMemo(() => data, [data]);++ const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {+ const result: ColumnDef<typeof rows[number]>[] = [+ {+ accessorKey: "name",+ header: "Name",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "description",+ header: "Description",+ cell: (item) => item.getValue(),+ },+ ];++ return hasAccounting+ ? result.concat([+ {+ accessorKey: "salesAccountId",+ header: "Sales Account",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "inventoryAccountId",+ header: "Inventory Account",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "discountAccountId",+ header: "Discount Account",+ cell: (item) => item.getValue(),+ },+ ])+ : result;+ }, [hasAccounting]);++ const renderContextMenu = useCallback(+ (row: typeof rows[number]) => {+ return (+ <>+ <MenuItem+ isDisabled={!permissions.can("update", "parts")}+ icon={<BsPencilSquare />}+ onClick={() => {+ navigate(`/x/parts/groups/${row.id}?${params.toString()}`);+ }}+ >+ Edit Part Group+ </MenuItem>+ <MenuItem+ isDisabled={!permissions.can("delete", "parts")}+ icon={<IoMdTrash />}+ onClick={() => {+ navigate(`/x/parts/groups/delete/${row.id}?${params.toString()}`);+ }}+ >+ Delete Part Group+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions]+ );++ return (+ <Table<typeof rows[number]>+ data={data}+ columns={columns}+ count={count}+ renderContextMenu={renderContextMenu}+ />+ );+});++PartGroupsTable.displayName = "PartGroupsTable";+export default PartGroupsTable;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/index.ts b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/index.tsnew file mode 100644index 0000000000..9ceb279c29--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTable/index.ts@@ -0,0 +1,3 @@+import PartGroupsTable from "./PartGroupsTable";++export default PartGroupsTable;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.tsxnew file mode 100644index 0000000000..a21c88d918--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/PartGroupsTableFilters.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 PartGroupsTableFilters = () => {+ 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", "parts") && (+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Part Group+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default PartGroupsTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/index.ts b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/index.tsnew file mode 100644index 0000000000..4bd33b238b--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/PartGroupsTableFilters/index.ts@@ -0,0 +1,3 @@+import PartGroupsTableFilters from "./PartGroupsTableFilters";++export default PartGroupsTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/PartGroups/index.ts b/apps/carbon/app/modules/parts/interfaces/PartGroups/index.tsnew file mode 100644index 0000000000..000e6b6296--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/PartGroups/index.ts@@ -0,0 +1,5 @@+import PartGroupForm from "./PartGroupForm";+import PartGroupsTable from "./PartGroupsTable";+import PartGroupsTableFilters from "./PartGroupsTableFilters";++export { PartGroupForm, PartGroupsTable, PartGroupsTableFilters };diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsxnew file mode 100644index 0000000000..bd5d460252--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/PartsTable.tsx@@ -0,0 +1,83 @@+import { MenuItem } from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useMemo } from "react";+import { BsPencilSquare } from "react-icons/bs";+import { Table } from "~/components";+import { useUrlParams } from "~/hooks";+import type { PartsTableRow } from "~/modules/parts";++type PartsTableProps = {+ data: PartsTableRow[];+ count: number;+};++const PartsTable = memo(({ data, count }: PartsTableProps) => {+ const navigate = useNavigate();+ const [params] = useUrlParams();++ const columns = useMemo<ColumnDef<PartsTableRow>[]>(() => {+ return [+ {+ accessorKey: "id",+ header: "Part ID",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "name",+ header: "Name",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "description",+ header: "Description",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "partType",+ header: "Part Type",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "replenishmentSystem",+ header: "Replenishment",+ cell: (item) => item.getValue(),+ },+ {+ // @ts-ignore+ accessorFn: (item) => item.partGroup?.name ?? "",+ header: "Part Group",+ cell: (item) => item.getValue(),+ },+ ];+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [params]);++ const renderContextMenu = useMemo(() => {+ // eslint-disable-next-line react/display-name+ return (row: PartsTableRow) => (+ <MenuItem+ icon={<BsPencilSquare />}+ onClick={() => navigate(`/x/part/${row.id}`)}+ >+ View Part+ </MenuItem>+ );+ }, [navigate]);++ return (+ <>+ <Table<PartsTableRow>+ count={count}+ columns={columns}+ data={data}+ withPagination+ renderContextMenu={renderContextMenu}+ />+ </>+ );+});++PartsTable.displayName = "PartTable";++export default PartsTable;diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/index.ts b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/index.tsnew file mode 100644index 0000000000..e0b6a661a1--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTable/index.ts@@ -0,0 +1,3 @@+import PartsTable from "./PartsTable";++export default PartsTable;diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsxnew file mode 100644index 0000000000..61ff3729a9--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/PartsTableFilters.tsx@@ -0,0 +1,102 @@+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 type { PartType } from "~/modules/parts";+import { mapRowsToOptions } from "~/utils/form";++type PartsTableFiltersProps = {+ partTypes: PartType[];+ partGroups: { id: string; name: string }[];+};++const PartsTableFilters = ({+ partTypes,+ partGroups,+}: PartsTableFiltersProps) => {+ const [params, setParams] = useUrlParams();+ const permissions = usePermissions();+ const partTypeOptions = partTypes.map((type) => ({+ value: type,+ label: type,+ }));++ const partGroupsOptions = mapRowsToOptions({+ data: partGroups,+ value: "id",+ label: "name",+ });++ 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="search"+ size="sm"+ minW={180}+ placeholder="Search Parts"+ />+ {partGroupsOptions && (+ <Select+ // @ts-ignore+ size="sm"+ isClearable+ value={partGroupsOptions.filter(+ (type) => type.value === params.get("group")+ )}+ options={partGroupsOptions}+ onChange={(selected) => {+ setParams({ group: selected?.value });+ }}+ aria-label="Groups"+ placeholder="Part Groups"+ minW={180}+ />+ )}+ {partTypeOptions.length > 0 && (+ <Select+ // @ts-ignore+ size="sm"+ value={partTypeOptions.filter(+ (type) => type.value === params.get("type")+ )}+ isClearable+ options={partTypeOptions}+ onChange={(selected) => {+ setParams({ type: selected?.value });+ }}+ aria-label="Part Type"+ placeholder="Part Type"+ minW={180}+ />+ )}+ </HStack>+ <HStack spacing={2}>+ {permissions.can("create", "parts") && (+ <Button+ as={Link}+ to={`../../part/new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Part+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default PartsTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/index.ts b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/index.tsnew file mode 100644index 0000000000..7180390d60--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Parts/PartsTableFilters/index.ts@@ -0,0 +1,3 @@+import PartsTableFilters from "./PartsTableFilters";++export default PartsTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/Parts/index.ts b/apps/carbon/app/modules/parts/interfaces/Parts/index.tsnew file mode 100644index 0000000000..27b98ba2ee--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Parts/index.ts@@ -0,0 +1,4 @@+import PartsTable from "./PartsTable";+import PartsTableFilters from "./PartsTableFilters";++export { PartsTable, PartsTableFilters };diff --git a/apps/carbon/app/modules/parts/interfaces/Toolbar/PartsTree.tsx b/apps/carbon/app/modules/parts/interfaces/Routing/PartsTree/PartsTree.tsxsimilarity index 100%rename from apps/carbon/app/modules/parts/interfaces/Toolbar/PartsTree.tsxrename to apps/carbon/app/modules/parts/interfaces/Routing/PartsTree/PartsTree.tsxdiff --git a/apps/carbon/app/modules/parts/interfaces/Routing/PartsTree/index.ts b/apps/carbon/app/modules/parts/interfaces/Routing/PartsTree/index.tsnew file mode 100644index 0000000000..a0a33672da--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/Routing/PartsTree/index.ts@@ -0,0 +1,3 @@+import PartsTree from "./PartsTree";++export default PartsTree;diff --git a/apps/carbon/app/modules/parts/interfaces/Toolbar/index.ts b/apps/carbon/app/modules/parts/interfaces/Routing/index.tssimilarity index 100%rename from apps/carbon/app/modules/parts/interfaces/Toolbar/index.tsrename to apps/carbon/app/modules/parts/interfaces/Routing/index.tsdiff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/UnitOfMeasureForm.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/UnitOfMeasureForm.tsxnew file mode 100644index 0000000000..f845f3b7e8--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/UnitOfMeasureForm.tsx@@ -0,0 +1,80 @@+import {+ Button,+ Drawer,+ DrawerBody,+ DrawerCloseButton,+ DrawerContent,+ DrawerFooter,+ DrawerHeader,+ DrawerOverlay,+ HStack,+ VStack,+} from "@chakra-ui/react";+import { useNavigate } from "@remix-run/react";+import { ValidatedForm } from "remix-validated-form";+import { Hidden, Input, Submit } from "~/components/Form";+import { usePermissions } from "~/hooks";+import { unitOfMeasureValidator } from "~/modules/parts";+import type { TypeOfValidator } from "~/types/validators";++type UnitOfMeasureFormProps = {+ initialValues: TypeOfValidator<typeof unitOfMeasureValidator>;+};++const UnitOfMeasureForm = ({ initialValues }: UnitOfMeasureFormProps) => {+ const permissions = usePermissions();+ const navigate = useNavigate();+ const onClose = () => navigate(-1);++ const isEditing = initialValues.id !== undefined;+ const isDisabled = isEditing+ ? !permissions.can("update", "parts")+ : !permissions.can("create", "parts");++ return (+ <Drawer onClose={onClose} isOpen={true} size="sm">+ <ValidatedForm+ validator={unitOfMeasureValidator}+ method="post"+ action={+ isEditing ? `/x/parts/uom/${initialValues.id}` : "/x/parts/uom/new"+ }+ defaultValues={initialValues}+ >+ <DrawerOverlay />+ <DrawerContent>+ <DrawerCloseButton />+ <DrawerHeader>+ {isEditing ? "Edit" : "New"} Unit of Measure+ </DrawerHeader>+ <DrawerBody pb={8}>+ <Hidden name="id" />+ <VStack spacing={4} alignItems="start">+ <Input name="name" label="Unit of Measure" />+ <Input+ name="code"+ label="Code"+ helperText="Unique, uppercase, without spaces"+ />+ </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 UnitOfMeasureForm;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/index.ts b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/index.tsnew file mode 100644index 0000000000..27ed28fa35--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasureForm/index.ts@@ -0,0 +1,3 @@+import UnitOfMeasureForm from "./UnitOfMeasureForm";++export default UnitOfMeasureForm;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsxnew file mode 100644index 0000000000..32e8a477bd--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/UnitOfMeasuresTable.tsx@@ -0,0 +1,82 @@+import { 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 { UnitOfMeasure } from "~/modules/parts";++type UnitOfMeasuresTableProps = {+ data: UnitOfMeasure[];+ count: number;+};++const UnitOfMeasuresTable = memo(+ ({ data, count }: UnitOfMeasuresTableProps) => {+ const [params] = useUrlParams();+ const navigate = useNavigate();+ const permissions = usePermissions();++ const columns = useMemo<ColumnDef<typeof data[number]>[]>(() => {+ return [+ {+ header: "Component",+ cell: ({ row }) => <p>{row.original.name}</p>,+ },+ {+ accessorKey: "name",+ header: "Name",+ cell: (item) => item.getValue(),+ },+ {+ accessorKey: "code",+ header: "Code",+ cell: (item) => item.getValue(),+ },+ ];+ }, []);++ const renderContextMenu = useCallback(+ (row: typeof data[number]) => {+ return (+ <>+ <MenuItem+ isDisabled={!permissions.can("update", "parts")}+ icon={<BsPencilSquare />}+ onClick={() => {+ navigate(`/x/parts/uom/${row.id}?${params.toString()}`);+ }}+ >+ Edit Unit of Measure+ </MenuItem>+ <MenuItem+ isDisabled={!permissions.can("delete", "parts")}+ icon={<IoMdTrash />}+ onClick={() => {+ navigate(`/x/parts/uom/delete/${row.id}?${params.toString()}`);+ }}+ >+ Delete Unit of Measure+ </MenuItem>+ </>+ );+ },+ [navigate, params, permissions]+ );++ return (+ <Table<typeof data[number]>+ data={data}+ columns={columns}+ count={count}+ renderContextMenu={renderContextMenu}+ withInlineEditing+ />+ );+ }+);++UnitOfMeasuresTable.displayName = "UnitOfMeasuresTable";+export default UnitOfMeasuresTable;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/index.ts b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/index.tsnew file mode 100644index 0000000000..b340f6f46d--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTable/index.ts@@ -0,0 +1,3 @@+import UnitOfMeasuresTable from "./UnitOfMeasuresTable";++export default UnitOfMeasuresTable;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsx b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.tsxnew file mode 100644index 0000000000..55ddada23b--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/UnitOfMeasuresTableFilters.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 UnitOfMeasuresTableFilters = () => {+ 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", "parts") && (+ <Button+ as={Link}+ to={`new?${params.toString()}`}+ colorScheme="brand"+ leftIcon={<IoMdAdd />}+ >+ New Unit of Measure+ </Button>+ )}+ </HStack>+ </HStack>+ );+};++export default UnitOfMeasuresTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/index.ts b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/index.tsnew file mode 100644index 0000000000..a000227b84--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/UnitOfMeasuresTableFilters/index.ts@@ -0,0 +1,3 @@+import UnitOfMeasuresTableFilters from "./UnitOfMeasuresTableFilters";++export default UnitOfMeasuresTableFilters;diff --git a/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/index.ts b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/index.tsnew file mode 100644index 0000000000..5c5857579c--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/UnitOfMeasure/index.ts@@ -0,0 +1,5 @@+import UnitOfMeasureForm from "./UnitOfMeasureForm";+import UnitOfMeasuresTable from "./UnitOfMeasuresTable";+import UnitOfMeasuresTableFilters from "./UnitOfMeasuresTableFilters";++export { UnitOfMeasureForm, UnitOfMeasuresTable, UnitOfMeasuresTableFilters };diff --git a/apps/carbon/app/modules/parts/interfaces/index.ts b/apps/carbon/app/modules/parts/interfaces/index.tsindex 57e6cb1ed4..0745960a92 100644--- a/apps/carbon/app/modules/parts/interfaces/index.ts+++ b/apps/carbon/app/modules/parts/interfaces/index.ts@@ -1,3 +1,8 @@-import { PartsTree } from "./Toolbar";+import usePartsSidebar from "./usePartsSidebar";-export { PartsTree };+export { usePartsSidebar };+export * from "./Part";+export * from "./Parts";+export * from "./PartGroups";+export * from "./Routing";+export * from "./UnitOfMeasure";diff --git a/apps/carbon/app/modules/parts/interfaces/usePartsSidebar.tsx b/apps/carbon/app/modules/parts/interfaces/usePartsSidebar.tsxnew file mode 100644index 0000000000..cb726be141--- /dev/null+++ b/apps/carbon/app/modules/parts/interfaces/usePartsSidebar.tsx@@ -0,0 +1,62 @@+import { usePermissions } from "~/hooks";+import type { AuthenticatedRouteGroup } from "~/types";++const partsRoutes: AuthenticatedRouteGroup[] = [+ {+ name: "Manage",+ routes: [+ {+ name: "Parts",+ to: "/x/parts/search",+ },+ {+ name: "Routing",+ to: "/x/parts/routing",+ role: "employee",+ },+ ],+ },+ {+ name: "Configure",+ routes: [+ {+ name: "Part Groups",+ to: "/x/parts/groups",+ role: "employee",+ },+ {+ name: "Units of Measure",+ to: "/x/parts/uom",+ role: "employee",+ },+ ],+ },+];++export default function usePartsSidebar() {+ const permissions = usePermissions();+ return {+ groups: partsRoutes+ .filter((group) => {+ const filteredRoutes = group.routes.filter((route) => {+ if (route.role) {+ return permissions.is(route.role);+ } else {+ return true;+ }+ });++ return filteredRoutes.length > 0;+ })+ .map((group) => ({+ ...group,+ routes: group.routes.filter((route) => {+ if (route.role) {+ return permissions.is(route.role);+ } else {+ return true;+ }+ }),+ })),+ };+}diff --git a/apps/carbon/app/modules/parts/services/index.ts b/apps/carbon/app/modules/parts/services/index.tsnew file mode 100644index 0000000000..a8afb5ec4d--- /dev/null+++ b/apps/carbon/app/modules/parts/services/index.ts@@ -0,0 +1,2 @@+export * from "./parts.form";+export * from "./parts.server";diff --git a/apps/carbon/app/modules/parts/services/parts.form.ts b/apps/carbon/app/modules/parts/services/parts.form.tsnew file mode 100644index 0000000000..2ef77dfa74--- /dev/null+++ b/apps/carbon/app/modules/parts/services/parts.form.ts@@ -0,0 +1,149 @@+import { withZod } from "@remix-validated-form/with-zod";+import { z } from "zod";+import { zfd } from "zod-form-data";++export const partValidator = withZod(+ z.object({+ id: z.string().min(1, { message: "Part ID is required" }).max(255),+ name: z.string().min(1, { message: "Name is required" }).max(255),+ description: zfd.text(z.string().optional()),+ blocked: zfd.checkbox(),+ active: zfd.checkbox(),+ replenishmentSystem: z.enum(["Buy", "Make", "Buy and Make"], {+ errorMap: (issue, ctx) => ({+ message: "Replenishment system is required",+ }),+ }),+ partGroupId: z.string().min(1, { message: "Part Group is required" }),+ partType: z.enum(["Inventory", "Non-Inventory", "Service"], {+ errorMap: (issue, ctx) => ({+ message: "Part type is required",+ }),+ }),+ unitOfMeasureCode: z+ .string()+ .min(1, { message: "Unit of Measure is required" }),+ })+);++export const partCostValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ costingMethod: z.enum(["Standard", "Average", "FIFO", "LIFO"], {+ errorMap: (issue, ctx) => ({+ message: "Costing method is required",+ }),+ }),+ standardCost: zfd.numeric(z.number().min(0)),+ unitCost: zfd.numeric(z.number().min(0)),+ costIsAdjusted: zfd.checkbox(),+ })+);++export const partGroupValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ name: z.string().min(1, { message: "Name is required" }).max(255),+ description: z.string().optional(),+ salesAccountId: zfd.text(z.string().optional()),+ discountAccountId: zfd.text(z.string().optional()),+ inventoryAccountId: zfd.text(z.string().optional()),+ // costOfGoodsSoldLaborAccountId: zfd.text(z.string().optional()),+ // costOfGoodsSoldMaterialAccountId: zfd.text(z.string().optional()),+ // costOfGoodsSoldOverheadAccountId: zfd.text(z.string().optional()),+ // costOfGoodsSoldSubcontractAccountId: zfd.text(z.string().optional()),+ })+);++export const partInventoryValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ shelfId: zfd.text(z.string().optional()),+ hasNewShelf: z.enum(["true", "false"]),+ stockoutWarning: zfd.checkbox(),+ unitVolume: zfd.numeric(z.number().min(0)),+ unitWeight: zfd.numeric(z.number().min(0)),+ })+);++export const partManufacturingValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ manufacturingPolicy: z.enum(["Make to Order", "Make to Stock"], {+ errorMap: (issue, ctx) => ({+ message: "Manufacturing policy is required",+ }),+ }),+ manufacturingLeadTime: zfd.numeric(z.number().min(0)),+ manufacturingBlocked: zfd.checkbox(),+ requiresConfiguration: zfd.checkbox(),+ scrapPercentage: zfd.numeric(z.number().min(0).max(100)),+ lotSize: zfd.numeric(z.number().min(0)),+ })+);++export const partPlanningValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ reorderingPolicy: z.enum(+ [+ "Manual Reorder",+ "Demand-Based Reorder",+ "Fixed Reorder Quantity",+ "Maximum Quantity",+ ],+ {+ errorMap: (issue, ctx) => ({+ message: "Reordering policy is required",+ }),+ }+ ),+ critical: zfd.checkbox(),+ safetyStockQuantity: zfd.numeric(z.number().min(0)),+ safetyStockLeadTime: zfd.numeric(z.number().min(0)),+ demandAccumulationPeriod: zfd.numeric(z.number().min(0)),+ demandReschedulingPeriod: zfd.numeric(z.number().min(0)),+ demandAccumulationIncludesInventory: zfd.checkbox(),+ reorderPoint: zfd.numeric(z.number().min(0)),+ reorderQuantity: zfd.numeric(z.number().min(0)),+ reorderMaximumInventory: zfd.numeric(z.number().min(0)),+ reorderOverflowLevel: zfd.numeric(z.number().min(0)),+ reorderTimeBucket: zfd.numeric(z.number().min(0)),+ minimumOrderQuantity: zfd.numeric(z.number().min(0)),+ maximumOrderQuantity: zfd.numeric(z.number().min(0)),+ orderMultiple: zfd.numeric(z.number().min(1)),+ })+);++export const partPurchasingValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ supplierId: zfd.text(z.string().optional()),+ supplierPartNumber: zfd.text(z.string().optional()),+ purchasingLeadTime: zfd.numeric(z.number().min(0)),+ purchasingUnitOfMeasureCode: zfd.text(z.string().optional()),+ purchasingBlocked: zfd.checkbox(),+ })+);++export const partUnitSalePriceValidator = withZod(+ z.object({+ partId: z.string().min(1, { message: "Part ID is required" }),+ unitSalePrice: zfd.numeric(z.number().min(0)),+ currencyCode: z.string().min(1, { message: "Currency is required" }),+ salesUnitOfMeasureCode: z+ .string()+ .min(1, { message: "Unit of Measure is required" }),+ salesBlocked: zfd.checkbox(),+ priceIncludesTax: zfd.checkbox(),+ allowInvoiceDiscount: zfd.checkbox(),+ })+);++export const unitOfMeasureValidator = withZod(+ z.object({+ id: zfd.text(z.string().optional()),+ code: z.string().min(1, { message: "Code is required" }).max(5),+ name: z.string().min(1, { message: "Name is required" }).max(50),+ })+);diff --git a/apps/carbon/app/modules/parts/services/parts.server.ts b/apps/carbon/app/modules/parts/services/parts.server.tsnew file mode 100644index 0000000000..96b7092c88--- /dev/null+++ b/apps/carbon/app/modules/parts/services/parts.server.ts@@ -0,0 +1,399 @@+import type { Database } from "@carbon/database";+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 type {+ partCostValidator,+ partInventoryValidator,+ partManufacturingValidator,+ partPlanningValidator,+ partPurchasingValidator,+ partUnitSalePriceValidator,+ partValidator,+} from "./parts.form";++export async function deletePartGroup(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partGroup").update({ active: false }).eq("id", id);+}++export async function deleteUnitOfMeasure(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("unitOfMeasure").delete().eq("id", id);+}++export async function getPartCost(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("partCost")+ .select(+ "partId, costingMethod, standardCost, unitCost, salesAccountId, discountAccountId, inventoryAccountId, costIsAdjusted"+ )+ .eq("partId", id)+ .single();+}++export async function getPartGroup(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("partGroup")+ .select(+ "id, name, description, salesAccountId, discountAccountId, inventoryAccountId"+ )+ .eq("id", id)+ .single();+}++export async function getPartGroups(+ client: SupabaseClient<Database>,+ args?: GenericQueryFilters & { name: string | null }+) {+ let query = client+ .from("partGroup")+ .select(+ "id, name, description, salesAccountId, discountAccountId, inventoryAccountId",+ {+ count: "exact",+ }+ );++ if (args?.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, "name");+ }++ return query;+}++export async function getPartGroupsList(+ client: SupabaseClient<Database>,+ args?: GenericQueryFilters & { name: string | null }+) {+ let query = client.from("partGroup").select("id, name", { count: "exact" });++ if (args?.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ if (args) {+ query = setGenericQueryFilters(query, args, "name");+ }++ return query;+}++export async function getPartInventory(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partInventory").select("*").eq("partId", id).single();+}++export async function getPartManufacturing(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partReplenishment").select("*").eq("partId", id).single();+}++export async function getPartPlanning(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partPlanning").select("*").eq("partId", id).single();+}++export async function getPartPurchasing(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partReplenishment").select("*").eq("partId", id).single();+}++export async function getParts(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & {+ search: string | null;+ type: string | null;+ group: string | null;+ }+) {+ let query = client+ .from("part")+ .select(+ "id, name, description, partType, partGroup(name), replenishmentSystem",+ {+ count: "exact",+ }+ );++ if (args.search) {+ query = query.or(+ `id.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`+ );+ }++ if (args.type) {+ query = query.eq("partType", args.type);+ }++ if (args.group) {+ query = query.eq("partGroupId", args.group);+ }++ query = setGenericQueryFilters(query, args, "id");+ return query;+}++export async function getPartSummary(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("part")+ .select(+ "id, name, description, partType, replenishmentSystem, partType, unitOfMeasureCode, partGroupId, blocked, active"+ )+ .eq("id", id)+ .single();+}++export async function getPartUnitSalePrice(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("partUnitSalePrice").select("*").eq("partId", id).single();+}++export function getPartTypes(): Database["public"]["Enums"]["partType"][] {+ return ["Inventory", "Non-Inventory", "Service"];+}++export function getPartRorderdingPolicies(): Database["public"]["Enums"]["partReorderingPolicy"][] {+ return [+ "Manual Reorder",+ "Demand-Based Reorder",+ "Fixed Reorder Quantity",+ "Maximum Quantity",+ ];+}++export function getPartReplenishmentSystems(): Database["public"]["Enums"]["partReplenishmentSystem"][] {+ return ["Buy", "Make", "Buy and Make"];+}++export function getPartManufacturingPolicies(): Database["public"]["Enums"]["partManufacturingPolicy"][] {+ return ["Make to Order", "Make to Stock"];+}++export function getPartCostingMethods(): Database["public"]["Enums"]["partCostingMethod"][] {+ return ["Standard", "Average", "FIFO", "LIFO"];+}++export async function getShelvesList(client: SupabaseClient<Database>) {+ return client.from("shelf").select("id").eq("active", true);+}++export async function getUnitOfMeasure(+ client: SupabaseClient<Database>,+ id: string+) {+ return client+ .from("unitOfMeasure")+ .select("id, name, code")+ .eq("id", id)+ .single();+}++export async function getUnitOfMeasures(+ client: SupabaseClient<Database>,+ args: GenericQueryFilters & { name: string | null }+) {+ let query = client.from("unitOfMeasure").select("id, name, code", {+ count: "exact",+ });++ if (args.name) {+ query = query.ilike("name", `%${args.name}%`);+ }++ query = setGenericQueryFilters(query, args, "name");+ return query;+}++export async function getUnitOfMeasuresList(client: SupabaseClient<Database>) {+ return client.from("unitOfMeasure").select("name, code");+}++export async function insertShelf(+ client: SupabaseClient<Database>,+ shelfId: string,+ userId: string+) {+ const shelfLookup = await client.from("shelf").select("id").eq("id", shelfId);+ if (shelfLookup.error) return shelfLookup;++ // the shelf is inactive, so we can just reactivate it+ if (shelfLookup.data?.length) {+ return client.from("shelf").update({ active: true }).eq("id", shelfId);+ }++ // otherwise we'll create a new shelf+ return client+ .from("shelf")+ .insert([+ {+ id: shelfId,+ createdBy: userId,+ },+ ])+ .select("id");+}++export async function upsertPart(+ client: SupabaseClient<Database>,+ part:+ | (TypeOfValidator<typeof partValidator> & { createdBy: string })+ | (TypeOfValidator<typeof partValidator> & { updatedBy: string })+) {+ if ("createdBy" in part) {+ return client.from("part").insert(part).select("id");+ }+ return client.from("part").update(part).eq("id", part.id);+}++export async function upsertPartCost(+ client: SupabaseClient<Database>,+ partCost: TypeOfValidator<typeof partCostValidator> & { updatedBy: string }+) {+ return client.from("partCost").update(partCost).eq("partId", partCost.partId);+}++export async function upsertPartInventory(+ client: SupabaseClient<Database>,+ partInventory: Omit<+ TypeOfValidator<typeof partInventoryValidator>,+ "hasNewShelf"+ > & {+ updatedBy: string;+ }+) {+ return client+ .from("partInventory")+ .update({+ ...partInventory,+ shelfId: partInventory.shelfId || null,+ })+ .eq("partId", partInventory.partId);+}++export async function upsertPartManufacturing(+ client: SupabaseClient<Database>,+ partManufacturing: TypeOfValidator<typeof partManufacturingValidator> & {+ updatedBy: string;+ }+) {+ return client+ .from("partReplenishment")+ .update(partManufacturing)+ .eq("partId", partManufacturing.partId);+}++export async function upsertPartPlanning(+ client: SupabaseClient<Database>,+ partPlanning: TypeOfValidator<typeof partPlanningValidator> & {+ updatedBy: string;+ }+) {+ return client+ .from("partPlanning")+ .update(partPlanning)+ .eq("partId", partPlanning.partId);+}++export async function upsertPartPurchasing(+ client: SupabaseClient<Database>,+ partPurchasing: TypeOfValidator<typeof partPurchasingValidator> & {+ updatedBy: string;+ }+) {+ return client+ .from("partReplenishment")+ .update(partPurchasing)+ .eq("partId", partPurchasing.partId);+}++export async function upsertPartGroup(+ client: SupabaseClient<Database>,+ partGroup:+ | {+ name: string;+ description?: string;+ salesAccountId?: string | null;+ inventoryAccountId?: string | null;+ discountAccountId?: string | null;+ createdBy: string;+ }+ | {+ id: string;+ name: string;+ description?: string;+ salesAccountId?: string | null;+ inventoryAccountId?: string | null;+ discountAccountId?: string | null;+ updatedBy: string;+ }+) {+ if ("createdBy" in partGroup) {+ return client.from("partGroup").insert([partGroup]).select("id");+ }+ return (+ client+ .from("partGroup")+ .update(partGroup)+ // @ts-ignore+ .eq("id", partGroup.id)+ .select("id")+ );+}++export async function upsertPartUnitSalePrice(+ client: SupabaseClient<Database>,+ partUnitSalePrice: TypeOfValidator<typeof partUnitSalePriceValidator> & {+ updatedBy: string;+ }+) {+ return client+ .from("partUnitSalePrice")+ .update(partUnitSalePrice)+ .eq("partId", partUnitSalePrice.partId);+}++export async function upsertUnitOfMeasure(+ client: SupabaseClient<Database>,+ unitOfMeasure:+ | { name: string; code: string; createdBy: string }+ | { id: string; name: string; code: string; updatedBy: string }+) {+ if ("id" in unitOfMeasure) {+ return client+ .from("unitOfMeasure")+ .update(unitOfMeasure)+ .eq("id", unitOfMeasure.id)+ .select("id");+ }++ return client.from("unitOfMeasure").insert([unitOfMeasure]).select("id");+}diff --git a/apps/carbon/app/modules/parts/types.ts b/apps/carbon/app/modules/parts/types.tsnew file mode 100644index 0000000000..e1acc3ef1d--- /dev/null+++ b/apps/carbon/app/modules/parts/types.ts@@ -0,0 +1,52 @@+import type { Database } from "@carbon/database";+import type {+ getPartCost,+ getPartGroups,+ getPartGroupsList,+ getParts,+ getPartSummary,+ getUnitOfMeasure,+ getUnitOfMeasuresList,+} from "./services";++export type PartCost = NonNullable<+ Awaited<ReturnType<typeof getPartCost>>+>["data"];++export type PartCostingMethod =+ Database["public"]["Enums"]["partCostingMethod"];++export type PartGroup = NonNullable<+ Awaited<ReturnType<typeof getPartGroups>>["data"]+>[number];++export type PartGroupListItem = NonNullable<+ Awaited<ReturnType<typeof getPartGroupsList>>["data"]+>[number];++export type PartReorderingPolicy =+ Database["public"]["Enums"]["partReorderingPolicy"];++export type PartReplenishmentSystem =+ Database["public"]["Enums"]["partReplenishmentSystem"];++export type PartSummary = NonNullable<+ Awaited<ReturnType<typeof getPartSummary>>+>["data"];++export type PartManufacturingPolicy =+ Database["public"]["Enums"]["partManufacturingPolicy"];++export type PartsTableRow = NonNullable<+ Awaited<ReturnType<typeof getParts>>["data"]+>[number];++export type PartType = Database["public"]["Enums"]["partType"];++export type UnitOfMeasure = NonNullable<+ Awaited<ReturnType<typeof getUnitOfMeasure>>["data"]+>;++export type UnitOfMeasureListItem = NonNullable<+ Awaited<ReturnType<typeof getUnitOfMeasuresList>>["data"]+>[number];diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsxindex c04ea3af80..dab5697096 100644--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SuppliersTable/SuppliersTable.tsx@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import { BsPencilSquare, BsPlus } from "react-icons/bs";import { Table } from "~/components";-import { usePermissions, useUrlParams } from "~/hooks";+import { useUrlParams } from "~/hooks";import type { Supplier } from "~/modules/purchasing";type SuppliersTableProps = {@@ -14,7 +14,6 @@ type SuppliersTableProps = {const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {const navigate = useNavigate();- const permissions = usePermissions();const [params] = useUrlParams();const columns = useMemo<ColumnDef<Supplier>[]>(() => {@@ -78,24 +77,21 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [params]);- const renderContextMenu = useMemo(() => {- return permissions.can("update", "purchasing")- ? (row: Supplier) => {- return (- <MenuItem- icon={<BsPencilSquare />}- onClick={() =>- navigate(- `/x/purchasing/suppliers/${row.id}?${params.toString()}`- )- }- >- Edit Supplier- </MenuItem>- );- }- : undefined;- }, [navigate, params, permissions]);+ const renderContextMenu = useMemo(+ // eslint-disable-next-line react/display-name+ () => (row: Supplier) =>+ (+ <MenuItem+ icon={<BsPencilSquare />}+ onClick={() =>+ navigate(`/x/purchasing/suppliers/${row.id}?${params.toString()}`)+ }+ >+ View Supplier+ </MenuItem>+ ),+ [navigate, params]+ );return (<>diff --git a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsxindex a49e1cf97a..93bd009ada 100644--- a/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx+++ b/apps/carbon/app/modules/resources/interfaces/Equipment/EquipmentTypeDetail/EquipmentTypeDetail.tsx@@ -20,7 +20,7 @@ import { useState } from "react";import { BsPencilSquare } from "react-icons/bs";import { IoMdTrash } from "react-icons/io";import { ConfirmDelete } from "~/components/Modals";-import type { EquipmentTypeDetail as EquipmentTypeDetailType } from "~/modules/resources";+import type { EquipmentTypeDetailType } from "~/modules/resources";import { useUrlParams } from "~/hooks";type Equipment = {@@ -88,7 +88,8 @@ const EquipmentTypeDetail = ({<VStack spacing={0} flexGrow={1} alignItems="start"><Text fontWeight="bold">{equipment.name}</Text><Text fontSize="sm" color="gray.500">- Work Center T00D00+ {/* @ts-ignore */}+ {equipment.location?.name}</Text></VStack><ActionMenu>{renderContextMenu(equipment)}</ActionMenu>diff --git a/apps/carbon/app/modules/resources/interfaces/People/PeopleTable/PeopleTable.tsx b/apps/carbon/app/modules/resources/interfaces/People/PeopleTable/PeopleTable.tsxindex 5e5d15107a..21a6ffbac3 100644--- a/apps/carbon/app/modules/resources/interfaces/People/PeopleTable/PeopleTable.tsx+++ b/apps/carbon/app/modules/resources/interfaces/People/PeopleTable/PeopleTable.tsx@@ -193,7 +193,7 @@ const PeopleTable = memo()}>- Edit Employee+ View Employee</MenuItem>);}diff --git a/apps/carbon/app/modules/resources/services/resources.server.ts b/apps/carbon/app/modules/resources/services/resources.server.tsindex f50b5d24d6..5639db326f 100644--- a/apps/carbon/app/modules/resources/services/resources.server.ts+++ b/apps/carbon/app/modules/resources/services/resources.server.ts@@ -394,7 +394,7 @@ export async function getEquipmentType(return client.from("equipmentType").select(- "id, name, color, description, requiredAbility, equipment(id, name)"+ "id, name, color, description, requiredAbility, equipment(id, name, location(id, name))").eq("active", true).eq("id", equipmentTypeId)diff --git a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsxindex d556ed04c5..14f079164a 100644--- a/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx+++ b/apps/carbon/app/modules/sales/interfaces/CustomerTypes/CustomerTypeForm/CustomerTypeForm.tsx@@ -28,8 +28,8 @@ const CustomerTypeForm = ({ initialValues }: CustomerTypeFormProps) => {const isEditing = initialValues.id !== undefined;const isDisabled = isEditing- ? !permissions.can("update", "purchasing")- : !permissions.can("create", "purchasing");+ ? !permissions.can("update", "sales")+ : !permissions.can("create", "sales");return (<Drawer onClose={onClose} isOpen={true} size="sm">diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsxindex c67bcfe39f..1354e80d07 100644--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomersTable/CustomersTable.tsx@@ -4,7 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import { BsPencilSquare, BsPlus } from "react-icons/bs";import { Table } from "~/components";-import { usePermissions, useUrlParams } from "~/hooks";+import { useUrlParams } from "~/hooks";import type { Customer } from "~/modules/sales";type CustomersTableProps = {@@ -14,7 +14,6 @@ type CustomersTableProps = {const CustomersTable = memo(({ data, count }: CustomersTableProps) => {const navigate = useNavigate();- const permissions = usePermissions();const [params] = useUrlParams();const columns = useMemo<ColumnDef<Customer>[]>(() => {@@ -77,22 +76,21 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {];}, []);- const renderContextMenu = useMemo(() => {- return permissions.can("update", "sales")- ? (row: Customer) => {- return (- <MenuItem- icon={<BsPencilSquare />}- onClick={() =>- navigate(`/x/sales/customers/${row.id}?${params.toString()}`)- }- >- Edit Customer- </MenuItem>- );- }- : undefined;- }, [navigate, params, permissions]);+ const renderContextMenu = useMemo(+ // eslint-disable-next-line react/display-name+ () => (row: Customer) =>+ (+ <MenuItem+ icon={<BsPencilSquare />}+ onClick={() =>+ navigate(`/x/sales/customers/${row.id}?${params.toString()}`)+ }+ >+ View Customer+ </MenuItem>+ ),+ [navigate, params]+ );return (<>diff --git a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsxindex 181a8620de..e0e6d75ce4 100644--- a/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx+++ b/apps/carbon/app/modules/users/interfaces/Employees/EmployeesTable/EmployeesTable.tsx@@ -196,14 +196,6 @@ const EmployeesTable = memo([deactivateEmployeeModal, navigate, params, resendInviteModal]);- // const editableComponents = useMemo(- // () => ({- // "user.firstName": EditableName,- // "user.lastName": EditableName,- // }),- // []- // );-return (<><Table<typeof rows[number]>diff --git a/apps/carbon/app/modules/users/services/users.server.ts b/apps/carbon/app/modules/users/services/users.server.tsindex 2c8ad46f43..c887c6c1af 100644--- a/apps/carbon/app/modules/users/services/users.server.ts+++ b/apps/carbon/app/modules/users/services/users.server.ts@@ -664,6 +664,7 @@ function makeCustomerClaims() {documents_view: true,jobs_view: true,sales_view: true,+ parts_view: true,};return claims;@@ -765,6 +766,7 @@ function makeSupplierClaims() {documents_view: true,inventory_view: true,purchasing_view: true,+ parts_view: true,};return claims;diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsxindex 837abcd274..6d8eca0449 100644--- a/apps/carbon/app/root.tsx+++ b/apps/carbon/app/root.tsx@@ -17,9 +17,13 @@ import React, { useContext, useEffect } from "react";import { getBrowserEnv } from "~/config/env";import { ServerStyleContext, ClientStyleContext } from "~/lib/emotion";import Background from "~/styles/background.css";+import NProgress from "~/styles/nprogress.css";export function links() {- return [{ rel: "stylesheet", href: Background }];+ return [+ { rel: "stylesheet", href: Background },+ { rel: "stylesheet", href: NProgress },+ ];}export const meta: MetaFunction = () => ({diff --git a/apps/carbon/app/routes/api+/accounting.currencies.tsx b/apps/carbon/app/routes/api+/accounting.currencies.tsxnew file mode 100644index 0000000000..f579eaaecb--- /dev/null+++ b/apps/carbon/app/routes/api+/accounting.currencies.tsx@@ -0,0 +1,10 @@+import type { LoaderArgs } from "@remix-run/node";+import { json } from "@remix-run/node";+import { getCurrenciesList } from "~/modules/accounting";+import { requirePermissions } from "~/services/auth";++export async function loader({ request }: LoaderArgs) {+ const authorized = await requirePermissions(request, {});++ return json(await getCurrenciesList(authorized.client));+}diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsxindex 0e3fd23d41..7d456e5852 100644--- a/apps/carbon/app/routes/x+/_layout.tsx+++ b/apps/carbon/app/routes/x+/_layout.tsx@@ -3,7 +3,8 @@ import { Flex, Grid, GridItem, VStack } from "@chakra-ui/react";import { SkipNavContent } from "@chakra-ui/skip-nav";import type { LoaderArgs } from "@remix-run/node";import { json } from "@remix-run/node";-import { Outlet, useLoaderData } from "@remix-run/react";+import { Outlet, useLoaderData, useTransition } from "@remix-run/react";+import NProgress from "nprogress";import { useEffect } from "react";import { IconSidebar, Topbar } from "~/components/Layout";import { getSupabase, SupabaseProvider } from "~/lib/supabase";@@ -56,7 +57,9 @@ export async function loader({ request }: LoaderArgs) {export default function AuthenticatedRoute() {const { session, result } = useLoaderData<typeof loader>();const notify = useNotification();+ const transition = useTransition();+ /* Toast Messages */useEffect(() => {if (result?.success === true) {notify.success(result.message);@@ -65,6 +68,15 @@ export default function AuthenticatedRoute() {}}, [result, notify]);+ /* NProgress */+ useEffect(() => {+ if (transition.state === "loading") {+ NProgress.start();+ } else {+ NProgress.done();+ }+ }, [transition.state]);+return (<SupabaseProvider session={session}><Grid h="100vh" w="100vw" templateColumns="auto 1fr">diff --git a/apps/carbon/app/routes/x+/part+/$partId.costing.tsx b/apps/carbon/app/routes/x+/part+/$partId.costing.tsxnew file mode 100644index 0000000000..4f36a26fa0--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.costing.tsx@@ -0,0 +1,101 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import { getAccountsList } from "~/modules/accounting";+import type { PartCostingMethod } from "~/modules/parts";+import {+ PartCostingForm,+ getPartCost,+ partCostValidator,+ upsertPartCost,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const [partCost, accounts] = await Promise.all([+ getPartCost(client, partId),+ getAccountsList(client),+ ]);++ if (partCost.error) {+ return redirect(+ "/x/parts",+ await flash(request, error(partCost.error, "Failed to load part costing"))+ );+ }+ if (accounts.error) {+ return redirect(+ "/x/parts",+ await flash(request, error(accounts.error, "Failed to load accounts"))+ );+ }++ return json({+ partCost: partCost.data,+ accounts: accounts.data,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partCostValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartCost = await upsertPartCost(client, {+ ...validation.data,+ partId,+ updatedBy: userId,+ });+ if (updatePartCost.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(updatePartCost.error, "Failed to update part costing")+ )+ );+ }++ return redirect(+ `/x/part/${partId}/costing`,+ await flash(request, success("Updated part costing"))+ );+}++export default function PartCostingRoute() {+ const sharedPartsData = useRouteData<{+ partCostingMethods: PartCostingMethod[];+ }>("/x/part");++ const { partCost, accounts } = useLoaderData<typeof loader>();+ return (+ <PartCostingForm+ initialValues={partCost}+ accounts={accounts}+ partCostingMethods={sharedPartsData?.partCostingMethods ?? []}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.index.tsx b/apps/carbon/app/routes/x+/part+/$partId.index.tsxnew file mode 100644index 0000000000..32a2de58de--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.index.tsx@@ -0,0 +1,86 @@+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useParams } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type {+ PartGroupListItem,+ PartReplenishmentSystem,+ PartSummary,+ PartType,+ UnitOfMeasureListItem,+} from "~/modules/parts";+import { PartForm, partValidator, upsertPart } from "~/modules/parts";+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: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePart = await upsertPart(client, {+ ...validation.data,+ id: partId,+ updatedBy: userId,+ });+ if (updatePart.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(request, error(updatePart.error, "Failed to update part"))+ );+ }++ return redirect(+ `/x/part/${partId}`,+ await flash(request, success("Updated part"))+ );+}++export default function PartBasicRoute() {+ const sharedPartsData = useRouteData<{+ partGroups: PartGroupListItem[];+ partTypes: PartType[];+ partReplenishmentSystems: PartReplenishmentSystem[];+ unitOfMeasures: UnitOfMeasureListItem[];+ }>("/x/part");++ const { partId } = useParams();+ const partData = useRouteData<PartSummary>(`/x/part/${partId}`);+ if (!partData) throw new Error("Could not find part data");++ const initialValues = {+ id: partData.id,+ name: partData.name ?? "",+ description: partData.description ?? undefined,+ partType: partData.partType,+ partGroupId: partData.partGroupId,+ replenishmentSystem: partData.replenishmentSystem,+ unitOfMeasureCode: partData.unitOfMeasureCode,+ blocked: partData.blocked,+ active: partData.active,+ };++ return (+ <PartForm+ initialValues={initialValues}+ partGroups={sharedPartsData?.partGroups ?? []}+ partTypes={sharedPartsData?.partTypes ?? []}+ partReplenishmentSystems={sharedPartsData?.partReplenishmentSystems ?? []}+ unitOfMeasures={sharedPartsData?.unitOfMeasures ?? []}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsxnew file mode 100644index 0000000000..a300773c02--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.inventory.tsx@@ -0,0 +1,114 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import {+ PartInventoryForm,+ getPartInventory,+ getShelvesList,+ insertShelf,+ partInventoryValidator,+ upsertPartInventory,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const [partInventory, shelves] = await Promise.all([+ getPartInventory(client, partId),+ getShelvesList(client),+ ]);++ if (partInventory.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(partInventory.error, "Failed to load part inventory")+ )+ );+ }+ if (shelves.error) {+ return redirect(+ "/x/parts",+ await flash(request, error(shelves.error, "Failed to load shelves"))+ );+ }++ return json({+ partInventory: partInventory.data,+ shelves: shelves.data.map((s) => s.id),+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partInventoryValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { hasNewShelf, ...update } = validation.data;++ if (hasNewShelf === "true" && update.shelfId) {+ const createShelf = await insertShelf(client, update.shelfId, userId);+ if (createShelf.error) {+ return redirect(+ `/x/part/${partId}/inventory`,+ await flash(+ request,+ error(createShelf.error, "Failed to create new shelf")+ )+ );+ }+ }++ const updatePartInventory = await upsertPartInventory(client, {+ ...update,+ partId,+ updatedBy: userId,+ });+ if (updatePartInventory.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(updatePartInventory.error, "Failed to update part inventory")+ )+ );+ }++ return redirect(+ `/x/part/${partId}/inventory`,+ await flash(request, success("Updated part inventory"))+ );+}++export default function PartInventoryRoute() {+ const { partInventory, shelves } = useLoaderData<typeof loader>();+ const initialValues = {+ ...partInventory,+ shelfId: partInventory.shelfId ?? undefined,+ };+ return <PartInventoryForm initialValues={initialValues} shelves={shelves} />;+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.manufacturing.tsx b/apps/carbon/app/routes/x+/part+/$partId.manufacturing.tsxnew file mode 100644index 0000000000..bd3c50a385--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.manufacturing.tsx@@ -0,0 +1,108 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type { PartManufacturingPolicy } from "~/modules/parts";+import { PartManufacturingForm } from "~/modules/parts";+import {+ getPartManufacturing,+ partManufacturingValidator,+ upsertPartManufacturing,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const partManufacturing = await getPartManufacturing(client, partId);++ if (partManufacturing.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(+ partManufacturing.error,+ "Failed to load part manufacturingturing"+ )+ )+ );+ }++ return json({+ partManufacturing: partManufacturing.data,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partManufacturingValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartManufacturing = await upsertPartManufacturing(client, {+ ...validation.data,+ partId,+ updatedBy: userId,+ });+ if (updatePartManufacturing.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(+ updatePartManufacturing.error,+ "Failed to update part manufacturing"+ )+ )+ );+ }++ return redirect(+ `/x/part/${partId}/manufacturing`,+ await flash(request, success("Updated part manufacturing"))+ );+}++export default function PartManufacturingRoute() {+ const sharedPartsData = useRouteData<{+ partManufacturingPolicies: PartManufacturingPolicy[];+ }>("/x/part");++ const { partManufacturing } = useLoaderData<typeof loader>();++ if (!sharedPartsData) throw new Error("Could not load shared parts data");++ const initialValues = {+ ...partManufacturing,+ lotSize: partManufacturing.lotSize ?? 0,+ };++ return (+ <PartManufacturingForm+ initialValues={initialValues}+ partManufacturingPolicies={sharedPartsData.partManufacturingPolicies}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.planning.tsx b/apps/carbon/app/routes/x+/part+/$partId.planning.tsxnew file mode 100644index 0000000000..9a4bc5d6b2--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.planning.tsx@@ -0,0 +1,96 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type { PartReorderingPolicy } from "~/modules/parts";+import {+ getPartPlanning,+ PartPlanningForm,+ partPlanningValidator,+ upsertPartPlanning,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const partPlanning = await getPartPlanning(client, partId);++ if (partPlanning.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(partPlanning.error, "Failed to load part planning")+ )+ );+ }++ return json({+ partPlanning: partPlanning.data,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partPlanningValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartPlanning = await upsertPartPlanning(client, {+ ...validation.data,+ partId,+ updatedBy: userId,+ });+ if (updatePartPlanning.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(updatePartPlanning.error, "Failed to update part planning")+ )+ );+ }++ return redirect(+ `/x/part/${partId}/planning`,+ await flash(request, success("Updated part planning"))+ );+}++export default function PartPlanningRoute() {+ const sharedPartsData = useRouteData<{+ partReorderingPolicies: PartReorderingPolicy[];+ }>("/x/part");++ const { partPlanning } = useLoaderData<typeof loader>();++ if (!sharedPartsData) throw new Error("Could not load shared parts data");+ return (+ <PartPlanningForm+ initialValues={partPlanning}+ partReorderingPolicies={sharedPartsData.partReorderingPolicies}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx b/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsxnew file mode 100644index 0000000000..083389eded--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.purchasing.tsx@@ -0,0 +1,102 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type { UnitOfMeasureListItem } from "~/modules/parts";+import {+ getPartPurchasing,+ PartPurchasingForm,+ partPurchasingValidator,+ upsertPartPurchasing,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const partPurchasing = await getPartPurchasing(client, partId);++ if (partPurchasing.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(partPurchasing.error, "Failed to load part purchasing")+ )+ );+ }++ return json({+ partPurchasing: partPurchasing.data,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partPurchasingValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartPurchasing = await upsertPartPurchasing(client, {+ ...validation.data,+ partId,+ updatedBy: userId,+ });+ if (updatePartPurchasing.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(updatePartPurchasing.error, "Failed to update part purchasing")+ )+ );+ }++ return redirect(+ `/x/part/${partId}/purchasing`,+ await flash(request, success("Updated part purchasing"))+ );+}++export default function PartPurchasingRoute() {+ const sharedPartData = useRouteData<{+ unitOfMeasures: UnitOfMeasureListItem[];+ }>("/x/part");+ const { partPurchasing } = useLoaderData<typeof loader>();++ const initialValues = {+ ...partPurchasing,+ supplierId: partPurchasing?.supplierId ?? undefined,+ supplierPartNumber: partPurchasing?.supplierPartNumber ?? undefined,+ purchasingUnitOfMeasureCode:+ partPurchasing?.purchasingUnitOfMeasureCode ?? "",+ };++ return (+ <PartPurchasingForm+ initialValues={initialValues}+ unitOfMeasures={sharedPartData?.unitOfMeasures ?? []}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.sale-price.tsx b/apps/carbon/app/routes/x+/part+/$partId.sale-price.tsxnew file mode 100644index 0000000000..877bccab0d--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.sale-price.tsx@@ -0,0 +1,101 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type { UnitOfMeasureListItem } from "~/modules/parts";+import {+ partUnitSalePriceValidator,+ upsertPartUnitSalePrice,+} from "~/modules/parts";+import { PartSalePriceForm, getPartUnitSalePrice } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const [partUnitSalePrice] = await Promise.all([+ getPartUnitSalePrice(client, partId),+ ]);++ if (partUnitSalePrice.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(partUnitSalePrice.error, "Failed to load part unit sale price")+ )+ );+ }++ return json({+ partUnitSalePrice: partUnitSalePrice.data,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ // validate with partsValidator+ const validation = await partUnitSalePriceValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updatePartUnitSalePrice = await upsertPartUnitSalePrice(client, {+ ...validation.data,+ partId,+ updatedBy: userId,+ });+ if (updatePartUnitSalePrice.error) {+ return redirect(+ `/x/part/${partId}`,+ await flash(+ request,+ error(updatePartUnitSalePrice.error, "Failed to update part sale price")+ )+ );+ }++ return redirect(+ `/x/part/${partId}/sale-price`,+ await flash(request, success("Updated part sale price"))+ );+}++export default function PartSalePriceRoute() {+ const sharedPartData = useRouteData<{+ unitOfMeasures: UnitOfMeasureListItem[];+ }>("/x/part");++ const { partUnitSalePrice } = useLoaderData<typeof loader>();++ const initialValues = {+ ...partUnitSalePrice,+ salesUnitOfMeasureCode: partUnitSalePrice?.salesUnitOfMeasureCode ?? "",+ };++ return (+ <PartSalePriceForm+ initialValues={initialValues}+ unitOfMeasures={sharedPartData?.unitOfMeasures ?? []}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/part+/$partId.tsx b/apps/carbon/app/routes/x+/part+/$partId.tsxnew file mode 100644index 0000000000..c8ced84830--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/$partId.tsx@@ -0,0 +1,46 @@+import { Grid } from "@chakra-ui/react";+import type { LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import { getPartSummary, PartPreview, PartSidebar } from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { error } from "~/utils/result";++export async function loader({ request, params }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const { partId } = params;+ if (!partId) throw new Error("Could not find partId");++ const partSummary = await getPartSummary(client, partId);+ if (partSummary.error) {+ return redirect(+ "/x/parts",+ await flash(+ request,+ error(partSummary.error, "Failed to load part summary")+ )+ );+ }++ return json(partSummary.data);+}++export default function PartsNewRoute() {+ return (+ <>+ <PartPreview />+ <Grid+ gridTemplateColumns={["1fr", "1fr", "2fr 8fr"]}+ gridColumnGap={8}+ w="full"+ >+ <PartSidebar />+ <Outlet />+ </Grid>+ </>+ );+}diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsxnew file mode 100644index 0000000000..ebbc4ae655--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx@@ -0,0 +1,46 @@+import { VStack } from "@chakra-ui/react";+import type { LoaderArgs, MetaFunction } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import {+ getPartCostingMethods,+ getPartGroupsList,+ getPartManufacturingPolicies,+ getPartRorderdingPolicies,+ getPartReplenishmentSystems,+ getPartTypes,+ getUnitOfMeasuresList,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";++export const meta: MetaFunction = () => ({+ title: "Carbon | Parts",+});++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const [partGroups, unitOfMeasures] = await Promise.all([+ getPartGroupsList(client),+ getUnitOfMeasuresList(client),+ ]);++ return {+ partCostingMethods: getPartCostingMethods(),+ partGroups: partGroups?.data ?? [],+ partManufacturingPolicies: getPartManufacturingPolicies(),+ partReorderingPolicies: getPartRorderdingPolicies(),+ partReplenishmentSystems: getPartReplenishmentSystems(),+ partTypes: getPartTypes(),+ unitOfMeasures: unitOfMeasures?.data ?? [],+ };+}++export default function PartRoute() {+ return (+ <VStack w="full" h="full" spacing={4} p={4}>+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/part+/flow.tsx b/apps/carbon/app/routes/x+/part+/flow.tsxnew file mode 100644index 0000000000..c62786eef2--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/flow.tsx@@ -0,0 +1,87 @@+import type { LoaderArgs, MetaFunction } from "@remix-run/node";+import { json } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { useCallback } from "react";+import type { Connection, Node, Edge } from "reactflow";+import ReactFlow, {+ Controls,+ Background,+ BackgroundVariant,+ addEdge,+ useNodesState,+ useEdgesState,+} from "reactflow";+import reactFlowStyles from "reactflow/dist/style.css";+import { requirePermissions } from "~/services/auth";++export const meta: MetaFunction = () => ({+ title: "Carbon | Parts",+});++export function links() {+ return [{ rel: "stylesheet", href: reactFlowStyles }];+}++export async function loader({ request }: LoaderArgs) {+ await requirePermissions(request, {+ view: "parts",+ });++ const nodes: Node[] = [+ {+ id: "1",+ data: { label: "Node 1" },+ position: { x: 250, y: 5 },+ type: "input",+ },+ {+ id: "2",+ data: { label: "Node 2" },+ position: { x: 100, y: 100 },+ },+ {+ id: "3",+ data: { label: "Node 3" },+ position: { x: 400, y: 100 },+ },+ {+ id: "4",+ data: { label: "Node 4" },+ position: { x: 400, y: 200 },+ type: "output",+ },+ ];++ const edges: Edge[] = [+ { id: "e1-2", source: "1", target: "2", animated: true },+ { id: "e1-3", source: "1", target: "3", animated: true },+ ];++ return json({ nodes, edges });+}++export default function PartsRoute() {+ const data = useLoaderData<typeof loader>();++ const [nodes, , onNodesChange] = useNodesState(data.nodes as Node[]);+ const [edges, setEdges, onEdgesChange] = useEdgesState(data.edges as Edge[]);++ const onConnect = useCallback(+ (params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)),+ [setEdges]+ );++ return (+ <ReactFlow+ fitView+ nodes={nodes}+ edges={edges}+ onConnect={onConnect}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ >+ <Background variant={BackgroundVariant.Lines} gap={16} size={1} />+ <Controls />+ </ReactFlow>+ );+}diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsxnew file mode 100644index 0000000000..fad01cef3f--- /dev/null+++ b/apps/carbon/app/routes/x+/part+/new.tsx@@ -0,0 +1,79 @@+import { Grid } from "@chakra-ui/react";+import type { ActionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import type {+ PartGroupListItem,+ PartReplenishmentSystem,+ PartType,+ UnitOfMeasureListItem,+} from "~/modules/parts";+import { PartForm, partValidator, upsertPart } from "~/modules/parts";+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: "parts",+ });++ const validation = await partValidator.validate(await request.formData());++ if (validation.error) {+ return validationError(validation.error);+ }++ const createPart = await upsertPart(client, {+ ...validation.data,+ active: true,+ createdBy: userId,+ });+ if (createPart.error) {+ return redirect(+ "/x/parts/search",+ await flash(request, error(createPart.error, "Failed to insert part"))+ );+ }++ const partId = createPart.data[0]?.id;++ return redirect(+ `/x/part/${partId}`,+ await flash(request, success("Created part"))+ );+}++export default function PartsNewRoute() {+ const routeData = useRouteData<{+ partGroups: PartGroupListItem[];+ partTypes: PartType[];+ partReplenishmentSystems: PartReplenishmentSystem[];+ unitOfMeasures: UnitOfMeasureListItem[];+ }>("/x/part");++ const initialValues = {+ name: "",+ description: "",+ };++ return (+ <Grid+ gridTemplateColumns={["1fr", "1fr", "2fr 4fr 2fr"]}+ gridColumnGap={8}+ w="full"+ >+ <div></div>+ <PartForm+ initialValues={initialValues}+ partGroups={routeData?.partGroups ?? []}+ partTypes={routeData?.partTypes ?? []}+ partReplenishmentSystems={routeData?.partReplenishmentSystems ?? []}+ unitOfMeasures={routeData?.unitOfMeasures ?? []}+ />+ </Grid>+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/_layout.tsx b/apps/carbon/app/routes/x+/parts+/_layout.tsxnew file mode 100644index 0000000000..b41fa0d29d--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/_layout.tsx@@ -0,0 +1,22 @@+import { Grid, VStack } from "@chakra-ui/react";+import type { MetaFunction } from "@remix-run/node";+import { Outlet } from "@remix-run/react";+import { GroupedContentSidebar } from "~/components/Layout/Sidebar";+import { usePartsSidebar } from "~/modules/parts";++export const meta: MetaFunction = () => ({+ title: "Carbon | Parts",+});++export default function PartsRoute() {+ const { groups } = usePartsSidebar();++ return (+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">+ <GroupedContentSidebar groups={groups} />+ <VStack w="full" h="full" spacing={0}>+ <Outlet />+ </VStack>+ </Grid>+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/groups.$groupId.tsx b/apps/carbon/app/routes/x+/parts+/groups.$groupId.tsxnew file mode 100644index 0000000000..17cb750a17--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/groups.$groupId.tsx@@ -0,0 +1,106 @@+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 { useRouteData } from "~/hooks";+import { PartGroupForm } from "~/modules/parts";+import {+ partGroupValidator,+ getPartGroup,+ upsertPartGroup,+} from "~/modules/parts";+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: "parts",+ role: "employee",+ });++ const { groupId } = params;+ if (!groupId) throw notFound("groupId not found");++ const partGroup = await getPartGroup(client, groupId);++ return json({+ partGroup: partGroup?.data ?? null,+ });+}++export async function action({ request, params }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const { groupId } = params;+ if (!groupId) throw new Error("Could not find groupId");++ const validation = await partGroupValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ name,+ description,+ salesAccountId,+ discountAccountId,+ inventoryAccountId,+ } = validation.data;++ const updatePartGroup = await upsertPartGroup(client, {+ id: groupId,+ name,+ description,+ salesAccountId: salesAccountId ?? null,+ discountAccountId: discountAccountId ?? null,+ inventoryAccountId: inventoryAccountId ?? null,+ updatedBy: userId,+ });++ if (updatePartGroup.error) {+ return json(+ {},+ await flash(+ request,+ error(updatePartGroup.error, "Failed to update part group")+ )+ );+ }++ return redirect(+ "/x/parts/groups",+ await flash(request, success("Updated part group"))+ );+}++export default function EditPartGroupsRoute() {+ const { partGroup } = useLoaderData<typeof loader>();+ const routeData = useRouteData<{+ accounts: { name: string; number: string }[];+ }>("/x/parts/groups");++ const initialValues = {+ id: partGroup?.id ?? undefined,+ name: partGroup?.name ?? "",+ description: partGroup?.description ?? "",+ salesAccountId: partGroup?.salesAccountId ?? "",+ discountAccountId: partGroup?.discountAccountId ?? "",+ inventoryAccountId: partGroup?.inventoryAccountId ?? "",+ };++ return (+ <PartGroupForm+ accounts={routeData?.accounts ?? []}+ initialValues={initialValues}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/groups.delete.$groupId.tsx b/apps/carbon/app/routes/x+/parts+/groups.delete.$groupId.tsxnew file mode 100644index 0000000000..f45e8a8f3b--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/groups.delete.$groupId.tsx@@ -0,0 +1,76 @@+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 { deletePartGroup, getPartGroup } from "~/modules/parts";+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: "parts",+ });+ const { groupId } = params;+ if (!groupId) throw notFound("groupId not found");++ const partGroup = await getPartGroup(client, groupId);+ if (partGroup.error) {+ return redirect(+ "/x/parts/groups",+ await flash(request, error(partGroup.error, "Failed to get part group"))+ );+ }++ return json({ partGroup: partGroup.data });+}++export async function action({ request, params }: ActionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "parts",+ });++ const { groupId } = params;+ if (!groupId) {+ return redirect(+ "/x/parts/groups",+ await flash(request, error(params, "Failed to get an part group id"))+ );+ }++ const { error: deleteTypeError } = await deletePartGroup(client, groupId);+ if (deleteTypeError) {+ return redirect(+ "/x/parts/groups",+ await flash(+ request,+ error(deleteTypeError, "Failed to delete part group")+ )+ );+ }++ return redirect(+ "/x/parts/groups",+ await flash(request, success("Successfully deleted part group"))+ );+}++export default function DeletePartGroupRoute() {+ const { groupId } = useParams();+ const { partGroup } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ if (!groupId || !partGroup) return null; // TODO - handle this better (404?)++ const onCancel = () => navigate("/x/parts/groups");++ return (+ <ConfirmDelete+ action={`/x/parts/groups/delete/${groupId}`}+ name={partGroup.name}+ text={`Are you sure you want to delete the part group: ${partGroup.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/groups.new.tsx b/apps/carbon/app/routes/x+/parts+/groups.new.tsxnew file mode 100644index 0000000000..b0e9319d72--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/groups.new.tsx@@ -0,0 +1,99 @@+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { validationError } from "remix-validated-form";+import { useRouteData } from "~/hooks";+import {+ PartGroupForm,+ partGroupValidator,+ upsertPartGroup,+} from "~/modules/parts";+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: "parts",+ });++ return null;+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const validation = await partGroupValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ name,+ description,+ salesAccountId,+ discountAccountId,+ inventoryAccountId,+ } = validation.data;++ const insertPartGroup = await upsertPartGroup(client, {+ name,+ description,+ salesAccountId,+ discountAccountId,+ inventoryAccountId,+ createdBy: userId,+ });+ if (insertPartGroup.error) {+ return json(+ {},+ await flash(+ request,+ error(insertPartGroup.error, "Failed to insert part group")+ )+ );+ }++ const partGroupId = insertPartGroup.data[0]?.id;+ if (!partGroupId) {+ return json(+ {},+ await flash(+ request,+ error(insertPartGroup, "Failed to insert part group")+ )+ );+ }++ return redirect(+ "/x/parts/groups",+ await flash(request, success("Part group created"))+ );+}++export default function NewPartGroupsRoute() {+ const routeData = useRouteData<{+ accounts: { name: string; number: string }[];+ }>("/x/parts/groups");++ const initialValues = {+ name: "",+ description: "",+ salesAccountId: "",+ discountAccountId: "",+ inventoryAccountId: "",+ };++ return (+ <PartGroupForm+ accounts={routeData?.accounts ?? []}+ initialValues={initialValues}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/groups.tsx b/apps/carbon/app/routes/x+/parts+/groups.tsxnew file mode 100644index 0000000000..c80a66020a--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/groups.tsx@@ -0,0 +1,68 @@+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 { getAccountsList } from "~/modules/accounting";+import {+ PartGroupsTable,+ PartGroupsTableFilters,+ getPartGroups,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ 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);++ const [partGroups, accounts] = await Promise.all([+ getPartGroups(client, {+ limit,+ offset,+ sorts,+ name,+ }),+ getAccountsList(client),+ ]);+ if (partGroups.error) {+ return redirect(+ "/x/parts",+ await flash(request, error(null, "Error loading part groups"))+ );+ }++ if (accounts.error) {+ return redirect(+ "/x/parts/groups",+ await flash(request, error(accounts.error, "Error loading accounts"))+ );+ }++ return json({+ partGroups: partGroups.data ?? [],+ count: partGroups.count ?? 0,+ accounts: accounts.data ?? [],+ });+}++export default function PartGroupsRoute() {+ const { partGroups, count } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <PartGroupsTableFilters />+ <PartGroupsTable data={partGroups} count={count ?? 0} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/index.tsx b/apps/carbon/app/routes/x+/parts+/index.tsxindex c62786eef2..02d3bb117b 100644--- a/apps/carbon/app/routes/x+/parts+/index.tsx+++ b/apps/carbon/app/routes/x+/parts+/index.tsx@@ -1,87 +1,5 @@-import type { LoaderArgs, MetaFunction } from "@remix-run/node";-import { json } from "@remix-run/node";-import { useLoaderData } from "@remix-run/react";-import { useCallback } from "react";-import type { Connection, Node, Edge } from "reactflow";-import ReactFlow, {- Controls,- Background,- BackgroundVariant,- addEdge,- useNodesState,- useEdgesState,-} from "reactflow";-import reactFlowStyles from "reactflow/dist/style.css";-import { requirePermissions } from "~/services/auth";+import { redirect } from "@remix-run/node";-export const meta: MetaFunction = () => ({- title: "Carbon | Parts",-});--export function links() {- return [{ rel: "stylesheet", href: reactFlowStyles }];-}--export async function loader({ request }: LoaderArgs) {- await requirePermissions(request, {- view: "parts",- });-- const nodes: Node[] = [- {- id: "1",- data: { label: "Node 1" },- position: { x: 250, y: 5 },- type: "input",- },- {- id: "2",- data: { label: "Node 2" },- position: { x: 100, y: 100 },- },- {- id: "3",- data: { label: "Node 3" },- position: { x: 400, y: 100 },- },- {- id: "4",- data: { label: "Node 4" },- position: { x: 400, y: 200 },- type: "output",- },- ];-- const edges: Edge[] = [- { id: "e1-2", source: "1", target: "2", animated: true },- { id: "e1-3", source: "1", target: "3", animated: true },- ];-- return json({ nodes, edges });-}--export default function PartsRoute() {- const data = useLoaderData<typeof loader>();-- const [nodes, , onNodesChange] = useNodesState(data.nodes as Node[]);- const [edges, setEdges, onEdgesChange] = useEdgesState(data.edges as Edge[]);-- const onConnect = useCallback(- (params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)),- [setEdges]- );-- return (- <ReactFlow- fitView- nodes={nodes}- edges={edges}- onConnect={onConnect}- onNodesChange={onNodesChange}- onEdgesChange={onEdgesChange}- >- <Background variant={BackgroundVariant.Lines} gap={16} size={1} />- <Controls />- </ReactFlow>- );+export async function loader() {+ return redirect("/x/parts/search");}diff --git a/apps/carbon/app/routes/x+/parts+/routing.tsx b/apps/carbon/app/routes/x+/parts+/routing.tsxnew file mode 100644index 0000000000..feab7bdee6--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/routing.tsx@@ -0,0 +1,5 @@+import { VStack } from "@chakra-ui/react";++export default function PartsConfiguratorRoute() {+ return <VStack w="full" h="full" spacing={0}></VStack>;+}diff --git a/apps/carbon/app/routes/x+/parts+/search.tsx b/apps/carbon/app/routes/x+/parts+/search.tsxnew file mode 100644index 0000000000..648de0c967--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/search.tsx@@ -0,0 +1,64 @@+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 {+ PartsTable,+ PartsTableFilters,+ getParts,+ getPartGroupsList,+ getPartTypes,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { getGenericQueryFilters } from "~/utils/query";+import { error } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const type = searchParams.get("type");+ const group = searchParams.get("group");++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const [parts, partTypes, partGroups] = await Promise.all([+ getParts(client, { search, type, group, limit, offset, sorts, filters }),+ getPartTypes(),+ getPartGroupsList(client),+ ]);++ if (parts.error) {+ redirect(+ "/x",+ await flash(request, error(parts.error, "Failed to fetch parts"))+ );+ }++ return json({+ count: parts.count ?? 0,+ parts: parts.data ?? [],+ partGroups: partGroups.data ?? [],+ partTypes: partTypes ?? [],+ });+}++export default function PartsSearchRoute() {+ const { count, parts, partTypes, partGroups } =+ useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <PartsTableFilters partTypes={partTypes} partGroups={partGroups} />+ <PartsTable data={parts} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/uom.$uomId.tsx b/apps/carbon/app/routes/x+/parts+/uom.$uomId.tsxnew file mode 100644index 0000000000..000bea4d95--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/uom.$uomId.tsx@@ -0,0 +1,83 @@+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 { UnitOfMeasureForm } from "~/modules/parts";+import {+ unitOfMeasureValidator,+ getUnitOfMeasure,+ upsertUnitOfMeasure,+} from "~/modules/parts";+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: "parts",+ role: "employee",+ });++ const { uomId } = params;+ if (!uomId) throw notFound("uomId not found");++ const unitOfMeasure = await getUnitOfMeasure(client, uomId);++ return json({+ unitOfMeasure: unitOfMeasure?.data ?? null,+ });+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "parts",+ });++ const validation = await unitOfMeasureValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, name, code } = validation.data;+ if (!id) throw new Error("id not found");++ const updateUnitOfMeasure = await upsertUnitOfMeasure(client, {+ id,+ name,+ code,+ updatedBy: userId,+ });++ if (updateUnitOfMeasure.error) {+ return json(+ {},+ await flash(+ request,+ error(updateUnitOfMeasure.error, "Failed to update unit of measure")+ )+ );+ }++ return redirect(+ "/x/parts/uom",+ await flash(request, success("Updated unit of measure"))+ );+}++export default function EditUnitOfMeasuresRoute() {+ const { unitOfMeasure } = useLoaderData<typeof loader>();++ const initialValues = {+ id: unitOfMeasure?.id ?? undefined,+ name: unitOfMeasure?.name ?? "",+ code: unitOfMeasure?.code ?? "",+ };++ return <UnitOfMeasureForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/parts+/uom.delete.$uomId.tsx b/apps/carbon/app/routes/x+/parts+/uom.delete.$uomId.tsxnew file mode 100644index 0000000000..6613150c77--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/uom.delete.$uomId.tsx@@ -0,0 +1,79 @@+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 { deleteUnitOfMeasure, getUnitOfMeasure } from "~/modules/parts";+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: "parts",+ });+ const { uomId } = params;+ if (!uomId) throw notFound("uomId not found");++ const unitOfMeasure = await getUnitOfMeasure(client, uomId);+ if (unitOfMeasure.error) {+ return redirect(+ "/x/parts/uom",+ await flash(+ request,+ error(unitOfMeasure.error, "Failed to get unit of measure")+ )+ );+ }++ return json({ unitOfMeasure: unitOfMeasure.data });+}++export async function action({ request, params }: ActionArgs) {+ const { client } = await requirePermissions(request, {+ delete: "parts",+ });++ const { uomId } = params;+ if (!uomId) {+ return redirect(+ "/x/parts/uom",+ await flash(request, error(params, "Failed to get an unit of measure id"))+ );+ }++ const { error: deleteTypeError } = await deleteUnitOfMeasure(client, uomId);+ if (deleteTypeError) {+ return redirect(+ "/x/parts/uom",+ await flash(+ request,+ error(deleteTypeError, "Failed to delete unit of measure")+ )+ );+ }++ return redirect(+ "/x/parts/uom",+ await flash(request, success("Successfully deleted unit of measure"))+ );+}++export default function DeleteUnitOfMeasureRoute() {+ const { uomId } = useParams();+ const { unitOfMeasure } = useLoaderData<typeof loader>();+ const navigate = useNavigate();++ if (!uomId || !unitOfMeasure) return null; // TODO - handle this better (404?)++ const onCancel = () => navigate("/x/parts/uom");++ return (+ <ConfirmDelete+ action={`/x/parts/uom/delete/${uomId}`}+ name={unitOfMeasure.name}+ text={`Are you sure you want to delete the unit of measure: ${unitOfMeasure.name}? This cannot be undone.`}+ onCancel={onCancel}+ />+ );+}diff --git a/apps/carbon/app/routes/x+/parts+/uom.new.tsx b/apps/carbon/app/routes/x+/parts+/uom.new.tsxnew file mode 100644index 0000000000..48d61576eb--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/uom.new.tsx@@ -0,0 +1,78 @@+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 {+ UnitOfMeasureForm,+ unitOfMeasureValidator,+ upsertUnitOfMeasure,+} from "~/modules/parts";+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: "parts",+ });++ return null;+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "parts",+ });++ const validation = await unitOfMeasureValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { name, code } = validation.data;++ const insertUnitOfMeasure = await upsertUnitOfMeasure(client, {+ name,+ code,+ createdBy: userId,+ });+ if (insertUnitOfMeasure.error) {+ return json(+ {},+ await flash(+ request,+ error(insertUnitOfMeasure.error, "Failed to insert unit of measure")+ )+ );+ }++ const unitOfMeasureId = insertUnitOfMeasure.data[0]?.id;+ if (!unitOfMeasureId) {+ return json(+ {},+ await flash(+ request,+ error(insertUnitOfMeasure, "Failed to insert unit of measure")+ )+ );+ }++ return redirect(+ "/x/parts/uom",+ await flash(request, success("Unit of measure created"))+ );+}++export default function NewUnitOfMeasuresRoute() {+ const initialValues = {+ name: "",+ code: "",+ };++ return <UnitOfMeasureForm initialValues={initialValues} />;+}diff --git a/apps/carbon/app/routes/x+/parts+/uom.tsx b/apps/carbon/app/routes/x+/parts+/uom.tsxnew file mode 100644index 0000000000..5e61dae76b--- /dev/null+++ b/apps/carbon/app/routes/x+/parts+/uom.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 {+ UnitOfMeasuresTable,+ UnitOfMeasuresTableFilters,+ getUnitOfMeasures,+} from "~/modules/parts";+import { requirePermissions } from "~/services/auth";+import { getGenericQueryFilters } from "~/utils/query";++export async function loader({ request }: LoaderArgs) {+ const { client } = await requirePermissions(request, {+ view: "parts",+ 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 getUnitOfMeasures(client, { name, limit, offset, sorts }));+}++export default function UnitOfMeasuresRoute() {+ const { data, count } = useLoaderData<typeof loader>();++ return (+ <VStack w="full" h="full" spacing={0}>+ <UnitOfMeasuresTableFilters />+ <UnitOfMeasuresTable data={data ?? []} count={count ?? 0} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/carbon/app/routes/x+/resources+/work-cells.cell.new.tsx b/apps/carbon/app/routes/x+/resources+/work-cells.cell.new.tsxindex 1a96fc9194..5783e107ca 100644--- a/apps/carbon/app/routes/x+/resources+/work-cells.cell.new.tsx+++ b/apps/carbon/app/routes/x+/resources+/work-cells.cell.new.tsx@@ -50,6 +50,6 @@ export async function action({ request }: ActionArgs) {return redirect(`/x/resources/work-cells`,- await flash(request, success("Created workCell"))+ await flash(request, success("Created work cell")));}diff --git a/apps/carbon/app/styles/nprogress.css b/apps/carbon/app/styles/nprogress.cssnew file mode 100644index 0000000000..8b5a5ac8ec--- /dev/null+++ b/apps/carbon/app/styles/nprogress.css@@ -0,0 +1,16 @@+/* Make clicks pass-through */+#nprogress {+ pointer-events: none;+}++#nprogress .bar {+ background: var(--chakra-ui-focus-ring-color);++ position: fixed;+ z-index: 1031;+ top: 0;+ left: 0;++ width: 100%;+ height: 2px;+}diff --git a/apps/carbon/package.json b/apps/carbon/package.jsonindex 69f987cb87..4e830cce3a 100644--- a/apps/carbon/package.json+++ b/apps/carbon/package.json@@ -45,10 +45,11 @@"framer-motion": "^10.0.0","lodash.debounce": "^4.0.8","lodash.words": "^4.2.0",+ "nprogress": "0.2.0","performant-array-to-tree": "1.11.0","react": "^18.2.0","react-dom": "^18.2.0",- "react-icons": "4.7.1",+ "react-icons": "^4.8.0","react-virtual": "2.10.4","reactflow": "^11.5.6","remix-flat-routes": "^0.5.7",@@ -60,6 +61,7 @@"@carbon/tsconfig": "*","@remix-run/dev": "1.13.0","@remix-run/serve": "1.13.0",+ "@types/nprogress": "^0.2.0","@types/react": "^18.0.21","@types/react-dom": "^18.0.6","typescript": "^4.9.3"diff --git a/packages/carbon-database/src/seed/employee-types.ts b/packages/carbon-database/src/seed/employee-types.tsindex adc5959757..5a2b525922 100644--- a/packages/carbon-database/src/seed/employee-types.ts+++ b/packages/carbon-database/src/seed/employee-types.ts@@ -27,6 +27,12 @@ export const employeeTypePermissionsDefinitions: Record<>> = {Admin: {+ Accounting: {+ create: true,+ update: true,+ delete: true,+ view: true,+ },Parts: {create: true,update: true,@@ -101,6 +107,12 @@ export const employeeTypePermissionsDefinitions: Record<},},"Project Manager": {+ Accounting: {+ create: false,+ update: false,+ delete: false,+ view: false,+ },Parts: {create: true,update: true,@@ -175,6 +187,12 @@ export const employeeTypePermissionsDefinitions: Record<},},Sales: {+ Accounting: {+ create: false,+ update: false,+ delete: false,+ view: false,+ },Parts: {create: false,update: false,@@ -230,10 +248,10 @@ export const employeeTypePermissionsDefinitions: Record<view: false,},Resources: {- create: true,- update: true,- delete: true,- view: true,+ create: false,+ update: false,+ delete: false,+ view: false,},Users: {create: false,diff --git a/packages/carbon-database/src/seed/features.ts b/packages/carbon-database/src/seed/features.tsindex 6eae1bd5e6..5ab30f9a5f 100644--- a/packages/carbon-database/src/seed/features.ts+++ b/packages/carbon-database/src/seed/features.ts@@ -1,6 +1,7 @@import { v4 as uuidv4 } from "uuid";const possibleFeatures = [+ "Accounting","Documents","Inventory","Jobs",diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.tsindex 868f987b6e..f57302f162 100644--- a/packages/carbon-database/src/types.ts+++ b/packages/carbon-database/src/types.ts@@ -44,6 +44,94 @@ export interface Database {createdAt?: string;};};+ account: {+ Row: {+ number: string;+ name: string;+ description: string | null;+ accountCategoryId: string | null;+ consolidatedRate:+ | Database["public"]["Enums"]["consolidatedRate"]+ | null;+ currencyCode: string | null;+ parentAccountNumber: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ controlAccount: boolean;+ cashAccount: boolean;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ number: string;+ name: string;+ description?: string | null;+ accountCategoryId?: string | null;+ consolidatedRate?:+ | Database["public"]["Enums"]["consolidatedRate"]+ | null;+ currencyCode?: string | null;+ parentAccountNumber?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ controlAccount?: boolean;+ cashAccount?: boolean;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ number?: string;+ name?: string;+ description?: string | null;+ accountCategoryId?: string | null;+ consolidatedRate?:+ | Database["public"]["Enums"]["consolidatedRate"]+ | null;+ currencyCode?: string | null;+ parentAccountNumber?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ controlAccount?: boolean;+ cashAccount?: boolean;+ active?: boolean;+ createdAt?: string;+ };+ };+ accountCategory: {+ Row: {+ category: Database["public"]["Enums"]["glAccountCategory"];+ type: Database["public"]["Enums"]["glAccountType"];+ normalBalance: Database["public"]["Enums"]["glNormalBalance"];+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ createdAt: string;+ };+ Insert: {+ category: Database["public"]["Enums"]["glAccountCategory"];+ type: Database["public"]["Enums"]["glAccountType"];+ normalBalance: Database["public"]["Enums"]["glNormalBalance"];+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ createdAt?: string;+ };+ Update: {+ category?: Database["public"]["Enums"]["glAccountCategory"];+ type?: Database["public"]["Enums"]["glAccountType"];+ normalBalance?: Database["public"]["Enums"]["glNormalBalance"];+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ createdAt?: string;+ };+ };address: {Row: {addressLine1: string | null;@@ -282,6 +370,50 @@ export interface Database {active?: boolean;};};+ currency: {+ Row: {+ name: string;+ code: string;+ symbol: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ symbolPlacementBefore: boolean;+ exchangeRate: number;+ currencyPrecision: number;+ isBaseCurrency: boolean;+ createdAt: string;+ };+ Insert: {+ name: string;+ code: string;+ symbol?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ symbolPlacementBefore?: boolean;+ exchangeRate?: number;+ currencyPrecision?: number;+ isBaseCurrency?: boolean;+ createdAt?: string;+ };+ Update: {+ name?: string;+ code?: string;+ symbol?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ symbolPlacementBefore?: boolean;+ exchangeRate?: number;+ currencyPrecision?: number;+ isBaseCurrency?: boolean;+ createdAt?: string;+ };+ };customer: {Row: {name: string;@@ -841,6 +973,200 @@ export interface Database {id?: number;};};+ part: {+ Row: {+ id: string;+ name: string;+ description: string | null;+ replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"];+ partGroupId: string;+ partType: Database["public"]["Enums"]["partType"];+ manufacturerPartNumber: string | null;+ unitOfMeasureCode: string;+ approvedBy: string | null;+ fromDate: string | null;+ toDate: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ blocked: boolean;+ active: boolean;+ approved: boolean;+ createdAt: string;+ };+ Insert: {+ id: string;+ name: string;+ description?: string | null;+ replenishmentSystem: Database["public"]["Enums"]["partReplenishmentSystem"];+ partGroupId: string;+ partType: Database["public"]["Enums"]["partType"];+ manufacturerPartNumber?: string | null;+ unitOfMeasureCode: string;+ approvedBy?: string | null;+ fromDate?: string | null;+ toDate?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ blocked?: boolean;+ active?: boolean;+ approved?: boolean;+ createdAt?: string;+ };+ Update: {+ id?: string;+ name?: string;+ description?: string | null;+ replenishmentSystem?: Database["public"]["Enums"]["partReplenishmentSystem"];+ partGroupId?: string;+ partType?: Database["public"]["Enums"]["partType"];+ manufacturerPartNumber?: string | null;+ unitOfMeasureCode?: string;+ approvedBy?: string | null;+ fromDate?: string | null;+ toDate?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ blocked?: boolean;+ active?: boolean;+ approved?: boolean;+ createdAt?: string;+ };+ };+ partCost: {+ Row: {+ partId: string;+ costingMethod: Database["public"]["Enums"]["partCostingMethod"];+ salesAccountId: string | null;+ discountAccountId: string | null;+ inventoryAccountId: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ standardCost: number;+ unitCost: number;+ costIsAdjusted: boolean;+ createdAt: string;+ };+ Insert: {+ partId: string;+ costingMethod: Database["public"]["Enums"]["partCostingMethod"];+ salesAccountId?: string | null;+ discountAccountId?: string | null;+ inventoryAccountId?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ standardCost?: number;+ unitCost?: number;+ costIsAdjusted?: boolean;+ createdAt?: string;+ };+ Update: {+ partId?: string;+ costingMethod?: Database["public"]["Enums"]["partCostingMethod"];+ salesAccountId?: string | null;+ discountAccountId?: string | null;+ inventoryAccountId?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ standardCost?: number;+ unitCost?: number;+ costIsAdjusted?: boolean;+ createdAt?: string;+ };+ };+ partGroup: {+ Row: {+ name: string;+ description: string | null;+ salesAccountId: string | null;+ discountAccountId: string | null;+ inventoryAccountId: string | null;+ costOfGoodsSoldLaborAccountId: string | null;+ costOfGoodsSoldMaterialAccountId: string | null;+ costOfGoodsSoldOverheadAccountId: string | null;+ costOfGoodsSoldSubcontractorAccountId: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ name: string;+ description?: string | null;+ salesAccountId?: string | null;+ discountAccountId?: string | null;+ inventoryAccountId?: string | null;+ costOfGoodsSoldLaborAccountId?: string | null;+ costOfGoodsSoldMaterialAccountId?: string | null;+ costOfGoodsSoldOverheadAccountId?: string | null;+ costOfGoodsSoldSubcontractorAccountId?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ name?: string;+ description?: string | null;+ salesAccountId?: string | null;+ discountAccountId?: string | null;+ inventoryAccountId?: string | null;+ costOfGoodsSoldLaborAccountId?: string | null;+ costOfGoodsSoldMaterialAccountId?: string | null;+ costOfGoodsSoldOverheadAccountId?: string | null;+ costOfGoodsSoldSubcontractorAccountId?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ };+ partInventory: {+ Row: {+ partId: string;+ shelfId: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ stockoutWarning: boolean;+ unitVolume: number;+ unitWeight: number;+ createdAt: string;+ };+ Insert: {+ partId: string;+ shelfId?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ stockoutWarning?: boolean;+ unitVolume?: number;+ unitWeight?: number;+ createdAt?: string;+ };+ Update: {+ partId?: string;+ shelfId?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ stockoutWarning?: boolean;+ unitVolume?: number;+ unitWeight?: number;+ createdAt?: string;+ };+ };partner: {Row: {id: string;@@ -890,11 +1216,176 @@ export interface Database {createdAt?: string;};};+ partPlanning: {+ Row: {+ partId: string;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ reorderingPolicy: Database["public"]["Enums"]["partReorderingPolicy"];+ critical: boolean;+ safetyStockQuantity: number;+ safetyStockLeadTime: number;+ demandAccumulationPeriod: number;+ demandReschedulingPeriod: number;+ demandAccumulationIncludesInventory: boolean;+ reorderPoint: number;+ reorderQuantity: number;+ reorderMaximumInventory: number;+ reorderOverflowLevel: number;+ reorderTimeBucket: number;+ minimumOrderQuantity: number;+ maximumOrderQuantity: number;+ orderMultiple: number;+ createdAt: string;+ };+ Insert: {+ partId: string;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ reorderingPolicy?: Database["public"]["Enums"]["partReorderingPolicy"];+ critical?: boolean;+ safetyStockQuantity?: number;+ safetyStockLeadTime?: number;+ demandAccumulationPeriod?: number;+ demandReschedulingPeriod?: number;+ demandAccumulationIncludesInventory?: boolean;+ reorderPoint?: number;+ reorderQuantity?: number;+ reorderMaximumInventory?: number;+ reorderOverflowLevel?: number;+ reorderTimeBucket?: number;+ minimumOrderQuantity?: number;+ maximumOrderQuantity?: number;+ orderMultiple?: number;+ createdAt?: string;+ };+ Update: {+ partId?: string;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ reorderingPolicy?: Database["public"]["Enums"]["partReorderingPolicy"];+ critical?: boolean;+ safetyStockQuantity?: number;+ safetyStockLeadTime?: number;+ demandAccumulationPeriod?: number;+ demandReschedulingPeriod?: number;+ demandAccumulationIncludesInventory?: boolean;+ reorderPoint?: number;+ reorderQuantity?: number;+ reorderMaximumInventory?: number;+ reorderOverflowLevel?: number;+ reorderTimeBucket?: number;+ minimumOrderQuantity?: number;+ maximumOrderQuantity?: number;+ orderMultiple?: number;+ createdAt?: string;+ };+ };+ partReplenishment: {+ Row: {+ partId: string;+ supplierId: string | null;+ supplierPartNumber: string | null;+ purchasingUnitOfMeasureCode: string | null;+ lotSize: number | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ purchasingLeadTime: number;+ purchasingBlocked: boolean;+ manufacturingPolicy: Database["public"]["Enums"]["partManufacturingPolicy"];+ manufacturingLeadTime: number;+ manufacturingBlocked: boolean;+ requiresConfiguration: boolean;+ scrapPercentage: number;+ createdAt: string;+ };+ Insert: {+ partId: string;+ supplierId?: string | null;+ supplierPartNumber?: string | null;+ purchasingUnitOfMeasureCode?: string | null;+ lotSize?: number | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ purchasingLeadTime?: number;+ purchasingBlocked?: boolean;+ manufacturingPolicy?: Database["public"]["Enums"]["partManufacturingPolicy"];+ manufacturingLeadTime?: number;+ manufacturingBlocked?: boolean;+ requiresConfiguration?: boolean;+ scrapPercentage?: number;+ createdAt?: string;+ };+ Update: {+ partId?: string;+ supplierId?: string | null;+ supplierPartNumber?: string | null;+ purchasingUnitOfMeasureCode?: string | null;+ lotSize?: number | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ purchasingLeadTime?: number;+ purchasingBlocked?: boolean;+ manufacturingPolicy?: Database["public"]["Enums"]["partManufacturingPolicy"];+ manufacturingLeadTime?: number;+ manufacturingBlocked?: boolean;+ requiresConfiguration?: boolean;+ scrapPercentage?: number;+ createdAt?: string;+ };+ };+ partUnitSalePrice: {+ Row: {+ partId: string;+ currencyCode: string;+ salesUnitOfMeasureCode: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ unitSalePrice: number;+ salesBlocked: boolean;+ priceIncludesTax: boolean;+ allowInvoiceDiscount: boolean;+ createdAt: string;+ };+ Insert: {+ partId: string;+ currencyCode: string;+ salesUnitOfMeasureCode?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ unitSalePrice?: number;+ salesBlocked?: boolean;+ priceIncludesTax?: boolean;+ allowInvoiceDiscount?: boolean;+ createdAt?: string;+ };+ Update: {+ partId?: string;+ currencyCode?: string;+ salesUnitOfMeasureCode?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ unitSalePrice?: number;+ salesBlocked?: boolean;+ priceIncludesTax?: boolean;+ allowInvoiceDiscount?: boolean;+ createdAt?: string;+ };+ };search: {Row: {id: number;name: string;- entity: Database["public"]["Enums"]["search_entity"] | null;+ entity: Database["public"]["Enums"]["searchEntity"] | null;uuid: string | null;link: string;description: string | null;@@ -903,7 +1394,7 @@ export interface Database {Insert: {id?: number;name: string;- entity?: Database["public"]["Enums"]["search_entity"] | null;+ entity?: Database["public"]["Enums"]["searchEntity"] | null;uuid?: string | null;link: string;description?: string | null;@@ -912,13 +1403,42 @@ export interface Database {Update: {id?: number;name?: string;- entity?: Database["public"]["Enums"]["search_entity"] | null;+ entity?: Database["public"]["Enums"]["searchEntity"] | null;uuid?: string | null;link?: string;description?: string | null;fts?: unknown | null;};};+ shelf: {+ Row: {+ id: string;+ locationId: string | null;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ id: string;+ locationId?: string | null;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ id?: string;+ locationId?: string | null;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ active?: boolean;+ createdAt?: string;+ };+ };shift: {Row: {name: string;@@ -1110,6 +1630,38 @@ export interface Database {createdAt?: string;};};+ unitOfMeasure: {+ Row: {+ code: string;+ name: string;+ createdBy: string;+ updatedBy: string | null;+ updatedAt: string | null;+ id: string;+ active: boolean;+ createdAt: string;+ };+ Insert: {+ code: string;+ name: string;+ createdBy: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ Update: {+ code?: string;+ name?: string;+ createdBy?: string;+ updatedBy?: string | null;+ updatedAt?: string | null;+ id?: string;+ active?: boolean;+ createdAt?: string;+ };+ };user: {Row: {id: string;@@ -1278,32 +1830,32 @@ export interface Database {Row: {userId: string;note: string;- createdBy: string;id: string;+ createdBy: string;+ updatedAt: string | null;noteRichText: Json;active: boolean;createdAt: string;- updatedAt: string | null;};Insert: {userId: string;note: string;- createdBy: string;id?: string;+ createdBy: string;+ updatedAt?: string | null;noteRichText?: Json;active?: boolean;createdAt?: string;- updatedAt?: string | null;};Update: {userId?: string;note?: string;- createdBy?: string;id?: string;+ createdBy?: string;+ updatedAt?: string | null;noteRichText?: Json;active?: boolean;createdAt?: string;- updatedAt?: string | null;};};workCell: {@@ -1552,6 +2104,7 @@ export interface Database {};};Enums: {+ consolidatedRate: "Average" | "Current" | "Historical";factor:| "Hours/Piece"| "Hours/100 Pieces"@@ -1564,7 +2117,37 @@ export interface Database {| "Seconds/Piece"| "Total Hours"| "Total Minutes";- search_entity:+ glAccountCategory:+ | "Bank"+ | "Accounts Receivable"+ | "Inventory"+ | "Other Current Asset"+ | "Fixed Asset"+ | "Accumulated Depreciation"+ | "Other Asset"+ | "Accounts Payable"+ | "Other Current Liability"+ | "Long Term Liability"+ | "Equity - No Close"+ | "Equity - Close"+ | "Retained Earnings"+ | "Income"+ | "Cost of Goods Sold"+ | "Expense"+ | "Other Income"+ | "Other Expense";+ glAccountType: "Balance Sheet" | "Income Statement";+ glNormalBalance: "Debit" | "Credit";+ partCostingMethod: "Standard" | "Average" | "LIFO" | "FIFO";+ partManufacturingPolicy: "Make to Order" | "Make to Stock";+ partReorderingPolicy:+ | "Manual Reorder"+ | "Demand-Based Reorder"+ | "Fixed Reorder Quantity"+ | "Maximum Quantity";+ partReplenishmentSystem: "Buy" | "Make" | "Buy and Make";+ partType: "Inventory" | "Non-Inventory" | "Service";+ searchEntity:| "Resource"| "Person"| "Customer"diff --git a/packages/carbon-database/supabase/migrations/20230123004316_users.sql b/packages/carbon-database/supabase/migrations/20230123004316_users.sqlindex 4c2b26b75e..36773ad706 100644--- a/packages/carbon-database/supabase/migrations/20230123004316_users.sql+++ b/packages/carbon-database/supabase/migrations/20230123004316_users.sql@@ -14,6 +14,9 @@ CREATE TABLE "user" (CONSTRAINT "user_pkey" PRIMARY KEY ("id"));+INSERT INTO "user" ("id", "email", "firstName", "lastName")+VALUES ('system', '[email protected]', 'System', 'Operation');+CREATE UNIQUE INDEX "index_user_email_key" ON "user"("email");CREATE INDEX "index_user_fullName" ON "user"("fullName");diff --git a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sqlindex fe5e0327ab..a52a21d831 100644--- a/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql+++ b/packages/carbon-database/supabase/migrations/20230123004612_suppliers-and-customers.sql@@ -113,6 +113,8 @@ CREATE TABLE "supplierContact" (CONSTRAINT "supplierContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "supplierContact_supplierId_index" ON "supplierContact"("supplierId");+CREATE TABLE "supplierAccount" ("id" TEXT NOT NULL,"supplierId" TEXT NOT NULL,@@ -122,6 +124,8 @@ CREATE TABLE "supplierAccount" (CONSTRAINT "supplierAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+CREATE INDEX "supplierAccount_supplierId_index" ON "supplierAccount"("supplierId");+CREATE TABLE "customerStatus" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -192,6 +196,8 @@ CREATE TABLE "customerContact" (CONSTRAINT "customerContact_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL);+CREATE INDEX "customerContact_customerId_index" ON "customerContact"("customerId");+CREATE TABLE "customerAccount" ("id" TEXT NOT NULL,"customerId" TEXT NOT NULL,@@ -200,3 +206,5 @@ CREATE TABLE "customerAccount" (CONSTRAINT "customerAccount_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "customerAccount_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);++CREATE INDEX "customerAccount_customerId_index" ON "customerAccount"("customerId");diff --git a/packages/carbon-database/supabase/migrations/20230123212853_search.sql b/packages/carbon-database/supabase/migrations/20230123212853_search.sqlindex fc5a59ad23..e2b6504f5c 100644--- a/packages/carbon-database/supabase/migrations/20230123212853_search.sql+++ b/packages/carbon-database/supabase/migrations/20230123212853_search.sql@@ -1,11 +1,11 @@-CREATE TYPE search_entity AS enum ('Resource', 'Person', 'Customer', 'Supplier', 'Job', 'Part', 'Purchase Order', 'Sales Order', 'Document');+CREATE TYPE "searchEntity" AS enum ('Resource', 'Person', 'Customer', 'Supplier', 'Job', 'Part', 'Purchase Order', 'Sales Order', 'Document');CREATE TABLE search (id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,name TEXT NOT NULL,description TEXT DEFAULT '',- entity search_entity,+ entity "searchEntity",uuid TEXT,link TEXT NOT NULL);diff --git a/packages/carbon-database/supabase/migrations/20230302030217_equipment.sql b/packages/carbon-database/supabase/migrations/20230302030217_equipment.sqlindex 2a64554986..26291301f9 100644--- a/packages/carbon-database/supabase/migrations/20230302030217_equipment.sql+++ b/packages/carbon-database/supabase/migrations/20230302030217_equipment.sql@@ -28,6 +28,36 @@ CREATE TABLE "department" (CONSTRAINT "department_parentDepartmentId_fkey" FOREIGN KEY ("parentDepartmentId") REFERENCES "department"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "department" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view departments" ON "department"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert departments" ON "department"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update departments" ON "department"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete departments" ON "department"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "workCellType" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -47,6 +77,36 @@ CREATE TABLE "workCellType" (CONSTRAINT "workCellType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "workCellType" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view work cell types" ON "workCellType"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert work cell types" ON "workCellType"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update work cell types" ON "workCellType"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete work cell types" ON "workCellType"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "workCell" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -69,6 +129,36 @@ CREATE TABLE "workCell" (CONSTRAINT "uq_workCell_name_departmentId" UNIQUE ("name", "departmentId"));+ALTER TABLE "workCell" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view work cells" ON "workCell"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert work cells" ON "workCell"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update work cells" ON "workCell"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete work cells" ON "workCell"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+ALTER TABLE "employeeJob"ADD COLUMN "departmentId" TEXT REFERENCES "department"("id") ON DELETE CASCADE ON UPDATE CASCADE,ADD COLUMN "workCellId" TEXT REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE;@@ -87,6 +177,36 @@ CREATE TABLE "crew" (CONSTRAINT "crew_workCellId_fkey" FOREIGN KEY ("workCellId") REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "crew" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view crews" ON "crew"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert crews" ON "crew"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update crews" ON "crew"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete crews" ON "crew"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "crewAbility" ("id" TEXT NOT NULL DEFAULT xid(),"crewId" TEXT NOT NULL,@@ -98,6 +218,37 @@ CREATE TABLE "crewAbility" (CONSTRAINT "crewAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "crewAbility" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view crew abilities" ON "crewAbility"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (get_my_claim('resources_view')::boolean) = true+ );++CREATE POLICY "Employees with resources_create can insert crew abilities" ON "crewAbility"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update crew abilities" ON "crewAbility"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete crew abilities" ON "crewAbility"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "equipmentType" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -117,6 +268,36 @@ CREATE TABLE "equipmentType" (CONSTRAINT "equipmentType_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);+ALTER TABLE "equipmentType" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view equipment types" ON "equipmentType"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert equipment types" ON "equipmentType"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update equipment types" ON "equipmentType"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete equipment types" ON "equipmentType"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+CREATE TABLE "equipment" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL UNIQUE,@@ -135,9 +316,74 @@ CREATE TABLE "equipment" (CONSTRAINT "equipment_pkey" PRIMARY KEY ("id"),CONSTRAINT "equipment_equipmentTypeId_fkey" FOREIGN KEY ("equipmentTypeId") REFERENCES "equipmentType"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "equipment_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_workCellId_fkey" FOREIGN KEY ("workCellId") REFERENCES "workCell"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "equipment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);--- TODO: insert/update search results with triggers+ALTER TABLE "equipment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view equipment" ON "equipment"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert equipment" ON "equipment"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update equipment" ON "equipment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete equipment" ON "equipment"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE FUNCTION public.create_equipment_search_result()+RETURNS TRIGGER AS $$+DECLARE+ equipment_type TEXT;+BEGIN+ equipment_type := (SELECT u."name" FROM public."equipmentType" et WHERE et.id = new."equipmentTypeId");+ INSERT INTO public.search(name, description, entity, uuid, link)+ VALUES (new.name, COALESCE(new.description, '') || ' ' || equipment_type, 'Resource', new.id, '/x/resources/equipment/list/' || new."equipmentTypeId" || '/' || new.id);+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_equipment_search_result+ AFTER INSERT on public.equipment+ FOR EACH ROW EXECUTE PROCEDURE public.create_equipment_search_result();++CREATE FUNCTION public.update_equipment_search_result()+RETURNS TRIGGER AS $$+DECLARE+ equipment_type TEXT;+BEGIN+ IF (old.name <> new.name OR old.description <> new.description OR old."equipmentTypeId" <> new."equipmentTypeId") THEN+ equipment_type := (SELECT u."name" FROM public."equipmentType" et WHERE et.id = new."equipmentTypeId");+ UPDATE public.search SET name = new.name, description = COALESCE(new.description, '') || ' ' || equipment_type+ WHERE entity = 'Resource' AND uuid = new.id;+ END IF;+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER update_equipment_search_result+ AFTER UPDATE on public.equipment+ FOR EACH ROW EXECUTE PROCEDURE public.update_equipment_search_result();++diff --git a/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql b/packages/carbon-database/supabase/migrations/20230315222231_holidays.sqlindex d356ec3aeb..224aeeafa0 100644--- a/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql+++ b/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql@@ -14,4 +14,34 @@ CREATE TABLE "holiday" (CONSTRAINT "holiday_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE);-CREATE VIEW "holiday_years" AS SELECT DISTINCT "year" FROM "holiday";\ No newline at end of file+CREATE VIEW "holiday_years" AS SELECT DISTINCT "year" FROM "holiday";++ALTER TABLE "holiday" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view holidays" ON "holiday"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert holidays" ON "holiday"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update holidays" ON "holiday"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete holidays" ON "holiday"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );\ No newline at end of filediff --git a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sqlindex c80c3722a4..10f056210f 100644--- a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql+++ b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql@@ -13,6 +13,37 @@ CREATE TABLE "contractor" (CONSTRAINT "contractor_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"));+ALTER TABLE "contractor" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view contractors" ON "contractor"+ FOR SELECT+ USING (+ coalesce(get_my_claim('resources_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert contractors" ON "contractor"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update contractors" ON "contractor"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete contractors" ON "contractor"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "contractorAbility" ("contractorId" TEXT NOT NULL,"abilityId" TEXT NOT NULL,@@ -25,6 +56,37 @@ CREATE TABLE "contractorAbility" (CONSTRAINT "contractorAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"));+ALTER TABLE "contractorAbility" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with resources_view can view contractorAbilities" ON "contractorAbility"+ FOR SELECT+ USING (+ coalesce(get_my_claim('resources_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_create can insert contractorAbilities" ON "contractorAbility"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('resources_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with resources_update can update contractorAbilities" ON "contractorAbility"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('resources_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with resources_delete can delete contractorAbilities" ON "contractorAbility"+ FOR DELETE+ USING (+ coalesce(get_my_claim('resources_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE VIEW "contractors_query" ASSELECTp.id AS "supplierContactId",diff --git a/packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sql b/packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sqlnew file mode 100644index 0000000000..90ad639696--- /dev/null+++ b/packages/carbon-database/supabase/migrations/20230330024715_chart-of-accounts.sql@@ -0,0 +1,223 @@+CREATE TABLE "currency" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "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,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "currency_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "currency_code_key" UNIQUE ("code"),+ 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');++CREATE INDEX "currency_code_index" ON "currency" ("code");++ALTER TABLE "currency" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view currencies" ON "currency"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );++CREATE POLICY "Employees with accounting_create can insert currencies" ON "currency"+ 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 currencies" ON "currency"+ 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 currencies" ON "currency"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "glAccountCategory" AS ENUM (+ 'Bank',+ 'Accounts Receivable',+ 'Inventory',+ 'Other Current Asset',+ 'Fixed Asset',+ 'Accumulated Depreciation',+ 'Other Asset',+ 'Accounts Payable',+ 'Other Current Liability',+ 'Long Term Liability',+ 'Equity - No Close',+ 'Equity - Close',+ 'Retained Earnings',+ 'Income',+ 'Cost of Goods Sold',+ 'Expense',+ 'Other Income',+ 'Other Expense'+);++CREATE TYPE "glAccountType" AS ENUM (+ 'Balance Sheet',+ 'Income Statement'+);++CREATE TYPE "glNormalBalance" AS ENUM (+ 'Debit',+ 'Credit'+);++CREATE TABLE "accountCategory" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "category" "glAccountCategory" NOT NULL,+ "type" "glAccountType" NOT NULL,+ "normalBalance" "glNormalBalance" NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "accountCategory_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "accountCategory_category_type_key" 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")+VALUES+ ('Bank', 'Balance Sheet', 'Credit', 'system'),+ ('Accounts Receivable', 'Balance Sheet', 'Credit', 'system'),+ ('Inventory', 'Balance Sheet', 'Debit', 'system'),+ ('Other Current Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Fixed Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Accumulated Depreciation', 'Balance Sheet', 'Credit', 'system'),+ ('Other Asset', 'Balance Sheet', 'Debit', 'system'),+ ('Accounts Payable', 'Balance Sheet', 'Debit', 'system'),+ ('Other Current Liability', 'Balance Sheet', 'Debit', 'system'),+ ('Long Term Liability', 'Balance Sheet', 'Debit', 'system'),+ ('Equity - No Close', 'Balance Sheet', 'Credit', 'system'),+ ('Equity - Close', 'Balance Sheet', 'Credit', 'system'),+ ('Retained Earnings', 'Balance Sheet', 'Credit', 'system'),+ ('Income', 'Income Statement', 'Credit', 'system'),+ ('Cost of Goods Sold', 'Income Statement', 'Debit', 'system'),+ ('Expense', 'Income Statement', 'Debit', 'system'),+ ('Other Income', 'Income Statement', 'Credit', 'system'),+ ('Other Expense', 'Income Statement', 'Debit', 'system');++ALTER TABLE "accountCategory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with accounting_view can view account categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ 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 categories" ON "accountCategory"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "consolidatedRate" AS ENUM (+ 'Average',+ 'Current',+ 'Historical'+);++CREATE TABLE "account" (+ "number" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "accountCategoryId" TEXT,+ "controlAccount" BOOLEAN NOT NULL DEFAULT false,+ "cashAccount" BOOLEAN NOT NULL DEFAULT false,+ "consolidatedRate" "consolidatedRate",+ "currencyCode" TEXT,+ "parentAccountNumber" TEXT,+ "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_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');++ALTER TABLE "account" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Certain employees can view accounts" ON "account"+ 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 accounts" ON "account"+ 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 accounts" ON "account"+ 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 accounts" ON "account"+ FOR DELETE+ USING (+ coalesce(get_my_claim('accounting_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );\ No newline at end of filediff --git a/packages/carbon-database/supabase/migrations/20230330024716_parts.sql b/packages/carbon-database/supabase/migrations/20230330024716_parts.sqlnew file mode 100644index 0000000000..57e964f7cf--- /dev/null+++ b/packages/carbon-database/supabase/migrations/20230330024716_parts.sql@@ -0,0 +1,656 @@+CREATE TABLE "partGroup" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "name" TEXT NOT NULL,+ "description" TEXT,+ "salesAccountId" TEXT,+ "discountAccountId" TEXT,+ "inventoryAccountId" TEXT,+ "costOfGoodsSoldLaborAccountId" TEXT,+ "costOfGoodsSoldMaterialAccountId" TEXT,+ "costOfGoodsSoldOverheadAccountId" TEXT,+ "costOfGoodsSoldSubcontractorAccountId" TEXT,+ "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 "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_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++ALTER TABLE "partGroup" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with parts_view can view part groups" ON "partGroup"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE POLICY "Employees with parts_create can insert part groups" ON "partGroup"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update part groups" ON "partGroup"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete part groups" ON "partGroup"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TYPE "partType" AS ENUM (+ 'Inventory',+ 'Non-Inventory',+ 'Service'+);++CREATE TYPE "partReplenishmentSystem" AS ENUM (+ 'Buy',+ 'Make',+ 'Buy and Make'+);++CREATE TYPE "partManufacturingPolicy" AS ENUM (+ 'Make to Order',+ 'Make to Stock'+);+++CREATE TYPE "partCostingMethod" AS ENUM (+ 'Standard',+ 'Average',+ 'LIFO',+ 'FIFO'+);++CREATE TYPE "partReorderingPolicy" AS ENUM (+ 'Manual Reorder',+ 'Demand-Based Reorder',+ 'Fixed Reorder Quantity',+ 'Maximum Quantity'+);++CREATE TABLE "unitOfMeasure" (+ "id" TEXT NOT NULL DEFAULT xid(),+ "code" TEXT NOT NULL,+ "name" 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 "unitOfMeasure_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "unitOfMeasure_code_key" UNIQUE ("code"),+ CONSTRAINT "unitOfMeasure_code_check" CHECK (char_length("code") <= 3),+ CONSTRAINT "unitOfMeasure_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "unitOfMeasure_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "unitOfMeasure_code_index" ON "unitOfMeasure"("code");++INSERT INTO "unitOfMeasure" ("code", "name", "createdBy")+VALUES+( 'EA', 'Each', 'system'),+( 'PCS', 'Pieces', 'system');++ALTER TABLE "unitOfMeasure" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view units of measure" ON "unitOfMeasure"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );+++CREATE POLICY "Employees with parts_create can insert units of measure" ON "unitOfMeasure"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update units of measure" ON "unitOfMeasure"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete units of measure" ON "unitOfMeasure"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "part" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "blocked" BOOLEAN NOT NULL DEFAULT false,+ "replenishmentSystem" "partReplenishmentSystem" NOT NULL,+ "partGroupId" TEXT NOT NULL,+ "partType" "partType" NOT NULL,+ "manufacturerPartNumber" TEXT,+ "unitOfMeasureCode" TEXT NOT NULL,+ "active" BOOLEAN NOT NULL DEFAULT true,+ "approved" BOOLEAN NOT NULL DEFAULT false,+ "approvedBy" TEXT,+ "fromDate" DATE,+ "toDate" DATE,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "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_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"),+ CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "part_name_index" ON "part"("name");+CREATE INDEX "part_description_index" ON "part"("description");+CREATE INDEX "part_partType_index" ON "part"("partType");+CREATE INDEX "part_partGroupId_index" ON "part"("partGroupId");+CREATE INDEX "part_replenishmentSystem_index" ON "part"("replenishmentSystem");++ALTER TABLE "part" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees can view parts" ON "part"+ FOR SELECT+ USING (+ (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_create can insert parts" ON "part"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update parts" ON "part"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete parts" ON "part"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE FUNCTION public.create_part_search_result()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public.search(name, description, entity, uuid, link)+ VALUES (new.id, new.id || ' ' || new.name || ' ' || COALESCE(new.description, ''), 'Part', new.id, '/x/part/' || new.id);+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_part_search_result+ AFTER INSERT on public.part+ FOR EACH ROW EXECUTE PROCEDURE public.create_part_search_result();++CREATE FUNCTION public.create_part_related_records()+RETURNS TRIGGER AS $$+BEGIN+ INSERT INTO public."partCost"("partId", "costingMethod", "createdBy")+ VALUES (new.id, 'Standard', new."createdBy");++ INSERT INTO public."partReplenishment"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partPlanning"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partInventory"("partId", "createdBy")+ VALUES (new.id, new."createdBy");++ INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")+ -- TODO: get default currency+ VALUES (new.id, 'USD', new."createdBy");++ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER create_part_related_records+ AFTER INSERT on public.part+ FOR EACH ROW EXECUTE PROCEDURE public.create_part_related_records();++CREATE FUNCTION public.update_part_search_result()+RETURNS TRIGGER AS $$+BEGIN+ IF (old.name <> new.name OR old.description <> new.description) THEN+ UPDATE public.search SET name = new.name, description = new.id || ' ' || new.name || ' ' || COALESCE(new.description, '')+ WHERE entity = 'Part' AND uuid = new.id;+ END IF;+ RETURN new;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++CREATE TRIGGER update_part_search_result+ AFTER UPDATE on public.customer+ FOR EACH ROW EXECUTE PROCEDURE public.update_part_search_result();+++CREATE TABLE "partCost" (+ "partId" TEXT NOT NULL,+ "costingMethod" "partCostingMethod" NOT NULL,+ "standardCost" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "unitCost" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "salesAccountId" TEXT,+ "discountAccountId" TEXT,+ "inventoryAccountId" TEXT,+ "costIsAdjusted" BOOLEAN NOT NULL DEFAULT false,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "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 "partGroup_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partGroup_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partCost_partId_index" ON "partCost" ("partId");++ALTER TABLE "partCost" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part costs" ON "partCost"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part costs" ON "partCost"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partUnitSalePrice" (+ "partId" TEXT NOT NULL,+ "unitSalePrice" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "currencyCode" TEXT NOT NULL,+ "salesUnitOfMeasureCode" TEXT,+ "salesBlocked" BOOLEAN NOT NULL DEFAULT false,+ "priceIncludesTax" BOOLEAN NOT NULL DEFAULT false,+ "allowInvoiceDiscount" 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 "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_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")+);++CREATE INDEX "partUnitSalePrice_partId_index" ON "partUnitSalePrice"("partId");++ALTER TABLE "partUnitSalePrice" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part sale prices" ON "partUnitSalePrice"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part sale prices" ON "partUnitSalePrice"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE TABLE "partReplenishment" (+ "partId" TEXT NOT NULL,+ "supplierId" TEXT,+ "supplierPartNumber" TEXT,+ "purchasingLeadTime" INTEGER NOT NULL DEFAULT 0,+ "purchasingUnitOfMeasureCode" TEXT,+ "purchasingBlocked" BOOLEAN NOT NULL DEFAULT false,+ "manufacturingPolicy" "partManufacturingPolicy" NOT NULL DEFAULT 'Make to Stock',+ "manufacturingLeadTime" INTEGER NOT NULL DEFAULT 0,+ "manufacturingBlocked" BOOLEAN NOT NULL DEFAULT false,+ "requiresConfiguration" BOOLEAN NOT NULL DEFAULT false,+ "scrapPercentage" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "lotSize" INTEGER,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partReplenishment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,+ CONSTRAINT "partReplenishment_purchaseUnitOfMeasureId_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,+ CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partReplenishment_partId_index" ON "partReplenishment" ("partId");+CREATE INDEX "partReplenishment_supplierId_index" ON "partReplenishment" ("supplierId");++ALTER TABLE "partReplenishment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part costs" ON "partReplenishment"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part costs" ON "partReplenishment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view parts they created or supply" ON "part"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Supliers with parts_create can insert parts" ON "part"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ );++CREATE POLICY "Suppliers with parts_update can update parts that they created or supply" ON "part"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_delete can delete parts that they created or supply" ON "part"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "createdBy" = auth.uid()::text+ OR (+ id IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_view can view part costs they supply" ON "partCost"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update parts costs that they supply" ON "partCost"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_view can view part replenishments they supply" ON "partReplenishment"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update parts replenishments that they supply" ON "partReplenishment"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ );++CREATE TABLE "shelf" (+ "id" TEXT NOT NULL,+ "locationId" TEXT,+ "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 "shelf_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "shelf_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("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");++ALTER TABLE "shelf" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view shelves" ON "shelf"+ FOR SELECT+ USING (+ auth.role() = 'authenticated'+ );+++CREATE POLICY "Employees with parts_create can insert shelves" ON "shelf"+ FOR INSERT+ WITH CHECK (+ coalesce(get_my_claim('parts_create')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+);++CREATE POLICY "Employees with parts_update can update shelves" ON "shelf"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_delete can delete shelves" ON "shelf"+ FOR DELETE+ USING (+ coalesce(get_my_claim('parts_delete')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "partPlanning" (+ "partId" TEXT NOT NULL,+ "reorderingPolicy" "partReorderingPolicy" NOT NULL DEFAULT 'Demand-Based Reorder',+ "critical" BOOLEAN NOT NULL DEFAULT false,+ "safetyStockQuantity" INTEGER NOT NULL DEFAULT 0,+ "safetyStockLeadTime" INTEGER NOT NULL DEFAULT 0,+ "demandAccumulationPeriod" INTEGER NOT NULL DEFAULT 0,+ "demandReschedulingPeriod" INTEGER NOT NULL DEFAULT 0,+ "demandAccumulationIncludesInventory" BOOLEAN NOT NULL DEFAULT false,+ "reorderPoint" INTEGER NOT NULL DEFAULT 0,+ "reorderQuantity" INTEGER NOT NULL DEFAULT 0,+ "reorderMaximumInventory" INTEGER NOT NULL DEFAULT 0,+ "reorderOverflowLevel" INTEGER NOT NULL DEFAULT 0,+ "reorderTimeBucket" INTEGER NOT NULL DEFAULT 5,+ "minimumOrderQuantity" INTEGER NOT NULL DEFAULT 0,+ "maximumOrderQuantity" INTEGER NOT NULL DEFAULT 0,+ "orderMultiple" INTEGER NOT NULL DEFAULT 1,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partPlanning_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE,+ CONSTRAINT "partPlanning_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),+ CONSTRAINT "partPlanning_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")+);++CREATE INDEX "partPlanning_partId_index" ON "partPlanning" ("partId");+ALTER TABLE "partPlanning" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part planning" ON "partPlanning"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part planning" ON "partPlanning"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );+++CREATE TABLE "partInventory" (+ "partId" TEXT NOT NULL,+ "shelfId" TEXT,+ "stockoutWarning" BOOLEAN NOT NULL DEFAULT true,+ "unitVolume" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "unitWeight" NUMERIC(15,5) NOT NULL DEFAULT 0,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ CONSTRAINT "partInventory_partId_shelfId_key" UNIQUE ("partId", "shelfId"),+ CONSTRAINT "partInventory_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE 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")+);++CREATE INDEX "partInventory_partId_index" ON "partInventory" ("partId");+CREATE INDEX "partInventory_shelfId_index" ON "partInventory" ("shelfId");++ALTER TABLE "partInventory" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Employees with part_view can view part planning" ON "partInventory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean,false)+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Employees with parts_update can update part planning" ON "partInventory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ );++CREATE POLICY "Suppliers with parts_view can view part inventory they supply" ON "partInventory"+ FOR SELECT+ USING (+ coalesce(get_my_claim('parts_view')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"supplier"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );++CREATE POLICY "Suppliers with parts_update can update part inventory that they supply" ON "partInventory"+ FOR UPDATE+ USING (+ coalesce(get_my_claim('parts_update')::boolean, false) = true+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb+ AND (+ "partId" IN (+ SELECT "partId" FROM "partReplenishment" WHERE "supplierId" IN (+ SELECT "supplierId" FROM "supplierAccount" WHERE id::uuid = auth.uid()+ )+ )+ )+ );\ No newline at end of filediff --git a/packages/carbon-react/package.json b/packages/carbon-react/package.jsonindex 0229ac9fc5..73c080ad72 100644--- a/packages/carbon-react/package.json+++ b/packages/carbon-react/package.json@@ -43,7 +43,7 @@"framer-motion": "^10.0.0","is-hotkey": "^0.2.0","react-colorful": "^5.6.1",- "react-icons": "^4.7.1",+ "react-icons": "^4.8.0","react-select": "^5.5.1"},"devDependencies": {diff --git a/packages/carbon-react/src/HTML/HTML.tsx b/packages/carbon-react/src/HTML/HTML.tsxindex 8cc38b3b95..9acfabdff6 100644--- a/packages/carbon-react/src/HTML/HTML.tsx+++ b/packages/carbon-react/src/HTML/HTML.tsx@@ -1,6 +1,6 @@import { Box } from "@chakra-ui/react";import { sanitize } from "dompurify";-import { useEffect, useState } from "react";+import { useMemo } from "react";import { reset } from "../Theme";type HTMLProps = {@@ -8,11 +8,8 @@ type HTMLProps = {};const HTML = ({ text }: HTMLProps) => {- const [html, setHtml] = useState<string>("");- const sanitizedHtml = { __html: html };-- useEffect(() => {- setHtml(sanitize(text));+ const sanitizedHtml = useMemo(() => {+ return { __html: sanitize(text) };}, [text]);return (diff --git a/packages/carbon-react/src/Inputs/Select/CreatableSelect.tsx b/packages/carbon-react/src/Inputs/Select/CreatableSelect.tsxnew file mode 100644index 0000000000..29bf7de71e--- /dev/null+++ b/packages/carbon-react/src/Inputs/Select/CreatableSelect.tsx@@ -0,0 +1,39 @@+/* eslint-disable react/display-name */+import { forwardRef, useId } from "react";+import type { MutableRefObject, ReactElement, RefAttributes } from "react";+import type { GroupBase, SelectInstance } from "react-select";+import CreatableReactSelect from "react-select/creatable";+import type { CreatableProps } from "react-select/creatable";+import useSelect from "./useSelect";++export type CreatableSelectComponent = <+ Option = unknown,+ IsMulti extends boolean = false,+ Group extends GroupBase<Option> = GroupBase<Option>+>(+ props: CreatableProps<Option, IsMulti, Group> &+ RefAttributes<SelectInstance<Option, IsMulti, Group>>+) => ReactElement;++const CreatableSelect = forwardRef(+ <Option, IsMulti extends boolean, Group extends GroupBase<Option>>(+ props: CreatableProps<Option, IsMulti, Group>,+ ref:+ | ((instance: SelectInstance<Option, IsMulti, Group> | null) => void)+ | MutableRefObject<SelectInstance<Option, IsMulti, Group> | null>+ | null+ ) => {+ const instanceId = useId();+ const selectProps = useSelect(props);++ return (+ <CreatableReactSelect+ instanceId={instanceId}+ ref={ref}+ {...selectProps}+ />+ );+ }+) as CreatableSelectComponent;++export default CreatableSelect;diff --git a/packages/carbon-react/src/Inputs/Select/index.ts b/packages/carbon-react/src/Inputs/Select/index.tsindex 8168a57c5c..0c2b1684b9 100644--- a/packages/carbon-react/src/Inputs/Select/index.ts+++ b/packages/carbon-react/src/Inputs/Select/index.ts@@ -1,5 +1,5 @@+import CreatableSelect from "./CreatableSelect";import Select from "./Select";import { createFilter } from "react-select";-export default Select;-export { createFilter };+export { CreatableSelect, Select, createFilter };diff --git a/packages/carbon-react/src/Inputs/index.ts b/packages/carbon-react/src/Inputs/index.tsindex fcd1c8d4a8..033c93b430 100644--- a/packages/carbon-react/src/Inputs/index.ts+++ b/packages/carbon-react/src/Inputs/index.ts@@ -6,11 +6,12 @@ import {TimePicker,} from "./Date";import { Editor, useEditor } from "./Editor";-import Select, { createFilter } from "./Select";+import { CreatableSelect, Select, createFilter } from "./Select";import type { OptionBase } from "./Select/types";export type { OptionBase, OptionProps, GroupBase };export {+ CreatableSelect,DatePicker,DateTimePicker,DateRangePicker,diff --git a/packages/carbon-react/src/index.tsx b/packages/carbon-react/src/index.tsxindex bd9e5044b7..dfac251646 100644--- a/packages/carbon-react/src/index.tsx+++ b/packages/carbon-react/src/index.tsx@@ -3,6 +3,7 @@ import Dot from "./Dot";import HTML from "./HTML";import type { OptionBase, OptionProps, GroupBase } from "./Inputs";import {+ CreatableSelect,DatePicker,DateTimePicker,DateRangePicker,@@ -33,6 +34,7 @@ export {Button,ClientOnly,ContextMenu,+ CreatableSelect,DatePicker,DateTimePicker,DateRangePicker,diff --git a/packages/carbon-redis/docker-compose.yml b/packages/carbon-redis/docker-compose.ymlindex 58b08d64d5..dd92c3f9de 100644--- a/packages/carbon-redis/docker-compose.yml+++ b/packages/carbon-redis/docker-compose.yml@@ -4,7 +4,7 @@ services:image: redis:7.0-alpinerestart: alwaysports:- - "6379:6379"+ - "6389:6379"command: redis-server --save 20 1 --loglevel warningvolumes:- cache:/datadiff --git a/www/package.json b/www/package.jsonindex 938f54b253..d2ed6f9105 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.7.1"+ "react-icons": "^4.8.0"},"devDependencies": {"@carbon/tsconfig": "*",diff --git a/yarn.lock b/yarn.lockindex 70ea3e1274..d8554c6d39 100644--- a/yarn.lock+++ b/yarn.lock@@ -4434,6 +4434,11 @@resolved "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz"integrity sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==+"@types/nprogress@^0.2.0":+ version "0.2.0"+ resolved "https://registry.yarnpkg.com/@types/nprogress/-/nprogress-0.2.0.tgz#86c593682d4199212a0509cc3c4d562bbbd6e45f"+ integrity sha512-1cYJrqq9GezNFPsWTZpFut/d4CjpZqA0vhqDUPFWYKF1oIyBz5qnoYMzR+0C/T96t3ebLAC1SSnwrVOm5/j74A==+"@types/object.omit@^3.0.0":version "3.0.0"resolved "https://registry.npmjs.org/@types/object.omit/-/object.omit-3.0.0.tgz"@@ -11589,6 +11594,11 @@ npm-run-path@^5.1.0:dependencies:path-key "^4.0.0"+ version "0.2.0"+ resolved "https://registry.yarnpkg.com/nprogress/-/nprogress-0.2.0.tgz#cb8f34c53213d895723fcbab907e9422adbcafb1"+ integrity sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==+nwsapi@^2.2.0:version "2.2.2"resolved "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.2.tgz"@@ -12607,10 +12617,10 @@ react-focus-lock@^2.9.2:use-callback-ref "^1.3.0"use-sidecar "^1.1.2"[email protected], react-icons@^4.7.1:- version "4.7.1"- resolved "https://registry.npmjs.org/react-icons/-/react-icons-4.7.1.tgz"- integrity sha512-yHd3oKGMgm7zxo3EA7H2n7vxSoiGmHk5t6Ou4bXsfcgWyhfDKMpyKfhHR6Bjnn63c+YXBLBPUql9H4wPJM6sXw==+react-icons@^4.8.0:+ version "4.8.0"+ resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-4.8.0.tgz#621e900caa23b912f737e41be57f27f6b2bff445"+ integrity sha512-N6+kOLcihDiAnj5Czu637waJqSnwlMNROzVZMhfX68V/9bu9qHaMIJC4UdozWoOk57gahFCNHwVvWzm0MTzRjg==react-is@^16.13.1, react-is@^16.7.0:version "16.13.1"