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: new company form, and separating permissions into users table

Brad Barbinf4d9153231c6
diff --git a/apps/carbon/app/components/Breadcrumb.tsx b/apps/carbon/app/components/Breadcrumb.tsx
index 1704f3f859..43c2baad14 100644
--- a/apps/carbon/app/components/Breadcrumb.tsx
+++ b/apps/carbon/app/components/Breadcrumb.tsx
@@ -56,7 +56,14 @@ const BreadcrumbLink = forwardRef<
}
>(({ className, children, isCurrentPage, ...props }, ref) => {
return (
- <Button variant="ghost" className={cn("px-2", className)} asChild>
+ <Button
+ variant="ghost"
+ className={cn(
+ "px-2 outline-none focus-visible:ring-transparent",
+ className
+ )}
+ asChild
+ >
{isCurrentPage ? (
<span aria-current="page" ref={ref} {...props}>
{children}
diff --git a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
index 1537c3b0a7..4bf5bdf2e2 100644
--- a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
@@ -19,7 +19,6 @@ import {
ModalHeader,
ModalTitle,
VStack,
- cn,
useDisclosure,
useWindowSize,
} from "@carbon/react";
@@ -116,7 +115,7 @@ function CompanyBreadcrumb() {
<Button
aria-current="page"
variant="ghost"
- className="px-2"
+ className="px-2 focus-visible:ring-transparent"
rightIcon={<LuChevronsUpDown />}
>
{routeData?.company.name}
@@ -129,11 +128,7 @@ function CompanyBreadcrumb() {
{routeData?.companies.map((c) => (
<DropdownMenuItem
key={c.companyId}
- className={cn(
- "flex items-center justify-between",
- c.id == routeData.company.id &&
- "bg-accent text-accent-foreground"
- )}
+ className="flex items-center justify-between"
>
<HStack>
<Avatar
@@ -170,7 +165,12 @@ function CompanyBreadcrumb() {
}}
>
<ModalContent>
- <ValidatedForm validator={companyValidator} method="post">
+ <ValidatedForm
+ action={path.to.newCompany}
+ validator={companyValidator}
+ method="post"
+ onSubmit={companyForm.onClose}
+ >
<ModalHeader>
<ModalTitle>Let's setup your new company</ModalTitle>
<ModalDescription>
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index f9fc4f6bc6..d548f3e4f4 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -389,9 +389,15 @@ export async function getEmployeeAbilities(
export async function getEmployeeJob(
client: SupabaseClient<Database>,
- employeeId: string
+ employeeId: string,
+ companyId: number
) {
- return client.from("employeeJob").select("*").eq("id", employeeId).single();
+ return client
+ .from("employeeJob")
+ .select("*")
+ .eq("id", employeeId)
+ .eq("companyId", companyId)
+ .single();
}
export async function getEmployeeSummary(
@@ -990,6 +996,7 @@ export async function updateEmployeeJob(
client: SupabaseClient<Database>,
employeeId: string,
employeeJob: z.infer<typeof employeeJobValidator> & {
+ companyId: number;
updatedBy: string;
customFields?: Json;
}
@@ -997,7 +1004,8 @@ export async function updateEmployeeJob(
return client
.from("employeeJob")
.update(sanitize(employeeJob))
- .eq("id", employeeId);
+ .eq("id", employeeId)
+ .eq("companyId", employeeJob.companyId);
}
export async function upsertContractor(
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 186f272cc9..5a7b3f0871 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -1233,10 +1233,10 @@ export async function upsertSalesOrder(
.select("id, salesOrderId");
}
- const [customerPayment, customerShipping, customer] = await Promise.all([
+ const [customerPayment, customerShipping, employee] = await Promise.all([
getCustomerPayment(client, salesOrder.customerId),
getCustomerShipping(client, salesOrder.customerId),
- getEmployeeJob(client, salesOrder.createdBy),
+ getEmployeeJob(client, salesOrder.createdBy, salesOrder.companyId),
]);
if (customerPayment.error) return customerPayment;
@@ -1252,7 +1252,7 @@ export async function upsertSalesOrder(
const { shippingMethodId, shippingTermId } = customerShipping.data;
- const locationId = customer?.data?.locationId ?? null;
+ const locationId = employee?.data?.locationId ?? null;
const order = await client
.from("salesOrder")
diff --git a/apps/carbon/app/modules/users/users.server.ts b/apps/carbon/app/modules/users/users.server.ts
index f4372aa54c..d2d38ec123 100644
--- a/apps/carbon/app/modules/users/users.server.ts
+++ b/apps/carbon/app/modules/users/users.server.ts
@@ -3,6 +3,7 @@ import { redis } from "@carbon/redis";
import { redirect } from "@remix-run/node";
import type { SupabaseClient } from "@supabase/supabase-js";
import crypto from "crypto";
+import logger from "~/lib/logger";
import { getSupabaseServiceRole } from "~/lib/supabase";
import { getSupplierContact } from "~/modules/purchasing";
import { getCustomerContact } from "~/modules/sales";
@@ -420,6 +421,7 @@ export async function getUserClaims(userId: string) {
// TODO: remove service role from here, and move it up a level
const rawClaims = await getClaims(getSupabaseServiceRole(), userId);
if (rawClaims.error || rawClaims.data === null) {
+ logger.error(rawClaims);
throw new Error("Failed to get claims");
}
@@ -788,7 +790,7 @@ export async function updateEmployee(
): Promise<Result> {
const updateEmployeeEmployeeType = await client
.from("employee")
- .upsert([{ id, employeeTypeId: employeeType }]);
+ .upsert([{ id, companyId, employeeTypeId: employeeType }]);
if (updateEmployeeEmployeeType.error)
return error(updateEmployeeEmployeeType.error, "Failed to update employee");
diff --git a/apps/carbon/app/modules/users/users.service.ts b/apps/carbon/app/modules/users/users.service.ts
index 8eb7267fe6..dfe430440f 100644
--- a/apps/carbon/app/modules/users/users.service.ts
+++ b/apps/carbon/app/modules/users/users.service.ts
@@ -67,9 +67,15 @@ export async function getCustomers(
export async function getEmployee(
client: SupabaseClient<Database>,
- id: string
+ id: string,
+ companyId: number
) {
- return client.from("employees").select("*").eq("id", id).single();
+ return client
+ .from("employees")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
}
export async function getEmployees(
diff --git a/apps/carbon/app/routes/_public+/login.tsx b/apps/carbon/app/routes/_public+/login.tsx
index dc2be84203..0788bc7e6d 100644
--- a/apps/carbon/app/routes/_public+/login.tsx
+++ b/apps/carbon/app/routes/_public+/login.tsx
@@ -65,7 +65,6 @@ export async function action({ request }: ActionFunctionArgs) {
headers: {
"Set-Cookie": await commitAuthSession(request, {
authSession,
- flashErrorMessage: null,
}),
},
});
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
index 25af3b75ad..9cb826f631 100644
--- a/apps/carbon/app/routes/onboarding+/company.tsx
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -66,7 +66,6 @@ export async function action({ request }: ActionFunctionArgs) {
// there are no entries in the userToCompany table which
// dictates RLS for the company table
- const supabaseClient = getSupabaseServiceRole();
const validation = await validator(onboardingCompanyValidator).validate(
await request.formData()
@@ -76,6 +75,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ const supabaseClient = getSupabaseServiceRole();
const { next, ...data } = validation.data;
let companyId: number | undefined;
diff --git a/apps/carbon/app/routes/x+/person+/$personId.job.tsx b/apps/carbon/app/routes/x+/person+/$personId.job.tsx
index 4bfed5be7c..d547d769c4 100644
--- a/apps/carbon/app/routes/x+/person+/$personId.job.tsx
+++ b/apps/carbon/app/routes/x+/person+/$personId.job.tsx
@@ -17,14 +17,14 @@ import { getCustomFields, setCustomFields } from "~/utils/form";
import { assertIsPost } from "~/utils/http";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "resources",
});
const { personId } = params;
if (!personId) throw new Error("Could not find personId");
- const job = await getEmployeeJob(client, personId);
+ const job = await getEmployeeJob(client, personId, companyId);
if (job.error) {
throw redirect(
path.to.people,
@@ -39,7 +39,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "resources",
});
const { personId } = params;
@@ -54,6 +54,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateJob = await updateEmployeeJob(client, personId, {
...validation.data,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData),
});
diff --git a/apps/carbon/app/routes/x+/person+/$personId.private.tsx b/apps/carbon/app/routes/x+/person+/$personId.private.tsx
index dcaceacfc0..84cf3e373f 100644
--- a/apps/carbon/app/routes/x+/person+/$personId.private.tsx
+++ b/apps/carbon/app/routes/x+/person+/$personId.private.tsx
@@ -43,7 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "resources",
});
const { personId } = params;
@@ -59,6 +59,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateJob = await updateEmployeeJob(client, personId, {
...validation.data,
+ companyId,
updatedBy: userId,
});
if (updateJob.error) {
diff --git a/apps/carbon/app/routes/x+/person+/$personId.public.tsx b/apps/carbon/app/routes/x+/person+/$personId.public.tsx
index eb565ada15..c6edfe9524 100644
--- a/apps/carbon/app/routes/x+/person+/$personId.public.tsx
+++ b/apps/carbon/app/routes/x+/person+/$personId.public.tsx
@@ -43,7 +43,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "resources",
});
const { personId } = params;
@@ -59,6 +59,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updateJob = await updateEmployeeJob(client, personId, {
...validation.data,
+ companyId,
updatedBy: userId,
});
if (updateJob.error) {
diff --git a/apps/carbon/app/routes/x+/settings+/company.new.tsx b/apps/carbon/app/routes/x+/settings+/company.new.tsx
new file mode 100644
index 0000000000..b27c59c169
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/company.new.tsx
@@ -0,0 +1,104 @@
+import { redis } from "@carbon/redis";
+import { validationError, validator } from "@carbon/remix-validated-form";
+import { getLocalTimeZone } from "@internationalized/date";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import logger from "~/lib/logger";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { insertEmployeeJob, upsertLocation } from "~/modules/resources";
+import {
+ companyValidator,
+ insertCompany,
+ seedCompany,
+} from "~/modules/settings";
+import {
+ addUserToCompany,
+ getPermissionCacheKey,
+} from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { commitAuthSession } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: ["settings", "users"],
+ });
+ const formData = await request.formData();
+ const validation = await validator(companyValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const client = getSupabaseServiceRole();
+
+ const companyInsert = await insertCompany(client, validation.data);
+ if (companyInsert.error) {
+ logger.error(companyInsert.error);
+ throw new Error("Fatal: failed to insert company");
+ }
+
+ let companyId = companyInsert.data?.id;
+ if (!companyId) {
+ throw new Error("Fatal: failed to get company ID");
+ }
+
+ const seed = await seedCompany(client, companyId, userId);
+ if (seed.error) {
+ logger.error(seed.error);
+ throw new Error("Fatal: failed to seed company");
+ }
+
+ // TODO: move all of this to transaction
+ const [locationInsert] = await Promise.all([
+ upsertLocation(client, {
+ ...validation.data,
+ name: "Headquarters",
+ companyId,
+ timezone: getLocalTimeZone(),
+ createdBy: userId,
+ }),
+ ]);
+
+ if (locationInsert.error) {
+ logger.error(locationInsert.error);
+ throw new Error("Fatal: failed to insert location");
+ }
+
+ const locationId = locationInsert.data?.id;
+ if (!locationId) {
+ throw new Error("Fatal: failed to get location ID");
+ }
+
+ const [userToCompany, job] = await Promise.all([
+ addUserToCompany(client, {
+ userId,
+ companyId,
+ }),
+ insertEmployeeJob(client, {
+ id: userId,
+ companyId,
+ locationId,
+ }),
+ redis.del(getPermissionCacheKey(userId)),
+ ]);
+
+ if (userToCompany.error) {
+ logger.error(userToCompany.error);
+ throw new Error("Fatal: failed to add user to company");
+ }
+
+ if (job.error) {
+ logger.error(job.error);
+ throw new Error("Fatal: failed to insert job");
+ }
+
+ throw redirect(path.to.authenticatedRoot, {
+ headers: {
+ "Set-Cookie": await commitAuthSession(request, {
+ company: companyId,
+ }),
+ },
+ });
+}
diff --git a/apps/carbon/app/routes/x+/settings+/company.tsx b/apps/carbon/app/routes/x+/settings+/company.tsx
index 0a5efeac4d..034b178559 100644
--- a/apps/carbon/app/routes/x+/settings+/company.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.tsx
@@ -124,6 +124,7 @@ export default function Company() {
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-[1fr_auto] gap-4 w-full">
+ {/* @ts-ignore */}
<CompanyForm company={initialValues} />
<CompanyLogoForm company={company} />
</div>
diff --git a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
index 24909202d3..ddaf1d5709 100644
--- a/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
+++ b/apps/carbon/app/routes/x+/users+/employees.$employeeId.tsx
@@ -33,7 +33,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const [rawClaims, employee, employeeTypes] = await Promise.all([
getClaims(client, employeeId),
- getEmployee(client, employeeId),
+ getEmployee(client, employeeId, companyId),
getEmployeeTypes(client, companyId),
]);
diff --git a/apps/carbon/app/services/session.server.ts b/apps/carbon/app/services/session.server.ts
index 344eda65d7..32b3bf6ec6 100644
--- a/apps/carbon/app/services/session.server.ts
+++ b/apps/carbon/app/services/session.server.ts
@@ -33,7 +33,7 @@ async function assertAuthSession(
const sessionStorage = createCookieSessionStorage({
cookie: {
- name: "__authSession",
+ name: "carbon",
httpOnly: true,
path: "/",
sameSite: "lax",
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 34fe036f73..4b516e9439 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -280,6 +280,7 @@ export const path = {
newAttributeForCategory: (id: string) =>
generatePath(`${x}/resources/attributes/list/${id}/new`),
newChartOfAccount: `${x}/accounting/charts/new`,
+ newCompany: `${x}/settings/company/new`,
newContractor: `${x}/resources/contractors/new`,
newCurrency: `${x}/accounting/currencies/new`,
newCustomer: `${x}/customer/new`,
diff --git a/packages/database/src/seed.ts b/packages/database/src/seed.ts
index 0bae8dddd1..716e8a8080 100644
--- a/packages/database/src/seed.ts
+++ b/packages/database/src/seed.ts
@@ -1,6 +1,6 @@
import { createClient } from "@supabase/supabase-js";
import * as dotenv from "dotenv";
-import { admin, claims } from "./seed/index";
+import { admin, claims, permissions } from "./seed/index";
import type { Database } from "./types";
dotenv.config();
@@ -48,9 +48,9 @@ async function seed() {
{
id,
email: admin.email,
- emailVerified: new Date().toISOString(),
firstName: admin.firstName,
lastName: admin.lastName,
+ permissions,
},
]);
if (upsertAdmin.error) throw upsertAdmin.error;
diff --git a/packages/database/src/seed/admin.ts b/packages/database/src/seed/admin.ts
index e9ee63a116..ca40b4ef43 100644
--- a/packages/database/src/seed/admin.ts
+++ b/packages/database/src/seed/admin.ts
@@ -7,10 +7,13 @@ const admin = {
const ALL_TEAMS_ID = 0;
-const claims: Record<string, string | number[]> = {
+const claims: Record<string, string> = {
role: "employee",
+};
+
+const permissions: Record<string, number[]> = {
settings_update: [ALL_TEAMS_ID],
users_update: [ALL_TEAMS_ID],
};
-export { admin, claims };
+export { admin, claims, permissions };
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index ff4b528ded..6ac27c8c97 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3643,17 +3643,17 @@ export type Database = {
}
employee: {
Row: {
- companyId: number | null
+ companyId: number
employeeTypeId: string
id: string
}
Insert: {
- companyId?: number | null
+ companyId: number
employeeTypeId: string
id: string
}
Update: {
- companyId?: number | null
+ companyId?: number
employeeTypeId?: string
id?: string
}
@@ -3815,28 +3815,28 @@ export type Database = {
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
@@ -15014,11 +15014,11 @@ export type Database = {
avatarUrl: string | null
createdAt: string
email: string
- emailVerified: string | null
firstName: string
fullName: string | null
id: string
lastName: string
+ permissions: Json | null
updatedAt: string | null
}
Insert: {
@@ -15027,11 +15027,11 @@ export type Database = {
avatarUrl?: string | null
createdAt?: string
email: string
- emailVerified?: string | null
firstName: string
fullName?: string | null
id: string
lastName: string
+ permissions?: Json | null
updatedAt?: string | null
}
Update: {
@@ -15040,11 +15040,11 @@ export type Database = {
avatarUrl?: string | null
createdAt?: string
email?: string
- emailVerified?: string | null
firstName?: string
fullName?: string | null
id?: string
lastName?: string
+ permissions?: Json | null
updatedAt?: string | null
}
Relationships: []
@@ -19541,20 +19541,6 @@ export type Database = {
Args: Record<PropertyKey, never>
Returns: number
}
- delete_claim: {
- Args: {
- uid: string
- claim: string
- }
- Returns: string
- }
- get_claim: {
- Args: {
- uid: string
- claim: string
- }
- Returns: Json
- }
get_claims: {
Args: {
uid: string
@@ -19574,8 +19560,10 @@ export type Database = {
}
Returns: Json
}
- get_my_claims: {
- Args: Record<PropertyKey, never>
+ get_my_permission: {
+ Args: {
+ claim: string
+ }
Returns: Json
}
get_permission_companies: {
@@ -19662,14 +19650,6 @@ export type Database = {
}
Returns: unknown
}
- set_claim: {
- Args: {
- uid: string
- claim: string
- value: Json
- }
- Returns: string
- }
users_for_groups: {
Args: {
groups: string[]
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index ff4b528ded..6ac27c8c97 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -3643,17 +3643,17 @@ export type Database = {
}
employee: {
Row: {
- companyId: number | null
+ companyId: number
employeeTypeId: string
id: string
}
Insert: {
- companyId?: number | null
+ companyId: number
employeeTypeId: string
id: string
}
Update: {
- companyId?: number | null
+ companyId?: number
employeeTypeId?: string
id?: string
}
@@ -3815,28 +3815,28 @@ export type Database = {
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "employees"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "employeeSummary"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "user"
referencedColumns: ["id"]
},
{
foreignKeyName: "employeeJob_id_fkey"
columns: ["id"]
- isOneToOne: true
+ isOneToOne: false
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
@@ -15014,11 +15014,11 @@ export type Database = {
avatarUrl: string | null
createdAt: string
email: string
- emailVerified: string | null
firstName: string
fullName: string | null
id: string
lastName: string
+ permissions: Json | null
updatedAt: string | null
}
Insert: {
@@ -15027,11 +15027,11 @@ export type Database = {
avatarUrl?: string | null
createdAt?: string
email: string
- emailVerified?: string | null
firstName: string
fullName?: string | null
id: string
lastName: string
+ permissions?: Json | null
updatedAt?: string | null
}
Update: {
@@ -15040,11 +15040,11 @@ export type Database = {
avatarUrl?: string | null
createdAt?: string
email?: string
- emailVerified?: string | null
firstName?: string
fullName?: string | null
id?: string
lastName?: string
+ permissions?: Json | null
updatedAt?: string | null
}
Relationships: []
@@ -19541,20 +19541,6 @@ export type Database = {
Args: Record<PropertyKey, never>
Returns: number
}
- delete_claim: {
- Args: {
- uid: string
- claim: string
- }
- Returns: string
- }
- get_claim: {
- Args: {
- uid: string
- claim: string
- }
- Returns: Json
- }
get_claims: {
Args: {
uid: string
@@ -19574,8 +19560,10 @@ export type Database = {
}
Returns: Json
}
- get_my_claims: {
- Args: Record<PropertyKey, never>
+ get_my_permission: {
+ Args: {
+ claim: string
+ }
Returns: Json
}
get_permission_companies: {
@@ -19662,14 +19650,6 @@ export type Database = {
}
Returns: unknown
}
- set_claim: {
- Args: {
- uid: string
- claim: string
- value: Json
- }
- Returns: string
- }
users_for_groups: {
Args: {
groups: string[]
diff --git a/packages/database/supabase/migrations/20230123004206_claims.sql b/packages/database/supabase/migrations/20230123004206_claims.sql
index aff96940aa..17ec966e99 100644
--- a/packages/database/supabase/migrations/20230123004206_claims.sql
+++ b/packages/database/supabase/migrations/20230123004206_claims.sql
@@ -1,3 +1,5 @@
+
+
CREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"
LANGUAGE "plpgsql"
AS $$
@@ -15,8 +17,8 @@ CREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"
IF EXISTS (
SELECT 1
- FROM jsonb_array_elements_text((current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->'users_update') AS j
- WHERE j::int = 0
+ FROM get_permission_companies_as_text('users_update') AS company
+ WHERE company::int = 0
) THEN
return true; -- user has user_update set to true
ELSE
@@ -31,26 +33,26 @@ CREATE OR REPLACE FUNCTION is_claims_admin() RETURNS "bool"
END;
$$;
-CREATE OR REPLACE FUNCTION get_my_claims() RETURNS "jsonb"
+CREATE OR REPLACE FUNCTION get_my_permission(claim text) RETURNS "jsonb"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
- DECLARE retval jsonb;
+ DECLARE permissions jsonb;
BEGIN
- -- TODO: we should be able to use (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'
- select raw_app_meta_data from auth.users into retval where id = auth.uid();
- return retval;
+ select coalesce(permissions->claim, null) from public.user into permissions where id = auth.uid()::text;
+ return permissions;
END;
$$;
+
CREATE OR REPLACE FUNCTION get_my_claim(claim text) RETURNS "jsonb"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
- DECLARE retval jsonb;
+ DECLARE claims jsonb;
BEGIN
-- TODO: we should be able to use (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'
- select coalesce(raw_app_meta_data->claim, null) from auth.users into retval where id = auth.uid();
- return retval;
+ select coalesce(raw_app_meta_data->claim, null) from auth.users into claims where id = auth.uid();
+ return claims;
END;
$$;
@@ -72,8 +74,8 @@ CREATE OR REPLACE FUNCTION get_permission_companies(claim text) RETURNS integer[
AS $$
DECLARE retval integer[];
BEGIN
- -- TODO: (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->
- select jsonb_to_integer_array(coalesce(raw_app_meta_data->claim, '[]')) from auth.users into retval where id = auth.uid();
+
+ select jsonb_to_integer_array(coalesce(permissions->claim, '[]')) from public.user into retval where id = auth.uid()::text;
return retval;
END;
@@ -85,7 +87,7 @@ CREATE OR REPLACE FUNCTION get_permission_companies_as_text(claim text) RETURNS
DECLARE retval text[];
BEGIN
-- TODO: (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->
- select jsonb_to_text_array(coalesce(raw_app_meta_data->claim, '[]')) from auth.users into retval where id = auth.uid();
+ select jsonb_to_text_array(coalesce(permissions->claim, '[]')) from public.user into retval where id = auth.uid()::text;
return retval;
END;
@@ -107,15 +109,15 @@ CREATE OR REPLACE FUNCTION has_company_permission(claim text, company integer) R
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
DECLARE
- claim_value integer[];
+ permission_value integer[];
BEGIN
-- TODO: (current_setting('request.jwt.claims', true)::jsonb)->'app_metadata'->claim
- SELECT jsonb_to_integer_array(coalesce(raw_app_meta_data->claim, '[]')) INTO claim_value FROM auth.users WHERE id = auth.uid();
- IF claim_value IS NULL THEN
+ SELECT jsonb_to_integer_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public.user WHERE id = auth.uid()::text;
+ IF permission_value IS NULL THEN
return false;
- ELSIF 0 = ANY(claim_value::integer[]) THEN
+ ELSIF 0 = ANY(permission_value::integer[]) THEN
return true;
- ELSIF company = ANY(claim_value::integer[]) THEN
+ ELSIF company = ANY(permission_value::integer[]) THEN
return true;
ELSE
return false;
@@ -127,13 +129,13 @@ CREATE OR REPLACE FUNCTION has_any_company_permission(claim text) RETURNS "bool"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
DECLARE
- claim_value integer[];
+ permission_value integer[];
BEGIN
- SELECT jsonb_to_integer_array(coalesce(raw_app_meta_data->claim, '[]')) INTO claim_value FROM auth.users WHERE id = auth.uid();
- IF claim_value IS NULL THEN
+ SELECT jsonb_to_integer_array(coalesce(permissions->claim, '[]')) INTO permission_value FROM public.user WHERE id = auth.uid()::text;
+ IF permission_value IS NULL THEN
return false;
- ELSIF array_length(claim_value, 1) > 0 THEN
+ ELSIF array_length(permission_value, 1) > 0 THEN
return true;
ELSE
return false;
@@ -152,56 +154,18 @@ CREATE OR REPLACE FUNCTION get_company_id_from_foreign_key(foreign_key TEXT, tbl
END;
$$;
-CREATE OR REPLACE FUNCTION get_claims(uid uuid) RETURNS "jsonb"
+CREATE OR REPLACE FUNCTION get_claims(uid text) RETURNS "jsonb"
LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
AS $$
- DECLARE retval jsonb;
+ DECLARE claims jsonb;
+ DECLARE perms jsonb;
BEGIN
- select raw_app_meta_data from auth.users into retval where id = uid::uuid;
- return retval;
+ select raw_app_meta_data from auth.users into claims where id = uid::uuid;
+ select permissions from public.user into perms where id = uid::text;
+ return (claims || perms)::jsonb;
END;
$$;
-CREATE OR REPLACE FUNCTION get_claim(uid uuid, claim text) RETURNS "jsonb"
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- DECLARE retval jsonb;
- BEGIN
- select coalesce(raw_app_meta_data->claim, null) from auth.users into retval where id = uid::uuid;
- return retval;
-
- END;
-$$;
-
-
-CREATE OR REPLACE FUNCTION set_claim(uid uuid, claim text, value jsonb) RETURNS "text"
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- BEGIN
- IF NOT is_claims_admin() THEN
- RETURN 'error: access denied';
- ELSE
- update auth.users set raw_app_meta_data =
- raw_app_meta_data ||
- json_build_object(claim, value)::jsonb where id = uid;
- return 'OK';
- END IF;
- END;
-$$;
-
-CREATE OR REPLACE FUNCTION delete_claim(uid uuid, claim text) RETURNS "text"
- LANGUAGE "plpgsql" SECURITY DEFINER SET search_path = public
- AS $$
- BEGIN
- IF NOT is_claims_admin() THEN
- RETURN 'error: access denied';
- ELSE
- update auth.users set raw_app_meta_data =
- raw_app_meta_data - claim where id = uid;
- return 'OK';
- END IF;
- END;
-$$;
NOTIFY pgrst, 'reload schema';
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20230123004316_users.sql b/packages/database/supabase/migrations/20230123004316_users.sql
index c37522c63f..81cbcdf614 100644
--- a/packages/database/supabase/migrations/20230123004316_users.sql
+++ b/packages/database/supabase/migrations/20230123004316_users.sql
@@ -7,7 +7,7 @@ CREATE TABLE "user" (
"about" TEXT NOT NULL DEFAULT '',
"avatarUrl" TEXT,
"active" BOOLEAN DEFAULT TRUE,
- "emailVerified" TIMESTAMP WITH TIME ZONE,
+ "permissions" JSONB DEFAULT '{}',
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedAt" TIMESTAMP WITH TIME ZONE,
diff --git a/packages/database/supabase/migrations/20230123004436_employee.sql b/packages/database/supabase/migrations/20230123004436_employee.sql
index afa4717848..95e58edd6c 100644
--- a/packages/database/supabase/migrations/20230123004436_employee.sql
+++ b/packages/database/supabase/migrations/20230123004436_employee.sql
@@ -2,10 +2,9 @@ CREATE TABLE "employee" (
"id" TEXT NOT NULL,
"companyId" INTEGER,
"employeeTypeId" TEXT NOT NULL,
- CONSTRAINT "employee_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "employee_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "employee_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "employee_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "employee_employeeCompany_unique" UNIQUE ("id", "companyId")
+ CONSTRAINT "employee_employeeTypeId_fkey" FOREIGN KEY ("employeeTypeId") REFERENCES "employeeType"("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE INDEX "employee_companyId_idx" ON "employee" ("companyId");
diff --git a/packages/database/supabase/migrations/20230123212853_search.sql b/packages/database/supabase/migrations/20230123212853_search.sql
index 8ea16ff511..88cb9f2c95 100644
--- a/packages/database/supabase/migrations/20230123212853_search.sql
+++ b/packages/database/supabase/migrations/20230123212853_search.sql
@@ -10,7 +10,7 @@ CREATE TABLE search (
link TEXT NOT NULL,
"companyId" INTEGER NOT NULL,
- CONSTRAINT search_uuid_unique UNIQUE (uuid),
+ CONSTRAINT search_uuid_unique UNIQUE ("uuid", "companyId"),
CONSTRAINT search_companyId_fkey FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
diff --git a/packages/database/supabase/migrations/20230224035103_shifts.sql b/packages/database/supabase/migrations/20230224035103_shifts.sql
index c79cb11114..2f51b3539d 100644
--- a/packages/database/supabase/migrations/20230224035103_shifts.sql
+++ b/packages/database/supabase/migrations/20230224035103_shifts.sql
@@ -207,7 +207,7 @@ CREATE TABLE "employeeJob" (
"updatedBy" TEXT,
"customFields" JSONB,
- CONSTRAINT "employeeJob_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "employeeJob_pkey" PRIMARY KEY ("id", "companyId"),
CONSTRAINT "employeeJob_id_fkey" FOREIGN KEY ("id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "employeeJob_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "employeeJob_shiftId_fkey" FOREIGN KEY ("shiftId") REFERENCES "shift"("id") ON DELETE CASCADE ON UPDATE CASCADE,
diff --git a/packages/database/supabase/migrations/20240119095150_integrations.sql b/packages/database/supabase/migrations/20240119095150_integrations.sql
index 325bcd0b2e..6f5e52ee46 100644
--- a/packages/database/supabase/migrations/20240119095150_integrations.sql
+++ b/packages/database/supabase/migrations/20240119095150_integrations.sql
@@ -14,7 +14,7 @@ CREATE TABLE "integration" (
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
- CONSTRAINT integration_pkey PRIMARY KEY ("id"),
+ CONSTRAINT integration_pkey PRIMARY KEY ("id", "companyId"),
CONSTRAINT integration_metadata CHECK (
active = false OR
json_matches_schema(jsonschema, metadata)
diff --git a/packages/utils/src/color.ts b/packages/utils/src/color.ts
index a0c7cad7ee..1b5d381b3c 100644
--- a/packages/utils/src/color.ts
+++ b/packages/utils/src/color.ts
@@ -14,7 +14,7 @@ const colors = [
{ background: "#8338ec", color: "#ffffff" },
{ background: "#ffadad", color: "#000000" },
{ background: "#ffd6a5", color: "#000000" },
- { background: "#fdffb6", color: "#000000" },
+ { background: "#4f46e5", color: "#ffffff" },
{ background: "#caffbf", color: "#000000" },
{ background: "#9bf6ff", color: "#000000" },
{ background: "#a0c4ff", color: "#000000" },