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: break notes out into separate component (#41)

Brad Barbin9cc3716502ba
diff --git a/SCHEMA.md b/SCHEMA.md
index 1f394d1d3c..2936a06d1b 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -1953,9 +1953,9 @@ CREATE POLICY "Employees with purchasing_delete can delete supplier contacts" ON
## `notes`
```sql
-CREATE TABLE "userNote" (
+CREATE TABLE "note" (
"id" TEXT NOT NULL DEFAULT xid(),
- "userId" TEXT NOT NULL,
+ "documentId" TEXT NOT NULL,
"note" TEXT NOT NULL,
"noteRichText" JSONB NOT NULL DEFAULT '{}'::jsonb,
"active" BOOLEAN NOT NULL DEFAULT true,
@@ -1964,48 +1964,39 @@ CREATE TABLE "userNote" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "notes_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "notes_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "notes_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-ALTER TABLE "userNote" ENABLE ROW LEVEL SECURITY;
+CREATE INDEX "notes_documentId_index" ON "note"("documentId");
+
+ALTER TABLE "note" ENABLE ROW LEVEL SECURITY;
-CREATE POLICY "Employees with resources_view can view notes" ON "userNote"
+CREATE POLICY "Employees can view notes" ON "note"
FOR SELECT
USING (
- coalesce(get_my_claim('resources_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Employees with resources_create can insert notes" ON "userNote"
+CREATE POLICY "Employees can insert notes" ON "note"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('resources_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Employees with resources_update can update their own notes" ON "userNote"
+CREATE POLICY "Employees can update their own notes" ON "note"
FOR UPDATE
USING (
- coalesce(get_my_claim('resources_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
AND "createdBy"::uuid = auth.uid()
);
-CREATE POLICY "Employees with resources_update can delete their own notes" ON "userNote"
+CREATE POLICY "Employees can delete their own notes" ON "note"
FOR DELETE
USING (
- coalesce(get_my_claim('resources_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
AND "createdBy"::uuid = auth.uid()
);
-CREATE POLICY "Employees with resources_delete can delete any note" ON "userNote"
- FOR UPDATE
- USING (
- coalesce(get_my_claim('resources_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
```
diff --git a/apps/carbon/app/components/Layout/SectionTitle/SectionTitle.tsx b/apps/carbon/app/components/Layout/SectionTitle/SectionTitle.tsx
index 29bcd76731..75423618c1 100644
--- a/apps/carbon/app/components/Layout/SectionTitle/SectionTitle.tsx
+++ b/apps/carbon/app/components/Layout/SectionTitle/SectionTitle.tsx
@@ -2,14 +2,13 @@ import type { StackProps } from "@chakra-ui/react";
import { Heading, Text, VStack } from "@chakra-ui/react";
type SectionTitleProps = StackProps & {
- title: string;
subtitle?: string;
};
-const SectionTitle = ({ title, subtitle, ...props }: SectionTitleProps) => {
+const SectionTitle = ({ children, subtitle, ...props }: SectionTitleProps) => {
return (
<VStack spacing={2} alignItems="start" w="full" my={4} {...props}>
- <Heading size="md">{title}</Heading>
+ <Heading size="md">{children}</Heading>
{subtitle && (
<Text fontSize={14} color="gray.500">
{subtitle}
diff --git a/apps/carbon/app/modules/account/ui/Profile/ProfileForm/ProfileForm.tsx b/apps/carbon/app/modules/account/ui/Profile/ProfileForm/ProfileForm.tsx
index 86251563c2..f8e0b9c12a 100644
--- a/apps/carbon/app/modules/account/ui/Profile/ProfileForm/ProfileForm.tsx
+++ b/apps/carbon/app/modules/account/ui/Profile/ProfileForm/ProfileForm.tsx
@@ -16,7 +16,7 @@ const ProfileForm = ({ user }: ProfileFormProps) => {
return (
<Box w="full">
- <SectionTitle title="Basic Information" />
+ <SectionTitle>Basic Information</SectionTitle>
<ValidatedForm
method="post"
action={
diff --git a/apps/carbon/app/modules/inventory/services/inventory.form.ts b/apps/carbon/app/modules/inventory/services/inventory.form.ts
index 9b65ef533d..a9ed111ccf 100644
--- a/apps/carbon/app/modules/inventory/services/inventory.form.ts
+++ b/apps/carbon/app/modules/inventory/services/inventory.form.ts
@@ -15,7 +15,7 @@ export const receiptSourceDocumentType = [
export const receiptValidator = withZod(
z.object({
- id: zfd.text(z.string().optional()),
+ id: z.string().min(1),
receiptId: z.string().min(1, { message: "Receipt ID is required" }),
locationId: zfd.text(z.string().optional()),
sourceDocument: z.enum(receiptSourceDocumentType).optional(),
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
index aa0e6218ec..50725b14e7 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -9,7 +9,6 @@ import {
DrawerFooter,
DrawerHeader,
DrawerOverlay,
- FormLabel,
Grid,
HStack,
VStack,
@@ -24,17 +23,21 @@ import {
Submit,
} from "~/components/Form";
import DataGrid from "~/components/Grid";
+import { SectionTitle } from "~/components/Layout";
import type { ReceiptLine, ReceiptSourceDocument } from "~/modules/inventory";
import {
receiptSourceDocumentType,
receiptValidator,
} from "~/modules/inventory";
+import type { Note } from "~/modules/shared";
+import { Notes } from "~/modules/shared";
import type { TypeOfValidator } from "~/types/validators";
import useReceiptForm from "./useReceiptForm";
type ReceiptFormProps = {
initialValues: TypeOfValidator<typeof receiptValidator>;
isPosted: boolean;
+ notes: Note[];
receiptLines?: ReceiptLine[];
};
@@ -43,14 +46,15 @@ const formId = "receipt-form";
const ReceiptForm = ({
initialValues,
isPosted,
+ notes,
receiptLines,
}: ReceiptFormProps) => {
const {
editableComponents,
locationId,
locations,
- internalReceiptItems,
- isEditing,
+ internalReceiptLines,
+ canPost,
isDisabled,
receiptLineColumns,
sourceDocumentId,
@@ -69,149 +73,126 @@ const ReceiptForm = ({
return (
<>
<Drawer onClose={onClose} isOpen={true} size="full">
- <ValidatedForm
- id={formId}
- validator={receiptValidator}
- method="post"
- action={
- isEditing
- ? `/x/inventory/receipts/${initialValues.id}`
- : `/x/inventory/receipts/new`
- }
- defaultValues={initialValues}
- style={{ width: "100%" }}
- >
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>{initialValues.receiptId}</DrawerHeader>
- <DrawerBody pb={8}>
- <VStack spacing={4} w="full" alignItems="start">
- <Menubar mb={2} mt={-2}>
- <MenubarItem
- isDisabled={!isEditing || isPosted}
- onClick={onPost}
- >
- Post Receipt
- </MenubarItem>
- </Menubar>
- <Grid
- gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
- gridColumnGap={8}
- w="full"
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{initialValues.receiptId}</DrawerHeader>
+ <DrawerBody pb={8}>
+ <VStack spacing={4} w="full" alignItems="start">
+ <Menubar mb={2} mt={-2}>
+ <MenubarItem isDisabled={!canPost || isPosted} onClick={onPost}>
+ Post Receipt
+ </MenubarItem>
+ </Menubar>
+
+ <Box w="full">
+ <ValidatedForm
+ id={formId}
+ validator={receiptValidator}
+ method="post"
+ action={`/x/inventory/receipts/${initialValues.id}`}
+ defaultValues={initialValues}
+ style={{ width: "100%" }}
>
- <Box w="full">
- <Hidden name="id" />
- <Hidden
- name="sourceDocumentReadableId"
- value={
- sourceDocuments.find((d) => d.id === sourceDocumentId)
- ?.name ?? ""
- }
- />
- <Hidden name="supplierId" value={supplierId ?? ""} />
- <VStack spacing={4} w="full" alignItems="start" minH="full">
- <Grid
- gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
- gridColumnGap={8}
- gridRowGap={4}
- w="full"
- >
- <Input name="receiptId" label="Receipt ID" isReadOnly />
- <SelectControlled
- name="locationId"
- label="Location"
- options={
- locations.map((l) => ({
- label: l.name,
- value: l.id,
- })) ?? []
- }
- value={locationId ?? undefined}
- onChange={(newValue) =>
- setLocationId(newValue as string)
- }
- isReadOnly={isPosted}
- />
- <Select
- name="sourceDocument"
- label="Source Document"
- options={receiptSourceDocumentType.map((v) => ({
- label: v,
- value: v,
- }))}
- onChange={(newValue) => {
- setSourceDocument(
- newValue.value as ReceiptSourceDocument
- );
- setSourceDocumentId(null);
- }}
- isReadOnly={isPosted}
- />
- <SelectControlled
- name="sourceDocumentId"
- label="Source Document ID"
- options={sourceDocuments.map((d) => ({
- label: d.name,
- value: d.id,
- }))}
- value={sourceDocumentId ?? undefined}
- onChange={(newValue) => {
- setSourceDocumentId(newValue as string);
- }}
- isReadOnly={isPosted}
- />
- <Input
- name="externalDocumentId"
- label="External Reference"
- />
- </Grid>
- </VStack>
- </Box>
- <VStack
- spacing={8}
- w="full"
- alignItems="start"
- py={[8, 8, 0]}
- >
- {/* TODO: notes component */}
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="flex-start">
- <FormLabel>Notes</FormLabel>
- </HStack>
- </VStack>
- {/* end notes component */}
- </VStack>
- </Grid>
- <VStack w="full" alignItems="start">
- <FormLabel>Receipt Lines</FormLabel>
- <DataGrid<ReceiptLine>
- data={internalReceiptItems}
- columns={receiptLineColumns}
- canEdit={!isPosted}
- contained={false}
- editableComponents={editableComponents}
+ <Hidden name="id" />
+ <Hidden
+ name="sourceDocumentReadableId"
+ value={
+ sourceDocuments.find((d) => d.id === sourceDocumentId)
+ ?.name ?? ""
+ }
/>
- </VStack>
+ <Hidden name="supplierId" value={supplierId ?? ""} />
+ <VStack spacing={4} w="full" alignItems="start" minH="full">
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
+ gridColumnGap={8}
+ gridRowGap={4}
+ w="full"
+ >
+ <Input name="receiptId" label="Receipt ID" isReadOnly />
+ <SelectControlled
+ name="locationId"
+ label="Location"
+ options={
+ locations.map((l) => ({
+ label: l.name,
+ value: l.id,
+ })) ?? []
+ }
+ value={locationId ?? undefined}
+ onChange={(newValue) =>
+ setLocationId(newValue as string)
+ }
+ isReadOnly={isPosted}
+ />
+ <Select
+ name="sourceDocument"
+ label="Source Document"
+ options={receiptSourceDocumentType.map((v) => ({
+ label: v,
+ value: v,
+ }))}
+ onChange={(newValue) => {
+ setSourceDocument(
+ newValue.value as ReceiptSourceDocument
+ );
+ setSourceDocumentId(null);
+ }}
+ isReadOnly={isPosted}
+ />
+ <SelectControlled
+ name="sourceDocumentId"
+ label="Source Document ID"
+ options={sourceDocuments.map((d) => ({
+ label: d.name,
+ value: d.id,
+ }))}
+ value={sourceDocumentId ?? undefined}
+ onChange={(newValue) => {
+ setSourceDocumentId(newValue as string);
+ }}
+ isReadOnly={isPosted}
+ />
+ <Input
+ name="externalDocumentId"
+ label="External Reference"
+ />
+ </Grid>
+ </VStack>
+ </ValidatedForm>
+ </Box>
+
+ <VStack w="full" alignItems="start">
+ <SectionTitle>Receipt Lines</SectionTitle>
+ <DataGrid<ReceiptLine>
+ data={internalReceiptLines}
+ columns={receiptLineColumns}
+ canEdit={!isPosted}
+ contained={false}
+ editableComponents={editableComponents}
+ />
</VStack>
- </DrawerBody>
- <DrawerFooter>
- <HStack spacing={2}>
- <Submit formId={formId} isDisabled={isDisabled}>
- Save
- </Submit>
- <Button
- size="md"
- colorScheme="gray"
- variant="solid"
- onClick={onClose}
- >
- Cancel
- </Button>
- </HStack>
- </DrawerFooter>
- </DrawerContent>
- </ValidatedForm>
+
+ <Notes notes={notes} documentId={initialValues.id} />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit formId={formId} isDisabled={isDisabled}>
+ Save
+ </Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
</Drawer>
<Outlet />
</>
diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
index c28158e32d..1dbff16e8a 100644
--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx
@@ -1,4 +1,4 @@
-import { useMatches, useNavigate } from "@remix-run/react";
+import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useState } from "react";
import { EditableNumber } from "~/components/Editable";
@@ -29,17 +29,17 @@ export default function useReceiptForm({
const { supabase } = useSupabase();
const isDisabled = !permissions.can("update", "inventory");
- const isEditing = !useMatches().some(({ pathname }) =>
- pathname.includes("new")
- );
const routeData = useRouteData<{
locations: ListItem[];
}>("/x/inventory/receipts");
- const [internalReceiptItems, setReceiptItems] = useState<ReceiptLine[]>(
+ const [internalReceiptLines, setReceiptLines] = useState<ReceiptLine[]>(
receiptLines ?? []
);
+ const canPost =
+ internalReceiptLines.length > 0 &&
+ internalReceiptLines.some((l) => l.receivedQuantity > 0);
const [locationId, setLocationId] = useState<string | null>(
receipt.locationId ?? user.defaults.locationId ?? null
@@ -58,18 +58,11 @@ export default function useReceiptForm({
);
const onClose = async () => {
- if (
- !isEditing &&
- (!sourceDocumentId || !locationId || receiptLines.length === 0)
- ) {
+ if (!sourceDocumentId || !locationId || internalReceiptLines.length === 0) {
await deleteReceipt();
}
- if (isEditing) {
- navigate(`/x/inventory/receipts`);
- } else {
- navigate(-1);
- }
+ navigate("/x/inventory/receipts");
};
const onPost = () => {
@@ -102,7 +95,7 @@ export default function useReceiptForm({
method: "DELETE",
}
)
- .then(console.log)
+ .then(() => console.log("successfully rolled back receipt sequence"))
.catch(console.error);
await supabase
@@ -114,7 +107,7 @@ export default function useReceiptForm({
}
}, [receipt.receiptId, supabase]);
- const deleteReceiptItems = useCallback(async () => {
+ const deleteReceiptLines = useCallback(async () => {
if (!supabase) throw new Error("supabase client is not defined");
return supabase
@@ -187,7 +180,7 @@ export default function useReceiptForm({
if (purchaseOrder.error) {
setError(purchaseOrder.error.message);
- setReceiptItems([]);
+ setReceiptLines([]);
break;
} else {
setSupplierId(purchaseOrder.data.supplierId);
@@ -195,7 +188,7 @@ export default function useReceiptForm({
if (receiptLines.error) {
setError(receiptLines.error.message);
- setReceiptItems([]);
+ setReceiptLines([]);
break;
}
@@ -204,11 +197,11 @@ export default function useReceiptForm({
receiptLines.data.length > 0
) {
// no need to insert and fetch lines if they already exist
- setReceiptItems(receiptLines.data);
+ setReceiptLines(receiptLines.data);
break;
}
- const deleteExistingLines = await deleteReceiptItems();
+ const deleteExistingLines = await deleteReceiptLines();
if (deleteExistingLines.error) {
setError(deleteExistingLines.error.message);
break;
@@ -265,7 +258,7 @@ export default function useReceiptForm({
if (insertError) {
setError(insertError.message);
- setReceiptItems([]);
+ setReceiptLines([]);
break;
}
@@ -276,17 +269,17 @@ export default function useReceiptForm({
if (selectError) {
setError(selectError.message);
- setReceiptItems([]);
+ setReceiptLines([]);
break;
}
- setReceiptItems(receiptLinesData ?? []);
+ setReceiptLines(receiptLinesData ?? []);
break;
default:
return;
}
}, [
- deleteReceiptItems,
+ deleteReceiptLines,
locationId,
receipt.receiptId,
receipt.sourceDocumentId,
@@ -381,8 +374,8 @@ export default function useReceiptForm({
error,
locationId,
locations: routeData?.locations ?? [],
- internalReceiptItems,
- isEditing,
+ internalReceiptLines,
+ canPost,
isDisabled,
receiptLineColumns,
sourceDocument,
diff --git a/apps/carbon/app/modules/resources/services/resources.form.ts b/apps/carbon/app/modules/resources/services/resources.form.ts
index a6478074bc..26286020c0 100644
--- a/apps/carbon/app/modules/resources/services/resources.form.ts
+++ b/apps/carbon/app/modules/resources/services/resources.form.ts
@@ -171,13 +171,6 @@ export const locationValidator = withZod(
})
);
-export const noteValidator = withZod(
- z.object({
- id: zfd.text(z.string().optional()),
- note: z.string().min(1, { message: "Note is required" }),
- })
-);
-
export const partnerValidator = withZod(
z.object({
id: z.string().min(20, { message: "Supplier Location is required" }),
diff --git a/apps/carbon/app/modules/resources/services/resources.server.ts b/apps/carbon/app/modules/resources/services/resources.server.ts
index 05f4022b40..7db45864a1 100644
--- a/apps/carbon/app/modules/resources/services/resources.server.ts
+++ b/apps/carbon/app/modules/resources/services/resources.server.ts
@@ -96,13 +96,6 @@ export async function deleteLocation(
return client.from("location").delete().eq("id", locationId);
}
-export async function deleteNote(
- client: SupabaseClient<Database>,
- noteId: string
-) {
- return client.from("userNote").update({ active: false }).eq("id", noteId);
-}
-
export async function deletePartner(
client: SupabaseClient<Database>,
partnerId: string
@@ -496,22 +489,6 @@ export async function getLocationsList(client: SupabaseClient<Database>) {
return client.from("location").select(`id, name`);
}
-export async function getNotes(
- client: SupabaseClient<Database>,
- userId: string
-) {
- return client
- .from("userNote")
- .select(
- // need to use user!notes_createdBy_fkey instead of user because there
- // are two possible users that could be joined on (the other is userId)
- "id, note, createdAt, user!notes_createdBy_fkey(id, fullName, avatarUrl)"
- )
- .eq("userId", userId)
- .eq("active", true)
- .order("createdAt");
-}
-
export async function getPartner(
client: SupabaseClient<Database>,
partnerId: string
@@ -637,7 +614,7 @@ export async function getPeople(
const userIds = employees.data.map((employee) => {
if (!employee.user || Array.isArray(employee.user))
throw new Error("employee.user is an array");
- return employee.user.id;
+ return employee.user?.id;
});
const attributeCategories = await getAttributes(client, userIds);
@@ -647,7 +624,7 @@ export async function getPeople(
if (!employee.user || Array.isArray(employee.user))
throw new Error("employee.user is an array");
- const userId = employee.user.id;
+ const userId = employee.user?.id;
const employeeAttributes =
attributeCategories.data.reduce<PersonAttributes>((acc, category) => {
@@ -850,17 +827,6 @@ export async function insertAttributeCategory(
.single();
}
-export async function insertNote(
- client: SupabaseClient<Database>,
- note: {
- userId: string;
- note: string;
- createdBy: string;
- }
-) {
- return client.from("userNote").insert([note]).select("id").single();
-}
-
export async function updateAbility(
client: SupabaseClient<Database>,
id: string,
diff --git a/apps/carbon/app/modules/resources/types.ts b/apps/carbon/app/modules/resources/types.ts
index 85611b04a2..91b883ea8e 100644
--- a/apps/carbon/app/modules/resources/types.ts
+++ b/apps/carbon/app/modules/resources/types.ts
@@ -1,24 +1,23 @@
import type {
- getAbility,
getAbilities,
+ getAbility,
getAttribute,
getAttributeCategories,
getAttributeCategory,
+ getContractors,
getDepartments,
getEmployeeAbilities,
getEmployeeJob,
- getEquipmentTypes,
- getEquipmentType,
getEquipment,
+ getEquipmentType,
+ getEquipmentTypes,
+ getHolidays,
getLocations,
- getNotes,
getPartners,
getPeople,
getShifts,
- getWorkCellTypes,
getWorkCellType,
- getHolidays,
- getContractors,
+ getWorkCellTypes,
} from "./services";
export type Ability = NonNullable<
@@ -115,10 +114,6 @@ export type Location = NonNullable<
Awaited<ReturnType<typeof getLocations>>["data"]
>[number];
-export type Note = NonNullable<
- Awaited<ReturnType<typeof getNotes>>["data"]
->[number];
-
export type Partner = NonNullable<
Awaited<ReturnType<typeof getPartners>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx b/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
index 7b320acf0e..678b67fcdd 100644
--- a/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
+++ b/apps/carbon/app/modules/resources/ui/Person/PersonJob/PersonJob.tsx
@@ -59,7 +59,7 @@ const PersonJob = ({ job }: PersonJobProps) => {
shiftId: job.shiftId ?? undefined,
}}
>
- <SectionTitle title="Job" />
+ <SectionTitle>Job</SectionTitle>
<VStack w="full" alignItems="start" spacing={4}>
<Input name="title" label="Title" />
<DatePicker name="startDate" label="Start Date" />
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonNotes/index.ts b/apps/carbon/app/modules/resources/ui/Person/PersonNotes/index.ts
deleted file mode 100644
index e58b216aef..0000000000
--- a/apps/carbon/app/modules/resources/ui/Person/PersonNotes/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import PersonNotes from "./PersonNotes";
-
-export default PersonNotes;
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonTabs/PersonTabs.tsx b/apps/carbon/app/modules/resources/ui/Person/PersonTabs/PersonTabs.tsx
index c1e84ac2c6..3a535c31d7 100644
--- a/apps/carbon/app/modules/resources/ui/Person/PersonTabs/PersonTabs.tsx
+++ b/apps/carbon/app/modules/resources/ui/Person/PersonTabs/PersonTabs.tsx
@@ -1,37 +1,43 @@
import {
+ Box,
Card,
CardBody,
+ Icon,
Tab,
- Tabs,
TabList,
TabPanel,
TabPanels,
- Box,
- Icon,
+ Tabs,
} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
import { BiLockAlt } from "react-icons/bi";
import { SectionTitle } from "~/components/Layout";
+import type { PrivateAttributes, PublicAttributes } from "~/modules/account";
import { ProfileForm, UserAttributesForm } from "~/modules/account";
-import type { PublicAttributes, PrivateAttributes } from "~/modules/account";
-import { PersonJob, PersonNotes } from "~/modules/resources";
-import type { EmployeeJob, Note } from "~/modules/resources";
+import type { EmployeeJob } from "~/modules/resources";
+import { PersonJob } from "~/modules/resources";
+import type { Note } from "~/modules/shared";
+import { Notes } from "~/modules/shared";
import type { User } from "~/modules/users";
type PersonTabsProps = {
user: User;
job: EmployeeJob;
+ notes: Note[];
publicAttributes: PublicAttributes[];
privateAttributes: PrivateAttributes[];
- notes: Note[];
};
const PersonsTabs = ({
user,
job,
+ notes,
publicAttributes,
privateAttributes,
- notes,
}: PersonTabsProps) => {
+ const { personId } = useParams();
+ if (!personId) throw new Error("Missing personId");
+
return (
<Card w="full">
<CardBody>
@@ -59,7 +65,7 @@ const PersonsTabs = ({
{publicAttributes.length ? (
publicAttributes.map((category: PublicAttributes) => (
<Box key={category.id} mb={8} w="full">
- <SectionTitle title={category.name} />
+ <SectionTitle>{category.name}</SectionTitle>
<UserAttributesForm attributeCategory={category} />
</Box>
))
@@ -73,7 +79,7 @@ const PersonsTabs = ({
{privateAttributes.length ? (
privateAttributes.map((category: PrivateAttributes) => (
<Box key={category.id} mb={8} w="full">
- <SectionTitle title={category.name} />
+ <SectionTitle>{category.name}</SectionTitle>
<UserAttributesForm attributeCategory={category} />
</Box>
))
@@ -84,7 +90,7 @@ const PersonsTabs = ({
)}
</TabPanel>
<TabPanel>
- <PersonNotes notes={notes} />
+ <Notes documentId={personId} notes={notes} />
</TabPanel>
</TabPanels>
</Tabs>
diff --git a/apps/carbon/app/modules/resources/ui/Person/index.ts b/apps/carbon/app/modules/resources/ui/Person/index.ts
index 607a4e6de9..381886c702 100644
--- a/apps/carbon/app/modules/resources/ui/Person/index.ts
+++ b/apps/carbon/app/modules/resources/ui/Person/index.ts
@@ -2,7 +2,6 @@ import PersonAbilities from "./PersonAbilities";
import PersonDaysOff from "./PersonDaysOff";
import PersonHeader from "./PersonHeader";
import PersonJob from "./PersonJob";
-import PersonNotes from "./PersonNotes";
import PersonOvertime from "./PersonOvertime";
import PersonTabs from "./PersonTabs";
@@ -11,7 +10,6 @@ export {
PersonDaysOff,
PersonHeader,
PersonJob,
- PersonNotes,
PersonOvertime,
PersonTabs,
};
diff --git a/apps/carbon/app/modules/resources/ui/index.ts b/apps/carbon/app/modules/resources/ui/index.ts
index ed44bba848..49ebce3757 100644
--- a/apps/carbon/app/modules/resources/ui/index.ts
+++ b/apps/carbon/app/modules/resources/ui/index.ts
@@ -1,6 +1,5 @@
import useResourcesSidebar from "./useResourcesSidebar";
-export { useResourcesSidebar };
export * from "./Abilities";
export * from "./Attributes";
export * from "./Contractors";
@@ -13,3 +12,4 @@ export * from "./People";
export * from "./Person";
export * from "./Shifts";
export * from "./WorkCells";
+export { useResourcesSidebar };
diff --git a/apps/carbon/app/modules/shared/index.ts b/apps/carbon/app/modules/shared/index.ts
new file mode 100644
index 0000000000..83b8af135e
--- /dev/null
+++ b/apps/carbon/app/modules/shared/index.ts
@@ -0,0 +1,3 @@
+export * from "./services";
+export * from "./types";
+export * from "./ui";
diff --git a/apps/carbon/app/modules/shared/services/index.ts b/apps/carbon/app/modules/shared/services/index.ts
new file mode 100644
index 0000000000..cffa448b28
--- /dev/null
+++ b/apps/carbon/app/modules/shared/services/index.ts
@@ -0,0 +1,2 @@
+export * from "./shared.form";
+export * from "./shared.server";
diff --git a/apps/carbon/app/modules/shared/services/shared.form.ts b/apps/carbon/app/modules/shared/services/shared.form.ts
new file mode 100644
index 0000000000..59ea9151f8
--- /dev/null
+++ b/apps/carbon/app/modules/shared/services/shared.form.ts
@@ -0,0 +1,11 @@
+import { withZod } from "@remix-validated-form/with-zod";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+
+export const noteValidator = withZod(
+ z.object({
+ id: zfd.text(z.string().optional()),
+ documentId: z.string().min(1),
+ note: z.string().min(1, { message: "Note is required" }),
+ })
+);
diff --git a/apps/carbon/app/modules/shared/services/shared.server.ts b/apps/carbon/app/modules/shared/services/shared.server.ts
new file mode 100644
index 0000000000..fa09a40648
--- /dev/null
+++ b/apps/carbon/app/modules/shared/services/shared.server.ts
@@ -0,0 +1,40 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+export async function deleteNote(
+ client: SupabaseClient<Database>,
+ noteId: string
+) {
+ return client.from("note").update({ active: false }).eq("id", noteId);
+}
+
+export async function getNotes(
+ client: SupabaseClient<Database>,
+ documentId: string
+) {
+ return client
+ .from("note")
+ .select("id, note, createdAt, user(id, fullName, avatarUrl)")
+ .eq("documentId", documentId)
+ .eq("active", true)
+ .order("createdAt");
+}
+
+export async function insertNote(
+ client: SupabaseClient<Database>,
+ note: {
+ note: string;
+ documentId: string;
+ createdBy: string;
+ }
+) {
+ return client.from("note").insert([note]).select("id").single();
+}
+
+export async function updateNote(
+ client: SupabaseClient<Database>,
+ id: string,
+ note: string
+) {
+ return client.from("note").update({ note }).eq("id", id);
+}
diff --git a/apps/carbon/app/modules/shared/types.ts b/apps/carbon/app/modules/shared/types.ts
new file mode 100644
index 0000000000..14a7d265be
--- /dev/null
+++ b/apps/carbon/app/modules/shared/types.ts
@@ -0,0 +1,5 @@
+import type { getNotes } from "./services";
+
+export type Note = NonNullable<
+ Awaited<ReturnType<typeof getNotes>>["data"]
+>[number];
diff --git a/apps/carbon/app/modules/resources/ui/Person/PersonNotes/PersonNotes.tsx b/apps/carbon/app/modules/shared/ui/Notes/Notes.tsx
similarity index 53%
rename from apps/carbon/app/modules/resources/ui/Person/PersonNotes/PersonNotes.tsx
rename to apps/carbon/app/modules/shared/ui/Notes/Notes.tsx
index ad06513103..4c51549a4a 100644
--- a/apps/carbon/app/modules/resources/ui/Person/PersonNotes/PersonNotes.tsx
+++ b/apps/carbon/app/modules/shared/ui/Notes/Notes.tsx
@@ -9,36 +9,34 @@ import {
Text,
VStack,
} from "@chakra-ui/react";
-import { Form, useParams } from "@remix-run/react";
+import { Form } from "@remix-run/react";
import { Fragment } from "react";
import { ValidatedForm } from "remix-validated-form";
import { Avatar } from "~/components";
-import { RichText, Submit } from "~/components/Form";
+import { Hidden, RichText, Submit } from "~/components/Form";
import { SectionTitle } from "~/components/Layout";
import { usePermissions, useUser } from "~/hooks";
-import type { Note } from "~/modules/resources";
-import { noteValidator } from "~/modules/resources";
+import type { Note } from "~/modules/shared";
+import { noteValidator } from "~/modules/shared";
-type PersonNoteProps = {
+type NotesProps = {
+ documentId: string;
notes: Note[];
};
-const PersonNotes = ({ notes }: PersonNoteProps) => {
+const Notes = ({ documentId, notes }: NotesProps) => {
const user = useUser();
const permissions = usePermissions();
-
- const { personId } = useParams();
- if (!personId) throw new Error("Missing personId");
-
- const canCreate = permissions.can("create", "resources");
- const canUpdate = permissions.can("update", "resources");
- const canDelete = permissions.can("delete", "resources");
+ const isEmployee = permissions.is("employee");
const borderColor = useColor("gray.200");
+ if (!isEmployee) return null;
+
return (
<Box w="full">
- <SectionTitle title="Notes" />
+ <SectionTitle>Notes</SectionTitle>
+
{notes.length > 0 ? (
<Grid
gridTemplateColumns="auto 1fr"
@@ -47,10 +45,11 @@ const PersonNotes = ({ notes }: PersonNoteProps) => {
w="full"
>
{notes.map((note) => {
- if (Array.isArray(note.user)) throw new Error("Invalid user");
+ if (!note.user || Array.isArray(note.user))
+ throw new Error("Invalid user");
return (
<Fragment key={note.id}>
- <Avatar path={user.avatarUrl} />
+ <Avatar path={note.user.avatarUrl} />
<VStack spacing={1} w="full" alignItems="start">
<Text fontWeight="bold">{note.user?.fullName}</Text>
<HTML text={note.note} />
@@ -58,10 +57,10 @@ const PersonNotes = ({ notes }: PersonNoteProps) => {
<Text color="gray.500">
{formatTimeAgo(note.createdAt)}
</Text>
- {(canDelete || canUpdate) && user.id === note.user?.id && (
+ {user.id === note.user.id && (
<Form
method="post"
- action={`/x/resources/person/${personId}/notes/delete/${note.id}`}
+ action={`/x/shared/notes/${note.id}/delete`}
>
<Button
type="submit"
@@ -84,33 +83,33 @@ const PersonNotes = ({ notes }: PersonNoteProps) => {
No notes
</Box>
)}
- {canCreate && (
- <Box pt={8} w="full">
- <ValidatedForm
- method="post"
- action={`/x/resources/person/${personId}/notes/new`}
- resetAfterSubmit
- validator={noteValidator}
- >
- <VStack spacing={3} w="full">
- <Box
- w="full"
- borderColor={borderColor}
- borderWidth={1}
- borderStyle="solid"
- borderRadius="md"
- >
- <RichText name="note" minH={160} />
- </Box>
- <Flex justifyContent="flex-end" w="full">
- <Submit>Comment</Submit>
- </Flex>
- </VStack>
- </ValidatedForm>
- </Box>
- )}
+
+ <Box pt={8} w="full">
+ <ValidatedForm
+ method="post"
+ action={`/x/shared/notes/new`}
+ resetAfterSubmit
+ validator={noteValidator}
+ >
+ <Hidden name="documentId" value={documentId} />
+ <VStack spacing={3} w="full">
+ <Box
+ w="full"
+ borderColor={borderColor}
+ borderWidth={1}
+ borderStyle="solid"
+ borderRadius="md"
+ >
+ <RichText name="note" minH={160} />
+ </Box>
+ <Flex justifyContent="flex-end" w="full">
+ <Submit>Add Note</Submit>
+ </Flex>
+ </VStack>
+ </ValidatedForm>
+ </Box>
</Box>
);
};
-export default PersonNotes;
+export default Notes;
diff --git a/apps/carbon/app/modules/shared/ui/Notes/index.ts b/apps/carbon/app/modules/shared/ui/Notes/index.ts
new file mode 100644
index 0000000000..3d34cb5223
--- /dev/null
+++ b/apps/carbon/app/modules/shared/ui/Notes/index.ts
@@ -0,0 +1,3 @@
+import Notes from "./Notes";
+
+export default Notes;
diff --git a/apps/carbon/app/modules/shared/ui/index.ts b/apps/carbon/app/modules/shared/ui/index.ts
new file mode 100644
index 0000000000..6fa98be72e
--- /dev/null
+++ b/apps/carbon/app/modules/shared/ui/index.ts
@@ -0,0 +1,3 @@
+import Notes from "./Notes";
+
+export { Notes };
diff --git a/apps/carbon/app/routes/x+/account+/personal.tsx b/apps/carbon/app/routes/x+/account+/personal.tsx
index da5b2f5dd2..956f737c4a 100644
--- a/apps/carbon/app/routes/x+/account+/personal.tsx
+++ b/apps/carbon/app/routes/x+/account+/personal.tsx
@@ -41,7 +41,7 @@ export default function AccountPersonal() {
{/* <PersonalDataForm personalData={{}} /> */}
{attributes.map((category: PrivateAttributes) => (
<Box key={category.id} mb={8} w="full">
- <SectionTitle title={category.name} />
+ <SectionTitle>{category.name}</SectionTitle>
<UserAttributesForm attributeCategory={category} />
</Box>
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
index bce7746f79..b38b334608 100644
--- a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.tsx
@@ -9,6 +9,7 @@ import {
receiptValidator,
upsertReceipt,
} from "~/modules/inventory";
+import { getNotes } from "~/modules/shared";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { assertIsPost, notFound } from "~/utils/http";
@@ -23,14 +24,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { receiptId } = params;
if (!receiptId) throw notFound("receiptId not found");
- const [receipt, receiptLines] = await Promise.all([
+ const [receipt, receiptLines, notes] = await Promise.all([
getReceipt(client, receiptId),
getReceiptLines(client, receiptId),
+ getNotes(client, receiptId),
]);
return json({
receipt: receipt?.data ?? null,
receiptLines: receiptLines?.data ?? [],
+ notes: notes?.data ?? [],
});
}
@@ -72,13 +75,16 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function EditReceiptsRoute() {
- const { receipt, receiptLines } = useLoaderData<typeof loader>();
- if (!receipt?.receiptId) throw notFound("receiptId not found");
- if (!receipt?.sourceDocumentId) throw notFound("sourceDocumentId not found");
+ const { receipt, receiptLines, notes } = useLoaderData<typeof loader>();
+
+ if (receipt === null) {
+ throw new Error("Receipt not found");
+ }
const initialValues = {
...receipt,
receiptId: receipt.receiptId ?? undefined,
+ externalDocumentId: receipt.externalDocumentId ?? undefined,
sourceDocument: (receipt.sourceDocument ??
"Purchase Order") as "Purchase Order",
sourceDocumentId: receipt.sourceDocumentId ?? undefined,
@@ -91,6 +97,7 @@ export default function EditReceiptsRoute() {
// @ts-ignore
initialValues={initialValues}
isPosted={!!receipt?.postingDate ?? false}
+ notes={notes}
receiptLines={receiptLines}
/>
);
diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
index 54c958401d..a4879d014f 100644
--- a/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
+++ b/apps/carbon/app/routes/x+/inventory+/receipts.new.tsx
@@ -1,24 +1,10 @@
-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 { useUser } from "~/hooks";
-import type { ReceiptSourceDocument } from "~/modules/inventory";
-import {
- ReceiptForm,
- receiptValidator,
- upsertReceipt,
-} from "~/modules/inventory";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { upsertReceipt } from "~/modules/inventory";
import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
-import { assertIsPost } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-// shouldRevalidate function
-export function shouldRevalidate() {
- return false;
-}
+import { error } from "~/utils/result";
export async function loader({ request }: LoaderFunctionArgs) {
const { client, userId } = await requirePermissions(request, {
@@ -28,7 +14,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const nextSequence = await getNextSequence(client, "receipt", userId);
if (nextSequence.error) {
return redirect(
- "/x/inventory/receipts/new",
+ request.headers.get("Referer") ?? "/x/inventory/receipts",
await flash(
request,
error(nextSequence.error, "Failed to get next sequence")
@@ -44,7 +30,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (insertReceipt.error) {
await rollbackNextSequence(client, "receipt", userId);
return redirect(
- "/x/inventory/receipts",
+ request.headers.get("Referer") ?? "/x/inventory/receipts",
await flash(
request,
error(insertReceipt.error, "Failed to generate receipt")
@@ -52,67 +38,5 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
- return json({
- receipt: {
- id: insertReceipt.data.id,
- receiptId: nextSequence.data,
- },
- });
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- create: "inventory",
- });
-
- const validation = await receiptValidator.validate(await request.formData());
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, ...data } = validation.data;
- if (!id) throw new Error("id not found");
-
- const updateReceipt = await upsertReceipt(client, {
- id,
- ...data,
- updatedBy: userId,
- });
- if (updateReceipt.error) {
- return json(
- {},
- await flash(
- request,
- error(updateReceipt.error, "Failed to update receipt")
- )
- );
- }
-
- return redirect(
- `/x/inventory/receipts/${id}`,
- await flash(request, success("Receipt created"))
- );
-}
-
-export default function NewReceiptsRoute() {
- const { receipt } = useLoaderData<typeof loader>();
- const { defaults } = useUser();
-
- const initialValues = {
- ...receipt,
- sourceDocument: "Purchase Order" as ReceiptSourceDocument,
- sourceDocumentId: "",
- locationId: defaults.locationId ?? undefined,
- };
-
- return (
- <ReceiptForm
- // @ts-expect-error
- initialValues={initialValues}
- isPosted={false}
- receiptLines={[]}
- />
- );
+ return redirect(`/x/inventory/receipts/${insertReceipt.data.id}`);
}
diff --git a/apps/carbon/app/routes/x+/resources+/person.$personId.notes.delete.$noteId.tsx b/apps/carbon/app/routes/x+/resources+/person.$personId.notes.delete.$noteId.tsx
deleted file mode 100644
index fabbbcccec..0000000000
--- a/apps/carbon/app/routes/x+/resources+/person.$personId.notes.delete.$noteId.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { LoaderFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { deleteNote } from "~/modules/resources";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- update: "resources",
- });
-
- const { noteId, personId } = params;
- if (!noteId) {
- return redirect(
- "/x/resources/people",
- await flash(request, error(params, "Failed to get a note id"))
- );
- }
- if (!personId) {
- return redirect(
- "/x/resources/people",
- await flash(request, error(params, "Failed to get a person id"))
- );
- }
-
- const removeNote = await deleteNote(client, noteId);
- if (removeNote.error) {
- return redirect(
- `/x/resources/person/${personId}`,
- await flash(request, error(removeNote.error, "Failed to delete note"))
- );
- }
-
- return redirect(
- `/x/resources/person/${personId}`,
- await flash(request, success("Successfully deleted note"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/resources+/person.$personId.notes.new.tsx b/apps/carbon/app/routes/x+/resources+/person.$personId.notes.new.tsx
deleted file mode 100644
index 80abead97b..0000000000
--- a/apps/carbon/app/routes/x+/resources+/person.$personId.notes.new.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { json } from "@remix-run/node";
-import { redirect } from "react-router";
-import { validationError } from "remix-validated-form";
-import { insertNote, noteValidator } from "~/modules/resources";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { assertIsPost } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId: createdBy } = await requirePermissions(request, {
- create: "resources",
- });
-
- const { personId: userId } = params;
- if (!userId) throw new Error("Missing personId");
-
- const validation = await noteValidator.validate(await request.formData());
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { note } = validation.data;
-
- const createNote = await insertNote(client, {
- userId,
- note,
- createdBy,
- });
-
- if (createNote.error) {
- return json(
- {},
- await flash(request, error(createNote.error, "Failed to create note"))
- );
- }
-
- return redirect(
- `/x/resources/person/${userId}`,
- await flash(request, success("Sucessfully created note"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/resources+/person.$personId.tsx b/apps/carbon/app/routes/x+/resources+/person.$personId.tsx
index b192440ed5..1fa8e20c0f 100644
--- a/apps/carbon/app/routes/x+/resources+/person.$personId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/person.$personId.tsx
@@ -16,7 +16,6 @@ import {
employeeJobValidator,
getEmployeeAbilities,
getEmployeeJob,
- getNotes,
PersonAbilities,
PersonDaysOff,
PersonHeader,
@@ -24,6 +23,7 @@ import {
PersonTabs,
upsertEmployeeJob,
} from "~/modules/resources";
+import { getNotes } from "~/modules/shared";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
import { assertIsPost } from "~/utils/http";
@@ -151,9 +151,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
export default function PersonRoute() {
const {
user,
+ notes,
publicAttributes,
privateAttributes,
- notes,
employeeAbilities,
employeeJob,
} = useLoaderData<typeof loader>();
@@ -166,9 +166,9 @@ export default function PersonRoute() {
<PersonTabs
user={user}
job={employeeJob}
+ notes={notes}
publicAttributes={publicAttributes}
privateAttributes={privateAttributes}
- notes={notes}
/>
</VStack>
<VStack spacing={4}>
diff --git a/apps/carbon/app/routes/x+/shared+/notes.$noteId.delete.tsx b/apps/carbon/app/routes/x+/shared+/notes.$noteId.delete.tsx
new file mode 100644
index 0000000000..857dc317ac
--- /dev/null
+++ b/apps/carbon/app/routes/x+/shared+/notes.$noteId.delete.tsx
@@ -0,0 +1,23 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { deleteNote } from "~/modules/shared";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {});
+
+ const { noteId } = params;
+ if (!noteId) throw new Error("noteId not found");
+
+ const result = await deleteNote(client, noteId);
+ if (result.error) {
+ throw redirect(
+ request.headers.get("Referer") ?? request.url,
+ await flash(request, error(result.error, "Error deleting note"))
+ );
+ }
+
+ return redirect(request.headers.get("Referer") ?? request.url);
+}
diff --git a/apps/carbon/app/routes/x+/shared+/notes.new.tsx b/apps/carbon/app/routes/x+/shared+/notes.new.tsx
new file mode 100644
index 0000000000..11f45ee778
--- /dev/null
+++ b/apps/carbon/app/routes/x+/shared+/notes.new.tsx
@@ -0,0 +1,34 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { insertNote, noteValidator } from "~/modules/shared";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {});
+
+ const validation = await noteValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { documentId, note } = validation.data;
+ const createNote = await insertNote(client, {
+ documentId,
+ note,
+ createdBy: userId,
+ });
+ if (createNote.error) {
+ throw redirect(
+ request.headers.get("Referer") ?? "/x",
+ await flash(request, error(createNote.error, "Error creating note"))
+ );
+ }
+
+ return redirect(request.headers.get("Referer") ?? "/x");
+}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index be6328d567..b2a0e79807 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2619,6 +2619,52 @@ export interface Database {
}
];
};
+ note: {
+ Row: {
+ active: boolean;
+ createdAt: string;
+ createdBy: string;
+ documentId: string;
+ id: string;
+ note: string;
+ noteRichText: Json;
+ updatedAt: string | null;
+ };
+ Insert: {
+ active?: boolean;
+ createdAt?: string;
+ createdBy: string;
+ documentId: string;
+ id?: string;
+ note: string;
+ noteRichText?: Json;
+ updatedAt?: string | null;
+ };
+ Update: {
+ active?: boolean;
+ createdAt?: string;
+ createdBy?: string;
+ documentId?: string;
+ id?: string;
+ note?: string;
+ noteRichText?: Json;
+ updatedAt?: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "notes_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "notes_createdBy_fkey";
+ columns: ["createdBy"];
+ referencedRelation: "user_default_view";
+ referencedColumns: ["userId"];
+ }
+ ];
+ };
part: {
Row: {
active: boolean;
@@ -6270,64 +6316,6 @@ export interface Database {
}
];
};
- userNote: {
- Row: {
- active: boolean;
- createdAt: string;
- createdBy: string;
- id: string;
- note: string;
- noteRichText: Json;
- updatedAt: string | null;
- userId: string;
- };
- Insert: {
- active?: boolean;
- createdAt?: string;
- createdBy: string;
- id?: string;
- note: string;
- noteRichText?: Json;
- updatedAt?: string | null;
- userId: string;
- };
- Update: {
- active?: boolean;
- createdAt?: string;
- createdBy?: string;
- id?: string;
- note?: string;
- noteRichText?: Json;
- updatedAt?: string | null;
- userId?: string;
- };
- Relationships: [
- {
- foreignKeyName: "notes_createdBy_fkey";
- columns: ["createdBy"];
- referencedRelation: "user";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "notes_createdBy_fkey";
- columns: ["createdBy"];
- referencedRelation: "user_default_view";
- referencedColumns: ["userId"];
- },
- {
- foreignKeyName: "notes_userId_fkey";
- columns: ["userId"];
- referencedRelation: "user";
- referencedColumns: ["id"];
- },
- {
- foreignKeyName: "notes_userId_fkey";
- columns: ["userId"];
- referencedRelation: "user_default_view";
- referencedColumns: ["userId"];
- }
- ];
- };
valueLedger: {
Row: {
actualCostPostedToGl: number;
diff --git a/packages/database/supabase/migrations/20230209041302_notes.sql b/packages/database/supabase/migrations/20230209041302_notes.sql
index 58da9f62d9..3411512ad2 100644
--- a/packages/database/supabase/migrations/20230209041302_notes.sql
+++ b/packages/database/supabase/migrations/20230209041302_notes.sql
@@ -1,6 +1,6 @@
-CREATE TABLE "userNote" (
+CREATE TABLE "note" (
"id" TEXT NOT NULL DEFAULT xid(),
- "userId" TEXT NOT NULL,
+ "documentId" TEXT NOT NULL,
"note" TEXT NOT NULL,
"noteRichText" JSONB NOT NULL DEFAULT '{}'::jsonb,
"active" BOOLEAN NOT NULL DEFAULT true,
@@ -9,45 +9,35 @@ CREATE TABLE "userNote" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "notes_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "notes_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "notes_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-ALTER TABLE "userNote" ENABLE ROW LEVEL SECURITY;
+CREATE INDEX "notes_documentId_index" ON "note"("documentId");
-CREATE POLICY "Employees with resources_view can view notes" ON "userNote"
+ALTER TABLE "note" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees can view notes" ON "note"
FOR SELECT
USING (
- coalesce(get_my_claim('resources_view')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Employees with resources_create can insert notes" ON "userNote"
+CREATE POLICY "Employees can insert notes" ON "note"
FOR INSERT
WITH CHECK (
- coalesce(get_my_claim('resources_create')::boolean,false)
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
);
-CREATE POLICY "Employees with resources_update can update their own notes" ON "userNote"
+CREATE POLICY "Employees can update their own notes" ON "note"
FOR UPDATE
USING (
- coalesce(get_my_claim('resources_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
AND "createdBy"::uuid = auth.uid()
);
-CREATE POLICY "Employees with resources_update can delete their own notes" ON "userNote"
+CREATE POLICY "Employees can delete their own notes" ON "note"
FOR DELETE
USING (
- coalesce(get_my_claim('resources_update')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ (get_my_claim('role'::text)) = '"employee"'::jsonb
AND "createdBy"::uuid = auth.uid()
);
-
-CREATE POLICY "Employees with resources_delete can delete any note" ON "userNote"
- FOR UPDATE
- USING (
- coalesce(get_my_claim('resources_delete')::boolean, false) = true
- AND (get_my_claim('role'::text)) = '"employee"'::jsonb
- );
\ No newline at end of file