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 theme color select form

Brad Barbin5f52f207b628
diff --git a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
index 2624b5d34e..8ac6eaafce 100644
--- a/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsx
@@ -9,6 +9,9 @@ import {
import { Link, useMatches } from "@remix-run/react";
import { BsFillHexagonFill } from "react-icons/bs";
import { z } from "zod";
+import { useRouteData } from "~/hooks";
+import type { Company } from "~/modules/settings";
+import { path } from "~/utils/path";
import { useSidebar } from "./useSidebar";
export const ModuleHandle = z.object({
@@ -16,6 +19,12 @@ export const ModuleHandle = z.object({
});
const IconSidebar = () => {
+ const routeData = useRouteData<{ company: Company }>(
+ path.to.authenticatedRoot
+ );
+
+ const company = routeData?.company;
+
const links = useSidebar();
const matchedModules = useMatches().reduce((acc, match) => {
if (match.handle) {
@@ -33,17 +42,31 @@ const IconSidebar = () => {
<div>
<TooltipProvider>
<VStack spacing={0} className="self-start sticky">
- <Button
- isIcon
- asChild
- variant="ghost"
- size="lg"
- className="rounded-none"
- >
- <Link to="/">
- <BsFillHexagonFill />
+ {company?.logo ? (
+ <Link
+ to="/"
+ className="flex w-[44px] h-[48px] p-2 items-center justify-center hover:bg-accent"
+ >
+ <img
+ src={company.logo}
+ alt={`${company.name} Logo`}
+ className="w-full"
+ />
</Link>
- </Button>
+ ) : (
+ <Button
+ isIcon
+ asChild
+ variant="ghost"
+ size="lg"
+ className="rounded-none"
+ >
+ <Link to="/">
+ <BsFillHexagonFill />
+ </Link>
+ </Button>
+ )}
+
{links.map((link) => {
const module = link.to.split("/")[2]; // link.to is "/x/parts" -- this returns "parts"
diff --git a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
index e21d24bc65..39de03b46f 100644
--- a/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
+++ b/apps/carbon/app/modules/account/ui/UserAttributes/UserAttributesForm.tsx
@@ -387,7 +387,7 @@ function renderTypedDisplay({
)}
<HStack className="justify-end w-full self-center">
<Button
- isDisabled={!isAuthorized && (!attribute.canSelfManage ?? true)}
+ isDisabled={!isAuthorized || !attribute.canSelfManage}
variant="ghost"
onClick={onOpen}
>
diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
index 2347a9673b..713dcefa72 100644
--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx
@@ -56,7 +56,7 @@ const PurchaseInvoiceLines = () => {
} = usePurchaseInvoiceLines();
const [, setPurchaseInvoiceTotals] = usePurchaseInvoiceTotals();
- const isEditable = !routeData?.purchaseInvoice?.postingDate ?? false;
+ const isEditable = !routeData?.purchaseInvoice?.postingDate;
const columns = useMemo<ColumnDef<PurchaseInvoiceLine>[]>(() => {
return [
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index 81a32a76cf..0fea009af6 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -35,3 +35,32 @@ export const sequenceValidator = withZod(
size: zfd.numeric(z.number().min(1).max(20)),
})
);
+
+export const themeValidator = withZod(
+ z.object({
+ primaryBackgroundLight: z
+ .string()
+ .min(1, { message: "Primary background light is required" }),
+ primaryForegroundLight: z
+ .string()
+ .min(1, { message: "Primary foreground light is required" }),
+ accentBackgroundLight: z
+ .string()
+ .min(1, { message: "Accent background light is required" }),
+ accentForegroundLight: z
+ .string()
+ .min(1, { message: "Accent foreground light is required" }),
+ primaryBackgroundDark: z
+ .string()
+ .min(1, { message: "Primary background dark is required" }),
+ primaryForegroundDark: z
+ .string()
+ .min(1, { message: "Primary foreground dark is required" }),
+ accentBackgroundDark: z
+ .string()
+ .min(1, { message: "Accent background dark is required" }),
+ accentForegroundDark: z
+ .string()
+ .min(1, { message: "Accent foreground dark is required" }),
+ })
+);
diff --git a/apps/carbon/app/modules/settings/settings.service.ts b/apps/carbon/app/modules/settings/settings.service.ts
index dce426dea1..edaf2827ed 100644
--- a/apps/carbon/app/modules/settings/settings.service.ts
+++ b/apps/carbon/app/modules/settings/settings.service.ts
@@ -6,7 +6,11 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { interpolateSequenceDate } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
-import type { companyValidator, sequenceValidator } from "./settings.models";
+import type {
+ companyValidator,
+ sequenceValidator,
+ themeValidator,
+} from "./settings.models";
export async function getCompany(client: SupabaseClient<Database>) {
const company = await client.from("company").select("*").single();
@@ -128,6 +132,10 @@ export async function getSequencesList(
return client.from("sequence").select("id").eq("table", table).order("table");
}
+export async function getTheme(client: SupabaseClient<Database>) {
+ return client.from("theme").select("*").single();
+}
+
export async function insertCompany(
client: SupabaseClient<Database>,
company: TypeOfValidator<typeof companyValidator>
@@ -200,3 +208,10 @@ export async function updateSequence(
) {
return client.from("sequence").update(sanitize(sequence)).eq("table", table);
}
+
+export async function updateTheme(
+ client: SupabaseClient<Database>,
+ theme: TypeOfValidator<typeof themeValidator> & { updatedBy: string }
+) {
+ return client.from("theme").update(theme).eq("id", true);
+}
diff --git a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index 94e6c7a486..5ff5878718 100644
--- a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -1,6 +1,6 @@
import { Avatar, Button, File, VStack, toast } from "@carbon/react";
import { useSubmit } from "@remix-run/react";
-import type { ChangeEvent } from "react";
+import { type ChangeEvent } from "react";
import { useSupabase } from "~/lib/supabase";
import type { Company } from "~/modules/settings";
import { path } from "~/utils/path";
@@ -64,12 +64,18 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
};
return (
- <VStack className="items-center p-8">
- <Avatar
- size="2xl"
- src={company?.logo ?? undefined}
- name={company?.name}
- />
+ <VStack className="items-center px-8">
+ {company?.logo ? (
+ <img
+ alt={`${company.name} Logo`}
+ width="128"
+ height="auto"
+ src={company.logo}
+ />
+ ) : (
+ <Avatar name={company?.name} size="2xl" />
+ )}
+
<File accept="image/*" onChange={uploadImage}>
{company.logo ? "Change" : "Upload"}
</File>
diff --git a/apps/carbon/app/modules/settings/ui/Theme/ThemeForm.tsx b/apps/carbon/app/modules/settings/ui/Theme/ThemeForm.tsx
new file mode 100644
index 0000000000..9dd6e8e1b1
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/Theme/ThemeForm.tsx
@@ -0,0 +1,45 @@
+import { VStack } from "@carbon/react";
+import { ValidatedForm } from "remix-validated-form";
+import { Color, Submit } from "~/components/Form";
+import { SectionTitle } from "~/components/Layout";
+import { themeValidator } from "~/modules/settings";
+import type { TypeOfValidator } from "~/types/validators";
+import { path } from "~/utils/path";
+
+type ThemeFormProps = {
+ theme: TypeOfValidator<typeof themeValidator>;
+};
+
+const ThemeForm = ({ theme }: ThemeFormProps) => {
+ return (
+ <div className="w-full">
+ <ValidatedForm
+ method="post"
+ action={path.to.theme}
+ validator={themeValidator}
+ defaultValues={theme}
+ >
+ <VStack spacing={4} className="max-w-[520px]">
+ <SectionTitle>Light Mode</SectionTitle>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <Color name="primaryBackgroundLight" label="Primary Background" />
+ <Color name="primaryForegroundLight" label="Primary Foreground" />
+ <Color name="accentBackgroundLight" label="Accent Background" />
+ <Color name="accentForegroundLight" label="Accent Foreground" />
+ </div>
+ <SectionTitle>Dark Mode</SectionTitle>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
+ <Color name="primaryBackgroundDark" label="Primary Background" />
+ <Color name="primaryForegroundDark" label="Primary Foreground" />
+ <Color name="accentBackgroundDark" label="Accent Background Dark" />
+ <Color name="accentForegroundDark" label="Accent Foreground Dark" />
+ </div>
+
+ <Submit>Save</Submit>
+ </VStack>
+ </ValidatedForm>
+ </div>
+ );
+};
+
+export default ThemeForm;
diff --git a/apps/carbon/app/modules/settings/ui/Theme/index.ts b/apps/carbon/app/modules/settings/ui/Theme/index.ts
new file mode 100644
index 0000000000..38ad126518
--- /dev/null
+++ b/apps/carbon/app/modules/settings/ui/Theme/index.ts
@@ -0,0 +1,3 @@
+import ThemeForm from "./ThemeForm";
+
+export { ThemeForm };
diff --git a/apps/carbon/app/modules/settings/ui/index.ts b/apps/carbon/app/modules/settings/ui/index.ts
index 841b19b323..04e838412c 100644
--- a/apps/carbon/app/modules/settings/ui/index.ts
+++ b/apps/carbon/app/modules/settings/ui/index.ts
@@ -3,4 +3,5 @@ import useSettingsSidebar from "./useSettingsSidebar";
export * from "./Company";
export * from "./Integrations";
export * from "./Sequences";
+export * from "./Theme";
export { useSettingsSidebar };
diff --git a/apps/carbon/app/modules/settings/ui/useSettingsSidebar.tsx b/apps/carbon/app/modules/settings/ui/useSettingsSidebar.tsx
index a20131aabb..bb499f5db1 100644
--- a/apps/carbon/app/modules/settings/ui/useSettingsSidebar.tsx
+++ b/apps/carbon/app/modules/settings/ui/useSettingsSidebar.tsx
@@ -1,3 +1,4 @@
+import { BsPaletteFill } from "react-icons/bs";
import { CgSync } from "react-icons/cg";
import { GoNumber } from "react-icons/go";
import { TbBuildingFactory2 } from "react-icons/tb";
@@ -32,6 +33,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
role: "employee",
icon: <GoNumber />,
},
+ {
+ name: "Theme",
+ to: path.to.theme,
+ role: "employee",
+ icon: <BsPaletteFill />,
+ },
],
},
];
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index 5e189cc2f8..a4fc894464 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -24,6 +24,7 @@ import Tailwind from "~/styles/tailwind.css";
export function links() {
return [
{ rel: "stylesheet", href: Tailwind },
+ { rel: "stylesheet", href: "/assets/theme.css" },
{ rel: "stylesheet", href: Background },
{ rel: "stylesheet", href: NProgress },
];
diff --git a/apps/carbon/app/routes/assets+/theme[.]css.ts b/apps/carbon/app/routes/assets+/theme[.]css.ts
new file mode 100644
index 0000000000..a0bb0340b4
--- /dev/null
+++ b/apps/carbon/app/routes/assets+/theme[.]css.ts
@@ -0,0 +1,51 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { getTheme } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {});
+
+ const theme = await getTheme(client);
+ if (theme.error) {
+ return new Response("", {
+ headers: {
+ "Content-Type": "text/css",
+ },
+ });
+ }
+
+ const {
+ primaryBackgroundLight,
+ primaryForegroundLight,
+ accentBackgroundLight,
+ accentForegroundLight,
+ primaryBackgroundDark,
+ primaryForegroundDark,
+ accentBackgroundDark,
+ accentForegroundDark,
+ } = theme.data;
+
+ console.log(theme.data);
+
+ let css = `
+ :root {
+ --primary: ${primaryBackgroundLight};
+ --primary-foreground: ${primaryForegroundLight};
+ --accent: ${accentBackgroundLight};
+ --accent-foreground: ${accentForegroundLight};
+ }
+
+ .dark {
+ --primary: ${primaryBackgroundDark};
+ --primary-foreground: ${primaryForegroundDark};
+ --accent: ${accentBackgroundDark};
+ --accent-foreground: ${accentForegroundDark};
+ }
+ `;
+
+ return new Response(css, {
+ headers: {
+ "Content-Type": "text/css",
+ },
+ });
+}
diff --git a/apps/carbon/app/routes/x+/settings+/company.tsx b/apps/carbon/app/routes/x+/settings+/company.tsx
index f334b437f8..ebe6df4ce0 100644
--- a/apps/carbon/app/routes/x+/settings+/company.tsx
+++ b/apps/carbon/app/routes/x+/settings+/company.tsx
@@ -1,14 +1,14 @@
import { VStack } from "@carbon/react";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import type { ActionFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import { PageTitle } from "~/components/Layout";
+import { useRouteData } from "~/hooks";
+import type { Company as CompanyType } from "~/modules/settings";
import {
CompanyForm,
CompanyLogoForm,
companyValidator,
- getCompany,
updateCompany,
updateLogo,
} from "~/modules/settings";
@@ -24,24 +24,11 @@ export const handle: Handle = {
to: path.to.company,
};
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {});
-
- const company = await getCompany(client);
-
- if (company.error || !company.data) {
- return redirect(
- path.to.settings,
- await flash(request, error(company.error, "Failed to get company"))
- );
- }
-
- return json({ company: company.data });
-}
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {});
+ const { client, userId } = await requirePermissions(request, {
+ update: "settings",
+ });
const formData = await request.formData();
if (formData.get("intent") === "about") {
@@ -98,7 +85,12 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function Company() {
- const { company } = useLoaderData<typeof loader>();
+ const routeData = useRouteData<{ company: CompanyType }>(
+ path.to.authenticatedRoot
+ );
+
+ const company = routeData?.company;
+ if (!company) throw new Error("Company not found");
const initialValues = {
name: company.name,
diff --git a/apps/carbon/app/routes/x+/settings+/theme.tsx b/apps/carbon/app/routes/x+/settings+/theme.tsx
new file mode 100644
index 0000000000..ac04dc321a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/settings+/theme.tsx
@@ -0,0 +1,100 @@
+import { VStack } from "@carbon/react";
+import { hexToHls, hslToHex } from "@carbon/utils";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { PageTitle } from "~/components/Layout";
+import {
+ ThemeForm,
+ getTheme,
+ themeValidator,
+ updateTheme,
+} from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import type { Handle } from "~/utils/handle";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export const handle: Handle = {
+ breadcrumb: "Theme",
+ to: path.to.theme,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const theme = await getTheme(client);
+ if (theme.error) {
+ return redirect(
+ path.to.settings,
+ await flash(request, error(theme.error, "Failed to get theme"))
+ );
+ }
+
+ const { id, updatedBy, updatedAt, ...themeData } = theme.data;
+
+ Object.keys(themeData).forEach((key) => {
+ // @ts-ignore
+ themeData[key] = hslToHex(themeData[key]);
+ });
+
+ return json({
+ theme: themeData,
+ });
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "settings",
+ });
+ const formData = await request.formData();
+
+ const validation = await themeValidator.validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const themeData = validation.data;
+ Object.keys(themeData).forEach((key) => {
+ // @ts-ignore
+ themeData[key] = hexToHls(themeData[key]);
+ });
+
+ const update = await updateTheme(client, {
+ ...validation.data,
+ updatedBy: userId,
+ });
+ if (update.error)
+ return json(
+ {},
+ await flash(request, error(update.error, "Failed to update theme"))
+ );
+
+ return json(
+ {},
+ await flash(request, success("Updated theme. Please refresh the page."))
+ );
+}
+
+export default function Theme() {
+ const { theme } = useLoaderData<typeof loader>();
+
+ const initialValues = theme;
+
+ return (
+ <VStack spacing={0} className="bg-background p-8 h-full">
+ <PageTitle
+ title="Theme"
+ subtitle="This information will be displayed on document headers."
+ />
+ <ThemeForm theme={initialValues} />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index a0021a2338..e18224a8f5 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -398,6 +398,7 @@ export const path = {
supplierTypes: `${x}/purchasing/supplier-types`,
tableSequence: (id: string) =>
generatePath(`${x}/settings/sequences/${id}`),
+ theme: `${x}/settings/theme`,
timecards: `${x}/timecards`,
uom: (id: string) => generatePath(`${x}/parts/uom/${id}`),
uoms: `${x}/parts/uom`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5f965f567f..30a56bd5bc 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8374,6 +8374,67 @@ export interface Database {
}
];
};
+ theme: {
+ Row: {
+ accentBackgroundDark: string;
+ accentBackgroundLight: string;
+ accentForegroundDark: string;
+ accentForegroundLight: string;
+ id: boolean;
+ primaryBackgroundDark: string;
+ primaryBackgroundLight: string;
+ primaryForegroundDark: string;
+ primaryForegroundLight: string;
+ updatedAt: string;
+ updatedBy: string;
+ };
+ Insert: {
+ accentBackgroundDark: string;
+ accentBackgroundLight: string;
+ accentForegroundDark: string;
+ accentForegroundLight: string;
+ id?: boolean;
+ primaryBackgroundDark: string;
+ primaryBackgroundLight: string;
+ primaryForegroundDark: string;
+ primaryForegroundLight: string;
+ updatedAt?: string;
+ updatedBy: string;
+ };
+ Update: {
+ accentBackgroundDark?: string;
+ accentBackgroundLight?: string;
+ accentForegroundDark?: string;
+ accentForegroundLight?: string;
+ id?: boolean;
+ primaryBackgroundDark?: string;
+ primaryBackgroundLight?: string;
+ primaryForegroundDark?: string;
+ primaryForegroundLight?: string;
+ updatedAt?: string;
+ updatedBy?: string;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "theme_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "theme_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "employeeSummary";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "theme_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "userDefaults";
+ referencedColumns: ["userId"];
+ }
+ ];
+ };
unitOfMeasure: {
Row: {
active: boolean;
@@ -9891,13 +9952,13 @@ export interface Database {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["customerCountryCode"];
+ columns: ["supplierCountryCode"];
referencedRelation: "country";
referencedColumns: ["id"];
},
{
foreignKeyName: "address_countryCode_fkey";
- columns: ["supplierCountryCode"];
+ columns: ["customerCountryCode"];
referencedRelation: "country";
referencedColumns: ["id"];
}
diff --git a/packages/database/supabase/migrations/20240201042223_theme.sql b/packages/database/supabase/migrations/20240201042223_theme.sql
new file mode 100644
index 0000000000..c9b4389622
--- /dev/null
+++ b/packages/database/supabase/migrations/20240201042223_theme.sql
@@ -0,0 +1,34 @@
+CREATE TABLE "theme" (
+ "id" BOOLEAN NOT NULL DEFAULT TRUE,
+ "primaryBackgroundLight" TEXT NOT NULL,
+ "primaryForegroundLight" TEXT NOT NULL,
+ "primaryBackgroundDark" TEXT NOT NULL,
+ "primaryForegroundDark" TEXT NOT NULL,
+ "accentBackgroundLight" TEXT NOT NULL,
+ "accentForegroundLight" TEXT NOT NULL,
+ "accentBackgroundDark" TEXT NOT NULL,
+ "accentForegroundDark" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT NOT NULL,
+
+ CONSTRAINT "theme_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "theme_id_check" CHECK ("id" = TRUE),
+ CONSTRAINT "theme_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE SET NULL
+);
+
+ALTER TABLE "theme" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Authenticated users can view themes" ON "theme"
+ FOR SELECT
+ USING (
+ auth.role() = 'authenticated'
+ );
+
+CREATE POLICY "Employees with settings_update can update themes" ON "theme"
+ FOR UPDATE
+ USING (
+ coalesce(get_my_claim('settings_update')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
+
diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sql
index 96271382d3..c9c2140f2c 100644
--- a/packages/database/supabase/seed.sql
+++ b/packages/database/supabase/seed.sql
@@ -3,6 +3,30 @@
INSERT INTO "user" ("id", "email", "firstName", "lastName")
VALUES ('system', '[email protected]', 'System', 'Operation');
+-- theme
+
+INSERT INTO "theme" (
+ "primaryBackgroundLight",
+ "primaryForegroundLight",
+ "primaryBackgroundDark",
+ "primaryForegroundDark",
+ "accentBackgroundLight",
+ "accentForegroundLight",
+ "accentBackgroundDark",
+ "accentForegroundDark",
+ "updatedBy"
+) VALUES (
+ '240 5.9% 10%',
+ '0 0% 98%',
+ '0 0% 98%',
+ '240 5.9% 10%',
+ '240 4.8% 89.9%',
+ '240 5.9% 10%',
+ '240 3.7% 15.9%',
+ '0 0% 98%',
+ 'system'
+);
+
-- currencies
INSERT INTO "currency" ("name", "code", "symbol", "exchangeRate", "decimalPlaces", "isBaseCurrency")
diff --git a/packages/utils/src/color.ts b/packages/utils/src/color.ts
new file mode 100644
index 0000000000..88c120e8dc
--- /dev/null
+++ b/packages/utils/src/color.ts
@@ -0,0 +1,86 @@
+export function hexToHls(hex: string) {
+ const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/;
+ let sColor = hex.toLowerCase();
+ if (sColor && reg.test(sColor)) {
+ if (sColor.length === 4) {
+ let sColorNew = "#";
+ for (let i = 1; i < 4; i += 1) {
+ sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
+ }
+ sColor = sColorNew;
+ }
+
+ const sColorChange = [];
+ for (let i = 1; i < 7; i += 2) {
+ sColorChange.push(parseInt(`0x${sColor.slice(i, i + 2)}`));
+ }
+ const r = sColorChange[0] / 255;
+ const g = sColorChange[1] / 255;
+ const b = sColorChange[2] / 255;
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ let h = 0;
+ let s = 0;
+ const l = (max + min) / 2;
+ if (max === min) {
+ h = 0;
+ s = 0;
+ } else {
+ const d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ default:
+ break;
+ }
+ h /= 6;
+ }
+ return `${Math.floor(h * 360)} ${Math.floor(s * 100)}% ${Math.floor(
+ l * 100
+ )}%)`;
+ }
+}
+
+function hue2rgb(p: number, q: number, t: number) {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+}
+
+export function hslToHex(hsl: string) {
+ let [h, s, l] = hsl
+ .split(" ")
+ .map((n) => n.split("%")[0])
+ .map(Number);
+
+ const h1 = h / 360;
+ const s1 = s / 100;
+ const l1 = l / 100;
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ if (s1 === 0) {
+ r = g = b = l1;
+ } else {
+ const q = l1 < 0.5 ? l1 * (1 + s1) : l1 + s1 - l1 * s1;
+ const p = 2 * l1 - q;
+ r = hue2rgb(p, q, h1 + 1 / 3);
+ g = hue2rgb(p, q, h1);
+ b = hue2rgb(p, q, h1 - 1 / 3);
+ }
+ const hex = `#${Math.floor(r * 255).toString(16)}${Math.floor(
+ g * 255
+ ).toString(16)}${Math.floor(b * 255).toString(16)}`;
+ return hex;
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 4cce6724bf..50050cb69c 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -1,4 +1,5 @@
export * from "./accounting";
+export * from "./color";
export * from "./date";
export * from "./file";
export * from "./geo";