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.

feat: add edge function to seed company when its created

Brad Barbin5cebcbd4de74
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index 91d6e86c50..3e3b9e4534 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -200,6 +200,7 @@ export async function getAttribute(
async function getAttributes(
client: SupabaseClient<Database>,
+ companyId: number,
userIds: string[]
) {
return client
@@ -213,6 +214,7 @@ async function getAttributes(
)
)`
)
+ .eq("companyId", companyId)
.eq("userAttribute.active", true)
.in("userAttribute.userAttributeValue.userId", [userIds])
.order("sortOrder", { foreignTable: "userAttribute", ascending: true });
@@ -220,6 +222,7 @@ async function getAttributes(
export async function getAttributeCategories(
client: SupabaseClient<Database>,
+ companyId: number,
args?: { search: string | null } & GenericQueryFilters
) {
let query = client
@@ -227,6 +230,7 @@ export async function getAttributeCategories(
.select("*, userAttribute(id, name, attributeDataType(id))", {
count: "exact",
})
+ .eq("companyId", companyId)
.eq("active", true)
.eq("userAttribute.active", true);
@@ -557,11 +561,12 @@ type Person = Employee & {
export async function getPeople(
client: SupabaseClient<Database>,
+ companyId: number,
args: GenericQueryFilters & {
search: string | null;
}
) {
- const employees = await getEmployees(client, args);
+ const employees = await getEmployees(client, companyId, args);
if (employees.error) return employees;
if (!employees.data) throw new Error("Failed to get employee data");
@@ -573,7 +578,7 @@ export async function getPeople(
return employee.user?.id;
});
- const attributeCategories = await getAttributes(client, userIds);
+ const attributeCategories = await getAttributes(client, companyId, userIds);
if (attributeCategories.error) return attributeCategories;
const people: Person[] = employees.data.map((employee) => {
@@ -1158,6 +1163,7 @@ export async function upsertShift(
shift:
| (Omit<z.infer<typeof shiftValidator>, "id"> & {
createdBy: string;
+ companyId: number;
customFields?: Json;
})
| (Omit<z.infer<typeof shiftValidator>, "id"> & {
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index a5429a1cd5..f8a0cb11c0 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -12,6 +12,8 @@ export async function getCompany(
client: SupabaseClient<Database>,
companyId: number
) {
+ console.log(`getCompany: ${companyId}`);
+
const company = await client
.from("company")
.select("*")
@@ -200,6 +202,17 @@ export async function rollbackNextSequence(
});
}
+export async function seedCompany(
+ client: SupabaseClient<Database>,
+ companyId: number
+) {
+ return client.functions.invoke("seed-company", {
+ body: {
+ id: companyId,
+ },
+ });
+}
+
export async function updateCompany(
client: SupabaseClient<Database>,
companyId: number,
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index 822dbcfa9d..7f273a34ed 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -72,10 +72,12 @@ export async function getEmployee(
export async function getEmployees(
client: SupabaseClient<Database>,
+ companyId: number,
args: GenericQueryFilters & {
search: string | null;
}
) {
+ // TODO: convert to view
let query = client
.from("employee")
.select(
@@ -106,9 +108,13 @@ export async function getEmployeeType(
export async function getEmployeeTypes(
client: SupabaseClient<Database>,
+ companyId: number,
args?: GenericQueryFilters & { search: string | null }
) {
- let query = client.from("employeeType").select("*", { count: "exact" });
+ let query = client
+ .from("employeeType")
+ .select("*", { count: "exact" })
+ .eq("companyId", companyId);
if (args?.search) {
query = query.ilike("name", `%${args.search}%`);
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index d6c79e0cf9..86aa1b4927 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -19,6 +19,7 @@ import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
import { Link, useLoaderData } from "@remix-run/react";
import { Hidden, Input, Submit } from "~/components/Form";
import { useOnboarding } from "~/hooks";
+import logger from "~/lib/logger";
import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getLocationsList,
@@ -29,10 +30,12 @@ import {
getCompany,
insertCompany,
onboardingCompanyValidator,
+ seedCompany,
updateCompany,
} from "~/modules/settings";
import { addUserToCompany } from "~/modules/users/users.server";
import { requirePermissions } from "~/services/auth/auth.server";
+import { commitAuthSession } from "~/services/session.server";
import { assertIsPost } from "~/utils/http";
export async function loader({ request }: ActionFunctionArgs) {
@@ -40,7 +43,8 @@ export async function loader({ request }: ActionFunctionArgs) {
update: "settings",
});
- const company = await getCompany(client, companyId);
+ const company = await getCompany(client, companyId ?? 1);
+ console.log({ company });
if (company.error || !company.data) {
return json({
company: null,
@@ -70,6 +74,8 @@ export async function action({ request }: ActionFunctionArgs) {
const { next, ...data } = validation.data;
+ let companyId: number | undefined;
+
const [company, locations] = await Promise.all([
getCompany(client, 1),
getLocationsList(client),
@@ -88,21 +94,21 @@ export async function action({ request }: ActionFunctionArgs) {
}),
]);
if (companyUpdate.error) {
- console.error(companyUpdate.error);
+ logger.error(companyUpdate.error);
throw new Error("Fatal: failed to update company");
}
if (locationUpdate.error) {
- console.error(locationUpdate.error);
+ logger.error(locationUpdate.error);
throw new Error("Fatal: failed to update location");
}
} else {
const companyInsert = await insertCompany(supabaseClient, data);
if (companyInsert.error) {
- console.error(companyInsert.error);
+ logger.error(companyInsert.error);
throw new Error("Fatal: failed to insert company");
}
- const companyId = companyInsert.data?.id;
+ companyId = companyInsert.data?.id;
if (!companyId) {
throw new Error("Fatal: failed to get company ID");
}
@@ -116,7 +122,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
if (locationInsert.error) {
- console.error(locationInsert.error);
+ logger.error(locationInsert.error);
throw new Error("Fatal: failed to insert location");
}
@@ -125,27 +131,38 @@ export async function action({ request }: ActionFunctionArgs) {
throw new Error("Fatal: failed to get location ID");
}
- const [userToCompany, job] = await Promise.all([
+ const [userToCompany, job, seed] = await Promise.all([
addUserToCompany(supabaseClient, userId, companyId),
insertEmployeeJob(supabaseClient, {
id: userId,
locationId,
}),
- // TODO: seed company
+ seedCompany(supabaseClient, companyId),
]);
if (userToCompany.error) {
- console.error(userToCompany.error);
+ logger.error(userToCompany.error);
throw new Error("Fatal: failed to add user to company");
}
if (job.error) {
- console.error(job.error);
+ logger.error(job.error);
throw new Error("Fatal: failed to insert job");
}
+
+ if (seed.error) {
+ logger.error(seed.error);
+ throw new Error("Fatal: failed to seed company");
+ }
}
- throw redirect(next);
+ throw redirect(next, {
+ headers: {
+ "Set-Cookie": await commitAuthSession(request, {
+ company: companyId ?? 1,
+ }),
+ },
+ });
}
export default function OnboardingCompany() {
diff --git a/apps/carbon/app/routes/x+/resources+/people.tsx b/apps/carbon/app/routes/x+/resources+/people.tsx
index cf2395e688..e6944bd7fd 100644
--- a/apps/carbon/app/routes/x+/resources+/people.tsx
+++ b/apps/carbon/app/routes/x+/resources+/people.tsx
@@ -21,7 +21,7 @@ export const handle: Handle = {
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "resources",
role: "employee",
});
@@ -34,9 +34,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
getGenericQueryFilters(searchParams);
const [attributeCategories, employeeTypes, people] = await Promise.all([
- getAttributeCategories(client),
- getEmployeeTypes(client),
- getPeople(client, { search, limit, offset, sorts, filters }),
+ getAttributeCategories(client, companyId),
+ getEmployeeTypes(client, companyId),
+ getPeople(client, companyId, { search, limit, offset, sorts, filters }),
]);
if (attributeCategories.error) {
throw redirect(
diff --git a/apps/carbon/app/routes/x+/resources+/shifts.new.tsx b/apps/carbon/app/routes/x+/resources+/shifts.new.tsx
index 4b968c65c6..ffe87306e4 100644
--- a/apps/carbon/app/routes/x+/resources+/shifts.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/shifts.new.tsx
@@ -11,7 +11,7 @@ import { error, success } from "~/utils/result";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "resources",
});
@@ -26,6 +26,7 @@ export async function action({ request }: ActionFunctionArgs) {
const createShift = await upsertShift(client, {
...data,
+ companyId,
createdBy: userId,
customFields: setCustomFields(formData),
});
diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.ts
index bd7baeb9d9..00db96b28b 100644
--- a/apps/carbon/app/services/auth/auth.server.ts
+++ b/apps/carbon/app/services/auth/auth.server.ts
@@ -186,7 +186,7 @@ export async function signInWithEmail(email: string, password: string) {
if (!data.session || error) return null;
const companies = await getCompaniesForUser(client, data.user.id);
- return makeAuthSession(data.session, companies?.[0] ?? -1);
+ return makeAuthSession(data.session, companies?.[0] ?? 1);
}
export async function refreshAccessToken(
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index adea112043..2753402a0c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -4551,6 +4551,7 @@ export type Database = {
approvedBy: string | null;
assignee: string | null;
blocked: boolean;
+ companyId: number;
createdAt: string;
createdBy: string;
customFields: Json | null;
@@ -4573,6 +4574,7 @@ export type Database = {
approvedBy?: string | null;
assignee?: string | null;
blocked?: boolean;
+ companyId: number;
createdAt?: string;
createdBy: string;
customFields?: Json | null;
@@ -4595,6 +4597,7 @@ export type Database = {
approvedBy?: string | null;
assignee?: string | null;
blocked?: boolean;
+ companyId?: number;
createdAt?: string;
createdBy?: string;
customFields?: Json | null;
@@ -4668,6 +4671,13 @@ export type Database = {
referencedRelation: "userDefaults";
referencedColumns: ["userId"];
},
+ {
+ foreignKeyName: "part_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "part_createdBy_fkey";
columns: ["createdBy"];
@@ -4705,10 +4715,10 @@ export type Database = {
},
{
foreignKeyName: "part_unitOfMeasureCode_fkey";
- columns: ["unitOfMeasureCode"];
+ columns: ["unitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "part_updatedBy_fkey";
@@ -5488,6 +5498,7 @@ export type Database = {
};
partReplenishment: {
Row: {
+ companyId: number;
conversionFactor: number;
createdAt: string;
createdBy: string;
@@ -5507,6 +5518,7 @@ export type Database = {
updatedBy: string | null;
};
Insert: {
+ companyId: number;
conversionFactor?: number;
createdAt?: string;
createdBy: string;
@@ -5526,6 +5538,7 @@ export type Database = {
updatedBy?: string | null;
};
Update: {
+ companyId?: number;
conversionFactor?: number;
createdAt?: string;
createdBy?: string;
@@ -5545,6 +5558,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "partReplenishment_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "partReplenishment_createdBy_fkey";
columns: ["createdBy"];
@@ -5631,10 +5651,10 @@ export type Database = {
},
{
foreignKeyName: "partReplenishment_purchaseUnitOfMeasureCode_fkey";
- columns: ["purchasingUnitOfMeasureCode"];
+ columns: ["purchasingUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "partReplenishment_updatedBy_fkey";
@@ -5833,6 +5853,7 @@ export type Database = {
partUnitSalePrice: {
Row: {
allowInvoiceDiscount: boolean;
+ companyId: number;
createdAt: string;
createdBy: string;
currencyCode: string;
@@ -5847,6 +5868,7 @@ export type Database = {
};
Insert: {
allowInvoiceDiscount?: boolean;
+ companyId: number;
createdAt?: string;
createdBy: string;
currencyCode: string;
@@ -5861,6 +5883,7 @@ export type Database = {
};
Update: {
allowInvoiceDiscount?: boolean;
+ companyId?: number;
createdAt?: string;
createdBy?: string;
currencyCode?: string;
@@ -5874,6 +5897,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "partUnitSalePrice_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "partUnitSalePrice_createdBy_fkey";
columns: ["createdBy"];
@@ -5932,10 +5962,10 @@ export type Database = {
},
{
foreignKeyName: "partUnitSalePrice_salesUnitOfMeasureId_fkey";
- columns: ["salesUnitOfMeasureCode"];
+ columns: ["salesUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "partUnitSalePrice_updatedBy_fkey";
@@ -5971,6 +6001,7 @@ export type Database = {
Row: {
active: boolean;
calculationMethod: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ companyId: number;
createdAt: string;
createdBy: string;
customFields: Json | null;
@@ -5985,6 +6016,7 @@ export type Database = {
Insert: {
active?: boolean;
calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ companyId: number;
createdAt?: string;
createdBy: string;
customFields?: Json | null;
@@ -5999,6 +6031,7 @@ export type Database = {
Update: {
active?: boolean;
calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"];
+ companyId?: number;
createdAt?: string;
createdBy?: string;
customFields?: Json | null;
@@ -6011,6 +6044,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "paymentTerm_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "paymentTerm_createdBy_fkey";
columns: ["createdBy"];
@@ -6998,6 +7038,7 @@ export type Database = {
Row: {
accountNumber: string | null;
assetId: string | null;
+ companyId: number;
conversionFactor: number | null;
createdAt: string;
createdBy: string;
@@ -7025,6 +7066,7 @@ export type Database = {
Insert: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId: number;
conversionFactor?: number | null;
createdAt?: string;
createdBy: string;
@@ -7052,6 +7094,7 @@ export type Database = {
Update: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId?: number;
conversionFactor?: number | null;
createdAt?: string;
createdBy?: string;
@@ -7077,20 +7120,6 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
- {
- foreignKeyName: "purchaseInvoiceLine_inventoryUnitOfMeasureCode_fkey";
- columns: ["inventoryUnitOfMeasureCode"];
- isOneToOne: false;
- referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
- },
- {
- foreignKeyName: "purchaseInvoiceLine_purchaseUnitOfMeasureCode_fkey";
- columns: ["purchaseUnitOfMeasureCode"];
- isOneToOne: false;
- referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
- },
{
foreignKeyName: "purchaseInvoiceLines_accountNumber_fkey";
columns: ["accountNumber"];
@@ -7105,6 +7134,13 @@ export type Database = {
referencedRelation: "accounts";
referencedColumns: ["number"];
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "purchaseInvoiceLines_createdBy_fkey";
columns: ["createdBy"];
@@ -7140,6 +7176,13 @@ export type Database = {
referencedRelation: "currency";
referencedColumns: ["code"];
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_inventoryUnitOfMeasureCode_fkey";
+ columns: ["inventoryUnitOfMeasureCode", "companyId"];
+ isOneToOne: false;
+ referencedRelation: "unitOfMeasure";
+ referencedColumns: ["code", "companyId"];
+ },
{
foreignKeyName: "purchaseInvoiceLines_invoiceId_fkey";
columns: ["invoiceId"];
@@ -7238,6 +7281,13 @@ export type Database = {
referencedRelation: "purchaseOrderLines";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_purchaseUnitOfMeasureCode_fkey";
+ columns: ["purchaseUnitOfMeasureCode", "companyId"];
+ isOneToOne: false;
+ referencedRelation: "unitOfMeasure";
+ referencedColumns: ["code", "companyId"];
+ },
{
foreignKeyName: "purchaseInvoiceLines_serviceId_fkey";
columns: ["serviceId"];
@@ -7919,6 +7969,7 @@ export type Database = {
Row: {
accountNumber: string | null;
assetId: string | null;
+ companyId: number;
conversionFactor: number | null;
createdAt: string;
createdBy: string;
@@ -7949,6 +8000,7 @@ export type Database = {
Insert: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId: number;
conversionFactor?: number | null;
createdAt?: string;
createdBy: string;
@@ -7979,6 +8031,7 @@ export type Database = {
Update: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId?: number;
conversionFactor?: number | null;
createdAt?: string;
createdBy?: string;
@@ -8051,10 +8104,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_inventoryUnitOfMeasureCode_fkey";
- columns: ["inventoryUnitOfMeasureCode"];
+ columns: ["inventoryUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "purchaseOrderLine_partId_fkey";
@@ -8100,10 +8153,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_purchaseUnitOfMeasureCode_fkey";
- columns: ["purchaseUnitOfMeasureCode"];
+ columns: ["purchaseUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "purchaseOrderLine_serviceId_fkey";
@@ -10267,6 +10320,7 @@ export type Database = {
};
requestForQuoteLine: {
Row: {
+ companyId: number;
createdAt: string | null;
createdBy: string;
customFields: Json | null;
@@ -10283,6 +10337,7 @@ export type Database = {
updatedBy: string | null;
};
Insert: {
+ companyId: number;
createdAt?: string | null;
createdBy: string;
customFields?: Json | null;
@@ -10299,6 +10354,7 @@ export type Database = {
updatedBy?: string | null;
};
Update: {
+ companyId?: number;
createdAt?: string | null;
createdBy?: string;
customFields?: Json | null;
@@ -10315,6 +10371,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "requestForQuoteLine_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "requestForQuoteLine_createdBy_fkey";
columns: ["createdBy"];
@@ -10415,10 +10478,10 @@ export type Database = {
},
{
foreignKeyName: "requestForQuoteLine_unitOfMeasureCode_fkey";
- columns: ["unitOfMeasureCode"];
+ columns: ["unitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "requestForQuoteLine_updatedBy_fkey";
@@ -11040,6 +11103,7 @@ export type Database = {
Row: {
accountNumber: string | null;
assetId: string | null;
+ companyId: number;
createdAt: string;
createdBy: string;
customFields: Json | null;
@@ -11068,6 +11132,7 @@ export type Database = {
Insert: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId: number;
createdAt?: string;
createdBy: string;
customFields?: Json | null;
@@ -11096,6 +11161,7 @@ export type Database = {
Update: {
accountNumber?: string | null;
assetId?: string | null;
+ companyId?: number;
createdAt?: string;
createdBy?: string;
customFields?: Json | null;
@@ -11222,10 +11288,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey";
- columns: ["unitOfMeasureCode"];
+ columns: ["unitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "salesOrderLine_updatedBy_fkey";
@@ -11741,6 +11807,7 @@ export type Database = {
};
sequence: {
Row: {
+ companyId: number;
id: string;
name: string;
next: number;
@@ -11753,6 +11820,7 @@ export type Database = {
updatedBy: string | null;
};
Insert: {
+ companyId: number;
id?: string;
name: string;
next?: number;
@@ -11765,6 +11833,7 @@ export type Database = {
updatedBy?: string | null;
};
Update: {
+ companyId?: number;
id?: string;
name?: string;
next?: number;
@@ -11777,6 +11846,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "sequence_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "sequence_updatedBy_fkey";
columns: ["updatedBy"];
@@ -13689,6 +13765,7 @@ export type Database = {
Row: {
active: boolean;
code: string;
+ companyId: number;
createdAt: string;
createdBy: string;
customFields: Json | null;
@@ -13700,6 +13777,7 @@ export type Database = {
Insert: {
active?: boolean;
code: string;
+ companyId: number;
createdAt?: string;
createdBy: string;
customFields?: Json | null;
@@ -13711,6 +13789,7 @@ export type Database = {
Update: {
active?: boolean;
code?: string;
+ companyId?: number;
createdAt?: string;
createdBy?: string;
customFields?: Json | null;
@@ -13720,6 +13799,13 @@ export type Database = {
updatedBy?: string | null;
};
Relationships: [
+ {
+ foreignKeyName: "unitOfMeasure_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "unitOfMeasure_createdBy_fkey";
columns: ["createdBy"];
@@ -15392,6 +15478,7 @@ export type Database = {
approvedBy: string | null;
assignee: string | null;
blocked: boolean | null;
+ companyId: number | null;
createdAt: string | null;
createdBy: string | null;
customFields: Json | null;
@@ -15469,6 +15556,13 @@ export type Database = {
referencedRelation: "userDefaults";
referencedColumns: ["userId"];
},
+ {
+ foreignKeyName: "part_companyId_fkey";
+ columns: ["companyId"];
+ isOneToOne: false;
+ referencedRelation: "company";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "part_createdBy_fkey";
columns: ["createdBy"];
@@ -15506,10 +15600,10 @@ export type Database = {
},
{
foreignKeyName: "part_unitOfMeasureCode_fkey";
- columns: ["unitOfMeasureCode"];
+ columns: ["unitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "part_updatedBy_fkey";
@@ -15744,6 +15838,7 @@ export type Database = {
Row: {
accountNumber: string | null;
assetId: string | null;
+ companyId: number | null;
conversionFactor: number | null;
createdAt: string | null;
createdBy: string | null;
@@ -15860,10 +15955,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_inventoryUnitOfMeasureCode_fkey";
- columns: ["inventoryUnitOfMeasureCode"];
+ columns: ["inventoryUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "purchaseOrderLine_partId_fkey";
@@ -15909,10 +16004,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_purchaseUnitOfMeasureCode_fkey";
- columns: ["purchaseUnitOfMeasureCode"];
+ columns: ["purchaseUnitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "purchaseOrderLine_serviceId_fkey";
@@ -16903,6 +16998,7 @@ export type Database = {
Row: {
accountNumber: string | null;
assetId: string | null;
+ companyId: number | null;
createdAt: string | null;
createdBy: string | null;
customerId: string | null;
@@ -17055,10 +17151,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey";
- columns: ["unitOfMeasureCode"];
+ columns: ["unitOfMeasureCode", "companyId"];
isOneToOne: false;
referencedRelation: "unitOfMeasure";
- referencedColumns: ["code"];
+ referencedColumns: ["code", "companyId"];
},
{
foreignKeyName: "salesOrderLine_updatedBy_fkey";
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index f369e95b87..ce926e35f8 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -4561,6 +4561,7 @@ export type Database = {
approvedBy: string | null
assignee: string | null
blocked: boolean
+ companyId: number
createdAt: string
createdBy: string
customFields: Json | null
@@ -4583,6 +4584,7 @@ export type Database = {
approvedBy?: string | null
assignee?: string | null
blocked?: boolean
+ companyId: number
createdAt?: string
createdBy: string
customFields?: Json | null
@@ -4605,6 +4607,7 @@ export type Database = {
approvedBy?: string | null
assignee?: string | null
blocked?: boolean
+ companyId?: number
createdAt?: string
createdBy?: string
customFields?: Json | null
@@ -4678,6 +4681,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "part_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "part_createdBy_fkey"
columns: ["createdBy"]
@@ -4715,10 +4725,10 @@ export type Database = {
},
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode"]
+ columns: ["unitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "part_updatedBy_fkey"
@@ -5498,6 +5508,7 @@ export type Database = {
}
partReplenishment: {
Row: {
+ companyId: number
conversionFactor: number
createdAt: string
createdBy: string
@@ -5517,6 +5528,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ companyId: number
conversionFactor?: number
createdAt?: string
createdBy: string
@@ -5536,6 +5548,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ companyId?: number
conversionFactor?: number
createdAt?: string
createdBy?: string
@@ -5555,6 +5568,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "partReplenishment_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "partReplenishment_createdBy_fkey"
columns: ["createdBy"]
@@ -5641,10 +5661,10 @@ export type Database = {
},
{
foreignKeyName: "partReplenishment_purchaseUnitOfMeasureCode_fkey"
- columns: ["purchasingUnitOfMeasureCode"]
+ columns: ["purchasingUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "partReplenishment_updatedBy_fkey"
@@ -5843,6 +5863,7 @@ export type Database = {
partUnitSalePrice: {
Row: {
allowInvoiceDiscount: boolean
+ companyId: number
createdAt: string
createdBy: string
currencyCode: string
@@ -5857,6 +5878,7 @@ export type Database = {
}
Insert: {
allowInvoiceDiscount?: boolean
+ companyId: number
createdAt?: string
createdBy: string
currencyCode: string
@@ -5871,6 +5893,7 @@ export type Database = {
}
Update: {
allowInvoiceDiscount?: boolean
+ companyId?: number
createdAt?: string
createdBy?: string
currencyCode?: string
@@ -5884,6 +5907,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "partUnitSalePrice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "partUnitSalePrice_createdBy_fkey"
columns: ["createdBy"]
@@ -5942,10 +5972,10 @@ export type Database = {
},
{
foreignKeyName: "partUnitSalePrice_salesUnitOfMeasureId_fkey"
- columns: ["salesUnitOfMeasureCode"]
+ columns: ["salesUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "partUnitSalePrice_updatedBy_fkey"
@@ -5981,6 +6011,7 @@ export type Database = {
Row: {
active: boolean
calculationMethod: Database["public"]["Enums"]["paymentTermCalculationMethod"]
+ companyId: number
createdAt: string
createdBy: string
customFields: Json | null
@@ -5995,6 +6026,7 @@ export type Database = {
Insert: {
active?: boolean
calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"]
+ companyId: number
createdAt?: string
createdBy: string
customFields?: Json | null
@@ -6009,6 +6041,7 @@ export type Database = {
Update: {
active?: boolean
calculationMethod?: Database["public"]["Enums"]["paymentTermCalculationMethod"]
+ companyId?: number
createdAt?: string
createdBy?: string
customFields?: Json | null
@@ -6021,6 +6054,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "paymentTerm_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "paymentTerm_createdBy_fkey"
columns: ["createdBy"]
@@ -7008,6 +7048,7 @@ export type Database = {
Row: {
accountNumber: string | null
assetId: string | null
+ companyId: number
conversionFactor: number | null
createdAt: string
createdBy: string
@@ -7035,6 +7076,7 @@ export type Database = {
Insert: {
accountNumber?: string | null
assetId?: string | null
+ companyId: number
conversionFactor?: number | null
createdAt?: string
createdBy: string
@@ -7062,6 +7104,7 @@ export type Database = {
Update: {
accountNumber?: string | null
assetId?: string | null
+ companyId?: number
conversionFactor?: number | null
createdAt?: string
createdBy?: string
@@ -7087,20 +7130,6 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
- {
- foreignKeyName: "purchaseInvoiceLine_inventoryUnitOfMeasureCode_fkey"
- columns: ["inventoryUnitOfMeasureCode"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
- },
- {
- foreignKeyName: "purchaseInvoiceLine_purchaseUnitOfMeasureCode_fkey"
- columns: ["purchaseUnitOfMeasureCode"]
- isOneToOne: false
- referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
- },
{
foreignKeyName: "purchaseInvoiceLines_accountNumber_fkey"
columns: ["accountNumber"]
@@ -7115,6 +7144,13 @@ export type Database = {
referencedRelation: "accounts"
referencedColumns: ["number"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_createdBy_fkey"
columns: ["createdBy"]
@@ -7150,6 +7186,13 @@ export type Database = {
referencedRelation: "currency"
referencedColumns: ["code"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_inventoryUnitOfMeasureCode_fkey"
+ columns: ["inventoryUnitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_invoiceId_fkey"
columns: ["invoiceId"]
@@ -7248,6 +7291,13 @@ export type Database = {
referencedRelation: "purchaseOrderLines"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_purchaseUnitOfMeasureCode_fkey"
+ columns: ["purchaseUnitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_serviceId_fkey"
columns: ["serviceId"]
@@ -7929,6 +7979,7 @@ export type Database = {
Row: {
accountNumber: string | null
assetId: string | null
+ companyId: number
conversionFactor: number | null
createdAt: string
createdBy: string
@@ -7959,6 +8010,7 @@ export type Database = {
Insert: {
accountNumber?: string | null
assetId?: string | null
+ companyId: number
conversionFactor?: number | null
createdAt?: string
createdBy: string
@@ -7989,6 +8041,7 @@ export type Database = {
Update: {
accountNumber?: string | null
assetId?: string | null
+ companyId?: number
conversionFactor?: number | null
createdAt?: string
createdBy?: string
@@ -8061,10 +8114,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_inventoryUnitOfMeasureCode_fkey"
- columns: ["inventoryUnitOfMeasureCode"]
+ columns: ["inventoryUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "purchaseOrderLine_partId_fkey"
@@ -8110,10 +8163,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_purchaseUnitOfMeasureCode_fkey"
- columns: ["purchaseUnitOfMeasureCode"]
+ columns: ["purchaseUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "purchaseOrderLine_serviceId_fkey"
@@ -10277,6 +10330,7 @@ export type Database = {
}
requestForQuoteLine: {
Row: {
+ companyId: number
createdAt: string | null
createdBy: string
customFields: Json | null
@@ -10293,6 +10347,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ companyId: number
createdAt?: string | null
createdBy: string
customFields?: Json | null
@@ -10309,6 +10364,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ companyId?: number
createdAt?: string | null
createdBy?: string
customFields?: Json | null
@@ -10325,6 +10381,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "requestForQuoteLine_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "requestForQuoteLine_createdBy_fkey"
columns: ["createdBy"]
@@ -10425,10 +10488,10 @@ export type Database = {
},
{
foreignKeyName: "requestForQuoteLine_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode"]
+ columns: ["unitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "requestForQuoteLine_updatedBy_fkey"
@@ -11050,6 +11113,7 @@ export type Database = {
Row: {
accountNumber: string | null
assetId: string | null
+ companyId: number
createdAt: string
createdBy: string
customFields: Json | null
@@ -11078,6 +11142,7 @@ export type Database = {
Insert: {
accountNumber?: string | null
assetId?: string | null
+ companyId: number
createdAt?: string
createdBy: string
customFields?: Json | null
@@ -11106,6 +11171,7 @@ export type Database = {
Update: {
accountNumber?: string | null
assetId?: string | null
+ companyId?: number
createdAt?: string
createdBy?: string
customFields?: Json | null
@@ -11232,10 +11298,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode"]
+ columns: ["unitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "salesOrderLine_updatedBy_fkey"
@@ -11751,6 +11817,7 @@ export type Database = {
}
sequence: {
Row: {
+ companyId: number
id: string
name: string
next: number
@@ -11763,6 +11830,7 @@ export type Database = {
updatedBy: string | null
}
Insert: {
+ companyId: number
id?: string
name: string
next?: number
@@ -11775,6 +11843,7 @@ export type Database = {
updatedBy?: string | null
}
Update: {
+ companyId?: number
id?: string
name?: string
next?: number
@@ -11787,6 +11856,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "sequence_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "sequence_updatedBy_fkey"
columns: ["updatedBy"]
@@ -13709,6 +13785,7 @@ export type Database = {
Row: {
active: boolean
code: string
+ companyId: number
createdAt: string
createdBy: string
customFields: Json | null
@@ -13720,6 +13797,7 @@ export type Database = {
Insert: {
active?: boolean
code: string
+ companyId: number
createdAt?: string
createdBy: string
customFields?: Json | null
@@ -13731,6 +13809,7 @@ export type Database = {
Update: {
active?: boolean
code?: string
+ companyId?: number
createdAt?: string
createdBy?: string
customFields?: Json | null
@@ -13740,6 +13819,13 @@ export type Database = {
updatedBy?: string | null
}
Relationships: [
+ {
+ foreignKeyName: "unitOfMeasure_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "unitOfMeasure_createdBy_fkey"
columns: ["createdBy"]
@@ -15412,6 +15498,7 @@ export type Database = {
approvedBy: string | null
assignee: string | null
blocked: boolean | null
+ companyId: number | null
createdAt: string | null
createdBy: string | null
customFields: Json | null
@@ -15489,6 +15576,13 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "part_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "part_createdBy_fkey"
columns: ["createdBy"]
@@ -15526,10 +15620,10 @@ export type Database = {
},
{
foreignKeyName: "part_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode"]
+ columns: ["unitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "part_updatedBy_fkey"
@@ -15764,6 +15858,7 @@ export type Database = {
Row: {
accountNumber: string | null
assetId: string | null
+ companyId: number | null
conversionFactor: number | null
createdAt: string | null
createdBy: string | null
@@ -15880,10 +15975,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_inventoryUnitOfMeasureCode_fkey"
- columns: ["inventoryUnitOfMeasureCode"]
+ columns: ["inventoryUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "purchaseOrderLine_partId_fkey"
@@ -15929,10 +16024,10 @@ export type Database = {
},
{
foreignKeyName: "purchaseOrderLine_purchaseUnitOfMeasureCode_fkey"
- columns: ["purchaseUnitOfMeasureCode"]
+ columns: ["purchaseUnitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "purchaseOrderLine_serviceId_fkey"
@@ -16923,6 +17018,7 @@ export type Database = {
Row: {
accountNumber: string | null
assetId: string | null
+ companyId: number | null
createdAt: string | null
createdBy: string | null
customerId: string | null
@@ -17075,10 +17171,10 @@ export type Database = {
},
{
foreignKeyName: "salesOrderLine_unitOfMeasureCode_fkey"
- columns: ["unitOfMeasureCode"]
+ columns: ["unitOfMeasureCode", "companyId"]
isOneToOne: false
referencedRelation: "unitOfMeasure"
- referencedColumns: ["code"]
+ referencedColumns: ["code", "companyId"]
},
{
foreignKeyName: "salesOrderLine_updatedBy_fkey"
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
new file mode 100644
index 0000000000..d95cb4281e
--- /dev/null
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -0,0 +1,277 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const { id: companyId } = await req.json();
+
+ try {
+ if (!companyId) throw new Error("Payload is missing id");
+
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+ await db.transaction().execute(async (trx) => {
+ const supplierStauses = ["Active", "Inactive", "Pending", "Rejected"].map(
+ (name) => ({ name, companyId, createdBy: "system" })
+ );
+ await trx.insertInto("supplierStatus").values(supplierStauses).execute();
+
+ const customerStauses = [
+ "Active",
+ "Inactive",
+ "Lead",
+ "On Hold",
+ "Cancelled",
+ ].map((name) => ({ name, companyId, createdBy: "system" }));
+ await trx.insertInto("customerStatus").values(customerStauses).execute();
+
+ const paymentTerms = [
+ {
+ name: "Net 15",
+ daysDue: 15,
+ calculationMethod: "Net",
+ daysDiscount: 0,
+ discountPercentage: 0,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Net 30",
+ daysDue: 30,
+ calculationMethod: "Net",
+ daysDiscount: 0,
+ discountPercentage: 0,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Net 60",
+ daysDue: 60,
+ calculationMethod: "Net",
+ daysDiscount: 0,
+ discountPercentage: 0,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "1% 10 Net 30",
+ daysDue: 30,
+ calculationMethod: "Net",
+ daysDiscount: 10,
+ discountPercentage: 1,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "2% 10 Net 30",
+ daysDue: 30,
+ calculationMethod: "Net",
+ daysDiscount: 10,
+ discountPercentage: 2,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "COD",
+ daysDue: 0,
+ calculationMethod: "Net",
+ daysDiscount: 0,
+ discountPercentage: 0,
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Net EOM 10th",
+ daysDue: 10,
+ calculationMethod: "End of Month",
+ daysDiscount: 0,
+ discountPercentage: 0,
+ companyId,
+ createdBy: "system",
+ },
+ ];
+ await trx.insertInto("paymentTerm").values(paymentTerms).execute();
+
+ const unitOfMeasures = [
+ {
+ name: "Each",
+ code: "EA",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Case",
+ code: "CS",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Pack",
+ code: "PK",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Pallet",
+ code: "PL",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Roll",
+ code: "RL",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Box",
+ code: "BX",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Bag",
+ code: "BG",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Drum",
+ code: "DR",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Gallon",
+ code: "GL",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Liter",
+ code: "LT",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Ounce",
+ code: "OZ",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Pound",
+ code: "LB",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Ton",
+ code: "TN",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Yard",
+ code: "YD",
+ companyId,
+ createdBy: "system",
+ },
+ {
+ name: "Meter",
+ code: "MT",
+ companyId,
+ createdBy: "system",
+ },
+ ];
+ await trx.insertInto("unitOfMeasure").values(unitOfMeasures).execute();
+
+ const sequences = [
+ {
+ table: "purchaseOrder",
+ name: "Purchase Order",
+ prefix: "PO",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ {
+ table: "purchaseInvoice",
+ name: "Purchase Invoice",
+ prefix: "AP",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ {
+ table: "receipt",
+ name: "Receipt",
+ prefix: "RE",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ {
+ table: "salesOrder",
+ name: "Sales Order",
+ prefix: "SO",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ {
+ table: "salesInvoice",
+ name: "Sales Invoice",
+ prefix: "AR",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ {
+ table: "requestForQuote",
+ name: "Request For Quote",
+ prefix: "RFQ",
+ suffix: null,
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId,
+ },
+ ];
+ await trx.insertInto("sequence").values(sequences).execute();
+ });
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index 6089fb054f..4627191c81 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -82,6 +82,7 @@ CREATE TABLE "unitOfMeasure" (
"code" TEXT NOT NULL,
"name" TEXT NOT NULL,
"active" BOOLEAN NOT NULL DEFAULT true,
+ "companyId" INTEGER NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -89,13 +90,17 @@ CREATE TABLE "unitOfMeasure" (
"customFields" JSONB,
CONSTRAINT "unitOfMeasure_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "unitOfMeasure_code_key" UNIQUE ("code"),
+ CONSTRAINT "unitOfMeasure_code_unique" UNIQUE ("code", "companyId"),
+ CONSTRAINT "unitOfMeasure_name_unique" UNIQUE ("name", "companyId"),
CONSTRAINT "unitOfMeasure_code_check" CHECK (char_length("code") <= 6),
+ CONSTRAINT "unitOfMeasure_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
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");
+CREATE INDEX "unitOfMeasure_name_index" ON "unitOfMeasure"("name");
+CREATE INDEX "unitOfMeasure_companyId_index" ON "unitOfMeasure"("companyId");
ALTER TABLE "unitOfMeasure" ENABLE ROW LEVEL SECURITY;
@@ -143,6 +148,7 @@ CREATE TABLE "part" (
"approvedBy" TEXT,
"fromDate" DATE,
"toDate" DATE,
+ "companyId" INTEGER NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -150,9 +156,10 @@ CREATE TABLE "part" (
"customFields" JSONB,
CONSTRAINT "part_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "part_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "part_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup"("id"),
CONSTRAINT "part_approvedBy_fkey" FOREIGN KEY ("approvedBy") REFERENCES "user"("id"),
+ CONSTRAINT "part_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "part_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "part_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
@@ -213,12 +220,12 @@ 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."partReplenishment"("partId", "companyId", "createdBy")
+ VALUES (new.id, new."companyId", new."createdBy");
- INSERT INTO public."partUnitSalePrice"("partId", "currencyCode", "createdBy")
+ INSERT INTO public."partUnitSalePrice"("partId", "companyId", "currencyCode", "createdBy")
-- TODO: get default currency
- VALUES (new.id, 'USD', new."createdBy");
+ VALUES (new.id, new."companyId", 'USD', new."createdBy");
RETURN new;
END;
@@ -299,6 +306,7 @@ CREATE TABLE "partUnitSalePrice" (
"salesBlocked" BOOLEAN NOT NULL DEFAULT false,
"priceIncludesTax" BOOLEAN NOT NULL DEFAULT false,
"allowInvoiceDiscount" BOOLEAN NOT NULL DEFAULT true,
+ "companyId" INTEGER NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -307,7 +315,8 @@ CREATE TABLE "partUnitSalePrice" (
CONSTRAINT "partUnitSalePrice_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partUnitSalePrice_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency"("code") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "partUnitSalePrice_salesUnitOfMeasureId_fkey" FOREIGN KEY ("salesUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL,
+ CONSTRAINT "partUnitSalePrice_salesUnitOfMeasureId_fkey" FOREIGN KEY ("salesUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL,
+ CONSTRAINT "partUnitSalePrice_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partUnitSalePrice_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partUnitSalePrice_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
@@ -422,6 +431,7 @@ CREATE TABLE "partReplenishment" (
"requiresConfiguration" BOOLEAN NOT NULL DEFAULT false,
"scrapPercentage" NUMERIC(15,5) NOT NULL DEFAULT 0,
"lotSize" INTEGER,
+ "companyId" INTEGER NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -430,7 +440,8 @@ CREATE TABLE "partReplenishment" (
CONSTRAINT "partReplenishment_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partReplenishment_preferredSupplierId_fkey" FOREIGN KEY ("preferredSupplierId") REFERENCES "supplier"("id") ON DELETE SET NULL,
- CONSTRAINT "partReplenishment_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "partReplenishment_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchasingUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "partReplenishment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "partReplenishment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partReplenishment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
diff --git a/packages/database/supabase/migrations/20230510035345_purchasing.sql b/packages/database/supabase/migrations/20230510035345_purchasing.sql
index 4e83844440..f397e430b2 100644
--- a/packages/database/supabase/migrations/20230510035345_purchasing.sql
+++ b/packages/database/supabase/migrations/20230510035345_purchasing.sql
@@ -12,6 +12,7 @@ CREATE TABLE "paymentTerm" (
"discountPercentage" NUMERIC(10,5) NOT NULL DEFAULT 0,
"calculationMethod" "paymentTermCalculationMethod" NOT NULL DEFAULT 'Net',
"active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -19,22 +20,24 @@ CREATE TABLE "paymentTerm" (
"customFields" JSONB,
CONSTRAINT "paymentTerm_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "paymentTerm_name_key" UNIQUE ("name", "active"),
+ CONSTRAINT "paymentTerm_name_key" UNIQUE ("name", "companyId", "active"),
+ CONSTRAINT "paymentTerm_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT "paymentTerm_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT,
CONSTRAINT "paymentTerm_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT
);
+CREATE INDEX "paymentTerm_name_idx" ON "paymentTerm" ("companyId");
ALTER TABLE "paymentTerm" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm"
FOR SELECT
USING (
(
- coalesce(get_my_claim('accounting_view')::boolean, false) = true OR
- coalesce(get_my_claim('parts_view')::boolean, false) = true OR
- coalesce(get_my_claim('resources_view')::boolean, false) = true OR
- coalesce(get_my_claim('sales_view')::boolean, false) = true OR
- coalesce(get_my_claim('purchasing_view')::boolean, false) = true
+ has_company_permission('accounting_view', "companyId") = true OR
+ has_company_permission('parts_view', "companyId") = true OR
+ has_company_permission('resources_view', "companyId") = true OR
+ has_company_permission('sales_view', "companyId") = true OR
+ has_company_permission('purchasing_view', "companyId") = true
)
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
@@ -43,21 +46,21 @@ CREATE POLICY "Certain employees can view payment terms" ON "paymentTerm"
CREATE POLICY "Employees with accounting_create can insert payment terms" ON "paymentTerm"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('accounting_create')::boolean,false)
+ has_company_permission('accounting_create', "companyId")
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
CREATE POLICY "Employees with accounting_update can update payment terms" ON "paymentTerm"
FOR UPDATE
USING (
- coalesce(get_my_claim('accounting_update')::boolean, false) = true
+ has_company_permission('accounting_update', "companyId") = true
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
CREATE POLICY "Employees with accounting_delete can delete payment terms" ON "paymentTerm"
FOR DELETE
USING (
- coalesce(get_my_claim('accounting_delete')::boolean, false) = true
+ has_company_permission('accounting_delete', "companyId") = true
AND (get_my_claim('role'::text)) = '"employee"'::jsonb
);
@@ -231,13 +234,15 @@ CREATE TABLE "purchaseOrderLine" (
"quantityToInvoice" NUMERIC(9,2) GENERATED ALWAYS AS (CASE WHEN "purchaseOrderLineType" = 'Comment' THEN 0 ELSE GREATEST(("purchaseQuantity" - "quantityInvoiced"), 0) END) STORED,
"quantityInvoiced" NUMERIC(9,2) DEFAULT 0,
"unitPrice" NUMERIC(9,2),
- "unitOfMeasureCode" TEXT,
+ "inventoryUnitOfMeasureCode" TEXT,
+ "purchaseUnitOfMeasureCode" TEXT,
"locationId" TEXT,
"shelfId" TEXT,
"setupPrice" NUMERIC(9,2),
"receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
"invoicedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
"requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -291,7 +296,8 @@ CREATE TABLE "purchaseOrderLine" (
CONSTRAINT "purchaseOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,
-- TODO: Add assetId foreign key
CONSTRAINT "purchaseOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
- CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "purchaseOrderLine_inventoryUnitOfMeasureCode_fkey" FOREIGN KEY ("inventoryUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "purchaseOrderLine_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchaseUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "purchaseOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT,
CONSTRAINT "purchaseOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT
);
diff --git a/packages/database/supabase/migrations/20230525025310_sequences.sql b/packages/database/supabase/migrations/20230525025310_sequences.sql
index 59dc1c82cf..e9dea815fa 100644
--- a/packages/database/supabase/migrations/20230525025310_sequences.sql
+++ b/packages/database/supabase/migrations/20230525025310_sequences.sql
@@ -18,6 +18,7 @@ CREATE TABLE "sequence" (
"next" INTEGER NOT NULL DEFAULT 1,
"size" INTEGER NOT NULL DEFAULT 5,
"step" INTEGER NOT NULL DEFAULT 1,
+ "companyId" INTEGER NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
"updatedBy" TEXT,
@@ -25,6 +26,7 @@ CREATE TABLE "sequence" (
CONSTRAINT "sequence_next_check" CHECK ("next" >= 0),
CONSTRAINT "sequence_size_check" CHECK ("size" >= 1),
CONSTRAINT "sequence_step_check" CHECK ("step" >= 1),
+ CONSTRAINT "sequence_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "sequence_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
diff --git a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
index 4626b2dc87..8a4b853cdb 100644
--- a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
+++ b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
@@ -134,7 +134,9 @@ CREATE TABLE "purchaseInvoiceLine" (
"totalAmount" NUMERIC(10, 2) GENERATED ALWAYS AS ("quantity" * "unitPrice") STORED,
"currencyCode" TEXT NOT NULL,
"exchangeRate" NUMERIC(10, 4) NOT NULL DEFAULT 1,
- "unitOfMeasureCode" TEXT,
+ "inventoryUnitOfMeasureCode" TEXT,
+ "purchaseUnitOfMeasureCode" TEXT,
+ "companyId" INTEGER NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedBy" TEXT,
@@ -192,7 +194,9 @@ CREATE TABLE "purchaseInvoiceLine" (
CONSTRAINT "purchaseInvoiceLines_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON UPDATE CASCADE ON DELETE RESTRICT,
-- CONSTRAINT "purchaseInvoiceLines_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "fixedAsset" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT "purchaseInvoiceLines_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON UPDATE CASCADE ON DELETE RESTRICT,
- CONSTRAINT "purchaseInvoiceLines_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON UPDATE CASCADE ON DELETE RESTRICT,
+ CONSTRAINT "purchaseInvoiceLines_inventoryUnitOfMeasureCode_fkey" FOREIGN KEY ("inventoryUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "purchaseInvoiceLines_purchaseUnitOfMeasureCode_fkey" FOREIGN KEY ("purchaseUnitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "purchaseInvoiceLines_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT "purchaseInvoiceLines_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT "purchaseInvoiceLines_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON UPDATE CASCADE ON DELETE RESTRICT
);
diff --git a/packages/database/supabase/migrations/20240204025905_rfq.sql b/packages/database/supabase/migrations/20240204025905_rfq.sql
index 90af7f5547..4811622278 100644
--- a/packages/database/supabase/migrations/20240204025905_rfq.sql
+++ b/packages/database/supabase/migrations/20240204025905_rfq.sql
@@ -34,6 +34,7 @@ CREATE TABLE "requestForQuoteLine" (
"unitOfMeasureCode" TEXT,
"locationId" TEXT,
"shelfId" TEXT,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT now(),
@@ -43,9 +44,10 @@ CREATE TABLE "requestForQuoteLine" (
CONSTRAINT "requestForQuoteLine_pkey" PRIMARY KEY ("id"),
CONSTRAINT "requestForQuoteLine_requestForQuoteId_fkey" FOREIGN KEY ("requestForQuoteId") REFERENCES "requestForQuote"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "requestForQuoteLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "requestForQuoteLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure"("code") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "requestForQuoteLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON UPDATE CASCADE ON DELETE SET NULL,
CONSTRAINT "requestForQuoteLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON UPDATE CASCADE ON DELETE SET NULL,
CONSTRAINT "requestForQuoteLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
+ CONSTRAINT "requestForQuoteLine_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "requestForQuoteLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "requestForQuoteLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
diff --git a/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql b/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
index 2fbfc78c0d..f2475d40d0 100644
--- a/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
+++ b/packages/database/supabase/migrations/20240402052512_purchasing-conversion-factors.sql
@@ -1,18 +1,5 @@
ALTER TABLE "purchaseOrderLine" ADD COLUMN "conversionFactor" NUMERIC(10, 2) DEFAULT 1;
-ALTER TABLE "purchaseOrderLine" ADD COLUMN "inventoryUnitOfMeasureCode" TEXT REFERENCES "unitOfMeasure" ("code");
-ALTER TABLE "purchaseOrderLine" ADD COLUMN "purchaseUnitOfMeasureCode" TEXT REFERENCES "unitOfMeasure" ("code");
-
-UPDATE "purchaseOrderLine" SET "inventoryUnitOfMeasureCode" = "unitOfMeasureCode";
-ALTER TABLE "purchaseOrderLine" DROP CONSTRAINT "purchaseOrderLine_unitOfMeasureCode_fkey";
-ALTER TABLE "purchaseOrderLine" DROP COLUMN "unitOfMeasureCode" CASCADE;
-
ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "conversionFactor" NUMERIC(10, 2) DEFAULT 1;
-ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "inventoryUnitOfMeasureCode" TEXT REFERENCES "unitOfMeasure" ("code");
-ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "purchaseUnitOfMeasureCode" TEXT REFERENCES "unitOfMeasure" ("code");
-
-UPDATE "purchaseInvoiceLine" SET "inventoryUnitOfMeasureCode" = "unitOfMeasureCode";
-ALTER TABLE "purchaseInvoiceLine" DROP CONSTRAINT "purchaseInvoiceLines_unitOfMeasureCode_fkey";
-ALTER TABLE "purchaseInvoiceLine" DROP COLUMN "unitOfMeasureCode" CASCADE;
ALTER TABLE "partSupplier" ADD COLUMN "unitPrice" NUMERIC(10, 2) DEFAULT 0;
diff --git a/packages/database/supabase/migrations/20240412224648_sales-orders.sql b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
index 211c519076..0854d4b3ea 100644
--- a/packages/database/supabase/migrations/20240412224648_sales-orders.sql
+++ b/packages/database/supabase/migrations/20240412224648_sales-orders.sql
@@ -89,6 +89,7 @@ CREATE TABLE "salesOrderLine" (
"sentComplete" BOOLEAN NOT NULL DEFAULT FALSE,
"invoicedComplete" BOOLEAN NOT NULL DEFAULT FALSE,
"requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,
+ "companyId" INTEGER NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"createdBy" TEXT NOT NULL,
"updatedAt" TIMESTAMP WITH TIME ZONE,
@@ -128,7 +129,7 @@ CREATE TABLE "salesOrderLine" (
CONSTRAINT "salesOrderLine_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON DELETE CASCADE ON UPDATE CASCADE,
-- TODO: Add assetId foreign key
CONSTRAINT "salesOrderLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE CASCADE,
- CONSTRAINT "salesOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode") REFERENCES "unitOfMeasure" ("code") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "salesOrderLine_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "salesOrderLine_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT,
CONSTRAINT "salesOrderLine_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT
);
diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sql
index b527167666..c96c075ab1 100644
--- a/packages/database/supabase/seed.sql
+++ b/packages/database/supabase/seed.sql
@@ -16,7 +16,8 @@ INSERT INTO "theme" (
-- currencies
INSERT INTO "currency" ("name", "code", "symbol", "exchangeRate", "decimalPlaces", "isBaseCurrency", "createdBy")
-VALUES ('US Dollar', 'USD', '$', 1, 2, TRUE, 'system'),
+VALUES
+ ('US Dollar', 'USD', '$', 1, 2, TRUE, 'system'),
('Canadian Dollar', 'CAD', 'CA$', 1, 2, FALSE, 'system'),
('Euro', 'EUR', '€', 1, 2, FALSE, 'system'),
('United Arab Emirates Dirham', 'AED', 'AED', 1, 2, FALSE, 'system'),
@@ -149,44 +150,42 @@ VALUES
-- -- supplier status
--- TODO:
-- INSERT INTO "supplierStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Pending', 'system'), ('Rejected', 'system');
-- -- customer status
--- TODO:
-- INSERT INTO "customerStatus" ("name", "createdBy") VALUES ('Active', 'system'), ('Inactive', 'system'), ('Lead', 'system'), ('On Hold', 'system'), ('Cancelled', 'system'), ('Archived', 'system');
--- unit of measure
+-- -- unit of measure
-INSERT INTO "unitOfMeasure" ("code", "name", "createdBy")
-VALUES
-( 'EA', 'Each', 'system'),
-( 'PCS', 'Pieces', 'system');
+-- INSERT INTO "unitOfMeasure" ("code", "name", "createdBy")
+-- VALUES
+-- ( 'EA', 'Each', 'system'),
+-- ( 'PCS', 'Pieces', 'system');
--- payment terms
+-- -- payment terms
-INSERT INTO "paymentTerm" ("name", "daysDue", "calculationMethod", "daysDiscount", "discountPercentage", "createdBy")
-VALUES
- ('Net 15', 15, 'Net', 0, 0, 'system'),
- ('Net 30', 30, 'Net', 0, 0, 'system'),
- ('Net 50', 50, 'Net', 0, 0, 'system'),
- ('Net 60', 60, 'Net', 0, 0, 'system'),
- ('Net 90', 90, 'Net', 0, 0, 'system'),
- ('1% 10 Net 30', 30, 'Net', 10, 1, 'system'),
- ('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),
- ('Due on Receipt', 0, 'Net', 0, 0, 'system'),
- ('Net EOM 10', 10, 'End of Month', 0, 0, 'system');
+-- INSERT INTO "paymentTerm" ("name", "daysDue", "calculationMethod", "daysDiscount", "discountPercentage", "createdBy")
+-- VALUES
+-- ('Net 15', 15, 'Net', 0, 0, 'system'),
+-- ('Net 30', 30, 'Net', 0, 0, 'system'),
+-- ('Net 50', 50, 'Net', 0, 0, 'system'),
+-- ('Net 60', 60, 'Net', 0, 0, 'system'),
+-- ('Net 90', 90, 'Net', 0, 0, 'system'),
+-- ('1% 10 Net 30', 30, 'Net', 10, 1, 'system'),
+-- ('2% 10 Net 30', 30, 'Net', 10, 2, 'system'),
+-- ('Due on Receipt', 0, 'Net', 0, 0, 'system'),
+-- ('Net EOM 10', 10, 'End of Month', 0, 0, 'system');
--- sequences
+-- -- sequences
-INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
-VALUES
- ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 6, 1),
- ('purchaseInvoice', 'Purchase Invoice', 'AP', NULL, 0, 6, 1),
- ('receipt', 'Receipt', 'RE', NULL, 0, 6, 1),
- ('requestForQuote', 'Request For Quote', 'RFQ', NULL, 0, 6, 1),
- ('quote', 'Quote', 'QUO', NULL, 0, 6, 1),
- ('salesOrder', 'Sales Order', 'SO', NULL, 0, 6, 1);
+-- INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step")
+-- VALUES
+-- ('purchaseOrder', 'Purchase Order', 'PO', NULL, 0, 6, 1),
+-- ('purchaseInvoice', 'Purchase Invoice', 'AP', NULL, 0, 6, 1),
+-- ('receipt', 'Receipt', 'RE', NULL, 0, 6, 1),
+-- ('requestForQuote', 'Request For Quote', 'RFQ', NULL, 0, 6, 1),
+-- ('quote', 'Quote', 'QUO', NULL, 0, 6, 1),
+-- ('salesOrder', 'Sales Order', 'SO', NULL, 0, 6, 1);
-- account categories