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.

Holidays (#21)

Brad Barbin7d47b31fb498
diff --git a/SCHEMA.md b/SCHEMA.md
index 9cc2042f8c..bc0ce1b57f 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -2432,3 +2432,27 @@ COMMIT;
ALTER publication supabase_realtime ADD TABLE "user";
```
+
+
+## `holidays`
+
+```sql
+CREATE TABLE "holiday" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "date" DATE NOT NULL,
+ "year" INTEGER GENERATED ALWAYS AS (EXTRACT(YEAR FROM "date")) STORED,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP NOT NULL DEFAULT now(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP,
+
+ CONSTRAINT "holiday_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "uq_holiday_date" UNIQUE ("date"),
+ CONSTRAINT "holiday_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "holiday_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE VIEW "holiday_years" AS SELECT DISTINCT "year" FROM "holiday";
+```
+
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index 6cd88bf63e..4dd229bad4 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -78,6 +78,11 @@ export default function useBreadcrumbs(): Route[] {
name: "Equipment",
to: match.pathname,
});
+ case "routes/x+/resources+/holidays":
+ return acc.concat({
+ name: "Holidays",
+ to: match.pathname,
+ });
case "routes/x+/resources+/locations":
return acc.concat({
name: "Locations",
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/HolidayForm.tsx b/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/HolidayForm.tsx
new file mode 100644
index 0000000000..aa1e504970
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/HolidayForm.tsx
@@ -0,0 +1,76 @@
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import { DatePicker, Hidden, Input, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { holidayValidator } from "~/services/resources";
+import type { TypeOfValidator } from "~/types/validators";
+
+type HolidayFormProps = {
+ initialValues: TypeOfValidator<typeof holidayValidator>;
+};
+
+const HolidayForm = ({ initialValues }: HolidayFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "resources")
+ : !permissions.can("create", "resources");
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={holidayValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/resources/holidays/${initialValues.id}`
+ : "/x/resources/holidays/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Holiday</DrawerHeader>
+ <DrawerBody pb={8}>
+ <Hidden name="id" />
+ <VStack spacing={4} alignItems="start">
+ <Input name="name" label="Holiday Name" />
+ <DatePicker name="date" label="Date" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+
+export default HolidayForm;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/index.ts b/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/index.ts
new file mode 100644
index 0000000000..3f91d5dc18
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidayForm/index.ts
@@ -0,0 +1,3 @@
+import HolidayForm from "./HolidayForm";
+
+export default HolidayForm;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/HolidaysTable.tsx b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/HolidaysTable.tsx
new file mode 100644
index 0000000000..a0e2e9d5bd
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/HolidaysTable.tsx
@@ -0,0 +1,78 @@
+import { MenuItem } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Holiday } from "~/interfaces/Resources/types";
+
+type HolidaysTableProps = {
+ data: Holiday[];
+ count: number;
+};
+
+const HolidaysTable = memo(({ data, count }: HolidaysTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const rows = data;
+
+ const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Holiday",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "date",
+ header: "Date",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, []);
+
+ const renderContextMenu = useCallback(
+ (row: typeof data[number]) => {
+ return (
+ <>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(`/x/resources/holidays/${row.id}?${params.toString()}`);
+ }}
+ >
+ Edit Holiday
+ </MenuItem>
+ <MenuItem
+ isDisabled={!permissions.can("delete", "resources")}
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/x/resources/holidays/delete/${row.id}?${params.toString()}`
+ );
+ }}
+ >
+ Delete Holiday
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<typeof rows[number]>
+ data={rows}
+ count={count}
+ columns={columns}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+HolidaysTable.displayName = "HolidaysTable";
+export default HolidaysTable;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/index.ts b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/index.ts
new file mode 100644
index 0000000000..2db43957c4
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTable/index.ts
@@ -0,0 +1,3 @@
+import HolidaysTable from "./HolidaysTable";
+
+export default HolidaysTable;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx
new file mode 100644
index 0000000000..b7302c6cf1
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/HolidaysTableFilters.tsx
@@ -0,0 +1,77 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+
+type HolidaysTableFiltersProps = {
+ years: number[];
+};
+
+const HolidaysTableFilters = ({ years }: HolidaysTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const borderColor = useColor("gray.200");
+
+ const yearsOptions = years.map((year) => ({
+ label: year.toString(),
+ value: year,
+ }));
+
+ return (
+ <HStack
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ justifyContent="space-between"
+ px={4}
+ py={3}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Search by name"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={
+ params.get("year")
+ ? yearsOptions.filter(
+ (year) => year.value.toString() === params.get("year")
+ )
+ : {
+ label: new Date().getFullYear().toString(),
+ value: new Date().getFullYear(),
+ }
+ }
+ options={yearsOptions}
+ onChange={(selected) => {
+ setParams({ year: selected?.value });
+ }}
+ aria-label="Year"
+ minW={180}
+ placeholder="Year"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "resources") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Holiday
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default HolidaysTableFilters;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/index.ts b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/index.ts
new file mode 100644
index 0000000000..decb1648eb
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/HolidaysTableFilters/index.ts
@@ -0,0 +1,3 @@
+import HolidaysTableFilters from "./HolidaysTableFilters";
+
+export default HolidaysTableFilters;
diff --git a/apps/carbon/app/interfaces/Resources/Holidays/index.ts b/apps/carbon/app/interfaces/Resources/Holidays/index.ts
new file mode 100644
index 0000000000..0d68abbd0f
--- /dev/null
+++ b/apps/carbon/app/interfaces/Resources/Holidays/index.ts
@@ -0,0 +1,5 @@
+import HolidayForm from "./HolidayForm";
+import HolidaysTable from "./HolidaysTable";
+import HolidaysTableFilters from "./HolidaysTableFilters";
+
+export { HolidayForm, HolidaysTable, HolidaysTableFilters };
diff --git a/apps/carbon/app/interfaces/Resources/types.ts b/apps/carbon/app/interfaces/Resources/types.ts
index 3287885ca7..0ea924d339 100644
--- a/apps/carbon/app/interfaces/Resources/types.ts
+++ b/apps/carbon/app/interfaces/Resources/types.ts
@@ -16,6 +16,7 @@ import type {
getShifts,
getWorkCellTypes,
getWorkCellType,
+ getHolidays,
} from "~/services/resources";
export type Ability = NonNullable<
@@ -100,6 +101,14 @@ export type EquipmentTypeDetail = NonNullable<
Awaited<ReturnType<typeof getEquipmentType>>["data"]
>;
+export type Holiday = NonNullable<
+ Awaited<ReturnType<typeof getHolidays>>["data"]
+>[number];
+
+export type Location = NonNullable<
+ Awaited<ReturnType<typeof getLocations>>["data"]
+>[number];
+
export type Note = NonNullable<
Awaited<ReturnType<typeof getNotes>>["data"]
>[number];
diff --git a/apps/carbon/app/routes/x+/resources+/holidays.$holidayId.tsx b/apps/carbon/app/routes/x+/resources+/holidays.$holidayId.tsx
new file mode 100644
index 0000000000..d263cf1eec
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/holidays.$holidayId.tsx
@@ -0,0 +1,87 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { HolidayForm } from "~/interfaces/Resources/Holidays";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import {
+ getHoliday,
+ holidayValidator,
+ upsertHoliday,
+} from "~/services/resources";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ });
+
+ const { holidayId } = params;
+ if (!holidayId) throw notFound("Holiday ID was not found");
+
+ const holiday = await getHoliday(client, holidayId);
+
+ if (holiday.error) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, error(holiday.error, "Failed to get holiday"))
+ );
+ }
+
+ return json({
+ holiday: holiday.data,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "resources",
+ });
+
+ const validation = await holidayValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, name, date } = validation.data;
+ if (!id) throw notFound("Holiday ID was not found");
+
+ const updateHoliday = await upsertHoliday(client, {
+ id,
+ name,
+ date,
+ updatedBy: userId,
+ });
+
+ if (updateHoliday.error) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(
+ request,
+ error(updateHoliday.error, "Failed to create holiday.")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, success("Holiday updated."))
+ );
+}
+
+export default function HolidayRoute() {
+ const { holiday } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: holiday.id,
+ name: holiday.name,
+ date: holiday.date,
+ };
+
+ return <HolidayForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/resources+/holidays.delete.$holidayId.tsx b/apps/carbon/app/routes/x+/resources+/holidays.delete.$holidayId.tsx
new file mode 100644
index 0000000000..d0dce9a9a0
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/holidays.delete.$holidayId.tsx
@@ -0,0 +1,80 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { requirePermissions } from "~/services/auth";
+import { deleteHoliday, getHoliday } from "~/services/resources";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ role: "employee",
+ });
+
+ const { holidayId } = params;
+ if (!holidayId) throw notFound("holidayId not found");
+
+ const holiday = await getHoliday(client, holidayId);
+ if (holiday.error) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, error(holiday.error, "Failed to get holiday"))
+ );
+ }
+
+ return json({
+ holiday: holiday.data,
+ });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "resources",
+ });
+
+ const { holidayId } = params;
+ if (!holidayId) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, error(params, "Failed to get holiday id"))
+ );
+ }
+
+ const { error: deleteHolidayError } = await deleteHoliday(client, holidayId);
+ if (deleteHolidayError) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(
+ request,
+ error(deleteHolidayError, "Failed to delete holiday")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, success("Successfully deleted holiday"))
+ );
+}
+
+export default function DeleteHolidayRoute() {
+ const { holidayId } = useParams();
+ const { holiday } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!holidayId || !holiday) return null;
+
+ const onCancel = () => navigate("/x/resources/holidays");
+
+ return (
+ <ConfirmDelete
+ action={`/x/resources/holidays/delete/${holidayId}`}
+ name={holiday.name}
+ text={`Are you sure you want to delete the holiday: ${holiday.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/resources+/holidays.new.tsx b/apps/carbon/app/routes/x+/resources+/holidays.new.tsx
new file mode 100644
index 0000000000..ad28c6d7e9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/holidays.new.tsx
@@ -0,0 +1,59 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { HolidayForm } from "~/interfaces/Resources/Holidays";
+import { requirePermissions } from "~/services/auth";
+import { holidayValidator, upsertHoliday } from "~/services/resources";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "resources",
+ });
+
+ const validation = await holidayValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { name, date } = validation.data;
+
+ const createHoliday = await upsertHoliday(client, {
+ name,
+ date,
+ createdBy: userId,
+ });
+
+ if (createHoliday.error) {
+ return redirect(
+ "/x/resources/holidays",
+ await flash(
+ request,
+ error(createHoliday.error, "Failed to create holiday.")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/holidays",
+ await flash(request, success("Holiday created."))
+ );
+}
+
+export default function NewHolidayRoute() {
+ const initialValues = {
+ name: "",
+ date: undefined,
+ };
+
+ return (
+ <HolidayForm
+ // @ts-expect-error
+ initialValues={initialValues}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/resources+/holidays.tsx b/apps/carbon/app/routes/x+/resources+/holidays.tsx
new file mode 100644
index 0000000000..35b873e200
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/holidays.tsx
@@ -0,0 +1,64 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ HolidaysTable,
+ HolidaysTableFilters,
+} from "~/interfaces/Resources/Holidays";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { getHolidays, getHolidayYears } from "~/services/resources";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const year = searchParams.get("year");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ const [holidays, years] = await Promise.all([
+ getHolidays(client, {
+ name,
+ year: year ? parseInt(year) : new Date().getFullYear(),
+ limit,
+ offset,
+ sorts,
+ }),
+ getHolidayYears(client),
+ ]);
+
+ if (holidays.error) {
+ return redirect(
+ "/x/resources",
+ await flash(request, error(holidays.error, "Failed to load holidays"))
+ );
+ }
+
+ return json({
+ holidays: holidays.data ?? [],
+ years:
+ years?.data?.map((d) => d.year as number).sort((a, b) => b - a) ?? [],
+ count: holidays.count ?? 0,
+ });
+}
+
+export default function Route() {
+ const { holidays, years, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <HolidaysTableFilters years={years} />
+ <HolidaysTable data={holidays} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/services/resources/resources.form.ts b/apps/carbon/app/services/resources/resources.form.ts
index fea965e194..4bf6e5ee8d 100644
--- a/apps/carbon/app/services/resources/resources.form.ts
+++ b/apps/carbon/app/services/resources/resources.form.ts
@@ -124,6 +124,14 @@ export const equipmentTypeValidator = withZod(
})
);
+export const holidayValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ date: z.string().min(1, { message: "Date is required" }),
+ })
+);
+
export const locationValidator = withZod(
z
.object({
diff --git a/apps/carbon/app/services/resources/resources.server.ts b/apps/carbon/app/services/resources/resources.server.ts
index 421257d642..04465d0acb 100644
--- a/apps/carbon/app/services/resources/resources.server.ts
+++ b/apps/carbon/app/services/resources/resources.server.ts
@@ -72,6 +72,13 @@ export async function deleteEquipmentType(
.eq("id", equipmentTypeId);
}
+export async function deleteHoliday(
+ client: SupabaseClient<Database>,
+ holidayId: string
+) {
+ return client.from("holiday").delete().eq("id", holidayId);
+}
+
export async function deleteLocation(
client: SupabaseClient<Database>,
locationId: string
@@ -374,6 +381,44 @@ export async function getEquipmentTypes(
return query;
}
+export async function getHoliday(
+ client: SupabaseClient<Database>,
+ holidayId: string
+) {
+ return client
+ .from("holiday")
+ .select(`id, name, date, year`)
+ .eq("id", holidayId)
+ .single();
+}
+
+export async function getHolidays(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null; year: number | null }
+) {
+ let query = client.from("holiday").select(`id, name, date, year`, {
+ count: "exact",
+ });
+
+ if (args?.name) {
+ query = query.ilike("name", `%${args.name}%`);
+ }
+
+ if (args?.year) {
+ query = query.eq("year", args.year);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "date");
+ }
+
+ return query;
+}
+
+export function getHolidayYears(client: SupabaseClient<Database>) {
+ return client.from("holiday_years").select("year");
+}
+
export async function getLocation(
client: SupabaseClient<Database>,
locationId: string
@@ -941,6 +986,27 @@ export async function upsertEquipmentType(
return client.from("equipmentType").insert([equipmentType]).select("id");
}
+export async function upsertHoliday(
+ client: SupabaseClient<Database>,
+ holiday:
+ | {
+ name: string;
+ date: string;
+ createdBy: string;
+ }
+ | {
+ id: string;
+ name: string;
+ date: string;
+ updatedBy: string;
+ }
+) {
+ if ("id" in holiday) {
+ return client.from("holiday").update(holiday).eq("id", holiday.id);
+ }
+ return client.from("holiday").insert(holiday).select("id");
+}
+
export async function upsertLocation(
client: SupabaseClient<Database>,
location:
diff --git a/apps/carbon/app/utils/query.ts b/apps/carbon/app/utils/query.ts
index c12bac48a1..a07f044e01 100644
--- a/apps/carbon/app/utils/query.ts
+++ b/apps/carbon/app/utils/query.ts
@@ -97,7 +97,8 @@ export function setGenericQueryFilters<
>(
query: PostgrestFilterBuilder<T, U, V>,
args: GenericQueryFilters,
- defaultSort?: string
+ defaultSort?: string,
+ defaultAsc = true
): PostgrestFilterBuilder<T, U, V> {
args.filters?.forEach((filter) => {
if (!filter.value) return;
@@ -122,7 +123,7 @@ export function setGenericQueryFilters<
});
} else if (defaultSort) {
query = query.order(defaultSort, {
- ascending: true,
+ ascending: defaultAsc,
});
}
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index e1a9b82258..d5ef9924c3 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -702,6 +702,38 @@ export interface Database {
createdAt?: string;
};
};
+ holiday: {
+ Row: {
+ name: string;
+ date: string;
+ createdBy: string;
+ updatedBy: string | null;
+ updatedAt: string | null;
+ id: string;
+ year: number | null;
+ createdAt: string;
+ };
+ Insert: {
+ name: string;
+ date: string;
+ createdBy: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ id?: string;
+ year?: number | null;
+ createdAt?: string;
+ };
+ Update: {
+ name?: string;
+ date?: string;
+ createdBy?: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ id?: string;
+ year?: number | null;
+ createdAt?: string;
+ };
+ };
location: {
Row: {
name: string;
@@ -1303,6 +1335,11 @@ export interface Database {
users: Json | null;
};
};
+ holiday_years: {
+ Row: {
+ year: number | null;
+ };
+ };
};
Functions: {
_xid_machine_id: {
diff --git a/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql b/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql
new file mode 100644
index 0000000000..d356ec3aeb
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230315222231_holidays.sql
@@ -0,0 +1,17 @@
+CREATE TABLE "holiday" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "date" DATE NOT NULL,
+ "year" INTEGER GENERATED ALWAYS AS (EXTRACT(YEAR FROM "date")) STORED,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP NOT NULL DEFAULT now(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP,
+
+ CONSTRAINT "holiday_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "uq_holiday_date" UNIQUE ("date"),
+ CONSTRAINT "holiday_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "holiday_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE VIEW "holiday_years" AS SELECT DISTINCT "year" FROM "holiday";
\ No newline at end of file