Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

refactor: migrations for multi-tenant - batch 14

Brad Barbin173f43569ae8
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index d9c0a6e133..2ef38a1114 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -482,28 +482,6 @@ export async function insertSupplierContact(
.single();
}
-export async function getUninvoicedReceipts(
- client: SupabaseClient<Database>,
- args?: GenericQueryFilters & {
- supplier: string | null;
- }
-) {
- let query = client.from("receiptsPostedNotInvoiced").select("*");
-
- if (args?.supplier) {
- query = query.eq("supplierId", args.supplier);
- }
-
- if (args)
- if (args) {
- query = setGenericQueryFilters(query, args, [
- { column: "name", ascending: true },
- ]);
- }
-
- return query;
-}
-
export async function insertSupplierLocation(
client: SupabaseClient<Database>,
supplierLocation: {
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index dd7fbe7edb..1a15de57b2 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -380,9 +380,15 @@ export async function getUserGroups(
export async function getUserDefaults(
client: SupabaseClient<Database>,
- userId: string
+ userId: string,
+ companyId: number
) {
- return client.from("userDefaults").select("*").eq("userId", userId).single();
+ return client
+ .from("userDefaults")
+ .select("*")
+ .eq("userId", userId)
+ .eq("companyId", companyId)
+ .maybeSingle();
}
async function insertCustomerAccount(
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 06d713f178..8397da7dbc 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -53,7 +53,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getUser(client, userId),
getUserClaims(request),
getUserGroups(client, userId),
- getUserDefaults(client, userId),
+ getUserDefaults(client, userId, companyId),
]);
if (!claims || user.error || !user.data || !groups.data) {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 034ccc353e..7dd128be6c 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -10092,6 +10092,7 @@ export type Database = {
receipt: {
Row: {
assignee: string | null
+ companyId: number
createdAt: string
createdBy: string
customFields: Json | null
@@ -10113,6 +10114,7 @@ export type Database = {
}
Insert: {
assignee?: string | null
+ companyId: number
createdAt?: string
createdBy: string
customFields?: Json | null
@@ -10134,6 +10136,7 @@ export type Database = {
}
Update: {
assignee?: string | null
+ companyId?: number
createdAt?: string
createdBy?: string
customFields?: Json | null
@@ -10182,6 +10185,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "receipt_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receipt_createdBy_fkey"
columns: ["createdBy"]
@@ -10305,6 +10315,7 @@ export type Database = {
}
receiptLine: {
Row: {
+ companyId: number
conversionFactor: number | null
createdAt: string
createdBy: string
@@ -10323,6 +10334,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ companyId: number
conversionFactor?: number | null
createdAt?: string
createdBy: string
@@ -10341,6 +10353,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ companyId?: number
conversionFactor?: number | null
createdAt?: string
createdBy?: string
@@ -10450,13 +10463,6 @@ export type Database = {
referencedRelation: "receipts"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "receiptLine_receiptId_fkey"
- columns: ["receiptId"]
- isOneToOne: false
- referencedRelation: "receiptsPostedNotInvoiced"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "receiptLine_shelfId_fkey"
columns: ["shelfId", "locationId"]
@@ -17272,6 +17278,7 @@ export type Database = {
receipts: {
Row: {
assignee: string | null
+ companyId: number | null
createdAt: string | null
createdBy: string | null
customFields: Json | null
@@ -17321,6 +17328,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "receipt_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receipt_createdBy_fkey"
columns: ["createdBy"]
@@ -17442,58 +17456,6 @@ export type Database = {
},
]
}
- receiptsPostedNotInvoiced: {
- Row: {
- estimatedCost: number | null
- id: string | null
- postingDate: string | null
- receiptId: string | null
- sourceDocument:
- | Database["public"]["Enums"]["receiptSourceDocument"]
- | null
- sourceDocumentId: string | null
- sourceDocumentReadableId: string | null
- supplierId: string | null
- supplierName: string | null
- }
- Relationships: [
- {
- foreignKeyName: "receipt_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "receipt_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "receipt_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "receipt_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "receipt_supplierId_fkey"
- columns: ["supplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
- ]
- }
requestForQuotes: {
Row: {
assignee: string | null
@@ -18482,14 +18444,9 @@ export type Database = {
},
]
}
- totalReceiptsPostedNotInvoiced: {
- Row: {
- total: number | null
- }
- Relationships: []
- }
userDefaults: {
Row: {
+ companyId: number | null
locationId: string | null
userId: string | null
}
@@ -18522,6 +18479,13 @@ export type Database = {
referencedRelation: "salesOrders"
referencedColumns: ["locationId"]
},
+ {
+ foreignKeyName: "location_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
]
}
}
@@ -18626,6 +18590,7 @@ export type Database = {
}
Returns: {
number: string
+ companyId: number
balance: number
balanceAtDate: number
netChange: number
diff --git a/packages/database/supabase/migrations/20230704160029_supplier-view.sql b/packages/database/supabase/migrations/20230704160029_supplier-view.sql
index c4d65c6ab6..359bfb05a8 100644
--- a/packages/database/supabase/migrations/20230704160029_supplier-view.sql
+++ b/packages/database/supabase/migrations/20230704160029_supplier-view.sql
@@ -8,7 +8,8 @@ CREATE OR REPLACE VIEW "suppliers" AS
ss.name AS "status",
po.count AS "orderCount",
p.count AS "partCount",
- s."customFields"
+ s."customFields",
+ s."companyId"
FROM "supplier" s
LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"
@@ -35,7 +36,8 @@ CREATE OR REPLACE VIEW "customers" AS
ct.name AS "type",
c."customerStatusId",
cs.name AS "status",
- c."customFields"
+ c."customFields",
+ c."companyId"
-- so.count AS "orderCount"
FROM "customer" c
LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
diff --git a/packages/database/supabase/migrations/20230704161623_parts-view.sql b/packages/database/supabase/migrations/20230704161623_parts-view.sql
index c925483f0f..b216707a30 100644
--- a/packages/database/supabase/migrations/20230704161623_parts-view.sql
+++ b/packages/database/supabase/migrations/20230704161623_parts-view.sql
@@ -9,6 +9,7 @@ CREATE OR REPLACE VIEW "parts" AS
p."replenishmentSystem",
p.active,
p."customFields",
+ p."companyId",
array_agg(ps."supplierId") AS "supplierIds"
FROM "part" p
LEFT JOIN "partGroup" pg ON pg.id = p."partGroupId"
@@ -21,5 +22,6 @@ CREATE OR REPLACE VIEW "parts" AS
pg.name,
p."replenishmentSystem",
p.active,
- p."customFields";
+ p."customFields",
+ p."companyId";
diff --git a/packages/database/supabase/migrations/20230705033431_warehouses.sql b/packages/database/supabase/migrations/20230705033431_warehouses.sql
deleted file mode 100644
index f1a3a5d5ad..0000000000
--- a/packages/database/supabase/migrations/20230705033431_warehouses.sql
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-
--- inbound warehouse request
--- is created automatically when a source document is released
--- is automatically deleted when the inventory put away gets everything handled
--- has a type
--- has a source document number
-
-
--- warehouse item journal
-
-
--- purchase receipt
--- return receipt
--- transfer receipt
-
--- part ledger entry pur
--- records the quantity change
-
--- value entry
--- records the value change
--- has a posting date
--- has an item ledger entry type (e.g. purchase, return, transfer, etc)
--- has an entry type (e.g. direct cost, indirect cost, etc)
--- has an adjustment checkbox
--- has a document type (e.g. purchase receipt, purchase invoice, sales invoice, etc)
--- has a document number
--- has an entry number (serial)
--- has a cost amount actual
--- has a cost amount expected
--- has an actual cost posted to gl
--- has an expected cost posted to gl
-
--- value entry - gl entry relation
--- has a value entry
--- has a gl entry
-
--- gl entry
-
-
--- warehouse entry
--- has an entry type (positive or negative)
--- has a part number
--- has a shelf
--- has a qty
-
-
--- inventory put away
--- has a warehouse
--- has a source document (assembly order, purchase order, purchase return order, inbound transfer, outbound transfer, sales order return, etc)
--- has a posting date
-
-
--- inventory put away lines
--- has a part number
--- has a description
--- has a shelf
--- has an order quantity
--- has a qty to handle
--- has a qty handled
--- has a calculated qty outstanding
--- has a uom and due date
-
-
diff --git a/packages/database/supabase/migrations/20230705033432_ledgers.sql b/packages/database/supabase/migrations/20230705033432_ledgers.sql
index cd3453a544..41b48abe35 100644
--- a/packages/database/supabase/migrations/20230705033432_ledgers.sql
+++ b/packages/database/supabase/migrations/20230705033432_ledgers.sql
@@ -142,7 +142,7 @@ CREATE POLICY "Employees with accounting_create can insert journal lines" ON "jo
has_company_permission('accounting_create', "companyId")
);
--- delete and update are not availble for journal lines
+-- delete and update are not available for journal lines
CREATE TYPE "partLedgerType" AS ENUM (
'Purchase',
@@ -215,24 +215,6 @@ CREATE POLICY "Employees with accounting_view can view the value ledger" ON "cos
has_company_permission('accounting_view', "companyId")
);
--- CREATE TABLE "costLedgerJournalLineRelation" (
--- "costLedgerId" TEXT NOT NULL,
--- "journalLineId" TEXT NOT NULL,
-
--- CONSTRAINT "costLedgerJournalLineRelation_pkey" PRIMARY KEY ("costLedgerId", "journalLineId"),
--- CONSTRAINT "costLedgerJournalLineRelation_costLedgerId_fkey" FOREIGN KEY ("costLedgerId") REFERENCES "costLedger"("id"),
--- CONSTRAINT "costLedgerJournalLineRelation_journalLineId_fkey" FOREIGN KEY ("journalLineId") REFERENCES "journalLine"("id")
--- );
-
--- ALTER TABLE "costLedgerJournalLineRelation" ENABLE ROW LEVEL SECURITY;
-
--- CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "costLedgerJournalLineRelation"
--- FOR SELECT
--- USING (
--- coalesce(get_my_claim('accounting_view')::boolean, false) = true AND
--- (get_my_claim('role'::text)) = '"employee"'::jsonb
--- );
-
CREATE TABLE "partLedger" (
"id" TEXT NOT NULL DEFAULT xid(),
@@ -313,6 +295,7 @@ CREATE OR REPLACE FUNCTION "journalLinesByAccountNumber" (
)
RETURNS TABLE (
"number" TEXT,
+ "companyId" INTEGER,
"balance" NUMERIC(19, 4),
"balanceAtDate" NUMERIC(19, 4),
"netChange" NUMERIC(19, 4)
@@ -322,13 +305,14 @@ AS $$
RETURN QUERY
SELECT
a."number",
+ a."companyId",
SUM(jl."amount") AS "balance",
SUM(CASE WHEN j."postingDate" <= to_date THEN jl."amount" ELSE 0 END) AS "balanceAtDate",
SUM(CASE WHEN j."postingDate" >= from_date AND j."postingDate" <= to_date THEN jl."amount" ELSE 0 END) AS "netChange"
FROM "account" a
LEFT JOIN "journalLine" jl ON jl."accountNumber" = a."number"
INNER JOIN "journal" j ON j."id" = jl."journalId"
- GROUP BY a."number";
+ GROUP BY a."number", a."companyId";
END;
$$;
diff --git a/packages/database/supabase/migrations/20230728025201_receipts.sql b/packages/database/supabase/migrations/20230728025201_receipts.sql
index 8c160a6ac9..f04e87310a 100644
--- a/packages/database/supabase/migrations/20230728025201_receipts.sql
+++ b/packages/database/supabase/migrations/20230728025201_receipts.sql
@@ -29,6 +29,7 @@ CREATE TABLE "receipt" (
"status" "receiptStatus" NOT NULL DEFAULT 'Draft',
"postingDate" DATE,
"invoiced" BOOLEAN DEFAULT FALSE,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -39,43 +40,47 @@ CREATE TABLE "receipt" (
CONSTRAINT "receipt_receiptId_key" UNIQUE ("receiptId"),
CONSTRAINT "receipt_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "receipt_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "receipt_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "receipt_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "receipt_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "receipt_receiptId_idx" ON "receipt" ("receiptId");
-CREATE INDEX "receipt_status_idx" ON "receipt" ("status");
-CREATE INDEX "receipt_locationId_idx" ON "receipt" ("locationId");
-CREATE INDEX "receipt_sourceDocumentId_idx" ON "receipt" ("sourceDocumentId");
-CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId");
+CREATE INDEX "receipt_receiptId_idx" ON "receipt" ("receiptId", "companyId");
+CREATE INDEX "receipt_status_idx" ON "receipt" ("status", "companyId");
+CREATE INDEX "receipt_locationId_idx" ON "receipt" ("locationId", "companyId");
+CREATE INDEX "receipt_sourceDocumentId_idx" ON "receipt" ("sourceDocumentId", "companyId");
+CREATE INDEX "receipt_supplierId_idx" ON "receipt" ("supplierId", "companyId");
+CREATE INDEX "receipt_companyId_idx" ON "receipt" ("companyId");
ALTER TABLE "receipt" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with inventory_view can view receipts" ON "receipt"
FOR SELECT
- USING (coalesce(get_my_claim('inventory_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb);
+ USING (
+ has_role('employee') AND
+ has_company_permission('inventory_view', "companyId")
+ );
CREATE POLICY "Employees with inventory_create can insert receipts" ON "receipt"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('inventory_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_create', "companyId")
);
CREATE POLICY "Employees with inventory_update can update receipts" ON "receipt"
FOR UPDATE
USING (
- coalesce(get_my_claim('inventory_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_update', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete receipts" ON "receipt"
FOR DELETE
USING (
- coalesce(get_my_claim('inventory_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_delete', "companyId")
);
ALTER publication supabase_realtime ADD TABLE "receipt";
@@ -92,6 +97,7 @@ CREATE TABLE "receiptLine" (
"shelfId" TEXT,
"unitOfMeasure" TEXT NOT NULL,
"unitPrice" NUMERIC(18, 4) NOT NULL,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -115,30 +121,30 @@ ALTER TABLE "receiptLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with inventory_view can view receipt lines" ON "receiptLine"
FOR SELECT
USING (
- coalesce(get_my_claim('inventory_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_view', "companyId")
);
CREATE POLICY "Employees with inventory_create can insert receipt lines" ON "receiptLine"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('inventory_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_create', "companyId")
);
CREATE POLICY "Employees with inventory_update can update receipt lines" ON "receiptLine"
FOR UPDATE
USING (
- coalesce(get_my_claim('inventory_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_update', "companyId")
);
CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "receiptLine"
FOR DELETE
USING (
- coalesce(get_my_claim('inventory_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('inventory_delete', "companyId")
);
CREATE OR REPLACE VIEW "receipts" WITH(SECURITY_INVOKER=true) AS
diff --git a/packages/database/supabase/migrations/20230810035313_defaults.sql b/packages/database/supabase/migrations/20230810035313_defaults.sql
index fa0be31661..cbeaf026cf 100644
--- a/packages/database/supabase/migrations/20230810035313_defaults.sql
+++ b/packages/database/supabase/migrations/20230810035313_defaults.sql
@@ -1,6 +1,8 @@
CREATE OR REPLACE VIEW "userDefaults" AS
SELECT
u.id as "userId",
+ l."companyId" as "companyId",
ej."locationId"
FROM "user" u
- LEFT JOIN "employeeJob" ej ON ej.id = u.id;
\ No newline at end of file
+ LEFT JOIN "employeeJob" ej ON ej.id = u.id
+ LEFT JOIN "location" l ON l.id = ej."locationId"
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230820020844_posting-groups.sql b/packages/database/supabase/migrations/20230820020844_posting-groups.sql
index 2facd587ce..0737f3aa43 100644
--- a/packages/database/supabase/migrations/20230820020844_posting-groups.sql
+++ b/packages/database/supabase/migrations/20230820020844_posting-groups.sql
@@ -174,15 +174,15 @@ ALTER TABLE "postingGroupInventory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view inventory posting groups" ON "postingGroupInventory"
FOR SELECT
USING (
- coalesce(get_my_claim('accounting_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update inventory posting groups" ON "postingGroupInventory"
FOR UPDATE
USING (
- coalesce(get_my_claim('accounting_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_update', "companyId")
);
@@ -221,15 +221,15 @@ ALTER TABLE "postingGroupPurchasing" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with accounting_view can view purchasing posting groups" ON "postingGroupPurchasing"
FOR SELECT
USING (
- coalesce(get_my_claim('accounting_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update purchasing posting groups" ON "postingGroupPurchasing"
FOR UPDATE
USING (
- coalesce(get_my_claim('accounting_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_update', "companyId")
);
CREATE TABLE "postingGroupSales" (
@@ -265,15 +265,15 @@ CREATE INDEX "postingGroupSales_companyId_idx" ON "postingGroupSales" ("companyI
CREATE POLICY "Employees with accounting_view can view sales posting groups" ON "postingGroupSales"
FOR SELECT
USING (
- coalesce(get_my_claim('accounting_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_view', "companyId")
);
CREATE POLICY "Employees with accounting_update can update sales posting groups" ON "postingGroupSales"
FOR UPDATE
USING (
- coalesce(get_my_claim('accounting_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('accounting_update', "companyId")
);
CREATE FUNCTION public.create_posting_groups_for_location()
diff --git a/packages/database/supabase/migrations/20230912210957_uninvoiced-receipts.sql b/packages/database/supabase/migrations/20230912210957_uninvoiced-receipts.sql
deleted file mode 100644
index fd491a7ca2..0000000000
--- a/packages/database/supabase/migrations/20230912210957_uninvoiced-receipts.sql
+++ /dev/null
@@ -1,45 +0,0 @@
-CREATE OR REPLACE VIEW "receiptsPostedNotInvoiced" AS
- SELECT
- r."id",
- r."receiptId",
- r."sourceDocument",
- r."sourceDocumentId",
- r."sourceDocumentReadableId",
- r."postingDate",
- r."supplierId",
- s."name" AS "supplierName",
- SUM(l."receivedQuantity" * l."unitPrice") AS "estimatedCost"
- FROM "receipt" r
- INNER JOIN "receiptLine" l
- ON l."receiptId" = r."receiptId"
- INNER JOIN "supplier" s
- ON s."id" = r."supplierId"
- WHERE r."status" = 'Posted'
- AND r."invoiced" = FALSE
- AND r."sourceDocument" != 'Manufacturing Consumption'
- AND r."sourceDocument" != 'Manufacturing Output'
- AND r."sourceDocument" != 'Inbound Transfer'
- AND r."sourceDocument" != 'Outbound Transfer'
-
- GROUP BY
- r."id",
- r."receiptId",
- r."sourceDocument",
- r."sourceDocumentId",
- r."sourceDocumentReadableId",
- r."postingDate",
- r."supplierId",
- s."name";
-;
-
-CREATE OR REPLACE VIEW "totalReceiptsPostedNotInvoiced" AS
- SELECT SUM(l."receivedQuantity" * l."unitPrice") AS "total"
- FROM "receipt" r
- INNER JOIN "receiptLine" l
- ON l."receiptId" = r."receiptId"
- WHERE r."status" = 'Posted'
- AND r."invoiced" = FALSE
- AND r."sourceDocument" != 'Manufacturing Consumption'
- AND r."sourceDocument" != 'Manufacturing Output'
- AND r."sourceDocument" != 'Inbound Transfer'
- AND r."sourceDocument" != 'Outbound Transfer';
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
index c7f22fc282..80a8ca0766 100644
--- a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
+++ b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
@@ -62,29 +62,29 @@ ALTER TABLE "purchaseInvoice" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoices" ON "purchaseInvoice"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP invoices" ON "purchaseInvoice"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('invoicing_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP invoices" ON "purchaseInvoice"
FOR UPDATE
USING (
- coalesce(get_my_claim('invoicing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_update', "companyId")
);
CREATE POLICY "Employees with invoicing_delete can delete AP invoices" ON "purchaseInvoice"
FOR DELETE
USING (
- coalesce(get_my_claim('invoicing_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_delete', "companyId")
);
@@ -104,8 +104,8 @@ ALTER TABLE "purchaseInvoiceStatusHistory" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoices status history" ON "purchaseInvoiceStatusHistory"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', (SELECT "companyId" FROM "purchaseInvoice" WHERE "id" = "invoiceId"))
);
@@ -211,29 +211,29 @@ ALTER TABLE "purchaseInvoiceLine" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice lines" ON "purchaseInvoiceLine"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP invoice lines" ON "purchaseInvoiceLine"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('invoicing_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP invoice lines" ON "purchaseInvoiceLine"
FOR UPDATE
USING (
- coalesce(get_my_claim('invoicing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_update', "companyId")
);
CREATE POLICY "Employees with invoicing_delete can delete AP invoice lines" ON "purchaseInvoiceLine"
FOR DELETE
USING (
- coalesce(get_my_claim('invoicing_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_delete', "companyId")
);
CREATE TABLE "purchaseInvoicePriceChange" (
@@ -257,8 +257,8 @@ ALTER TABLE "purchaseInvoicePriceChange" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice price changes" ON "purchaseInvoicePriceChange"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', (SELECT "companyId" FROM "purchaseInvoice" WHERE "id" = "invoiceId"))
);
CREATE OR REPLACE FUNCTION "purchaseInvoiceLine_update_price_change"()
@@ -322,31 +322,30 @@ ALTER TABLE "purchasePayment" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP payments" ON "purchasePayment"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', "companyId")
);
CREATE POLICY "Employees with invoicing_create can insert AP payments" ON "purchasePayment"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('invoicing_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_create', "companyId")
);
CREATE POLICY "Employees with invoicing_update can update AP payments" ON "purchasePayment"
FOR UPDATE
USING (
- "paymentDate" IS NULL
- AND coalesce(get_my_claim('invoicing_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_update', "companyId")
);
CREATE POLICY "Employees with invoicing_delete can delete AP payments" ON "purchasePayment"
FOR DELETE
USING (
- "paymentDate" IS NULL
- AND coalesce(get_my_claim('invoicing_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ "paymentDate" IS NULL AND
+ has_role('employee') AND
+ has_company_permission('invoicing_delete', "companyId")
);
CREATE TABLE "purchaseInvoicePaymentRelation" (
@@ -364,8 +363,8 @@ ALTER TABLE "purchaseInvoicePaymentRelation" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Employees with invoicing_view can view AP invoice/payment relations" ON "purchaseInvoicePaymentRelation"
FOR SELECT
USING (
- coalesce(get_my_claim('invoicing_view')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ has_role('employee') AND
+ has_company_permission('invoicing_view', (SELECT "companyId" FROM "purchaseInvoice" WHERE "id" = "invoiceId"))
);
@@ -390,6 +389,7 @@ CREATE OR REPLACE VIEW "purchaseInvoices" AS
pi."totalAmount",
pi."totalTax",
pi."balance",
+ pi."companyId",
pi."createdBy",
pi."createdAt",
pi."updatedBy",