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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add missing elements to issue report
Brad Barbin1b7f14a9c637
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex f539708b04..8a23d6eea2 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -1022,9 +1022,25 @@ export async function updateIssueTaskStatus(const finalAssignee = assignee || userId;+ // Set completedDate to today when status is "Completed"+ const updateData: {+ status: string;+ updatedBy?: string;+ assignee?: string | null;+ completedDate?: string;+ } = {+ status,+ updatedBy: userId,+ assignee: finalAssignee,+ };++ if (status === "Completed") {+ updateData.completedDate = new Date().toISOString().split("T")[0];+ }+return client.from(table)- .update({ status, updatedBy: userId, assignee: finalAssignee })+ .update(updateData).eq("id", id).select("nonConformanceId").single();diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsxindex 772a9682da..fa478891f7 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx@@ -30,8 +30,8 @@ import { Editor } from "@carbon/react/Editor";import { formatDate } from "@carbon/utils";import { parseDate } from "@internationalized/date";import { useFetchers, useParams, useSubmit } from "@remix-run/react";-import { nanoid } from "nanoid";import type { DragControls } from "framer-motion";+import { nanoid } from "nanoid";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuCalendar,@@ -62,8 +62,10 @@ import { getPrivateUrl, path } from "~/utils/path";export function TaskProgress({tasks,+ className,}: {tasks: { status: IssueInvestigationTask["status"] }[];+ className?: string;}) {const completedOrSkippedTasks = tasks.filter((task) => task.status === "Completed" || task.status === "Skipped"@@ -71,7 +73,7 @@ export function TaskProgress({const progressPercentage = (completedOrSkippedTasks / tasks.length) * 100;return (- <div className="flex flex-col items-end gap-2 pt-2 pr-14">+ <div className={cn("flex flex-col items-end gap-2 pt-2 pr-14", className)}><Progress value={progressPercentage} className="h-2 w-24" /><span className="text-xs text-muted-foreground">{completedOrSkippedTasks} of {tasks.length} complete@@ -276,12 +278,15 @@ export function TaskItem({const submit = useSubmit();const hasStartedRef = useRef(false);- const taskTitle =- type === "investigation"- ? (task as IssueInvestigationTask).name- : type === "action"+ let taskTitle =+ type === "action"? (task as IssueActionTask).name: (task as IssueReviewer).title;++ if (task.supplierId) {+ taskTitle = `Supplier ${taskTitle}`;+ }+return (<div className="rounded-lg border w-full flex flex-col bg-card"><div className="flex w-full justify-between px-4 py-2 items-center">diff --git a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsxindex d06e7c7c29..73e5f668c7 100644--- a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx@@ -6,6 +6,7 @@ import {getIssue,getIssueActionTasks,getIssueApprovalTasks,+ getIssueAssociations,getIssueItems,getIssueReviewers,getIssueTypes,@@ -42,6 +43,77 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getIssueItems(client, id, companyId),]);+ // Get associations separately (returns plain object, not wrapped in { data })+ const associations = await getIssueAssociations(client, id, companyId);++ // Get job operation step records for action tasks+ const actionTaskIds = actionTasks.data?.map((task) => task.id) ?? [];+ const jobOperationStepRecords =+ actionTaskIds.length > 0+ ? await client+ .from("jobOperationStep")+ .select(+ "id, name, nonConformanceActionId, operationId, jobOperationStepRecord(*)"+ )+ .in("nonConformanceActionId", actionTaskIds)+ .not("nonConformanceActionId", "is", null)+ : { data: [] };++ // Get job IDs from job operations+ const operationIds =+ jobOperationStepRecords.data+ ?.map((step: any) => step.operationId)+ .filter(Boolean) ?? [];+ const jobOperations =+ operationIds.length > 0+ ? await client+ .from("jobOperation")+ .select("id, jobId, job(jobId)")+ .in("id", operationIds)+ : { data: [] };++ // Create a map of operationId -> jobId+ const operationToJobId: Record<string, string> = {};+ jobOperations.data?.forEach((op: any) => {+ if (op.job?.jobId) {+ operationToJobId[op.id] = op.job.jobId;+ }+ });++ // Build assignee and record creator lookup map+ const uniqueUsers = new Set<string>();+ actionTasks.data?.forEach((task) => {+ if (task.assignee) uniqueUsers.add(task.assignee);+ });++ // Add createdBy users from job operation step records+ jobOperationStepRecords.data?.forEach((step: any) => {+ step.jobOperationStepRecord?.forEach((record: any) => {+ if (record.createdBy) uniqueUsers.add(record.createdBy);+ });+ });++ const userNames: Record<string, string> = {};+ if (uniqueUsers.size > 0) {+ const userResults = await Promise.all(+ Array.from(uniqueUsers).map((userId) =>+ client+ .from("user")+ .select("id, fullName, firstName, lastName")+ .eq("id", userId)+ .single()+ )+ );++ userResults.forEach((result) => {+ if (result.data) {+ userNames[result.data.id] =+ result.data.fullName ??+ `${result.data.firstName} ${result.data.lastName}`;+ }+ });+ }+if (company.error) {console.error(company.error);}@@ -89,6 +161,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {requiredActions={requiredActions.data ?? []}reviewers={reviewers.data ?? []}items={items.data ?? []}+ associations={associations}+ assignees={userNames}+ jobOperationStepRecords={jobOperationStepRecords.data ?? []}+ operationToJobId={operationToJobId}/>);diff --git a/apps/erp/app/routes/share+/scar.$id.tsx b/apps/erp/app/routes/share+/scar.$id.tsxindex 1b418d92e2..9839cbaa51 100644--- a/apps/erp/app/routes/share+/scar.$id.tsx+++ b/apps/erp/app/routes/share+/scar.$id.tsx@@ -37,14 +37,10 @@ import { LuChevronRight } from "react-icons/lu";import z from "zod";import { zfd } from "zod-form-data";import { getSupplier } from "~/modules/purchasing";-import type {- IssueActionTask,- IssueInvestigationTask,-} from "~/modules/quality";+import type { IssueActionTask } from "~/modules/quality";import {getIssueActionTasks,getIssueFromExternalLink,- getIssueInvestigationTasks,nonConformanceTaskStatus,updateIssueTaskContent,updateIssueTaskStatus,@@ -70,22 +66,16 @@ const translations = {"Issue not found": "Issue not found","Oops! The link you're trying to access is not valid.":"Oops! The link you're trying to access is not valid.",- Actions: "Actions",- Investigations: "Investigations",},es: {"Issue not found": "No se encontró el problema","Oops! The link you're trying to access is not valid.":"¡Ups! El enlace al que intenta acceder no es válido.",- Actions: "Acciones",- Investigations: "Investigaciones",},de: {"Issue not found": "Problem nicht gefunden","Oops! The link you're trying to access is not valid.":"Ups! Der Link, den Sie aufrufen möchten, ist nicht gültig.",- Actions: "Aktionen",- Investigations: "Untersuchungen",},};@@ -127,23 +117,16 @@ export async function loader({ params, request }: LoaderFunctionArgs) {});}- const [company, supplier, actionTasks, investigationTasks] =- await Promise.all([- getCompany(serviceRole, externalLink.data.companyId),- getSupplier(serviceRole, issue.data.supplierId),- getIssueActionTasks(- serviceRole,- issue.data.nonConformanceId,- externalLink.data.companyId,- issue.data.supplierId- ),- getIssueInvestigationTasks(- serviceRole,- issue.data.nonConformanceId,- externalLink.data.companyId,- issue.data.supplierId- ),- ]);+ const [company, supplier, actionTasks] = await Promise.all([+ getCompany(serviceRole, externalLink.data.companyId),+ getSupplier(serviceRole, issue.data.supplierId),+ getIssueActionTasks(+ serviceRole,+ issue.data.nonConformanceId,+ externalLink.data.companyId,+ issue.data.supplierId+ ),+ ]);return json({state: IssueState.Valid,@@ -152,7 +135,6 @@ export async function loader({ params, request }: LoaderFunctionArgs) {company: company.data,supplier: supplier.data,actionTasks: actionTasks.data,- investigationTasks: investigationTasks.data,},strings,});@@ -160,7 +142,7 @@ export async function loader({ params, request }: LoaderFunctionArgs) {export const scarValidator = z.object({taskId: zfd.text(z.string()),- type: z.enum(["action", "investigation"]),+ type: z.enum(["action"]),supplierId: zfd.text(z.string()),status: z.enum(nonConformanceTaskStatus).optional(),content: z@@ -209,20 +191,12 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const tasks =- validation.data.type === "action"- ? await getIssueActionTasks(- serviceRole,- issue.data.nonConformanceId,- externalLink.data.companyId,- issue.data.supplierId- )- : await getIssueInvestigationTasks(- serviceRole,- issue.data.nonConformanceId,- externalLink.data.companyId,- issue.data.supplierId- );+ const tasks = await getIssueActionTasks(+ serviceRole,+ issue.data.nonConformanceId,+ externalLink.data.companyId,+ issue.data.supplierId+ );const isTaskValid = tasks.data?.find((t) => t.id === validation.data.taskId);if (!isTaskValid) {@@ -324,11 +298,11 @@ function useTaskStatus({}: {task: {id?: string;- status: IssueInvestigationTask["status"];+ status: IssueActionTask["status"];supplierId: string | null;};- type: "investigation" | "action" | "approval" | "review";- onChange?: (status: IssueInvestigationTask["status"]) => void;+ type: "action" | "approval" | "review";+ onChange?: (status: IssueActionTask["status"]) => void;}) {const { id } = useParams();if (!id) throw new Error("Could not find external quote id");@@ -336,7 +310,7 @@ function useTaskStatus({const submit = useSubmit();const onOperationStatusChange = useCallback(- (taskId: string, status: IssueInvestigationTask["status"]) => {+ (taskId: string, status: IssueActionTask["status"]) => {onChange?.(status);submit({@@ -373,7 +347,7 @@ function useTaskNotes({initialContent: JSONContent;taskId: string;supplierId: string;- type: "investigation" | "action" | "approval" | "review";+ type: "action" | "approval" | "review";}) {const { id } = useParams();if (!id) throw new Error("Could not find external quote id");@@ -404,8 +378,8 @@ export function TaskItem({type,isDisabled = false,}: {- task: IssueInvestigationTask | IssueActionTask;- type: "investigation" | "action" | "review";+ task: IssueActionTask;+ type: "action" | "review";isDisabled?: boolean;permissionsOverride?: Permissions;}) {@@ -427,10 +401,7 @@ export function TaskItem({const hasStartedRef = useRef(false);- const taskTitle =- type === "investigation"- ? (task as IssueInvestigationTask).name- : (task as IssueActionTask).name;+ const taskTitle = task.name;return (<div className="rounded-lg border w-full flex flex-col"><div className="flex w-full justify-between px-4 py-2 items-center">@@ -502,41 +473,33 @@ export function TaskItem({export function TaskList({tasks,isDisabled,- type,strings,}: {- tasks: IssueActionTask[] | IssueInvestigationTask[];+ tasks: IssueActionTask[];isDisabled: boolean;- type: "action" | "investigation";strings: (typeof translations)["en"];}) {if (tasks.length === 0) return null;return (- <Card className="w-full" isCollapsible>- <HStack className="justify-between w-full">- <CardHeader>- <CardTitle className="flex items-center gap-2">- {type === "action" ? strings["Actions"] : strings["Investigations"]}- </CardTitle>- </CardHeader>- <TaskProgress tasks={tasks} />+ <>+ <HStack className="justify-center w-full">+ <TaskProgress tasks={tasks} className="pr-0" /></HStack>- <CardContent>- <VStack spacing={3}>- {tasks- .sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? 0)- .map((task) => (- <TaskItem- key={task.id}- task={task}- type={type}- isDisabled={isDisabled}- />- ))}- </VStack>- </CardContent>- </Card>++ <VStack spacing={3}>+ {tasks+ .sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? 0)+ .map((task) => (+ <TaskItem+ key={task.id}+ task={task}+ type="action"+ isDisabled={isDisabled}+ />+ ))}+ </VStack>+ </>);}@@ -547,7 +510,7 @@ const Issue = ({data: IssueData;strings: (typeof translations)["en"];}) => {- const { company, issue, actionTasks, investigationTasks, supplier } = data;+ const { company, issue, actionTasks, supplier } = data;const { id } = useParams();if (!id) throw new Error("Could not find external quote id");@@ -567,18 +530,9 @@ const Issue = ({<Card className="w-full max-w-5xl mx-auto gap-4"><Header company={company} issue={issue} supplier={supplier} /><CardContent className="gap-4">- {investigationTasks?.length ? (- <TaskList- tasks={investigationTasks}- type="investigation"- isDisabled={issue.status === "Closed"}- strings={strings}- />- ) : null}{actionTasks?.length ? (<TaskListtasks={actionTasks}- type="action"isDisabled={issue.status === "Closed"}strings={strings}/>diff --git a/apps/erp/app/routes/x+/issue+/$id.details.tsx b/apps/erp/app/routes/x+/issue+/$id.details.tsxindex f510b10efb..b6dfc28656 100644--- a/apps/erp/app/routes/x+/issue+/$id.details.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.details.tsx@@ -116,8 +116,8 @@ export default function IssueDetailsRoute() {<VStack spacing={2}><IssueContentid={id}- title={nonConformance?.name ?? ""}- subTitle={nonConformance?.nonConformanceId ?? ""}+ title={"Description of Issue"}+ subTitle={nonConformance?.name}content={nonConformance?.content as JSONContent}isDisabled={nonConformance?.status === "Closed"}/>diff --git a/llm/cache/user-employee-job-relationships.md b/llm/cache/user-employee-job-relationships.mdnew file mode 100644index 0000000000..455d609908--- /dev/null+++ b/llm/cache/user-employee-job-relationships.md@@ -0,0 +1,266 @@+# User and EmployeeJob Relationships++## Overview++The Carbon system manages employee data through interconnected tables: `user`, `employee`, and `employeeJob`. Here's how to retrieve a user's full name from their user ID and understand employee relationships.++## Table Structure++### user table+Located at: `packages/database/src/types.ts`++Primary fields for names:+```typescript+{+ id: string (UUID, matches Supabase auth.users.id)+ email: string+ firstName: string+ lastName: string+ fullName: string | null+ avatarUrl: string | null+ active: boolean | null+ // ... other fields+}+```++### employee table+Links users to companies:+```typescript+{+ id: string (FK to user.id)+ employeeTypeId: string+ companyId: string+ active: boolean+}+```++### employeeJob table+Stores job-specific information for employees:+```typescript+{+ id: string (FK to user.id, matches employee.id)+ companyId: string (FK to company.id)+ departmentId: string | null (FK to department.id)+ locationId: string | null (FK to location.id)+ managerId: string | null (FK to user.id for manager)+ shiftId: string | null (FK to shift.id)+ title: string | null+ startDate: string | null+ tags: string[] | null+ customFields: Json | null+ updatedAt: string | null+ updatedBy: string | null+}+```++## Getting User Full Name from User ID++### Direct Query (Simplest)+```typescript+import type { SupabaseClient, Database } from "@carbon/database";++// Get user by ID - will have firstName, lastName, and fullName+const { data: user, error } = await client+ .from("user")+ .select("id, email, firstName, lastName, fullName")+ .eq("id", userId)+ .single();++// fullName is the preferred field (can be null)+// Fallback pattern: user.fullName || `${user.firstName} ${user.lastName}`+```++### From Auth Context+If you have the current user session:+```typescript+import { getCarbon, requirePermissions } from "@carbon/auth";++const { user } = await requirePermissions(request, {+ view: "module",+});++// user.fullName directly available+console.log(user.fullName); // e.g., "John Doe" or null+```++## Employee Join Patterns++### employees View+A pre-built view that joins user and employee tables efficiently.++**Location**: Created in migration `20241208004151_invites.sql`++**Definition**:+```sql+SELECT+ u.id,+ u."email",+ u."firstName",+ u."lastName",+ u."fullName" AS "name",+ u."avatarUrl",+ e."employeeTypeId",+ e."companyId",+ e."active"+FROM "user" u+INNER JOIN "employee" e ON e.id = u.id+WHERE u.active = TRUE+```++**Usage**:+```typescript+// Get employees with names+const { data: employees } = await client+ .from("employees")+ .select("id, name, firstName, lastName, email, employeeTypeId, active")+ .eq("companyId", companyId);+```++### employeeSummary View (Recommended for Full Context)+A comprehensive view that includes job information.++**Location**: Created in migration `20240103010721_employee-summary.sql`++**Definition**:+```sql+SELECT+ u.id,+ u."fullName" AS "name",+ u."avatarUrl",+ e."companyId",+ ej.title,+ ej."startDate",+ d.name AS "departmentName",+ l.name AS "locationName",+ m."fullName" AS "managerName"+FROM "employee" e+INNER JOIN "user" u ON u.id = e.id+LEFT JOIN "employeeJob" ej ON e.id = ej.id AND e."companyId" = ej."companyId"+LEFT OUTER JOIN "location" l ON l.id = ej."locationId"+LEFT OUTER JOIN "user" m ON m.id = ej."managerId"+LEFT OUTER JOIN "department" d ON d.id = ej."departmentId"+```++**Usage**:+```typescript+// Get complete employee summary with job details+const { data: employeeSummary } = await client+ .from("employeeSummary")+ .select("*")+ .eq("id", employeeId)+ .eq("companyId", companyId)+ .single();++// Returns: {+// id, name (fullName), avatarUrl, companyId,+// title, startDate, departmentName, locationName, managerName+// }+```++### employeesAcrossCompanies View+For getting employees that exist across multiple companies.++**Definition**:+```sql+SELECT+ u.id,+ u.email,+ u."firstName",+ u."lastName",+ u."fullName" AS "name",+ u."avatarUrl",+ u.active,+ array_agg(e."companyId") as "companyId"+FROM "user" u+INNER JOIN "employee" e ON e.id = u.id+WHERE u.active = TRUE+GROUP BY u.id, u.email, u."firstName", u."lastName", u."fullName", u."avatarUrl", u.active+```++## How to Get Employee Names in Different Contexts++### From Service Patterns+Used in `apps/erp/app/modules/users/users.service.ts`:++```typescript+export async function getEmployees(+ client: SupabaseClient<Database>,+ companyId: string,+ args: GenericQueryFilters & { search: string | null }+) {+ let query = client+ .from("employees")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args.search) {+ query = query.ilike("name", `%${args.search}%`);+ }+ // ...+ return query;+}+```++### From People Service+When getting employee job information:++```typescript+import { getEmployees } from "~/modules/users/users.service";++// Get employee with job details+const { data: employeeJob } = await client+ .from("employeeJob")+ .select("*")+ .eq("id", employeeId)+ .eq("companyId", companyId)+ .single();++// To get the employee's full name:+const { data: employee } = await client+ .from("employees")+ .select("id, name, firstName, lastName")+ .eq("id", employeeId)+ .eq("companyId", companyId)+ .single();+```++## Key Foreign Key Relationships++1. **employeeJob.id** -> **user.id**: The employee's record (one-to-one per company)+2. **employeeJob.managerId** -> **user.id**: The manager's ID (can be null)+3. **employee.id** -> **user.id**: Links employee role to user+4. **user.id**: The primary identifier used across all these tables++## Performance Considerations++- **employeeSummary view** is ideal when you need employee name + job context+- Use the **employees view** for simple employee lists with names+- For just user names, query the **user table** directly with the ID+- Manager names are already joined in **employeeSummary** (use `managerName` field)++## Type Definitions++### Employee Type (from users.service.ts)+```typescript+type Employee = NonNullable<+ Awaited<ReturnType<typeof getEmployees>>["data"]+>[number];+```++### User Type (from authentication-system.md)+```typescript+{+ id: string+ email: string+ firstName: string+ lastName: string+ fullName: string | null+ about: string+ avatarUrl: string | null+ active: boolean | null+ admin: boolean | null+ developer: boolean | null+ createdAt: string+ updatedAt: string | null+}+```diff --git a/packages/documents/src/pdf/IssuePDF.tsx b/packages/documents/src/pdf/IssuePDF.tsxindex 378d83c6d6..3a5071b379 100644--- a/packages/documents/src/pdf/IssuePDF.tsx+++ b/packages/documents/src/pdf/IssuePDF.tsx@@ -4,7 +4,7 @@ import { createTw } from "react-pdf-tailwind";import type { JSONContent } from "@carbon/react";import type { PDF } from "../types";-import { Header, Note, Summary, Template } from "./components";+import { Footer, Header, Note, Summary, Template } from "./components";type ListItem = {id: string;@@ -20,6 +20,29 @@ type ActionTask =supplier: { name: string } | null;};+type JobOperationStepRecord =+ Database["public"]["Tables"]["jobOperationStepRecord"]["Row"];++type JobOperationStepWithRecords = {+ id: string;+ name: string | null;+ operationId: string;+ nonConformanceActionId: string | null;+ jobOperationStepRecord: JobOperationStepRecord[];+};++type Associations = {+ items: any[];+ customers: any[];+ suppliers: any[];+ jobOperations: any[];+ purchaseOrderLines: any[];+ salesOrderLines: any[];+ shipmentLines: any[];+ receiptLines: any[];+ trackedEntities: any[];+};+interface IssuePDFProps extends PDF {nonConformance: Database["public"]["Tables"]["nonConformance"]["Row"];nonConformanceTypes: Database["public"]["Tables"]["nonConformanceType"]["Row"][];@@ -27,6 +50,10 @@ interface IssuePDFProps extends PDF {requiredActions: ListItem[];reviewers: Database["public"]["Tables"]["nonConformanceReviewer"]["Row"][];items: IssueItem[];+ associations?: Associations | null;+ assignees?: Record<string, string>;+ jobOperationStepRecords?: JobOperationStepWithRecords[];+ operationToJobId?: Record<string, string>;}// Initialize tailwind-styled-components@@ -55,6 +82,10 @@ const IssuePDF = ({requiredActions,reviewers,items,+ associations,+ assignees = {},+ jobOperationStepRecords = [],+ operationToJobId = {},title = "Issue Report",}: IssuePDFProps) => {// Sort action tasks by sortOrder@@ -99,53 +130,169 @@ const IssuePDF = ({},]}/>- <View style={tw("flex flex-col gap-2 mb-10")}>+ <View style={tw("flex flex-col gap-2 mb-4")}><View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold")}>{nonConformance.name}</Text>+ <Text style={[tw("font-bold"), { letterSpacing: -0.5 }]}>+ {nonConformance.name}+ </Text></View></View>+ {associations && (+ <View style={tw("mb-10")}>+ <View style={tw("flex flex-col gap-1")}>+ {associations.items?.map((item: any) => (+ <View+ key={item.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>Item:</Text>+ </View>+ <Text>{item.documentReadableId}</Text>+ {item.disposition && (+ <>+ <Text>-</Text>+ <Text>{item.disposition}</Text>+ </>+ )}+ {item.quantity && (+ <>+ <Text>-</Text>+ <Text>Qty: {item.quantity}</Text>+ </>+ )}+ </View>+ ))}+ {associations.customers?.map((customer: any) => (+ <View+ key={customer.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Customer:+ </Text>+ </View>+ <Text>{customer.documentReadableId}</Text>+ </View>+ ))}+ {associations.suppliers?.map((supplier: any) => (+ <View+ key={supplier.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Supplier:+ </Text>+ </View>+ <Text>{supplier.documentReadableId}</Text>+ </View>+ ))}+ {associations.jobOperations?.map((job: any) => (+ <View+ key={job.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Job Operation:+ </Text>+ </View>+ <Text>{job.documentReadableId}</Text>+ </View>+ ))}+ {associations.purchaseOrderLines?.map((po: any) => (+ <View+ key={po.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Purchase Order:+ </Text>+ </View>+ <Text>{po.documentReadableId}</Text>+ </View>+ ))}+ {associations.salesOrderLines?.map((so: any) => (+ <View+ key={so.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Sales Order:+ </Text>+ </View>+ <Text>{so.documentReadableId}</Text>+ </View>+ ))}+ {associations.shipmentLines?.map((shipment: any) => (+ <View+ key={shipment.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Shipment:+ </Text>+ </View>+ <Text>{shipment.documentReadableId}</Text>+ </View>+ ))}+ {associations.receiptLines?.map((receipt: any) => (+ <View+ key={receipt.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>Receipt:</Text>+ </View>+ <Text>{receipt.documentReadableId}</Text>+ </View>+ ))}+ {associations.trackedEntities?.map((entity: any) => (+ <View+ key={entity.id}+ style={tw("flex flex-row gap-2 text-sm py-1")}+ >+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Tracked Entity:+ </Text>+ </View>+ <Text>{entity.documentReadableId}</Text>+ </View>+ ))}+ </View>+ </View>+ )}{Object.keys(nonConformance.content ?? {}).length > 0 && (- <View- style={tw("flex flex-col gap-2 border-b border-gray-300 mb-10")}- >+ <View style={tw("flex flex-col gap-2 mb-10")}><View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold")}>Overview</Text>+ <Text style={[tw("font-bold"), { letterSpacing: -0.5 }]}>+ Description of Issue+ </Text></View>- <Note content={nonConformance.content as JSONContent} />- </View>- )}- {items.length > 0 && (- <View style={tw("mb-10")} wrap={false}>- <Text style={tw("font-bold mb-2")}>Dispositions</Text>- {items.map((item) => (- <View- key={item.id}- style={tw("flex flex-col gap-1 py-2 border-b border-gray-300")}- >- <View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold text-sm")}>{item.name}</Text>- <Badge>{item.disposition ?? "Pending"}</Badge>- </View>- {item.quantity > 0 && (- <Text style={tw("text-sm text-gray-500")}>- Quantity: {item.quantity}- </Text>- )}- </View>- ))}+ <View style={tw("flex flex-col my-2")}>+ <Note content={nonConformance.content as JSONContent} />+ </View></View>)}+{sortedActionTasks.length > 0 && (- <View style={tw("mb-10")} wrap={false}>- <Text style={tw("font-bold mb-2")}>Actions</Text>+ <View style={tw("mb-10")}>{sortedActionTasks.map((task) => (<Viewkey={task.id}- style={tw("flex flex-col gap-2 border-b border-gray-300 mb-10")}+ style={tw("flex flex-col gap-2 mb-10")}+ wrap={false}><View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold")}>+ <Text style={[tw("font-bold"), { letterSpacing: -0.5 }]}>+ {task.supplier?.name ? "Supplier " : ""}{requiredActions.find((action) => action.id === task.actionTypeId@@ -153,18 +300,109 @@ const IssuePDF = ({}</Text></View>- {task.supplier?.name && (- <View style={tw("flex flex-row items-center gap-2")}>- <Badge>{task.supplier.name}</Badge>+ <View style={tw("flex flex-col gap-1")}>+ {task.supplier?.name && (+ <View style={tw("flex flex-row gap-2 text-sm")}>+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Supplier:+ </Text>+ </View>+ <Text>{task.supplier.name}</Text>+ </View>+ )}+ {task.assignee && assignees[task.assignee] && (+ <View style={tw("flex flex-row gap-2 text-sm")}>+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ {task.supplier?.name ? "Verified by" : "Completed by"}+ :+ </Text>+ </View>+ <Text>{assignees[task.assignee]}</Text>+ </View>+ )}+ {task.completedDate && (+ <View style={tw("flex flex-row gap-2 text-sm")}>+ <View style={tw("w-1/4")}>+ <Text style={tw("font-bold text-[#7d7d7d]")}>+ Completed on:+ </Text>+ </View>+ <Text>{task.completedDate}</Text>+ </View>+ )}+ </View>+ {Object.keys(task.notes ?? {}).length > 0 && (+ <View style={tw("flex flex-col my-2")}>+ <Note content={task.notes as JSONContent} /></View>)}- {task.completedDate && (- <Text style={tw("text-sm")}>- Completed: {task.completedDate}- </Text>- )}- {Object.keys(task.notes ?? {}).length > 0 && (- <Note content={task.notes as JSONContent} />+ {/* Job Operation Step Records */}+ {jobOperationStepRecords+ .filter((step) => step.nonConformanceActionId === task.id)+ .some((step) =>+ step.jobOperationStepRecord?.some(+ (record) => record.booleanValue !== null+ )+ ) && (+ <View style={tw("flex flex-col gap-2")}>+ <Text+ style={[tw("font-bold text-sm"), { letterSpacing: -0.5 }]}+ >+ Inspections+ </Text>+ {jobOperationStepRecords+ .filter((step) => step.nonConformanceActionId === task.id)+ .map((step) =>+ step.jobOperationStepRecord+ ?.filter((record) => record.booleanValue !== null)+ .map((record) => (+ <View+ key={record.id}+ style={tw("flex flex-row gap-2 text-sm")}+ >+ <View+ style={{+ width: 12,+ height: 12,+ border: "1px solid #000",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ marginTop: 2,+ }}+ >+ {record.booleanValue && (+ <Text+ style={{ fontSize: 10, fontWeight: "bold" }}+ >+ ✓+ </Text>+ )}+ </View>+ <View style={tw("flex flex-col")}>+ <Text style={tw("font-medium")}>+ {step.name}+ </Text>+ <Text style={tw("text-xs")}>+ {operationToJobId[step.operationId] && (+ <>+ Job {operationToJobId[step.operationId]} •{" "}+ </>+ )}+ {assignees[record.createdBy] || "Unknown"} •{" "}+ {+ new Date(record.createdAt)+ .toISOString()+ .split("T")[0]+ }+ </Text>+ </View>+ </View>+ ))+ )}+ </View>)}</View>))}@@ -172,15 +410,18 @@ const IssuePDF = ({)}{reviewers.length > 0 && (- <View style={tw("mb-5")} wrap={false}>- <Text style={tw("font-bold mb-2")}>Reviewers</Text>+ <View style={tw("mb-5")}>+ <Text style={[tw("font-bold mb-2"), { letterSpacing: -0.5 }]}>+ Reviewers+ </Text>{reviewers.map((reviewer) => (- <View- key={reviewer.id}- style={tw("flex flex-col gap-2 py-2 border-b border-gray-300")}- >+ <View key={reviewer.id} style={tw("flex flex-col gap-2 py-2")}><View style={tw("flex flex-row justify-between")}>- <Text style={tw("font-bold text-sm")}>{reviewer.title}</Text>+ <Text+ style={[tw("font-bold text-sm"), { letterSpacing: -0.5 }]}+ >+ {reviewer.title}+ </Text><Text style={tw("text-gray-500 text-sm")}>{reviewer.status}</Text>@@ -194,18 +435,9 @@ const IssuePDF = ({</View>)}</View>+ <Footer nonConformanceId={nonConformance.nonConformanceId} /></Template>);};export default IssuePDF;--function Badge({ children }: { children: React.ReactNode }) {- return (- <Text- style={tw("text-xs bg-gray-100 px-2 py-1 rounded border border-gray-300")}- >- {children}- </Text>- );-}diff --git a/packages/documents/src/pdf/components/Footer.tsx b/packages/documents/src/pdf/components/Footer.tsxnew file mode 100644index 0000000000..8c17145904--- /dev/null+++ b/packages/documents/src/pdf/components/Footer.tsx@@ -0,0 +1,35 @@+import { Text, View } from "@react-pdf/renderer";+import { createTw } from "react-pdf-tailwind";++const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"],+ },+ },+});++interface FooterProps {+ nonConformanceId: string;+}++const Footer = ({ nonConformanceId }: FooterProps) => {+ return (+ <View style={tw("absolute bottom-0 left-0 right-0 px-10 pb-5")} fixed>+ <View+ style={tw(+ "flex flex-row justify-between items-center text-sm text-gray-500"+ )}+ >+ <Text>Issue #{nonConformanceId}</Text>+ <Text+ render={({ pageNumber, totalPages }) =>+ `${pageNumber} of ${totalPages}`+ }+ />+ </View>+ </View>+ );+};++export default Footer;diff --git a/packages/documents/src/pdf/components/index.ts b/packages/documents/src/pdf/components/index.tsindex 4852933e18..4cf9e726a8 100644--- a/packages/documents/src/pdf/components/index.ts+++ b/packages/documents/src/pdf/components/index.ts@@ -1,6 +1,7 @@+import Footer from "./Footer";import { Header, JobHeader } from "./Header";import Note from "./Note";import Summary from "./Summary";import Template from "./Template";-export { Header, JobHeader, Note, Summary, Template };+export { Footer, Header, JobHeader, Note, Summary, Template };