Build a digital quality control and inspection checklist system for manufacturing and food businesses
* Preview is for reference only. Actual results may vary depending on the AI model, variable values, and tools used.
You are a senior full-stack engineer specialising in production quality management systems for Malaysian food and manufacturing SMEs. Build a complete digital Quality Control Checklist System for {{company_name}} that replaces paper-based QC forms and Excel tracking, with full support for {{compliance_standards}} compliance documentation requirements.
## Tech Stack
- **Framework**: Next.js 14 (App Router) + TypeScript
- **Styling**: Tailwind CSS + shadcn/ui component library
- **Backend/Database**: Supabase (PostgreSQL + Auth + Row Level Security)
- **File Storage**: Supabase Storage (for inspection photos)
- **PDF Generation**: @react-pdf/renderer (compliance audit reports)
- **Forms**: react-hook-form + zod validation
- **Charts**: Recharts for dashboard analytics
- **Deployment**: Vercel
## Database Schema
Create the following tables in Supabase:
sql
-- Product master
CREATE TABLE products (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
company_id uuid NOT NULL,
name_en text NOT NULL,
name_zh text,
sku text UNIQUE NOT NULL,
category text NOT NULL, -- sauce / rte / frozen / beverage
unit text NOT NULL DEFAULT 'pcs',
target_weight_g numeric,
weight_tolerance_g numeric,
halal_certified boolean DEFAULT false,
mesti_certified boolean DEFAULT false,
is_active boolean DEFAULT true,
created_at timestamptz DEFAULT now()
);
-- Production batches
CREATE TABLE batches (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
product_id uuid REFERENCES products(id),
batch_number text UNIQUE NOT NULL, -- e.g. B-20241015-003
production_date date NOT NULL,
expiry_date date,
quantity_produced numeric NOT NULL,
production_line text,
status text DEFAULT 'pending_qc'
CHECK (status IN ('pending_qc','in_inspection','passed','failed','on_hold','released')),
created_at timestamptz DEFAULT now()
);
-- Reusable checklist templates
CREATE TABLE checklist_templates (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name text NOT NULL,
product_category text, -- NULL means applies to all products
compliance_standard text, -- JAKIM / MeSTI / GMP / HACCP
version integer DEFAULT 1,
is_active boolean DEFAULT true,
created_by uuid REFERENCES auth.users(id),
created_at timestamptz DEFAULT now()
);
-- Sections within a template (e.g. Visual Inspection, Measurements)
CREATE TABLE checklist_sections (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
template_id uuid REFERENCES checklist_templates(id) ON DELETE CASCADE,
title_en text NOT NULL,
title_zh text,
display_order integer NOT NULL,
created_at timestamptz DEFAULT now()
);
-- Individual checklist items within a section
CREATE TABLE checklist_items (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
section_id uuid REFERENCES checklist_sections(id) ON DELETE CASCADE,
label_en text NOT NULL,
label_zh text,
item_type text NOT NULL
CHECK (item_type IN ('pass_fail','measurement','text','photo')),
is_critical boolean DEFAULT false, -- critical fail = whole batch fails
target_value numeric,
tolerance_plus numeric,
tolerance_minus numeric,
unit text, -- g / °C / % etc.
required_photo boolean DEFAULT false,
display_order integer NOT NULL,
hint_text text, -- guidance shown to inspector on mobile
created_at timestamptz DEFAULT now()
);
-- One inspection record per batch per checklist execution
CREATE TABLE inspections (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
batch_id uuid REFERENCES batches(id),
template_id uuid REFERENCES checklist_templates(id),
inspector_id uuid REFERENCES inspectors(id),
supervisor_id uuid REFERENCES inspectors(id),
status text DEFAULT 'in_progress'
CHECK (status IN ('in_progress','pending_review','approved','rejected')),
overall_result text
CHECK (overall_result IN ('pass','fail','conditional_pass')),
total_items integer DEFAULT 0,
passed_items integer DEFAULT 0,
failed_items integer DEFAULT 0,
na_items integer DEFAULT 0,
critical_failure boolean DEFAULT false,
inspected_at timestamptz DEFAULT now(),
submitted_at timestamptz,
approved_at timestamptz,
notes text,
created_at timestamptz DEFAULT now()
);
-- Individual item results within an inspection
CREATE TABLE inspection_items (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
inspection_id uuid REFERENCES inspections(id) ON DELETE CASCADE,
checklist_item_id uuid REFERENCES checklist_items(id),
result text CHECK (result IN ('pass','fail','na')),
measured_value numeric,
target_value numeric,
tolerance_plus numeric,
tolerance_minus numeric,
text_response text,
notes text,
created_at timestamptz DEFAULT now()
);
-- Photo evidence per inspection item
CREATE TABLE inspection_photos (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
inspection_item_id uuid REFERENCES inspection_items(id) ON DELETE CASCADE,
storage_path text NOT NULL,
caption text,
uploaded_at timestamptz DEFAULT now()
);
-- Inspectors and supervisors
CREATE TABLE inspectors (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid REFERENCES auth.users(id),
full_name text NOT NULL,
employee_id text UNIQUE,
role text CHECK (role IN ('inspector','supervisor','manager')),
certifications text[], -- e.g. ARRAY['GMP','HACCP','JAKIM Halal']
certification_expiry date,
is_active boolean DEFAULT true,
created_at timestamptz DEFAULT now()
);
-- Corrective actions raised for failed items
CREATE TABLE corrective_actions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
inspection_id uuid REFERENCES inspections(id),
inspection_item_id uuid REFERENCES inspection_items(id),
description text NOT NULL,
assigned_to uuid REFERENCES inspectors(id),
due_date date,
status text DEFAULT 'open'
CHECK (status IN ('open','in_progress','resolved','verified')),
resolution_notes text,
resolved_at timestamptz,
created_at timestamptz DEFAULT now()
);
-- Performance indexes (Postgres does NOT auto-index foreign keys)
CREATE INDEX idx_batches_product_id ON batches(product_id);
CREATE INDEX idx_batches_status ON batches(status);
CREATE INDEX idx_inspections_batch_id ON inspections(batch_id);
CREATE INDEX idx_inspections_inspector_id ON inspections(inspector_id);
CREATE INDEX idx_inspections_inspected_at ON inspections(inspected_at);
CREATE INDEX idx_inspection_items_inspection_id ON inspection_items(inspection_id);
CREATE INDEX idx_corrective_actions_inspection_id ON corrective_actions(inspection_id);
## Core Feature Modules
### 1. Checklist Template Builder (/admin/templates)
Build a drag-and-drop template editor:
- Organise items into named Sections; sections can be reordered via drag-and-drop
- Items within each section are also orderable
- Four item types:
- **pass_fail**: Large Pass / Fail / N/A radio buttons
- **measurement**: Numeric input with real-time tolerance check (green tick or red cross)
- **text**: Free-text textarea for qualitative observations
- **photo**: Camera capture — inspection cannot proceed without uploading at least one photo
- Each item has a **Critical** toggle — if any critical item is Fail, the entire batch auto-fails regardless of other results
- Optional **hint_text** per item provides on-screen guidance for floor inspectors using mobile devices
- Template versioning: editing a published template creates a new version; historical inspections always reference the version that was active at the time
- Templates can be scoped to a product category (e.g. frozen food only) or left as universal
### 2. Inspection Execution (/inspection/new)
This is the primary interface, optimised for tablet and mobile use on the factory floor:
**Step 1 — Select Batch**
- Scan a batch QR code or enter batch number manually
- Show product details, production date, quantity produced
- System auto-recommends the correct checklist template based on product category
- Pre-fill inspector name from the authenticated session
**Step 2 — Section-by-Section Inspection**
- Top progress bar showing current section (e.g. Section 2 of 5 — Measurements)
- Each item in the current section is rendered according to its type
- pass_fail: Large colour-coded buttons — Pass (green), Fail (red), N/A (grey) — minimum 44px height for touch targets
- measurement: Numeric keypad input with live indicator showing whether value is within tolerance bounds
- photo: Triggers device camera; multiple photos per item allowed; thumbnail preview shown
- When an item is marked Fail, a mandatory notes field expands — inspector must explain the failure before moving on
- Critical items are highlighted with a red CRITICAL badge
- Draft auto-saves to localStorage every 30 seconds so data is not lost if the browser closes
**Step 3 — Summary and Submission**
- Summary card: total items, pass count, fail count, N/A count, computed pass rate percentage
- List all failed items grouped by section; highlight critical failures in red
- For each Fail item, prompt inspector to create a Corrective Action record (description, assignee, due date) — this is mandatory before submission
- Auto-calculate overall_result:
- Any critical item failed → overall_result = 'fail', critical_failure = true
- Non-critical failure rate ≥ 5% → overall_result = 'fail'
- Non-critical failure rate < 5% and no critical failures → overall_result = 'conditional_pass'
- Zero failures → overall_result = 'pass'
- Inspector touch-signature capture using a canvas element
- On submit: batch status updates to 'pending_review'; supervisor receives in-app and email notification
### 3. Supervisor Review and Approval (/inspection/review)
- Queue of all inspections in 'pending_review' status, sorted by criticality then timestamp
- Full inspection detail view: every item result, measured values, photos, inspector notes
- Approve button: sets inspection status = 'approved', batch status = 'passed' or 'released'
- Reject button: sets status = 'rejected', requires reason; batch remains on hold; creates a re-inspection task
- Failed batches: supervisor must select disposition (quarantine / rework / destroy) before approval completes
- One-click PDF report generation for approved inspections
### 4. Analytics Dashboard (/dashboard)
Key metric cards at the top:
- Today's Inspections (count)
- Overall Pass Rate for current day / week / month with colour coding
- Pending Review count (amber warning if > 0)
- Open Corrective Actions count
- Inspectors with expiring certifications (within 30 days)
Charts section using Recharts:
- 30-day pass rate trend line chart with a reference line at the target threshold (e.g. 95%)
- Top 10 most frequent failure points bar chart — identifies systemic production issues
- Inspector performance table: inspections completed, average pass rate, average items per inspection
- Upcoming scheduled inspections calendar widget for the current week
- Products flagged as high-risk (3+ consecutive failed batches) — displayed as a warning alert card
### 5. Batch Traceability (/batches)
- Paginated batch list with filters: product, date range, status, production line
- Batch detail page: full inspection history timeline, all associated photos, corrective action resolution status
- Traceability export: CSV download of all batch-inspection data for a date range (for auditors)
- Auto-flag logic: when a product accumulates 3 consecutive failed batches, set a high_risk flag and email the production manager
- Record retention: apply Supabase retention policy or cron job to archive records older than 5 years to cold storage rather than deleting (regulatory requirement)
### 6. PDF Compliance Report Generation
Generate a formally structured PDF inspection report containing:
- Company letterhead (logo, company name, registration number, halal cert number)
- Batch information block: batch number, product name, production date, quantity
- Full checklist results table: section, item, result (colour coded), measured value vs target, tolerance, notes
- Photo evidence grid (thumbnail per item with caption)
- Corrective actions summary table
- Inspector digital signature and timestamp
- Supervisor approval signature and timestamp
- Report reference number (INS-YYYYMMDD-NNNN)
- Footer citing applicable standards: {{compliance_standards}}
## UI/UX Design Specifications
### Colour System and Layout
- Navigation bar: dark navy (#0F172A) background, white text, company name left, user avatar right
- Content area: white background (#FFFFFF), card borders slate-200
- Accent colour: yellow/gold (#FCD34D) for CTA buttons, pass rate numbers, progress bars — used sparingly
- Status colours: Pass = green-500 (#22C55E), Fail = red-500 (#EF4444), N/A = slate-400, Pending = amber-500 (#F59E0B)
- Typography: Inter for Latin, Noto Sans SC for Chinese characters, both loaded via next/font
### Mobile-First Inspection Form
- All interactive targets minimum 44px height
- Pass/Fail buttons full-width on mobile, side-by-side on desktop
- Sticky section progress bar at top during inspection
- Numeric inputs use inputmode="decimal" to trigger numeric keyboard on iOS/Android
- Offline draft persistence via localStorage; show a banner if unsaved draft is detected on page load
### Bilingual Support (Chinese Primary)
- Default language: Simplified Chinese
- Language toggle in header switches the entire UI to English
- All database-facing labels store both label_en and label_zh
- Error messages and validation text in Chinese by default
## Row Level Security Policies
sql
-- Inspectors can only access their own in-progress inspections
CREATE POLICY "inspector_own_inspections" ON inspections
FOR ALL USING (
inspector_id = (
SELECT id FROM inspectors
WHERE user_id = (SELECT auth.uid())
)
);
-- Supervisors and managers can view all inspections
CREATE POLICY "supervisor_view_all_inspections" ON inspections
FOR SELECT USING (
EXISTS (
SELECT 1 FROM inspectors
WHERE user_id = (SELECT auth.uid())
AND role IN ('supervisor','manager')
)
);
-- Only managers can create or modify checklist templates
CREATE POLICY "manager_manage_templates" ON checklist_templates
FOR ALL USING (
EXISTS (
SELECT 1 FROM inspectors
WHERE user_id = (SELECT auth.uid())
AND role = 'manager'
)
);
-- Anyone authenticated can read published templates and items
CREATE POLICY "auth_read_templates" ON checklist_templates
FOR SELECT USING (is_active = true AND (SELECT auth.uid()) IS NOT NULL);
## App Route Structure
app/
├── (auth)/login/page.tsx
├── dashboard/page.tsx
├── inspection/
│ ├── new/page.tsx # Multi-step inspection wizard
│ ├── [id]/page.tsx # Inspection detail view
│ └── review/page.tsx # Supervisor approval queue
├── batches/
│ ├── page.tsx # Batch list with filters
│ └── [id]/page.tsx # Batch detail + traceability
├── products/page.tsx
├── corrective-actions/page.tsx
├── admin/
│ ├── templates/page.tsx # Template builder
│ ├── inspectors/page.tsx
│ └── reports/page.tsx
└── api/
├── inspections/route.ts
├── batches/route.ts
└── reports/[id]/route.ts # Serve generated PDF
## Business Rules Summary
1. **Auto-fail on critical items**: Any item with is_critical = true that receives result = 'fail' immediately sets overall_result = 'fail' and critical_failure = true. This logic runs server-side in a Supabase function and cannot be overridden from the client.
2. **Mandatory supervisor sign-off**: Batches with overall_result = 'fail' or 'conditional_pass' must receive supervisor approval before batch status can change from 'pending_review'.
3. **Corrective action gate**: Inspectors cannot submit an inspection that contains Fail items unless every failed item has at least one corrective_action record linked to it.
4. **Record retention**: Inspection records, photos, and PDFs are retained for a minimum of 5 years. Implement a Supabase cron job that moves records older than 5 years to an archive table rather than deleting them.
5. **Recurring failure alerts**: A Postgres trigger or Edge Function checks after each inspection insert — if the same product has 3 consecutive failed batch inspections, send an email alert to all managers and set the product's high_risk flag.
6. **Inspector certification gate**: Inspectors whose certification_expiry is in the past cannot submit new inspections. Show a warning banner 30 days before expiry.
Product types covered: {{product_types}}
Checklist categories to support: {{checklist_categories}}
Compliance standards required: {{compliance_standards}}
Once all features are implemented, verify that the system produces documentation sufficient to satisfy an audit by JAKIM (Halal certification), SIRIM, and the Malaysian Ministry of Agriculture.