Author SHA1 Message Date
humam 3c55be5052 feat: add payroll, time clocks, and leave request modules
- Implemented PayrollPage for managing payroll runs with CRUD operations.
- Created TimeClocksPage for tracking employee clock-ins and clock-outs.
- Developed TimeSheetsPage for displaying employee timesheets.
- Added EmployeeCertificationForm and EmployeeDocumentForm for managing employee certifications and documents.
- Introduced LeaveRequestForm for submitting and managing leave requests.
- Added usePermissions hook for UI-side permission checks.
- Created LeaveRequestsClient and PayrollClient for API interactions.
2026-05-21 13:30:06 +04:00
humam 0d591b9807 feat: remove production environment configuration file 2026-05-21 13:29:58 +04:00
humam 4f0a2f790f feat: add logo field to settings schema and update settings client to handle file uploads
feat: integrate dialog close context in vendor select field and CRUD dialog components

feat: enhance vendor general info to format status using utility function

feat: implement form dialog context for managing dialog close actions

feat: add async select field dialog close context for better form handling

fix: update form mutation hook to close dialog on successful submission

feat: extend document print types to include expense and credit note

feat: add settings update payload type to include logo and other fields

feat: create employee attendance and work history pages with resource management

feat: implement payment made and received detail pages with actions

feat: add quick shortcuts component for easy navigation in the dashboard

feat: create actions for payment made and received with print and delete options

feat: implement dialog close context for better dialog management

feat: add error parsing utility for improved error handling in API responses
2026-05-19 17:56:39 +04:00
humam 2d6e3c5734 feat: add API endpoints for creating inspections from templates and sharing documents 2026-05-18 14:43:11 +04:00
humam 5570527e69 Merge branch 'fix/back-front-validation-alignment' into dev 2026-05-18 13:31:05 +04:00
humam 4bfd8c84a9 feat: add template checkpoint edit dialog and vendor management components
- Implemented TemplateCheckpointEditDialog for creating and editing inspection checkpoints.
- Added VendorActions component for managing vendor actions including edit, activate/deactivate, and delete.
- Created VendorContext for managing vendor state across components.
- Developed VendorGeneralInfo component to display detailed vendor information.
- Introduced AedSymbol and Money components for consistent currency representation.
- Added PromptDialog for user input prompts throughout the application.
- Implemented RelationLink component for unified related-data display in CRUD tables.
- Created InspectionTemplatesClient for API interactions related to inspection templates.
2026-05-18 12:08:42 +04:00
humam 54d11f01b4 feat: enhance import/export functionality with detailed results dialog and improved data handling 2026-05-15 11:34:23 +04:00
humam fcbba6247d feat: add document sharing functionality across various modules
- Introduced ShareDocumentButton component for sharing documents.
- Added ShareDocumentDialog for email and WhatsApp sharing options.
- Integrated document sharing in estimates, invoices, inspections, job cards, bills, and purchase orders.
- Implemented useDocumentShare hook for handling share logic.
- Created DocumentShareClient for API interactions related to document sharing.
- Updated layouts and actions to include sharing options for relevant entities.
2026-05-14 12:21:01 +04:00
humam 05b55b5721 fix: add staleTime to job card expense, parts, and services queries; update job card general info and payments received components 2026-05-13 17:20:59 +04:00
humam 6b356d2855 fix estimate table and expense items 2026-05-13 15:55:40 +04:00
Najjar\NajjarV02 464402f4d6 Merge fix/back-front-validation-alignment into dev 2026-05-12 17:34:16 +04:00
Najjar\NajjarV02andClaude Opus 4.7 cc7dc1bd17 fix: align frontend zod schemas with backend validation rules
Tightened frontend zod schemas where backend required fields the frontend marked optional, and matched enum/format constraints.

Schemas:
- vehicle-document: document_type required
- parts: shop_type, category, unit_type, department, sku required
- inspections: customer, vehicle, department, inspection_category, employee, order_number, date, time required
- appointments: service_writer required, cross-field to_time > from_time
- vendor-credits: vendor + vendor_credit_date required
- job-cards: documents[].document_type_id required
- expense-items: category, unit_type, department, sku required
- inventory-adjustments: reference_number, date required
- tasks: task_type, task_section required
- shop-timings: in_time, out_time enforce HH:MM:SS regex
- vendor-credit: subject + vendor + vendor_credit_date required

Settings:
- shop-type: shop_type + note required
- insurance-types: description field added, required
- make-and-models: shop_type required, year 1900..2100
- departments: assignment_type required enum (AssignmentType)
- company: website URL validation, latitude/longitude range, first_day_of_work enum, string max lengths
- configurations: 4 fields enum-typed (was raw strings)

Inline forms:
- job-card service/part/expense-item: relations required (part/service/expense_item/department)
- job-card recommendation: max 255
- vehicles/inline-forms/shop-type: shop_type + note required
- vehicles/inline-forms/body-type: shop_type_id pulled from parent form context, guard on submit
- vehicles/inline-forms/color: code field added, required
- services/inline-forms/department: assignment_type required enum
- tasks/task-section: arrangement required integer
- invoices/invoice-edit: status + discount enum-typed

Auth:
- login: password min 6 (was 8; backend allows 6)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 16:22:26 +04:00
239 changed files with 11917 additions and 1569 deletions
+13
View File
@@ -0,0 +1,13 @@
{
"permissions": {
"allow": [
"Bash(pnpm --version)",
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
]
},
"enabledMcpjsonServers": [
"code-review-graph"
],
"enableAllProjectMcpServers": true
}
+1
View File
@@ -11,6 +11,7 @@ node_modules
.env.development.local
.env.test.local
.env.production.local
.env.prod
# Testing
coverage
+486
View File
@@ -0,0 +1,486 @@
# Garage ERP — Feature Gap Plan vs. Industry Leaders
> Comparison of the current Reparee Garage ERP against established automotive
> workshop management platforms (GarageBox, Tekmetric, Shopmonkey, AutoLeap,
> Garage Hive, Mitchell 1 Manager SE, MaxxTraxx, Workshop Software).
>
> Goal: list what does **not** yet exist in this codebase, group it by impact,
> and give each gap an implementation hint so it can be picked up later.
---
## 1. What Reparee already has (baseline)
Captured from the current backend (`reparee_backend/`) controllers/models and
dashboard navigation (`apps/dashboard/config/navGroups.tsx`):
**Sales & service workflow**
- Customers (with notes, types, referral sources, import/export)
- Vehicles (owners, makes/models, body types, fuel, transmission, colors,
documents, mileage history, import/export)
- Inspections + Inspection Templates (categories, checkpoints, labels)
- Public share link for inspections (token-based, rate-limited)
- Estimates → Job Cards → Invoices (services, parts, expense items, internal
notes, labels, document attachments)
- Credit Notes
- Payments Received
- Appointments (calendar)
**Purchases**
- Vendors (addresses, status, credits)
- Expenses & Expense Items
- Purchase Orders (with internal notes, labels)
- Bills
- Payments Made
- Vendor Credits
**Items / inventory**
- Services and Service Groups (with includes/pricing/parts)
- Parts (with categories, unit types)
- Inventory Adjustments
- Labor Rates, Taxes
**HR / productivity**
- Employees (with documents, certifications, avatar, performance, permissions)
- Departments, Roles (with `permission.check` middleware on every route)
- Leave Requests + Leave Balance
- Payroll Runs + Entries + Slips
- Tasks, Task Sections, Task Types, TimeSheet
- Shop Calendar, Shop Timing, Holidays
**Platform**
- PDF generation via `DocumentPrintController` + Blade templates
- Document share tokens
- Settings (company, including logo + Terms & Conditions in `privacy_policy`)
- i18n EN/AR with RTL
- OpenAPI client (`packages/api/`) regenerated from backend spec
**Sidebar shows planned-but-disabled groups** (commented out in
`navGroups.tsx`): CRM (leads/calls/tasks), Marketing (service reminders,
ratings/reviews, Google reviews), Accountants (manual journals, chart of
accounts), Reports, Payroll, Integrations, Templates.
---
## 2. Priority matrix
| Tier | Meaning |
|------|---------|
| **P0** | Table-stakes for a modern garage SaaS — competitors all ship it, customers ask first |
| **P1** | Significant value-add, expected by mid-market shops |
| **P2** | Differentiators / nice-to-haves |
| **P3** | Long-tail integrations and advanced workflows |
---
## 3. P0 — Table-stakes gaps
### 3.1 Reporting & Analytics dashboard
**Status:** No `/reports` route exists; sidebar entry is commented out. A
`/` dashboard page exists but is not analytics-rich.
**What competitors ship:**
- Revenue by day/week/month, by service category, by technician
- Open jobs / WIP value, ARO (Average Repair Order), gross profit %
- Aging receivables (already implicit in invoices, no view)
- Parts margin, labor margin
- Technician productivity (billed hours vs. clocked hours)
- Inventory turnover, stock-outs
- Customer retention / first-visit vs. repeat
**Plan:**
- New backend controllers: `ReportController` exposing aggregations
(revenue, AR aging, technician utilization, inventory turnover).
- New dashboard area: `apps/dashboard/app/(authenticated)/reports/`
with sub-routes per report.
- Re-use TanStack Query + a chart lib already approved (or ask before adding
recharts / visx). KPIs on home page should pull from the same endpoints.
### 3.2 Service Reminders (mileage- and time-based)
**Status:** `Vehicle` has mileage logs (`VehicleMileAndKm`) and documents
have expiry dates, but no reminder engine. Sidebar Marketing group is
commented out.
**What competitors ship:**
- "Next service in 5,000 km" rules per vehicle/service
- Insurance / registration / inspection expiry reminders
- Auto-send via email/SMS X days before due
- Customer can click to book
**Plan:**
- New model: `ServiceReminderRule` (per vehicle or template per make/model:
due_at_date, due_at_mileage, service_group_id, channel).
- Scheduled job (Laravel scheduler) that scans daily and queues notifications.
- Channel adapters wired to the notification stack from §3.3.
- UI under `productivity` or new `marketing/` area.
### 3.3 Customer notifications (Email / SMS / WhatsApp)
**Status:** No notification channels found beyond document share links. No
`Notification` or messaging tables in models.
**What competitors ship:**
- Twilio/Vonage SMS, WhatsApp Business API
- Two-way SMS thread per customer/job (Tekmetric, Shopmonkey)
- Templated estimate-ready / job-ready / pickup-ready messages
- Inbox view of all customer conversations
**Plan:**
- Add `notification_channels` config + adapter interface
(`App\Services\Notifications\Channel`).
- Provider drivers behind feature flags (SMS via Twilio/MessageBird, email
via existing Laravel mail, WhatsApp via Meta Cloud API).
- Tables: `customer_messages` (inbound + outbound), `notification_templates`
(subject/body, locale, type).
- Dashboard inbox under `/sales/customers/[id]/messages` + global `/inbox`.
### 3.4 Customer-facing portal (estimate approval, history)
**Status:** Only `PublicInspectionController` exists for public viewing.
Estimates and invoices have no customer-side approval flow.
**What competitors ship:**
- Customer logs in (or magic-link) and sees: vehicles, history, estimates,
invoices, upcoming appointments.
- One-click approve / decline / partial-approve on estimate line items
(digital authorization with audit trail).
- Pay invoice via portal.
**Plan:**
- Reuse `DocumentShare` token pattern, broaden into a `customer_portal_token`.
- New `PublicEstimateController` mirroring `PublicInspectionController`,
with POST endpoints for approve/decline per line item.
- Persist signature/IP/timestamp on `EstimateAuthorisationHistory` (model
already exists — confirm fields cover approvals from portal).
- Frontend: new public route group `app/portal/` (no auth, token-scoped).
### 3.5 Online payments
**Status:** `PaymentMode` table exists, payments are recorded manually. No
gateway integration.
**What competitors ship:**
- Stripe / Square / regional gateway integration
- "Pay invoice" link inside email/SMS
- Saved cards, partial payments, tips
- Reconciliation back to `PaymentRecieved`
**Plan:**
- Pluggable gateway driver under `App\Services\Payments\`.
- New endpoint `POST /api/invoices/{id}/payment-link` returns hosted URL.
- Webhook handler that creates `PaymentRecieved` rows on capture.
- Frontend `pay/[token]` page bundled with the portal in §3.4.
### 3.6 Audit log
**Status:** No audit/activity table found.
**What competitors ship:** Who changed what, when, on every business
record. Required for shops with multiple staff.
**Plan:**
- Adopt `spatie/laravel-activitylog` (request before adding the dep) or
hand-roll a polymorphic `activity_log` table.
- Log on estimate/job-card/invoice state transitions, permission changes,
payment events.
- Read-only view at `/settings/activity-log`.
### 3.7 Workflow / Kanban board for Job Cards
**Status:** Job Cards live in a list view. No status pipeline UI.
**What competitors ship:** Drag-and-drop columns ("Checked-in", "Awaiting
Parts", "In Progress", "QC", "Ready for Pickup"). Drives the shop's day.
**Plan:**
- Add `job_card_status` (enum or FK to `job_card_statuses` table editable
in settings).
- Backend: status transition endpoint with allowed-transition guard.
- Frontend: new `/sales/job-cards/board` route using dnd-kit (already in
the React ecosystem; confirm dep). Cards link to existing detail page.
### 3.8 Vehicle service history (per VIN, cross-customer)
**Status:** History is currently scoped via the vehicle's job cards, but
there is no consolidated "vehicle history" tab summarizing services,
inspections, mileage, and recommendations together.
**Plan:**
- New endpoint `GET /api/vehicles/{id}/timeline` merging job cards,
inspections, recommendations, document expiries, mileage events into a
single chronological feed.
- Tab on the vehicle detail page rendering the timeline.
### 3.9 Recommended / deferred work tracking
**Status:** `FastShopRecommendation` and `ShopRecommendation` models exist
but there is no "deferred services" view that follows the vehicle across
visits.
**Plan:**
- Extend recommendations with `status` (open/accepted/declined/expired) and
`next_followup_at`.
- Surface on vehicle detail, estimate creation ("pull deferred items"), and
in service-reminder logic (§3.2).
---
## 4. P1 — Significant value-add
### 4.1 Technician time tracking on job cards (clock in/out per labor line)
**Status:** Generic `TimeSheet` exists but is not bound to job-card lines.
The sidebar already shows "Time Clocks" — confirm whether implemented or
stubbed.
**Plan:**
- New table `job_card_labor_time` (job_card_service_id, employee_id,
started_at, stopped_at).
- Mobile-friendly start/stop UI on the job-card page (tap-and-go).
- Feed billed-vs-clocked into the productivity report (§3.1).
### 4.2 Estimate templates / service packages with menus
**Status:** Service Groups exist (`ServiceGroup`, `ServiceGroupService`,
`ServiceGroupPart`, `ServiceGroupPricing`). Gap: no canned "menus" UI
(e.g., "30k-mile service" preset that drops services + parts + labor onto
an estimate in one click).
**Plan:**
- Repurpose Service Groups as menus; add a "Add menu" picker on the
estimate editor that expands the group into individual lines (so they
can still be edited).
### 4.3 Customer digital signature on documents
**Status:** Documents print to PDF; no signature capture.
**Plan:**
- Add a signature pad component (svg path → PNG) on the customer portal
approval screen (§3.4) and in-shop tablet flow.
- Persist as a `document_signatures` row (signer name, type, timestamp,
IP/UA, image blob in storage).
- Embed signature in printed PDF.
### 4.4 Parts barcode / QR scanning
**Status:** Parts have SKUs but no barcode field or scan UI.
**Plan:**
- Add `barcode` column to `parts`.
- Use the device camera (BarcodeDetector API) on the inventory adjustment
and job-card "Add part" dialogs.
### 4.5 Tablet / shop-floor UI
**Status:** UI is desktop-first.
**Plan:**
- Audit job-card detail, inspection editor, and time-clock screens for
touch targets and one-hand portrait use.
- Optional dedicated route `/floor/[job-card]` with a stripped-down layout.
### 4.6 Photos & videos on inspections (with public share)
**Status:** `InspectionCheckPointAttachment` and `InspectionAttachment`
models exist — confirm whether the share link renders attachments.
**Plan:**
- Verify the public inspection view (`PublicInspectionController@show`)
exposes media URLs with signed access.
- Add front-camera capture in the inspection editor for fast photo-taking.
### 4.7 Multi-location / branch support
**Status:** `Settings` is single-tenant; no `branch_id` scoping on
business records.
**Plan:** This is a bigger lift. Phased:
1. Add `branches` table and `branch_id` FK on the major aggregates
(job_cards, invoices, vehicles, parts, employees).
2. Default to a single seeded branch for existing deployments.
3. Add branch selector in header and scope queries via global scope.
### 4.8 Custom fields
**Status:** No custom-field infrastructure.
**Plan:**
- New `custom_field_definitions` (entity_type, key, label, type, options)
and `custom_field_values` (polymorphic).
- Render dynamically on customer/vehicle/job-card forms.
### 4.9 Marketing campaigns
**Status:** Sidebar has the group commented out.
**Plan:**
- Reuse §3.3 channels.
- New `marketing_campaigns` (name, audience filter, template_id, schedule)
and `marketing_sends` (per-recipient log).
- Audience builder uses the customer/vehicle filters already in the table
views.
### 4.10 Ratings & reviews capture
**Plan:**
- Post-pickup auto-message asking for a rating (1–5) and free text.
- If 4–5, deep-link to Google review URL (configurable in settings).
- Internal review wall + ability to publish to a public testimonials
endpoint.
### 4.11 Accounting export (QuickBooks / Xero / Zoho)
**Status:** No GL / chart of accounts (sidebar group is disabled).
**Plan (lightweight first):**
- CSV export of invoices, payments, bills, payments-made tagged with
configurable account codes.
- Later: OAuth integration with QuickBooks Online / Xero APIs.
### 4.12 Tire & wheel module (heavy in GarageBox, Tekmetric)
**Plan:** Tire size lookup, DOT tracking, storage racks (off-season tire
storage is a common revenue line in cold-climate markets). Skip unless
target market needs it.
### 4.13 Warranty tracking on parts and services
**Plan:**
- Add `warranty_months` / `warranty_km` on parts and services.
- Show "under warranty" badge when re-invoicing the same VIN within the
window. Block billing or flag for review.
### 4.14 Fleet customer accounts
**Plan:**
- Allow a customer to own many vehicles already supported, but add a
"fleet" customer type with: bulk PO upload, monthly statement instead of
per-invoice billing, optional driver/vehicle list.
### 4.15 Online appointment booking widget
**Plan:**
- Public route `/book` that surfaces shop services + free calendar slots
(derived from `ShopTiming` and existing appointments).
- Creates a draft `Appointment` + customer/vehicle if new.
- Embed snippet for the shop's marketing site.
---
## 5. P2 — Differentiators
### 5.1 VIN decoder integration (NHTSA free API + paid Carfax)
- NHTSA `vpic.nhtsa.dot.gov/api/` is free, no auth — wire it into the
vehicle create form to auto-fill make/model/year/engine from VIN.
- Carfax/AutoCheck for paid history reports (US/CA).
### 5.2 OEM repair info integration (Mitchell 1, AllData, Identifix, Haynes)
- Big lift, paid feeds. Out of scope for v1; design the parts/services
data model so labor times can be imported.
### 5.3 Parts catalog integrations (WorldPac, NAPA PROLink, PartsTech)
- Real-time pricing + availability + ordering from inside a job card.
- Phase 1: PartsTech (aggregator) since it covers the most vendors.
### 5.4 Two-way calendar sync (Google / Microsoft)
- iCal feed for read-only first.
- Full two-way sync via Google Calendar API later.
### 5.5 AI-assisted estimate writer
- "Customer says: knocking noise on left front when braking" → suggested
service lines + parts list from history of similar jobs. Useful and
novel; defer until enough invoice data exists.
### 5.6 Mobile apps (technician + customer)
- React Native (or PWA first) sharing `@garage/api`.
- Technician: today's jobs, start/stop labor, take photos, mark complete.
- Customer: portal features (§3.4) packaged as an app.
### 5.7 OBD-II / telematics integration
- Long tail. Plan only the data model now (`vehicle_telemetry_events`).
### 5.8 Loyalty / gift cards / membership plans
- "Service plan: 2 oil changes/year + 10% off for $X/mo".
- Recurring billing on top of §3.5.
### 5.9 Discounts and promo codes at line-item or document level
- Currently no promo entity. Add `discounts` (code, type, %/amount, scope,
expiry, usage cap) with hook in estimate/invoice totals.
### 5.10 Multi-currency
- `Settings` is implicitly single-currency. Add currency on documents and a
daily rates table if shops need cross-border invoicing.
---
## 6. P3 — Long-tail / future
- Insurance claim workflow (estimator → adjuster handoff, photos packet,
EMS export).
- Inventory replenishment automation (min/max → auto PO draft).
- Bay / lift management (assign job card to a bay; show bay utilization).
- AI photo damage assessment for inspections.
- Recall lookup (NHTSA recall API by VIN).
- TPMS / tire pressure history per vehicle.
- Public price-list / "instant quote" widget.
- Webhook system for third-party integrators.
- Bring-your-own-domain customer portal branding.
- Backup export of entire tenant data (GDPR-friendly).
---
## 7. Cross-cutting platform work
These aren't a single feature, but unlock many of the above:
1. **Background job runner** — Laravel Horizon + Redis if not already set
up; required for §3.2, §3.3, §4.9.
2. **Storage policy** — confirm S3-compatible storage so signatures,
media, and PDFs scale.
3. **Feature flag system** — many of the above are tenant-gated; even a
simple `tenant_features` table beats hard-coded toggles.
4. **OpenAPI coverage** — every new backend endpoint must add an
annotation so `packages/api` stays in sync (already a project
convention).
5. **Permission seeds** — every new route requires a matching permission
(project rule: routes are gated by `permission.check`).
6. **Lang pairs** — every `lang/en/*.php` key must have a matching
`lang/ar/*.php` key (project rule).
7. **PDF template** — every new printable type needs an entry in
`DocumentPrintController::TYPES` plus a Blade template under
`resources/views/pdf/`.
---
## 8. Suggested phased roadmap
A pragmatic build order that maximizes early customer value and reuses
infrastructure:
**Phase 1 — "Looks competitive"** (P0 core)
- Reporting dashboard (§3.1)
- Workflow board for job cards (§3.7)
- Audit log (§3.6)
- Vehicle timeline (§3.8)
- Recommended / deferred work tracking (§3.9)
**Phase 2 — "Talks to the customer"**
- Notifications channel (§3.3) — SMS + email first
- Customer portal w/ estimate approval (§3.4)
- Online payments (§3.5)
- Service reminders (§3.2)
- Ratings & reviews capture (§4.10)
**Phase 3 — "Runs the shop floor"**
- Technician time tracking on labor (§4.1)
- Estimate menus / service packages UI (§4.2)
- Photos on inspections, end-to-end (§4.6)
- Customer digital signature (§4.3)
- Tablet / shop-floor UI polish (§4.5)
**Phase 4 — "Scales the business"**
- Multi-location (§4.7)
- Custom fields (§4.8)
- Marketing campaigns (§4.9)
- Online booking widget (§4.15)
- Accounting exports (§4.11)
**Phase 5 — "Differentiators"**
- VIN decoder (§5.1)
- Parts catalog integrations (§5.3)
- Calendar sync (§5.4)
- Loyalty / memberships (§5.8)
- Mobile apps (§5.6)
---
## 9. Open questions to confirm before starting
1. Target market geography — drives gateway choice (Stripe vs. local), SMS
provider, accounting integration (QuickBooks vs. Zoho vs. Tally), and
whether tire/snow modules matter.
2. Is multi-tenancy single-DB (current) or DB-per-tenant?
3. Are Horizon + Redis available in production today?
4. Is there an approved chart library, or does adding one need a green
light? (CLAUDE.md says no new deps without approval.)
5. Should the customer portal share auth with the dashboard (Sanctum) or
use a token-only public route like inspections do today?
+551
View File
@@ -0,0 +1,551 @@
# Reparee → Garage Box Feature Parity — Implementation Roadmap
> **Purpose of this doc.** Single source of truth for closing the gap between Reparee's current dashboard and Garage Box. Captures the gap analysis, the canonical Reparee patterns to mimic, and a per-phase implementation spec detailed enough for a fresh agent to pick up any phase and ship it without re-discovering conventions.
> **Status (2026-05-21).** Phase 1 (Integrations placeholder) is the only phase ready to execute. Phases 2–8 are spec'd here but not started. Pick one, re-open it in a focused planning session, and implement.
---
## 0. Reading order
1. **Part A — Gap analysis** (what's missing and why).
2. **Part B — Project conventions cheatsheet** (the patterns every phase MUST follow).
3. **Part C — Phase index** (the at-a-glance table).
4. **Part D — Per-phase implementation specs** (Phases 1–8, in recommended build order).
---
## Part A — Gap analysis (Garage Box vs Reparee)
Legend: ✅ exists ⚠️ partial / different location ❌ missing
### Already covered
- **Sales** (Customers, Vehicles, Inspections, Estimates, Job Cards, Invoices, Payments Received, Credit Notes) — ✅
- **Purchases** (Vendors, Expenses, POs, Bills, Payments Made, Vendor Credits) — ✅
- **Employees / Productivity** (Employees, Time Clocks, Time Sheets, Payroll, Shop Calendars, Shop Timing, Holidays, Tasks, Leave Requests) — ✅ (Reparee adds Leave Requests beyond Garage Box)
- **Items** (Services, Parts, Expense Item, Service Group, Inventory Adjustments) — ✅
- **Settings** Company / Shop Types / Tax & Rates / Configurations — ✅
### Gaps
| Garage Box | Status in Reparee | Phase |
|---|---|---|
| Settings → Integrations | ❌ → placeholder | **Phase 1** |
| Settings → Master (hub for body types + make & model + other lookups) | ❌ as a hub (data scattered) | **Phase 2** |
| Settings → Templates (notification template library, ~35 templates × 4 channels) | ⚠️ only inspection templates | **Phase 3** |
| Reports (top-level module) | ❌ | **Phase 4** |
| CRM (Leads pipeline, Calls log + calendar, Tasks pipeline) | ❌ (Reparee has only productivity tasks, not CRM tasks) | **Phase 5** |
| Marketing (Service Reminders, Rating & Reviews, Google Business Reviews) | ❌ | **Phase 6** |
| Settings → Integrations (real connectors: Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp) | ❌ | **Phase 7** |
| Accountants (Chart of Accounts + Manual Journals + default account wiring) | ❌ | **Phase 8** |
### Cross-cutting Garage Box conventions to mimic
- **Pipelines** (Leads, Tasks) have user-editable column **sections** (add / rename / reorder). Default sections seeded on first run.
- **`+ Label`** chip on every record (taxonomy / colored tags).
- **Configurable doc-number sequences** with a gear icon next to the `#` field (`LD-000001`, `CL-000001`, `TK-000001`, `JN-000001`, etc.).
- **Notification templates** are channel-aware (SMS / WhatsApp / Email / Push) with per-channel toggles.
- **Per-row Department filter** is universal — every list view has a Department dropdown in the toolbar.
---
## Part B — Project conventions cheatsheet (MUST follow in every phase)
> Every phase below assumes these patterns. Don't re-invent.
### B1. Frontend module structure
- **Modules live at** `garage-erp/apps/dashboard/modules/<area>/`.
- Each resource gets: `<resource>-form.tsx`, `<resource>.schema.ts` (Zod), optional `<resource>-actions.tsx`, optional inline section components (e.g. `<resource>-services-section.tsx`).
- **Reference**: `garage-erp/apps/dashboard/modules/estimates/` is the canonical example. Mirror its file layout for any new resource.
### B2. Routes (Next.js App Router)
- List page: `app/(authenticated)/<area>/<resource>/page.tsx` (`"use client"` + `ResourcePage<Client>`).
- Detail page: `app/(authenticated)/<area>/<resource>/[id]/page.tsx` (async server component, uses `getServerApi()` + `DashboardPage`).
- Sub-tabs of a detail (e.g. notes, documents): `[id]/<subroute>/page.tsx`.
- **Reference**: `app/(authenticated)/sales/estimates/page.tsx` (list) + `[id]/page.tsx` (detail).
### B3. Tables & row actions
- Use TanStack Table via `ResourcePage` wrapper.
- Row actions via `actionsColumn({ extraItems: (row) => [...] })`.
- Print buttons via `useDocumentPrint(type, id)` from `apps/dashboard/shared/hooks/use-document-print.ts`.
### B4. Forms
- React Hook Form 7 + Zod 4. Schema lives in `<resource>.schema.ts`.
- Use `useResourceForm<FormValues, ApiPayload>({ schema, resourceId, initialize, mapToFormValues })` from `apps/dashboard/shared/hooks/`.
- Mutations: `useFormMutation` for create/update; invalidate via `tableQuery.invalidateQuery()` or the resource's query key.
### B5. Sidebar navigation
- Single source: `garage-erp/apps/dashboard/config/navGroups.tsx` — hard-coded, **no i18n layer**.
- Add a new group entry or a sub-item; pick a `lucide-react` icon already imported (or add to the import block at top of file).
### B6. API client (`@garage/api`)
- All clients extend `CrudClient<INDEX_ROUTE, BY_ID_ROUTE>` (path: `packages/api/src/clients/<name>.ts`).
- After backend changes, **regenerate**: `pnpm --filter @garage/api generate` (runs `generate:openapi && generate:types`).
- The generated files in `packages/api/` are NOT hand-edited; only the thin client wrappers are.
### B7. Backend routes
- **Legacy string controller resolution** in `reparee_backend/routes/api.php`:
```php
Route::get('/leads', 'LeadController@index');
Route::post('/leads', 'LeadController@store');
// etc.
```
- **Every route is gated** by `permission.check` middleware (auto-applied group-wide).
### B8. Backend controllers
- Standard CRUD shape: `index`, `show`, `store`, `update`, `destroy` returning `JsonResponse`.
- Path: `reparee_backend/app/Http/Controllers/Api/<Name>Controller.php`.
- Use `vyuldashev/laravel-openapi` annotations so OpenAPI spec stays in sync (mirror `EstimateController`).
### B9. Models & migrations
- Models in `reparee_backend/app/Models/`. Use `$fillable`, `$casts`, relations.
- Migrations: `php artisan make:migration create_<table>_table` → standard `Schema::create` with `$table->id()` + `timestamps()`.
### B10. Permissions
- Permissions are **columns on the `roles` table**: `can_{view|create|update|delete}_{resource}`.
- To add a new resource:
1. Create a migration that adds the four boolean columns to `roles` (default `false`).
2. Update `database/seeders/RoleSeeder.php` so Super Admin gets `true` for all new columns (it auto-discovers `can_*` columns — verify).
3. The `permission.check` middleware reads the column name from the route name; ensure route is named `<resource>.<ability>` or matches its existing convention.
- **Reference migration**: `2026_04_06_120000_create_roles_table_and_refactor_employee_permissions.php`.
### B11. i18n (backend)
- Pairs required: every new key in `lang/en/<file>.php` MUST have the matching `lang/ar/<file>.php` key in the same change.
- Use `__('api.<area>.<key>')` in controllers and responses.
- Dashboard nav labels are NOT translated (hard-coded in `navGroups.tsx`).
### B12. Document-print (PDF)
- Single entry: `POST /api/document-print` → `DocumentPrintController@handle`.
- To add a printable type:
1. Add string to `DocumentPrintController::TYPES`.
2. Add `payload<Type>()` method on the controller.
3. Add `resources/views/pdf/document-print-<type>.blade.php`.
4. Add the type to the `DocumentPrintType` union in `packages/api/src/clients/document-print.ts`.
### B13. Pipeline-with-sections precedent
- `TaskSection` model + `task-section-form.tsx` already exist. Fields: `title`, `arrangement` (sort order), `is_default`.
- Reuse this pattern for `LeadSection`, `CallSection` (if needed), `JournalSection`, etc.
### B14. House rules (from `CLAUDE.md`)
- Never `git commit / push / tag / reset --hard / rebase` — stop at file edits.
- Don't add new dependencies without explicit approval.
- After edits, run `pnpm --filter dashboard typecheck`, `pnpm --filter dashboard lint`, and `php -l` on changed PHP files, then report results.
- Match existing conventions before introducing new patterns.
---
## Part C — Phase index
| # | Phase | Effort | Backend changes | Frontend changes | Depends on |
|---|---|---|---|---|---|
| 1 | Integrations placeholder | XS (1 hr) | none | 2 files | — |
| 2 | Settings → Master hub | S (1 day) | none (regroup) | 1 layout + tabs | — |
| 3 | Notification Templates library | M (3 days) | new table + CRUD + permission | full module | — |
| 4 | Reports (4 reports locked) | M (1 wk) | 4 aggregation endpoints | reports module + 4 reports w/ Recharts | reads existing data |
| 5 | CRM (Leads, Calls, Tasks-CRM) | XL (2–3 wks) | 3 resources + sections + permissions + i18n | 3 modules + pipelines | reuses TaskSection pattern |
| 6 | Marketing (Reminders email+SMS, Reviews) | L (1–2 wks) | reminder engine + Twilio integration + reviews | 3 sub-pages | needs Phase 3 (templates); Twilio composer dep |
| 7 | ~~Integrations (real)~~ | DEFERRED | — | — | — |
| 8A | Accountants — COA + Manual Journals | L (1.5 wks) | ledger UI only, no auto-post | 3 sub-pages | — |
| 8B | Accountants — auto-posting | L (1–2 wks) | observers on Invoice/Bill/Payment/Expense + reversal | linkage panels on source docs | requires 8A stable |
---
## Part D — Per-phase implementation specs
# Phase 1 — Settings → Integrations (Coming Soon)
**Goal.** Add an Integrations entry under Settings that renders a "Coming soon" placeholder.
### Backend
None.
### Frontend
1. **Edit** `garage-erp/apps/dashboard/config/navGroups.tsx` (around line 183):
- There is already a commented-out entry:
```tsx
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> }
```
- Uncomment it but change `href` to `/settings/integrations` (single page, no sub-tabs yet).
- Insert between `Inspection Templates` and `Configurations`. Confirm `PlugZapIcon` is in the top-of-file imports; if not, add `PlugZapIcon` to the `lucide-react` import.
2. **Create** `garage-erp/apps/dashboard/app/(authenticated)/settings/integrations/page.tsx`:
- Use `DashboardPage` with `headerProps={{ title: "Integrations" }}` (match `settings/insurance-types/page.tsx`).
- Centered `Empty` block (from `@/shared/components/ui/empty`):
- `EmptyMedia`: `<PlugZapIcon className="size-12 text-muted-foreground" />`
- `EmptyTitle`: "Coming soon"
- `EmptyDescription`: "Connect WhatsApp, payments, accounting and email providers. Available in an upcoming release."
### Verification
1. `pnpm --filter dashboard dev`.
2. Sidebar → Settings expands → new "Integrations" entry visible between Inspection Templates and Configurations.
3. Click → page renders with the Empty state.
4. `pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`.
### Out of scope
Sub-tabs (Providers / Integrations), any provider logic, backend.
---
# Phase 2 — Settings → Master hub
**Goal.** Group existing lookup data screens under one "Master" sidebar entry with tabs, matching Garage Box's UX.
### Tabs (in order)
1. Body Types (existing `/settings/...`)
2. Make & Model (existing `/settings/make-and-models`)
3. Insurance Types (existing `/settings/insurance-types`)
4. Departments (existing `/settings/departments`)
5. Shop Types (move from top-level OR alias)
6. Vehicle Transmissions, Fuel Types, Colors, Unit Types, Payment Terms, Payment Modes, Labor Rates, Reasons, Referral Sources, Document Types, Labels — surface those that currently lack a dedicated screen.
### Backend
None new. Verify every tab's data source has a controller in `app/Http/Controllers/Api/` (most already do: `MakeAndModelController`, `InsuranceTypeController`, `DepartmentController`, `VehicleBodyTypeController`, `VehicleTransmissionController`, `VehicleFuelTypeController`, `VehicleColorController`, `UnitTypeController`, `PaymentTermController`, `PaymentModeController`, `LaborRateController`, `ReasonController`, `ReferralSourceController`, `DocumentTypeController`, `LabelController`).
### Frontend
1. **Create** `app/(authenticated)/settings/master/layout.tsx` with a `Tabs` header (use existing `Tabs` from `packages/ui`) and the 11+ tab labels above.
2. **Create** `app/(authenticated)/settings/master/page.tsx` that redirects to `./body-types`.
3. **Create** `app/(authenticated)/settings/master/<each-tab>/page.tsx`. Each is a thin wrapper that imports and renders the existing module list component from `modules/settings/<existing-folder>/`.
4. **Edit** `config/navGroups.tsx`: add `{ title: "Master", href: "/settings/master", icon: <DatabaseIcon /> }` after Integrations. **Keep** the existing top-level entries (Insurance Types, Departments, Make & Models) in the Settings list — they coexist as aliases for backwards-compat (per Part F decision).
### Verification
1. Sidebar → Settings → Master → tabs render and each tab CRUDs correctly.
2. Direct URL `/settings/master/insurance-types` works.
3. Removed/aliased entries still resolve to the same screen.
---
# Phase 3 — Notification Templates library
**Goal.** Manage ~35 notification templates (per Garage Box screenshot 16) with per-channel toggles and bodies. Required for Phase 6 (Marketing) and any reminder/automation.
### Data model
| Table | Columns |
|---|---|
| `notification_templates` | `id`, `key` (unique e.g. `appointment_created`), `title`, `description` (nullable), `created_at`, `updated_at` |
| `notification_template_channels` | `id`, `notification_template_id` (FK), `channel` enum(`sms`,`whatsapp`,`email`,`push`), `enabled` bool, `subject` (nullable, for email), `body` text, `created_at`, `updated_at` |
Seed all template `key`s from this list (extracted from Garage Box image 16):
- `appointment_assigned`, `appointment_cancelled`, `appointment_confirmed`, `appointment_create`, `appointment_no_shows`, `appointment_reminder`, `appointment_requested`, `appointment_reschedule`, `appointment_unconfirmed`
- `attendance_details`, `attendance_reminder`
- `call_assigned`, `call_cancelled`, `call_completed`, `call_rescheduled`, `call_scheduled`
- `estimate_approved_by_admin`, `estimate_approved_by_customer`, `estimate_send`
- `job_card_customer`, `job_card_technician`
- `login_otp`
- `new_lead_notification`
- `part_requisition_create`
- `purchase_order_create`
- `ratings_reviews_link`
- `salary_change_notification`
- `send_customer_statement`, `send_inspection`, `send_invoice`, `send_vendor_statement`
- `service_reminder_cancelled`, `service_reminder_reschedule`, `service_reminder_scheduled`, `service_reminder_send`
- `work_request_form_send`, `workorder_create`
### Backend
- `NotificationTemplateController` (`index`, `show`, `update` only — templates are seeded, not user-created).
- Routes (string-resolution style):
```php
Route::get('/notification-templates', 'NotificationTemplateController@index');
Route::get('/notification-templates/{key}', 'NotificationTemplateController@show');
Route::put('/notification-templates/{key}', 'NotificationTemplateController@update');
```
- Permissions: `can_view_notification_templates`, `can_update_notification_templates` (skip create/delete — seed-managed).
- Lang keys in `lang/en/api.php` + `lang/ar/api.php` under `notification_templates`.
### Frontend
1. **Module** `apps/dashboard/modules/notification-templates/` with `notification-template-row.tsx`, `notification-template-edit-dialog.tsx`, `notification-template.schema.ts`.
2. **Route** `app/(authenticated)/settings/templates/notifications/page.tsx` — TanStack Table with columns: Title, SMS (✓/—), WhatsApp, Email, Push, Actions.
3. **Sidebar entry**: `config/navGroups.tsx` add `{ title: "Templates", href: "/settings/templates/notifications", icon: <FileTextIcon /> }` between Inspection Templates and Integrations. (Or restructure existing `/settings/templates` if free.)
4. **Edit dialog**: tabs per channel, body editor with **variable picker** (e.g. `{{customer.name}}`, `{{vehicle.plate}}`, `{{appointment.date}}`). Variables list lives in a `notification-template-variables.ts` constants file co-located with the module.
5. **API client**: `packages/api/src/clients/notification-templates.ts` extends `CrudClient`.
### Verification
1. Seeded list shows all 35+ rows.
2. Toggle a channel → persists.
3. Edit body → re-render shows updated body.
4. Backend `__('api.notification_templates.updated')` returns Arabic when locale is `ar`.
---
# Phase 4 — Reports
**Goal.** Top-level Reports module with categorized reports across Sales, Purchases, Inventory, Employees, Accountants.
### Reports to ship (v1 — locked per Part F)
1. **Sales by Customer** — revenue grouped by customer with date range + department filter.
2. **Invoices Aging** — outstanding invoices bucketed 0–30 / 31–60 / 61–90 / 90+ days.
3. **Technician Productivity** — hours logged vs billable per technician, derived from `TimeSheet` + job-card service rows.
4. **Inventory Valuation + Low-Stock** — current stock value by part + list of parts under reorder threshold.
All other reports candidates (Sales by Service/Vehicle, Payments Summary, Estimates Conversion, Purchases by Vendor, Bills Aging, Stock Movement, Attendance, Payroll, Job Card Turnaround/Status) are deferred to a follow-up phase. Architect the reports module so adding the 5th report is trivial.
### Charting
Use **Recharts** via the already-installed wrapper `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency. Wrapper exports `ChartContainer`, `ChartTooltip`, `ChartTooltipContent`, etc. — mimic shadcn's chart usage docs.
### Backend
- `app/Http/Controllers/Api/Reports/` directory — one controller per report category (`SalesReportController`, `PurchasesReportController`, etc.).
- Each report = single GET endpoint accepting `from`, `to`, optional `department_id`, `customer_id`, etc. Returns aggregated rows.
- Use Eloquent + `selectRaw` aggregations. Index any frequently-grouped columns via migration.
- Routes grouped under `/api/reports/...`. New permission per category: `can_view_reports_sales`, `can_view_reports_purchases`, ...
- **No new models or tables** — pure read aggregation over existing data.
- Lang keys for report titles in `lang/en/reports.php` + `lang/ar/reports.php`.
### Frontend
1. **Module** `apps/dashboard/modules/reports/` with:
- `report-card.tsx` (preview tile in the index).
- `report-filters.tsx` (date range, department, customer/vendor).
- One subdirectory per category: `sales/`, `purchases/`, `inventory/`, `employees/`, `job-cards/`. Each contains a `<report-name>-report.tsx` data view.
2. **Routes**:
- `app/(authenticated)/reports/page.tsx` — index grid of report cards grouped by category.
- `app/(authenticated)/reports/<category>/<slug>/page.tsx` — individual report view with filters + table + export buttons.
3. **Sidebar**: add a new top-level group `{ title: "Reports", href: "/reports", icon: <BarChart3Icon /> }` after Items/Employees in `navGroups.tsx`.
4. **Export**: reuse `useDocumentPrint` pattern for PDF; for Excel use existing `maatwebsite/excel` backend integration (add new export classes in `app/Exports/Reports/`).
5. **Charts**: prefer `recharts` if already in `packages/ui` dependencies; otherwise propose to user before adding.
### Verification
1. Each report renders with sample data filtered by date range.
2. PDF export uses the same layout shell as other prints (`resources/views/pdf/layouts/document.blade.php`).
3. Excel export downloads a valid `.xlsx`.
4. Permissions block access when role lacks `can_view_reports_<category>`.
---
# Phase 5 — CRM (Leads, Calls, Tasks-CRM)
**Goal.** Add the missing CRM module with three pipelines: Leads, Calls, Tasks (distinct from existing productivity tasks). Mirrors Garage Box screenshots 1–8.
### Sub-phase 5a — Leads
#### Data model
| Table | Key columns |
|---|---|
| `lead_sections` | `id`, `title`, `arrangement`, `is_default`, `kind` enum(`open`,`won`,`lost`) (kind drives default behavior). Reuse `TaskSection` pattern. |
| `leads` | `id`, `number` (unique, e.g. `LD-000001`), `title`, `date`, `lead_owner_id` (FK users), `referral_source_id` (FK), `lead_status_id` (FK), `department_id`, `description`, `lead_section_id` (FK), `customer_id` (nullable), `vehicle_id` (nullable), salutation, first/last/company name, phone, email, address fields, vehicle fields (make, model, plate, body_type_id). |
| `lead_services` | pivot to services |
| `lead_parts` | pivot to parts |
| `lead_labels` | pivot to `labels` table |
#### Backend
- `LeadController`, `LeadSectionController`, `LeadServiceController`, `LeadPartController` (mirror Estimate's split).
- Permissions: `can_view_leads`, `can_create_leads`, `can_update_leads`, `can_delete_leads`, plus `can_manage_lead_sections`.
- Number sequence: reuse `InvoiceSequenceController` pattern (add `LeadSequenceController`).
- Lang keys under `lang/en/api.php` `leads` section + `lang/ar/api.php`.
- OpenAPI annotations on each method.
#### Frontend
- **Module** `apps/dashboard/modules/leads/` with `lead-form.tsx`, `lead.schema.ts`, `lead-pipeline.tsx` (Kanban view), `lead-actions.tsx`, inline sections for services/parts.
- **Routes** `app/(authenticated)/crm/leads/page.tsx` (Kanban + table toggle), `[id]/page.tsx` (detail).
- **Sidebar** new group `{ title: "CRM", icon: <UsersIcon />, items: [Leads, Calls, Tasks] }` after Purchases in `navGroups.tsx`.
- **Pipeline UI**: Kanban with `@dnd-kit` (check if already in deps before adding). Each column = a `LeadSection`. "+ Section" button opens a section dialog (reuse `task-section-form.tsx` pattern).
- **API client** `packages/api/src/clients/leads.ts`.
### Sub-phase 5b — Calls
#### Data model
| Table | Key columns |
|---|---|
| `calls` | `id`, `number` (`CL-000001`), `call_for` (polymorphic morphs to Customer/Lead), `vehicle_id`, `status` enum(`requested`,`scheduled`,`completed`,`cancelled`), `type` enum(`inbound`,`outbound`), `subject`, `call_owner_id`, `call_date`, `from_time`, `to_time`, `department_id`, `purpose_id` (FK to lookup), `agenda` text, `outcome_id` (nullable FK), `description`, `duration_minutes`, `duration_seconds`, `voice_recording_path`, `send_notification` bool. |
| `call_reminders` | `id`, `call_id`, `unit` int, `unit_type` enum(`minute`,`hour`,`day`), `event` enum(`before`,`after`), `channel` enum(`sms`,`email`,`whatsapp`). |
| `call_purposes`, `call_outcomes` | lookups |
#### Backend
- `CallController` (CRUD + special endpoints: `complete`, `cancel`, `reschedule`).
- `CallReminderController` (nested).
- Reminder dispatcher: a Laravel scheduled job in `app/Console/Commands/SendDueCallReminders.php` runs every minute, sends pending reminders via the relevant notification template (Phase 3) through the provider configured in Phase 7. If Phase 7 not yet shipped, log-only.
- Permissions: standard four + `can_log_calls`, `can_complete_calls`.
#### Frontend
- **Module** `apps/dashboard/modules/calls/` with `call-form.tsx` (schedule), `call-log-form.tsx` (log), `call.schema.ts`, `call-calendar.tsx`.
- **Routes** `app/(authenticated)/crm/calls/page.tsx` (table + tabs Requested/Scheduled/Completed/Cancelled), `crm/calls/calendar/page.tsx` (month view), `[id]/page.tsx`.
### Sub-phase 5c — Tasks (CRM)
**Approach locked per Part F: Option A — extend existing `tasks` table.**
#### Migration
Add to the existing `tasks` table:
- `context` enum (`productivity`, `crm`), default `productivity`, NOT NULL.
- `customer_id` nullable FK to `customers`.
- `vehicle_id` nullable FK to `vehicles`.
- Index on `(context, status)` for the pipeline filter.
#### Backend
- Backfill existing rows to `context = 'productivity'`.
- All existing `TaskController` queries get a `->where('context', 'productivity')` filter so `/productivity/tasks` keeps showing only what it shows today.
- Add `CrmTaskController` (thin) that scopes to `context = 'crm'` and exposes the same CRUD + section endpoints. Reuse the `TaskSection` table for sections (add a `context` column there too, same enum).
- Permissions: introduce `can_view_crm_tasks`, `can_create_crm_tasks`, `can_update_crm_tasks`, `can_delete_crm_tasks` separate from the existing productivity-task permissions.
#### Frontend
- New module `apps/dashboard/modules/crm-tasks/` mirroring Leads pipeline pattern (Kanban with sections).
- Route `app/(authenticated)/crm/tasks/page.tsx` (Kanban + table toggle).
- Re-use schema fragments from `modules/tasks/` where possible — extract shared bits to a `modules/tasks/shared/` if duplication grows.
### Verification (Phase 5 overall)
1. Pipeline drag-and-drop persists section + arrangement.
2. New lead with vehicle info creates a corresponding draft Customer + Vehicle (or links existing) — confirm desired behavior.
3. Call scheduled with a 10-min reminder → cron job fires at expected time.
4. Number sequences advance correctly when a record is created.
---
# Phase 6 — Marketing (Service Reminders + Reviews)
**Goal.** Automate service reminders based on mileage / time, plus collect and surface customer reviews.
### Service Reminders
- New table `service_reminders`: `id`, `customer_id`, `vehicle_id`, `reminder_type` (`mileage` / `time`), `interval_value`, `interval_unit`, `last_triggered_at`, `next_due_at`, `status` enum(`scheduled`,`sent`,`cancelled`), `channels` JSON (subset of `['email','sms']`).
- Scheduled command `app/Console/Commands/SendDueServiceReminders.php` runs daily; sends via Phase 3 templates (`service_reminder_send`).
- **Channels (per Part F)**: **Email** via Laravel `Mail::to(...)->send(...)` using the configured mail sender; **SMS** via Twilio.
- Install `twilio/sdk` (Composer) — flag this dependency add for user approval per CLAUDE.md house rules.
- Add a `NotificationDispatcher` service in `app/Services/Notifications/` with `sendEmail()` and `sendSms()` methods. Reads Twilio credentials from `config/services.php` (`twilio.sid`, `twilio.token`, `twilio.from`) which read from `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`).
- WhatsApp/Push channel toggles render but are disabled with a "Requires integration" tooltip — wiring up to providers happens in deferred Phase 7.
- Frontend: `app/(authenticated)/marketing/service-reminders/page.tsx` — list with status tabs, "Create reminder" form with Email + SMS channel checkboxes.
### Rating & Reviews
- New table `customer_reviews`: `id`, `customer_id`, `job_card_id`, `rating` 1–5, `comment`, `submitted_at`, `source` enum(`internal`,`google`).
- Public-facing review form already partially served by `PublicInspectionController` pattern — extend with `PublicReviewController`.
- After job-card completion, fire `ratings_reviews_link` template (Phase 3).
- Frontend list at `app/(authenticated)/marketing/reviews/page.tsx`.
### Google Business Reviews
- Read-only sync via Google Business Profile API (requires Phase 7 Google integration).
- Background job polls every 6 h.
- Render in same Reviews list with `source = google` badge.
### Sidebar
- Add CRM-style group `{ title: "Marketing", icon: <MegaphoneIcon />, items: [Service Reminders, Reviews, Google Reviews] }` after CRM.
### Verification
1. Create a mileage-based reminder → next_due_at calculated.
2. Cron tick at due time → template send is recorded (or logged if Phase 7 incomplete).
3. Submit a public review → appears in admin list.
---
# Phase 7 — Integrations (real connectors) — DEFERRED
**Status (per Part F decision): NOT IN ROADMAP.** The Phase 1 "Coming soon" placeholder is the long-term state for now. Twilio (SMS) and Laravel mail (email) used by Phase 6 are configured via `.env` only — no user-facing integrations UI.
Keep this spec as reference for when integrations become a priority later.
**Goal (when revived).** Replace the Phase 1 placeholder with a real Providers/Integrations page connecting Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp. Twilio also moves into the UI at that point.
### Data model
| Table | Key columns |
|---|---|
| `integration_providers` | seeded list: `id`, `key` (slug), `name`, `purpose`, `icon_path`, `auth_type` (`oauth2`/`api_key`/`webhook`), `is_active`. |
| `integration_connections` | per-tenant connection: `id`, `provider_id`, `credentials` (encrypted JSON), `status` (`connected`/`disconnected`/`error`), `last_synced_at`. |
### Backend
- `IntegrationProviderController` (list), `IntegrationConnectionController` (CRUD + `connect`, `disconnect`, `test`).
- One service class per provider in `app/Services/Integrations/<Provider>/`. Each implements a common contract `IntegrationDriver` with `connect()`, `disconnect()`, `sendMessage()`, `pullData()`.
- OAuth callback routes: `/integrations/{provider}/callback`.
- Permissions: `can_manage_integrations`.
- Lang keys for connection status messages.
### Frontend
- **Replace** the Phase 1 placeholder page with `app/(authenticated)/settings/integrations/page.tsx` showing a `Tabs` of "Providers" (catalog) + "Integrations" (connected list).
- **Provider catalog tile** with "Connect" button → opens OAuth popup or credentials dialog.
- Update `navGroups.tsx`: `href: "/settings/integrations/providers"` (the original commented-out path).
### Verification
1. Connect Google → OAuth popup → callback persists tokens → "Connected" badge appears.
2. Test SMS via Vonage → message delivered (in sandbox).
3. Disconnect → credentials zeroed.
### Out of scope for first cut
Real-time webhook handlers for each provider (do them incrementally, one provider per follow-up PR).
---
# Phase 8 — Accountants
**Goal.** Introduce a real general ledger. Split into two sub-phases per Part F: ship the ledger UI first (8A), wire auto-posting into existing modules afterward (8B).
## Phase 8A — Chart of Accounts + Manual Journals + Default Configuration
Ship the standalone ledger. No existing controllers are touched. Users can manually post journal entries; nothing auto-posts.
### Data model
| Table | Key columns |
|---|---|
| `chart_of_accounts` | `id`, `name`, `code` (nullable), `account_type` enum(`asset`,`liability`,`equity`,`income`,`expense`,`cogs`), `parent_id` (nullable, for sub-accounts), `is_system` bool (lock icon in UI), `note`. |
| `journals` | `id`, `number` (`JN-000001`), `date`, `reference`, `notes`, `total_amount` (must balance), `posted_by`, `posted_at`. |
| `journal_lines` | `id`, `journal_id`, `account_id`, `debit`, `credit`, `description`. Constraint: sum(debit) == sum(credit) per journal. |
| `default_account_settings` | single-row config table for: `sales_account_id`, `purchase_account_id`, `inventory_account_id`, `adjustment_account_id`, `customer_advance_account_id`, `deposit_to_account_id`, `vendor_advance_account_id`, `paid_through_account_id`, `purchase_discount_account_id`, `expense_account_id`. |
### Seed
Seed ~80 standard accounts matching Garage Box screenshot 9 (Accounts Payable, Accounts Receivable, Advance Tax, … VAT Payable). Mark system accounts (`is_system = true`).
### Backend (8A only)
- `ChartOfAccountController`, `JournalController`, `DefaultAccountSettingsController`.
- Permissions: `can_view_accountants`, `can_manage_chart_of_accounts`, `can_post_journals`.
- OpenAPI annotations.
- **No changes to existing controllers** in this sub-phase — Invoices/Bills/Payments/Expenses are untouched.
### Frontend
- **Sidebar group** `{ title: "Accountants", icon: <BookOpenIcon />, items: [Manual Journals, Chart Of Accounts] }` after Purchases.
- **Module** `apps/dashboard/modules/accountants/` with `chart-of-account-list.tsx`, `chart-of-account-form.tsx`, `journal-form.tsx` (multi-line debit/credit with running balance check), `default-account-settings-form.tsx`.
- **Routes**: `app/(authenticated)/accountants/chart-of-accounts/page.tsx`, `accountants/manual-journals/page.tsx`, `[id]/page.tsx`.
### Verification (8A)
1. Seed list matches Garage Box exactly (account names + types).
2. Create a manual journal with unbalanced lines → backend rejects.
3. Default Configuration dialog persists.
4. Invoices/Bills/Payments/Expenses still work unchanged (no regression).
## Phase 8B — Auto-posting + cross-doc linking
Wire the ledger into operational modules. **Only start after 8A is stable in production.**
### Backend
- New service `app/Services/Accounting/JournalPoster.php` with methods like `postInvoice(Invoice $i)`, `postBill(Bill $b)`, `postPaymentReceived(...)`, `postPaymentMade(...)`, `postExpense(...)`.
- Hook into existing controllers via Eloquent `created` / `updated` model observers (cleaner than editing every controller). Observers live in `app/Observers/`, registered in `EventServiceProvider`.
- Each posted journal gets a `source_type` + `source_id` morphable pair so it links back to the originating document.
- Reversal logic: when a source doc is deleted or voided, post the reverse journal (don't soft-delete the original).
- New permission: `can_post_automatic_journals` (default true for finance roles).
### Frontend
- On Invoice / Bill / Payment / Expense detail pages: add a "Journal Entry" panel showing the posted journal lines (read-only) with a deep link to `/accountants/manual-journals/<id>`.
- On Journal detail: show "Source Document" link back to the originating doc.
### Verification (8B)
1. Create an Invoice → Journal auto-posts (debit AR, credit Sales, credit Tax).
2. Edit Invoice amount → existing journal reversed + new one posted.
3. Delete Invoice → reversal posted; original journal preserved for audit.
4. Default Configuration changes are respected on next post.
5. Audit trail: every Journal has a non-null `source_type`/`source_id` when auto-posted.
---
## Part E — Cross-cutting follow-ups (every phase finishes with)
1. Run **`pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`** — must pass.
2. Run **`php -l`** on every changed PHP file.
3. Regenerate API client if backend changed: **`pnpm --filter @garage/api generate`**.
4. Update lang pairs (`lang/en/*.php` + `lang/ar/*.php`).
5. Update permission migration + seeder for any new permission columns.
6. Use the `code-review-graph` MCP `detect_changes_tool` + `get_review_context_tool` before opening the PR to self-review.
7. Update `claude-timeline/YYYY-MM-DD.md` with a one-line note about the phase shipped (per global memory rule).
8. **Do not commit** — leave the diff for the user to review.
---
## Part F — Resolved decisions (2026-05-21)
All open questions answered by the user. These are now binding for the phases referenced.
- **Phase 2 (Master)** → **Keep top-level entries as aliases.** Insurance Types, Departments, Make & Models remain in the Settings sidebar AND appear under Master tabs. Backwards-compat for bookmarks. No redirects, no removals.
- **Phase 4 (Reports) — charts** → **Use Recharts (already installed)** via the existing wrapper at `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency.
- **Phase 4 (Reports) — v1 scope** → ship exactly these four reports:
1. Sales by Customer
2. Invoices Aging (0–30 / 31–60 / 61–90 / 90+ days)
3. Technician Productivity (hours logged vs billable per technician)
4. Inventory Valuation + Low-Stock
All other reports listed in Phase 4 are deferred.
- **Phase 5c (CRM Tasks)** → **Extend the existing `tasks` table** (Option A). Add `context` enum (`productivity` | `crm`), nullable `customer_id`, nullable `vehicle_id`. All existing task queries get a `context = 'productivity'` filter.
- **Phase 6 (Marketing reminders) — channels** → **Email + SMS in v1; WhatsApp deferred.**
- Email sends via Laravel's configured mail sender (`config/mail.php`) — works out of the box, no Integrations UI required.
- SMS sends via **Twilio**. Configured server-side via `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`) — not surfaced in the Integrations page yet.
- WhatsApp channel toggles are visible but disabled with a "Requires integration" tooltip.
- **Phase 7 (Integrations real)** → **Stays "coming soon."** The Phase 1 placeholder is the long-term state for now. Twilio + Laravel mail are configured server-side only; no user-facing connector UI in this roadmap. Phase 7's detailed spec is preserved as a future reference but no work is planned.
- **Phase 8 (Accountants)** → **Split into two sub-phases:**
- **Phase 8A**: Chart of Accounts + Manual Journals + Default Configuration UI. No automatic posting from other modules.
- **Phase 8B**: Auto-post journals on Invoice / Bill / Payment / Expense create + link from each source doc to its posted journal entry. Big blast radius — ship only after 8A is stable.
@@ -5,11 +5,12 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { RelationLink } from "@/shared/components/relation-link"
import { formatEnum } from "@/shared/utils/formatters"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
@@ -26,6 +27,9 @@ export default function AppointmentsPage() {
<ResourcePage<AppointmentsClient>
pageTitle="Appointments"
routeKey={APPOINTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search appointments..."
statusFilter={{ statuses: AppointmentStatus }}
getClient={(api) => api.appointments}
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -77,7 +81,7 @@ export default function AppointmentsPage() {
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
return (
<Badge className={colorClass}>
{status?.replace("_", " ") ?? "—"}
{formatEnum(status)}
</Badge>
)
},
@@ -86,22 +90,14 @@ export default function AppointmentsPage() {
id: "job_card",
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
cell: ({ row }) => {
const jobCardId = (row.original as any).job_card_id
if (!jobCardId) return <span className="text-muted-foreground">—</span>
const item = row.original as any
const jobCardId = item.job_card_id ?? item.job_card?.id
return (
<Button
variant="outline"
size="sm"
className="h-7 gap-1.5"
onClick={(e) => {
e.stopPropagation()
router.push(`/sales/job-cards/${jobCardId}`)
}}
>
<ClipboardListIcon className="size-3" />
#{jobCardId}
<ExternalLinkIcon className="size-3" />
</Button>
<RelationLink
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
icon={ClipboardListIcon}
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
/>
)
},
},
@@ -201,15 +201,20 @@ export default function InventoryAdjustmentsPage() {
<ResourcePage<InventoryAdjustmentsClient>
pageTitle="Inventory Adjustments"
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search adjustments..."
getClient={(api) => api.inventoryAdjustments}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Inventory Adjustment">
{(resourceId) => (
<FormDialog
title="Inventory Adjustment"
classNames={{ dialogContent: "lg:min-w-4xl" }}
>
{(resourceId, { close }) => (
<InventoryAdjustmentForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
onSuccess={() => { invalidateQuery(); close() }}
/>
)}
</FormDialog>
@@ -12,15 +12,20 @@ export default function ExpenseItemPage() {
<ResourcePage<ExpenseItemsClient>
pageTitle="Expense Items"
routeKey={EXPENSE_ITEM_ROUTES.INDEX}
searchable
searchPlaceholder="Search expense items..."
getClient={(api) => api.expenseItems}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Expense Item">
{(resourceId) => (
{(resourceId, { close }) => (
<ExpenseItemForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
onSuccess={() => {
invalidateQuery()
close()
}}
/>
)}
</FormDialog>
@@ -17,6 +17,8 @@ export default function PartsPage() {
<ResourcePage<PartsClient>
pageTitle="Parts"
routeKey={PARTS_ROUTES.INDEX}
searchable
searchPlaceholder="Search parts..."
getClient={(api) => api.parts}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -24,6 +26,7 @@ export default function PartsPage() {
<ImportDataButton
onImport={(file) => api.parts.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Parts"
/>
<ExportDataButton
onExport={(filters) => api.parts.exportData(filters)}
@@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
<ResourcePage<ServiceGroupsClient>
pageTitle="Service Groups"
routeKey={SERVICE_GROUP_ROUTES.INDEX}
searchable
searchPlaceholder="Search service groups..."
getClient={(api) => api.serviceGroups}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -17,6 +17,8 @@ export default function ServicesPage() {
<ResourcePage<ServicesClient>
pageTitle="Services"
routeKey={SERVICE_ROUTES.INDEX}
searchable
searchPlaceholder="Search services..."
getClient={(api) => api.services}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -24,6 +26,7 @@ export default function ServicesPage() {
<ImportDataButton
onImport={(file) => api.services.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Services"
/>
<ExportDataButton
onExport={(filters) => api.services.exportData(filters)}
@@ -0,0 +1,100 @@
"use client"
import { use } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { Badge } from "@/shared/components/ui/badge"
import { TIME_SHEET_ROUTES } from "@garage/api"
import type { TimeSheetsClient } from "@garage/api"
import { ClockIcon } from "lucide-react"
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
general: "secondary",
order: "default",
task: "outline",
}
function formatTime(value: unknown) {
if (!value || typeof value !== "string") return "—"
return value.length >= 5 ? value.slice(0, 5) : value
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function formatCost(value: unknown) {
if (value === null || value === undefined) return "—"
const n = Number(value)
if (!Number.isFinite(n)) return "—"
return n.toFixed(2)
}
export default function EmployeeAttendancePage({ params }: { params: Promise<{ id: string }> }) {
const { id: employeeId } = use(params)
return (
<ResourcePage<TimeSheetsClient>
pageTitle="Attendance"
routeKey={TIME_SHEET_ROUTES.INDEX}
getClient={(api) => api.timeSheets}
extraParams={{ employee_id: employeeId }}
header={null}
statusFilter={{
statuses: ["general", "order", "task"],
paramKey: "activity_type",
allLabel: "All",
}}
columns={() => [
{
accessorKey: "date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<ClockIcon className="size-4 text-muted-foreground" />
<span>{formatDate((row.original as any).date)}</span>
</div>
),
},
{
accessorKey: "clock_in",
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
},
{
accessorKey: "clock_out",
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
},
{
accessorKey: "duration",
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
},
{
accessorKey: "activity_type",
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
cell: ({ row }) => {
const type = (row.original as any).activity_type ?? "general"
return <Badge variant={ACTIVITY_VARIANT[type] ?? "secondary"}>{type}</Badge>
},
},
{
accessorKey: "calculated_total_cost",
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
cell: ({ row }) => formatCost((row.original as any).calculated_total_cost),
},
{
accessorKey: "note",
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
cell: ({ row }) => {
const v = (row.original as any).note
return v ? <span className="text-sm">{v}</span> : "—"
},
},
]}
/>
)
}
@@ -0,0 +1,179 @@
"use client"
import { useState } from "react"
import { useParams } from "next/navigation"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { Plus, Trash2, ExternalLinkIcon, AwardIcon } from "lucide-react"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { EmployeeCertificationForm } from "@/modules/employees/employee-certification-form"
type CertRow = {
id: number
name: string
issuer?: string | null
certificate_number?: string | null
issued_date?: string | null
expiry_date?: string | null
file_url?: string | null
is_expired?: boolean
notes?: string | null
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
export default function EmployeeCertificationsPage() {
const { id: employeeId } = useParams<{ id: string }>()
const api = useAuthApi()
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
const queryKey = ["employee-certifications", employeeId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.employees.listCertifications(employeeId) as Promise<{ data: CertRow[] | { data: CertRow[] } }>,
})
const rows: CertRow[] = Array.isArray((data as any)?.data)
? (data as any).data
: ((data as any)?.data?.data ?? [])
const deleteMutation = useMutation({
mutationFn: (id: number) => api.employees.destroyCertification(employeeId, String(id)),
onSuccess: () => {
toast.success("Certification deleted")
queryClient.invalidateQueries({ queryKey })
},
onError: () => toast.error("Failed to delete"),
})
async function handleDelete(row: CertRow) {
const ok = await confirm({
title: "Delete certification?",
description: `Permanently delete "${row.name}"?`,
confirmLabel: "Delete",
variant: "destructive",
})
if (ok) deleteMutation.mutate(row.id)
}
const columns: ColumnDef<CertRow>[] = [
{
accessorKey: "name",
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<AwardIcon className="size-4 text-muted-foreground" />
<span className="font-medium">{row.original.name}</span>
</div>
),
},
{
accessorKey: "issuer",
header: ({ column }) => <ColumnHeader column={column} title="Issuer" />,
cell: ({ row }) => row.original.issuer ?? "—",
},
{
accessorKey: "certificate_number",
header: ({ column }) => <ColumnHeader column={column} title="Cert #" />,
cell: ({ row }) => {
const v = row.original.certificate_number
return v ? <span className="font-mono text-xs">{v}</span> : "—"
},
},
{
accessorKey: "issued_date",
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
cell: ({ row }) => formatDate(row.original.issued_date),
},
{
accessorKey: "expiry_date",
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<span>{formatDate(row.original.expiry_date)}</span>
{row.original.is_expired && <Badge variant="destructive">Expired</Badge>}
</div>
),
},
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<div className="flex justify-end gap-1">
{row.original.file_url && (
<Button variant="ghost" size="icon" asChild>
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
<ExternalLinkIcon className="size-4" />
</a>
</Button>
)}
<Button
variant="ghost"
size="icon"
disabled={deleteMutation.isPending}
onClick={() => handleDelete(row.original)}
>
<Trash2 className="size-4 text-destructive" />
</Button>
</div>
),
},
]
return (
<DashboardPage
headerProps={{
title: "Certifications",
actions: (
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="size-4" />
Add Certification
</Button>
),
}}
>
<DataTable
columns={columns}
data={rows}
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
/>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Certification</DialogTitle>
</DialogHeader>
<EmployeeCertificationForm
employeeId={employeeId}
onSuccess={() => {
setOpen(false)
queryClient.invalidateQueries({ queryKey })
}}
onCancel={() => setOpen(false)}
/>
</DialogContent>
</Dialog>
</DashboardPage>
)
}
@@ -0,0 +1,182 @@
"use client"
import { useState } from "react"
import { useParams } from "next/navigation"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { Plus, Trash2, ExternalLinkIcon, FileTextIcon } from "lucide-react"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { EmployeeDocumentForm } from "@/modules/employees/employee-document-form"
import { formatEnum } from "@/shared/utils/formatters"
type DocRow = {
id: number
name: string
type: string
file_url?: string
issued_date?: string | null
expiry_date?: string | null
notes?: string | null
created_at?: string
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function isExpired(value: unknown) {
if (!value || typeof value !== "string") return false
const d = new Date(value)
return !Number.isNaN(d.getTime()) && d.getTime() < Date.now()
}
export default function EmployeeDocumentsPage() {
const { id: employeeId } = useParams<{ id: string }>()
const api = useAuthApi()
const queryClient = useQueryClient()
const [open, setOpen] = useState(false)
const queryKey = ["employee-documents", employeeId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.employees.listDocuments(employeeId) as Promise<{ data: DocRow[] | { data: DocRow[] } }>,
})
const rows: DocRow[] = Array.isArray((data as any)?.data)
? (data as any).data
: ((data as any)?.data?.data ?? [])
const deleteMutation = useMutation({
mutationFn: (id: number) => api.employees.destroyDocument(employeeId, String(id)),
onSuccess: () => {
toast.success("Document deleted")
queryClient.invalidateQueries({ queryKey })
},
onError: () => toast.error("Failed to delete document"),
})
async function handleDelete(row: DocRow) {
const ok = await confirm({
title: "Delete document?",
description: `Permanently delete "${row.name}"?`,
confirmLabel: "Delete",
variant: "destructive",
})
if (ok) deleteMutation.mutate(row.id)
}
const columns: ColumnDef<DocRow>[] = [
{
accessorKey: "name",
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<FileTextIcon className="size-4 text-muted-foreground" />
<span className="font-medium">{row.original.name}</span>
</div>
),
},
{
accessorKey: "type",
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
cell: ({ row }) => <Badge variant="outline">{formatEnum(row.original.type)}</Badge>,
},
{
accessorKey: "issued_date",
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
cell: ({ row }) => formatDate(row.original.issued_date),
},
{
accessorKey: "expiry_date",
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
cell: ({ row }) => {
const v = row.original.expiry_date
if (!v) return "—"
return (
<div className="flex items-center gap-2">
<span>{formatDate(v)}</span>
{isExpired(v) && <Badge variant="destructive">Expired</Badge>}
</div>
)
},
},
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<div className="flex justify-end gap-1">
{row.original.file_url && (
<Button variant="ghost" size="icon" asChild>
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
<ExternalLinkIcon className="size-4" />
</a>
</Button>
)}
<Button
variant="ghost"
size="icon"
disabled={deleteMutation.isPending}
onClick={() => handleDelete(row.original)}
>
<Trash2 className="size-4 text-destructive" />
</Button>
</div>
),
},
]
return (
<DashboardPage
headerProps={{
title: "Documents",
actions: (
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="size-4" />
Upload Document
</Button>
),
}}
>
<DataTable
columns={columns}
data={rows}
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
/>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Upload Document</DialogTitle>
</DialogHeader>
<EmployeeDocumentForm
employeeId={employeeId}
onSuccess={() => {
setOpen(false)
queryClient.invalidateQueries({ queryKey })
}}
onCancel={() => setOpen(false)}
/>
</DialogContent>
</Dialog>
</DashboardPage>
)
}
@@ -28,6 +28,13 @@ export default async function layout(props: {
actions={<EmployeeActions employeeId={id} />}
tabs={[
{ href: `/productivity/employees/${id}`, label: 'Details' },
{ href: `/productivity/employees/${id}/attendance`, label: 'Attendance' },
{ href: `/productivity/employees/${id}/work-history`, label: 'Work History' },
{ href: `/productivity/employees/${id}/documents`, label: 'Documents' },
{ href: `/productivity/employees/${id}/certifications`, label: 'Certifications' },
{ href: `/productivity/employees/${id}/leave`, label: 'Leave' },
{ href: `/productivity/employees/${id}/payroll`, label: 'Payroll' },
{ href: `/productivity/employees/${id}/performance`, label: 'Performance' },
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
]}
>
@@ -0,0 +1,164 @@
"use client"
import { use, useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { useAuthApi } from "@/shared/useApi"
import { useEmployee } from "@/modules/employees/employee-context"
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
import type { LeaveRequestsClient } from "@garage/api"
import { CalendarIcon, PlaneIcon, ActivityIcon } from "lucide-react"
import { formatEnum } from "@/shared/utils/formatters"
type Balance = {
annual_total: number
annual_used: number
annual_remaining: number
sick_total: number
sick_used: number
sick_remaining: number
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
if (status === "approved") return "default"
if (status === "rejected") return "destructive"
if (status === "cancelled") return "outline"
return "secondary"
}
function BalanceCard({ icon: Icon, label, used, total, remaining }: {
icon: React.ComponentType<{ className?: string }>
label: string
used: number
total: number
remaining: number
}) {
const pct = total > 0 ? Math.min(100, (used / total) * 100) : 0
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
<Icon className="size-4" />
{label}
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-semibold">{remaining}<span className="ml-1 text-sm font-normal text-muted-foreground">/ {total}</span></div>
<p className="mt-1 text-xs text-muted-foreground">{used} used</p>
<div className="mt-2 h-2 w-full overflow-hidden rounded bg-muted">
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
</div>
</CardContent>
</Card>
)
}
export default function EmployeeLeavePage({ params }: { params: Promise<{ id: string }> }) {
const { id: employeeId } = use(params)
const api = useAuthApi()
const employee = useEmployee()
const balanceQuery = useQuery({
queryKey: ["employee-leave-balance", employeeId],
queryFn: () => api.employees.getLeaveBalance(employeeId) as Promise<{ data: Balance }>,
})
const balance = (balanceQuery.data as any)?.data as Balance | undefined
return (
<div className="space-y-4">
{balance && (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-2 px-4 pt-4">
<BalanceCard
icon={PlaneIcon}
label="Annual Leave"
used={Number(balance.annual_used)}
total={Number(balance.annual_total)}
remaining={Number(balance.annual_remaining)}
/>
<BalanceCard
icon={ActivityIcon}
label="Sick Leave"
used={Number(balance.sick_used)}
total={Number(balance.sick_total)}
remaining={Number(balance.sick_remaining)}
/>
</div>
)}
<ResourcePage<LeaveRequestsClient>
pageTitle="Leave History"
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
getClient={(api) => api.leaveRequests}
extraParams={{ employee_id: employeeId }}
header={null}
headerProps={({ invalidateQuery }) => ({
actions: (
<FormDialog title="New Leave Request">
{() => (
<LeaveRequestForm
presetEmployee={{ id: employeeId, label: employee?.label ?? "" }}
onSuccess={() => {
invalidateQuery()
balanceQuery.refetch()
}}
/>
)}
</FormDialog>
),
})}
columns={() => [
{
accessorKey: "leave_type",
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<CalendarIcon className="size-4 text-muted-foreground" />
<Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>
</div>
),
},
{
accessorKey: "start_date",
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
cell: ({ row }) => formatDate((row.original as any).start_date),
},
{
accessorKey: "end_date",
header: ({ column }) => <ColumnHeader column={column} title="End" />,
cell: ({ row }) => formatDate((row.original as any).end_date),
},
{
accessorKey: "days",
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
cell: ({ row }) => (row.original as any).days ?? "—",
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const s = (row.original as any).status as string
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
},
},
{
accessorKey: "reason",
header: ({ column }) => <ColumnHeader column={column} title="Reason" />,
cell: ({ row }) => (row.original as any).reason ?? "—",
},
]}
/>
</div>
)
}
@@ -0,0 +1,121 @@
"use client"
import { use } from "react"
import { useQuery } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { useAuthApi } from "@/shared/useApi"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { Badge } from "@/shared/components/ui/badge"
import { formatEnum } from "@/shared/utils/formatters"
type Slip = {
id: number
payroll_run?: { id?: number; reference?: string; period_start?: string; period_end?: string; status?: string }
hours_worked: number
base_salary: number
commission_amount: number
allowances: number
deductions: number
net_pay: number
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function fmt(v: unknown) {
const n = Number(v)
if (!Number.isFinite(n)) return "—"
return n.toFixed(2)
}
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" {
if (status === "paid") return "default"
if (status === "finalized") return "outline"
return "secondary"
}
export default function EmployeePayrollPage({ params }: { params: Promise<{ id: string }> }) {
const { id: employeeId } = use(params)
const api = useAuthApi()
const { data, isLoading } = useQuery({
queryKey: ["employee-payroll-slips", employeeId],
queryFn: () => api.employees.listPayrollSlips(employeeId) as Promise<{ data: Slip[] | { data: Slip[] } }>,
})
const rows: Slip[] = Array.isArray((data as any)?.data)
? (data as any).data
: ((data as any)?.data?.data ?? [])
const columns: ColumnDef<Slip>[] = [
{
accessorKey: "payroll_run",
header: ({ column }) => <ColumnHeader column={column} title="Run" />,
cell: ({ row }) => {
const r = row.original.payroll_run
return r?.reference ?? (r?.id ? `#${r.id}` : "—")
},
},
{
accessorKey: "period",
header: () => <span>Period</span>,
cell: ({ row }) => {
const r = row.original.payroll_run
if (!r) return "—"
return `${formatDate(r.period_start)} → ${formatDate(r.period_end)}`
},
},
{
accessorKey: "hours_worked",
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
cell: ({ row }) => fmt(row.original.hours_worked),
},
{
accessorKey: "base_salary",
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
cell: ({ row }) => fmt(row.original.base_salary),
},
{
accessorKey: "commission_amount",
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
cell: ({ row }) => fmt(row.original.commission_amount),
},
{
accessorKey: "deductions",
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
cell: ({ row }) => fmt(row.original.deductions),
},
{
accessorKey: "net_pay",
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
cell: ({ row }) => <span className="font-semibold">{fmt(row.original.net_pay)}</span>,
},
{
id: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const s = row.original.payroll_run?.status
if (!s) return "—"
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
},
},
]
return (
<DashboardPage headerProps={{ title: "Payroll Slips" }}>
<DataTable
columns={columns}
data={rows}
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
/>
</DashboardPage>
)
}
@@ -0,0 +1,121 @@
"use client"
import { useMemo, useState } from "react"
import { useParams } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import { ClockIcon, WrenchIcon, CheckCircle2Icon, TimerIcon, PercentIcon } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Button } from "@/shared/components/ui/button"
import { Field, FieldLabel } from "@/shared/components/ui/field"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
type PerfData = {
period: { from: string; to: string }
hours_worked: number
jobs_total: number
jobs_completed: number
avg_job_duration_hours: number
completion_rate: number
}
function StatCard({
icon: Icon,
label,
value,
suffix,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string | number
suffix?: string
}) {
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
<Icon className="size-4" />
{label}
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-semibold">
{value}
{suffix && <span className="ml-1 text-base font-normal text-muted-foreground">{suffix}</span>}
</div>
</CardContent>
</Card>
)
}
function firstOfMonth() {
const d = new Date()
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
}
function lastOfMonth() {
const d = new Date()
return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
}
export default function EmployeePerformancePage() {
const { id: employeeId } = useParams<{ id: string }>()
const api = useAuthApi()
const [fromInput, setFromInput] = useState(firstOfMonth())
const [toInput, setToInput] = useState(lastOfMonth())
const [from, setFrom] = useState(fromInput)
const [to, setTo] = useState(toInput)
const { data, isLoading, isFetching } = useQuery({
queryKey: ["employee-performance", employeeId, from, to],
queryFn: () => api.employees.performance(employeeId, { from, to }) as Promise<{ data: PerfData }>,
})
const perf = useMemo(() => (data as any)?.data as PerfData | undefined, [data])
return (
<DashboardPage
headerProps={{
title: perf ? `Performance · ${perf.period.from} → ${perf.period.to}` : "Performance",
actions: (
<div className="flex items-end gap-2">
<Field>
<FieldLabel>From</FieldLabel>
<Input type="date" value={fromInput} onChange={(e) => setFromInput(e.target.value)} />
</Field>
<Field>
<FieldLabel>To</FieldLabel>
<Input type="date" value={toInput} onChange={(e) => setToInput(e.target.value)} />
</Field>
<Button
size="sm"
disabled={isFetching}
onClick={() => {
setFrom(fromInput)
setTo(toInput)
}}
>
{isFetching ? "Loading..." : "Apply"}
</Button>
</div>
),
}}
>
{isLoading && !perf ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : !perf ? (
<p className="text-sm text-muted-foreground">No data.</p>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
<StatCard icon={ClockIcon} label="Hours Worked" value={perf.hours_worked.toFixed(2)} suffix="h" />
<StatCard icon={WrenchIcon} label="Jobs Assigned" value={perf.jobs_total} />
<StatCard icon={CheckCircle2Icon} label="Jobs Completed" value={perf.jobs_completed} />
<StatCard icon={TimerIcon} label="Avg Job Duration" value={perf.avg_job_duration_hours.toFixed(2)} suffix="h" />
<StatCard icon={PercentIcon} label="Completion Rate" value={perf.completion_rate} suffix="%" />
</div>
)}
</DashboardPage>
)
}
@@ -0,0 +1,110 @@
"use client"
import { use, useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { Badge } from "@/shared/components/ui/badge"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { JOB_CARD_ROUTES } from "@garage/api"
import type { JobCardsClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { WrenchIcon } from "lucide-react"
import { formatEnum } from "@/shared/utils/formatters"
const ROLE_PARAM = {
technician: "primary_technician_id",
sales: "sales_person_id",
writer: "service_writer_id",
} as const
type RoleKey = keyof typeof ROLE_PARAM
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" | "destructive" {
if (!status) return "secondary"
if (status === "completed" || status === "delivered") return "default"
if (status === "cancelled") return "destructive"
return "outline"
}
export default function EmployeeWorkHistoryPage({ params }: { params: Promise<{ id: string }> }) {
const { id: employeeId } = use(params)
const router = useRouter()
const [role, setRole] = useState<RoleKey>("technician")
const paramKey = ROLE_PARAM[role]
return (
<div className="space-y-3">
<div className="px-4 pt-4">
<Tabs value={role} onValueChange={(v) => setRole(v as RoleKey)}>
<TabsList variant="line">
<TabsTrigger value="technician">As Technician</TabsTrigger>
<TabsTrigger value="sales">As Sales Person</TabsTrigger>
<TabsTrigger value="writer">As Service Writer</TabsTrigger>
</TabsList>
</Tabs>
</div>
<ResourcePage<JobCardsClient>
key={role}
pageTitle="Work History"
routeKey={JOB_CARD_ROUTES.INDEX}
searchable
searchPlaceholder="Search by job number, plate, customer..."
getClient={(api) => api.jobCards}
extraParams={{ [paramKey]: employeeId }}
header={null}
onRowClick={(row) => router.push(`/sales/job-cards/${(row as any).id}`)}
columns={() => [
{
accessorKey: "order_number",
header: ({ column }) => <ColumnHeader column={column} title="Job #" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<WrenchIcon className="size-4 text-muted-foreground" />
<span className="font-mono text-xs">{(row.original as any).order_number ?? "—"}</span>
</div>
),
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
if (!c) return "—"
return `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() || c.email || "—"
},
},
{
accessorKey: "vehicle",
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
if (!v) return "—"
const display = `${v.make ?? ""} ${v.model ?? ""}`.trim()
return display || v.license_plate || "—"
},
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const s = (row.original as any).status
return s ? <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge> : "—"
},
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Opened" />,
cell: ({ row }) => formatDate((row.original as any).created_at),
},
]}
/>
</div>
)
}
@@ -1,23 +1,89 @@
"use client"
import { useMemo, useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { ImportDataButton } from "@/shared/components/import-data-button"
import { ExportDataButton } from "@/shared/components/export-data-button"
import { EmployeeForm } from "@/modules/employees/employee-form"
import { useAuthApi } from "@/shared/useApi"
import { EMPLOYEE_ROUTES } from "@garage/api"
import type { EmployeesClient } from "@garage/api"
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
import { Badge } from "@/shared/components/ui/badge"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { useRouter } from "next/navigation"
import { formatEnum } from "@/shared/utils/formatters"
const TYPE_OPTIONS = [
{ value: "all", label: "All types" },
{ value: "employee", label: "Employee" },
{ value: "sales_person", label: "Sales Person" },
]
function initialsOf(first?: string | null, last?: string | null) {
const f = (first ?? "").trim()[0] ?? ""
const l = (last ?? "").trim()[0] ?? ""
return (f + l).toUpperCase() || "?"
}
export default function EmployeesPage() {
const router = useRouter()
const api = useAuthApi()
const [typeFilter, setTypeFilter] = useState<string>("all")
const extraParams = useMemo(() => {
if (typeFilter === "all") return undefined
return { type: typeFilter }
}, [typeFilter])
return (
<ResourcePage<EmployeesClient>
pageTitle="Employees"
routeKey={EMPLOYEE_ROUTES.INDEX}
searchable
searchPlaceholder="Search employees..."
statusFilter={{ statuses: ["active", "inactive"] }}
extraParams={extraParams}
getClient={(api) => api.employees}
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
tableHeader={() => (
<div className="flex items-center gap-2">
<Select value={typeFilter} onValueChange={setTypeFilter}>
<SelectTrigger className="w-44">
<SelectValue placeholder="All types" />
</SelectTrigger>
<SelectContent>
{TYPE_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className="flex items-center gap-2">
<ImportDataButton
onImport={(file) => api.employees.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Employees"
onDownloadSample={() => api.employees.downloadImportSample() as Promise<Blob>}
sampleFileName="employees-import-sample"
/>
<ExportDataButton
onExport={(filters) => api.employees.exportData(filters)}
fileName="employees"
/>
<FormDialog title="Employee">
{(resourceId) => (
<EmployeeForm
@@ -27,6 +93,7 @@ export default function EmployeesPage() {
/>
)}
</FormDialog>
</div>
),
})}
columns={({ actionsColumn }) => [
@@ -34,8 +101,16 @@ export default function EmployeesPage() {
accessorKey: "first_name",
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
cell: ({ row }) => {
const { first_name, last_name } = row.original
return `${first_name ?? ""} ${last_name ?? ""}`.trim()
const r = row.original as any
const fullName = `${r.first_name ?? ""} ${r.last_name ?? ""}`.trim() || "—"
return (
<div className="flex items-center gap-2">
<Avatar size="sm">
<AvatarFallback>{initialsOf(r.first_name, r.last_name)}</AvatarFallback>
</Avatar>
<span className="font-medium">{fullName}</span>
</div>
)
},
},
{
@@ -45,15 +120,32 @@ export default function EmployeesPage() {
{
accessorKey: "phone",
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
cell: ({ row }) => (row.original as any).phone ?? "—",
},
{
accessorKey: "position",
header: ({ column }) => <ColumnHeader column={column} title="Position" />,
accessorKey: "type",
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
cell: ({ row }) => {
const t = (row.original as any).type
if (!t) return "—"
return <Badge variant="outline">{t === "sales_person" ? "Sales Person" : "Employee"}</Badge>
},
},
{
accessorKey: "department",
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
cell: ({ row }) => (row.original as any).department?.name ?? "—",
cell: ({ row }) => {
const d = (row.original as any).department?.name
return d ? <Badge variant="secondary">{d}</Badge> : "—"
},
},
{
accessorKey: "role",
header: ({ column }) => <ColumnHeader column={column} title="Role" />,
cell: ({ row }) => {
const r = (row.original as any).role?.name
return r ? <Badge variant="secondary">{r}</Badge> : "—"
},
},
{
accessorKey: "status",
@@ -62,7 +154,7 @@ export default function EmployeesPage() {
const status = row.original.status
return (
<span className={status === "active" ? "text-green-600" : "text-red-600"}>
{status}
{formatEnum(status)}
</span>
)
},
@@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
<ResourcePage<HolidayYearsClient>
pageTitle="Holiday Years"
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
searchable
searchPlaceholder="Search holidays..."
getClient={(api) => api.holidayYears}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -0,0 +1,152 @@
"use client"
import { useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
import type { LeaveRequestsClient } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { useAuthApi } from "@/shared/useApi"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { CheckIcon, XIcon } from "lucide-react"
import { confirm } from "@/shared/components/confirm-dialog"
import { formatEnum } from "@/shared/utils/formatters"
import { usePermissions } from "@/shared/hooks/use-permissions"
type LeaveRow = {
id: number
leave_type: string
start_date?: string
end_date?: string
days?: number
status: string
reason?: string | null
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
if (status === "approved") return "default"
if (status === "rejected") return "destructive"
if (status === "cancelled") return "outline"
return "secondary"
}
export default function LeaveRequestsPage() {
const api = useAuthApi()
const queryClient = useQueryClient()
const perms = usePermissions()
async function handleDecision(id: number, action: "approve" | "reject") {
const ok = await confirm({
title: action === "approve" ? "Approve request?" : "Reject request?",
description: `This will mark the leave request as ${action}d.`,
confirmLabel: action === "approve" ? "Approve" : "Reject",
variant: action === "approve" ? "default" : "destructive",
})
if (!ok) return
const promise = action === "approve"
? api.leaveRequests.approve(String(id))
: api.leaveRequests.reject(String(id))
toast.promise(promise, {
loading: action === "approve" ? "Approving..." : "Rejecting...",
success: action === "approve" ? "Approved" : "Rejected",
error: "Failed",
})
await promise
queryClient.invalidateQueries({ queryKey: [LEAVE_REQUEST_ROUTES.INDEX] })
}
return (
<ResourcePage<LeaveRequestsClient>
pageTitle="Leave Requests"
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
getClient={(api) => api.leaveRequests}
statusFilter={{
statuses: ["pending", "approved", "rejected", "cancelled"],
paramKey: "status",
allLabel: "All",
}}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: perms.canCreate("leave_requests") ? (
<FormDialog title="Leave Request">
{(resourceId) => (
<LeaveRequestForm
resourceId={resourceId}
initialData={selectedItem}
onSuccess={invalidateQuery}
/>
)}
</FormDialog>
) : null,
})}
columns={({ actionsColumn }) => [
{
accessorKey: "employee",
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
cell: ({ row }) => {
const e = (row.original as any).employee
if (!e) return "—"
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
},
},
{
accessorKey: "leave_type",
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
cell: ({ row }) => <Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>,
},
{
accessorKey: "start_date",
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
cell: ({ row }) => formatDate((row.original as any).start_date),
},
{
accessorKey: "end_date",
header: ({ column }) => <ColumnHeader column={column} title="End" />,
cell: ({ row }) => formatDate((row.original as any).end_date),
},
{
accessorKey: "days",
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
cell: ({ row }) => (row.original as any).days ?? "—",
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const s = (row.original as any).status as string
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
},
},
{
id: "decide",
header: () => <span className="sr-only">Decide</span>,
cell: ({ row }) => {
const r = row.original as LeaveRow
if (r.status !== "pending" || !perms.canUpdate("leave_requests")) return null
return (
<div className="flex justify-end gap-1">
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "approve")}>
<CheckIcon className="size-4 text-green-600" />
</Button>
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "reject")}>
<XIcon className="size-4 text-destructive" />
</Button>
</div>
)
},
},
actionsColumn(),
]}
/>
)
}
@@ -0,0 +1,259 @@
"use client"
import { use } from "react"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { toast } from "sonner"
import { CheckCircle2Icon, RefreshCwIcon, BanknoteIcon, Trash2, DownloadIcon } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { confirm } from "@/shared/components/confirm-dialog"
import { useRouter } from "next/navigation"
import { formatEnum } from "@/shared/utils/formatters"
type Entry = {
id: number
employee_id: number
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
hours_worked: number
overtime_hours: number
base_salary: number
commission_amount: number
allowances: number
deductions: number
net_pay: number
note?: string | null
}
type Run = {
id: number
reference?: string
period_start: string
period_end: string
status: "draft" | "finalized" | "paid"
entries: Entry[]
note?: string | null
finalized_at?: string | null
paid_at?: string | null
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function fmtCurrency(value: unknown) {
const n = Number(value)
if (!Number.isFinite(n)) return "—"
return n.toFixed(2)
}
function statusVariant(status: string): "default" | "secondary" | "outline" {
if (status === "paid") return "default"
if (status === "finalized") return "outline"
return "secondary"
}
export default function PayrollRunPage({ params }: { params: Promise<{ id: string }> }) {
const { id: runId } = use(params)
const api = useAuthApi()
const queryClient = useQueryClient()
const router = useRouter()
const queryKey = ["payroll-run", runId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.payroll.show(runId) as Promise<{ data: Run; totals: Record<string, number> }>,
})
const run = (data as any)?.data as Run | undefined
const totals = (data as any)?.totals as Record<string, number> | undefined
const refetch = () => queryClient.invalidateQueries({ queryKey })
const finalizeMutation = useMutation({
mutationFn: () => api.payroll.finalize(runId),
onSuccess: () => {
toast.success("Run finalized")
refetch()
},
onError: () => toast.error("Failed to finalize"),
})
const regenerateMutation = useMutation({
mutationFn: () => api.payroll.regenerate(runId),
onSuccess: () => {
toast.success("Entries regenerated")
refetch()
},
onError: () => toast.error("Failed to regenerate"),
})
const markPaidMutation = useMutation({
mutationFn: () => api.payroll.markPaid(runId),
onSuccess: () => {
toast.success("Marked as paid")
refetch()
},
onError: () => toast.error("Failed to mark paid"),
})
const deleteMutation = useMutation({
mutationFn: () => api.payroll.destroy(runId),
onSuccess: () => {
toast.success("Run deleted")
router.push("/productivity/payroll")
},
onError: () => toast.error("Failed to delete"),
})
async function handleDelete() {
const ok = await confirm({
title: "Delete payroll run?",
description: "This permanently removes the run and all its entries.",
confirmLabel: "Delete",
variant: "destructive",
})
if (ok) deleteMutation.mutate()
}
const columns: ColumnDef<Entry>[] = [
{
accessorKey: "employee",
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
cell: ({ row }) => {
const e = row.original.employee
if (!e) return `#${row.original.employee_id}`
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
},
},
{
accessorKey: "hours_worked",
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
cell: ({ row }) => fmtCurrency(row.original.hours_worked),
},
{
accessorKey: "base_salary",
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
cell: ({ row }) => fmtCurrency(row.original.base_salary),
},
{
accessorKey: "commission_amount",
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
cell: ({ row }) => fmtCurrency(row.original.commission_amount),
},
{
accessorKey: "allowances",
header: ({ column }) => <ColumnHeader column={column} title="Allowances" />,
cell: ({ row }) => fmtCurrency(row.original.allowances),
},
{
accessorKey: "deductions",
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
cell: ({ row }) => fmtCurrency(row.original.deductions),
},
{
accessorKey: "net_pay",
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
cell: ({ row }) => <span className="font-semibold">{fmtCurrency(row.original.net_pay)}</span>,
},
{
id: "slip",
header: () => <span className="sr-only">Slip</span>,
cell: ({ row }) => (
<Button variant="ghost" size="icon" asChild>
<a
href={`/api/payroll/runs/${runId}/entries/${row.original.id}/slip`}
target="_blank"
rel="noopener noreferrer"
title="Download slip PDF"
>
<DownloadIcon className="size-4" />
</a>
</Button>
),
},
]
if (isLoading && !run) {
return <DashboardPage>Loading...</DashboardPage>
}
if (!run) {
return <DashboardPage>Run not found.</DashboardPage>
}
const entries = run.entries ?? []
return (
<DashboardPage
headerProps={{
title: `${run.reference ?? `Payroll #${run.id}`} · ${formatDate(run.period_start)} → ${formatDate(run.period_end)}`,
actions: (
<div className="flex items-center gap-2">
<Badge variant={statusVariant(run.status)}>{formatEnum(run.status)}</Badge>
{run.status === "draft" && (
<>
<Button size="sm" variant="outline" disabled={regenerateMutation.isPending} onClick={() => regenerateMutation.mutate()}>
<RefreshCwIcon className="size-4" />
Regenerate
</Button>
<Button size="sm" disabled={finalizeMutation.isPending} onClick={() => finalizeMutation.mutate()}>
<CheckCircle2Icon className="size-4" />
Finalize
</Button>
<Button size="sm" variant="destructive" disabled={deleteMutation.isPending} onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</Button>
</>
)}
{run.status === "finalized" && (
<Button size="sm" disabled={markPaidMutation.isPending} onClick={() => markPaidMutation.mutate()}>
<BanknoteIcon className="size-4" />
Mark Paid
</Button>
)}
</div>
),
}}
>
{totals && (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 mb-4">
{[
{ label: "Gross Base", value: totals.gross_base },
{ label: "Commission", value: totals.commission },
{ label: "Allowances", value: totals.allowances },
{ label: "Deductions", value: totals.deductions },
{ label: "Net Total", value: totals.net_pay },
].map((t) => (
<Card key={t.label}>
<CardHeader className="pb-1">
<CardTitle className="text-xs font-medium text-muted-foreground">{t.label}</CardTitle>
</CardHeader>
<CardContent>
<div className="text-lg font-semibold">{fmtCurrency(t.value)}</div>
</CardContent>
</Card>
))}
</div>
)}
<DataTable
columns={columns}
data={entries}
pagination={{ page: 1, pageSize: entries.length || 10, pageCount: 1, total: entries.length }}
sorting={[]}
onChange={() => {}}
isLoading={false}
/>
</DashboardPage>
)
}
@@ -0,0 +1,102 @@
"use client"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { PayrollRunForm } from "@/modules/payroll/payroll-run-form"
import { PAYROLL_ROUTES } from "@garage/api"
import type { PayrollClient } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { useRouter } from "next/navigation"
import { formatEnum } from "@/shared/utils/formatters"
type RunRow = {
id: number
reference?: string | null
period_start?: string
period_end?: string
status: string
entries_count?: number
generated_at?: string | null
finalized_at?: string | null
paid_at?: string | null
}
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function statusVariant(status: string): "default" | "secondary" | "outline" {
if (status === "paid") return "default"
if (status === "finalized") return "outline"
return "secondary"
}
export default function PayrollPage() {
const router = useRouter()
return (
<ResourcePage<PayrollClient>
pageTitle="Payroll"
routeKey={PAYROLL_ROUTES.RUNS_INDEX}
getClient={(api) => api.payroll}
statusFilter={{
statuses: ["draft", "finalized", "paid"],
paramKey: "status",
}}
onRowClick={(row) => router.push(`/productivity/payroll/${(row as any).id}`)}
headerProps={({ invalidateQuery }) => ({
actions: (
<FormDialog title="Payroll Run">
{() => (
<PayrollRunForm
onSuccess={(runId) => {
invalidateQuery()
if (runId) router.push(`/productivity/payroll/${runId}`)
}}
/>
)}
</FormDialog>
),
})}
columns={({ actionsColumn }) => [
{
accessorKey: "reference",
header: ({ column }) => <ColumnHeader column={column} title="Reference" />,
cell: ({ row }) => <span className="font-mono text-xs">{(row.original as any).reference ?? `#${(row.original as any).id}`}</span>,
},
{
accessorKey: "period_start",
header: ({ column }) => <ColumnHeader column={column} title="Period Start" />,
cell: ({ row }) => formatDate((row.original as any).period_start),
},
{
accessorKey: "period_end",
header: ({ column }) => <ColumnHeader column={column} title="Period End" />,
cell: ({ row }) => formatDate((row.original as any).period_end),
},
{
accessorKey: "entries_count",
header: ({ column }) => <ColumnHeader column={column} title="Entries" />,
cell: ({ row }) => (row.original as any).entries_count ?? "—",
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const s = (row.original as any).status as string
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
},
},
{
accessorKey: "finalized_at",
header: ({ column }) => <ColumnHeader column={column} title="Finalized" />,
cell: ({ row }) => formatDate((row.original as any).finalized_at),
},
actionsColumn({ onEdit: undefined }),
]}
/>
)
}
@@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
<ResourcePage<ShopCalendarsClient>
pageTitle="Shop Calendars"
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop calendars..."
getClient={(api) => api.shopCalendars}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
<ResourcePage<ShopTimingsClient>
pageTitle="Shop Timings"
routeKey={SHOP_TIMING_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop timings..."
getClient={(api) => api.shopTimings}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { TaskForm } from "@/modules/tasks/task-form"
import { TASK_ROUTES } from "@garage/api"
import { TASK_ROUTES, TaskStatus } from "@garage/api"
import type { TasksClient } from "@garage/api"
export default function TasksPage() {
return (
<ResourcePage<TasksClient>
routeKey={TASK_ROUTES.INDEX}
searchable
searchPlaceholder="Search tasks..."
statusFilter={{ statuses: TaskStatus }}
getClient={(api) => api.tasks}
headerProps={({ selectedItem, invalidateQuery }) => ({
title: "Tasks",
@@ -0,0 +1,163 @@
"use client"
import { useMemo, useState } from "react"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { LogInIcon, LogOutIcon, TimerIcon, SearchIcon } from "lucide-react"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { Card, CardContent } from "@/shared/components/ui/card"
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { EMPLOYEE_ROUTES } from "@garage/api"
type Employee = {
id: number
first_name?: string
last_name?: string
email?: string
designation?: string
department?: { id?: number; name?: string }
track_attendance?: boolean
has_active_time_sheet?: boolean
active_time_sheet?: { id?: number; clock_in?: string; date?: string } | null
status?: string
}
function initialsOf(first?: string | null, last?: string | null) {
const f = (first ?? "").trim()[0] ?? ""
const l = (last ?? "").trim()[0] ?? ""
return (f + l).toUpperCase() || "?"
}
function formatTime(value: unknown) {
if (!value || typeof value !== "string") return "—"
return value.length >= 5 ? value.slice(0, 5) : value
}
export default function TimeClocksPage() {
const api = useAuthApi()
const queryClient = useQueryClient()
const [search, setSearch] = useState("")
const employeesQuery = useQuery({
queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }],
queryFn: () => api.employees.list({ per_page: 100, status: "active" } as any) as Promise<{ data: Employee[] }>,
})
const employees: Employee[] = useMemo(() => {
const rows: Employee[] = (employeesQuery.data as any)?.data ?? []
if (!search) return rows
const q = search.toLowerCase()
return rows.filter((e) => {
const name = `${e.first_name ?? ""} ${e.last_name ?? ""}`.toLowerCase()
return name.includes(q) || (e.email ?? "").toLowerCase().includes(q)
})
}, [employeesQuery.data, search])
const refetch = () => queryClient.invalidateQueries({ queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }] })
const clockInMutation = useMutation({
mutationFn: (employeeId: number) => api.timeSheets.clockIn({ employee_id: employeeId } as any),
onSuccess: () => {
toast.success("Clocked in")
refetch()
},
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock in"),
})
const clockOutMutation = useMutation({
mutationFn: (timeSheetId: number) => api.timeSheets.clockOut({ time_sheet_id: timeSheetId } as any),
onSuccess: () => {
toast.success("Clocked out")
refetch()
},
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock out"),
})
return (
<DashboardPage
headerProps={{
title: "Time Clocks",
actions: (
<div className="relative w-64">
<SearchIcon className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search employees..."
className="pl-8"
/>
</div>
),
}}
>
{employeesQuery.isLoading ? (
<p className="text-sm text-muted-foreground">Loading...</p>
) : employees.length === 0 ? (
<p className="text-sm text-muted-foreground">No employees found.</p>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{employees.map((emp) => {
const fullName = `${emp.first_name ?? ""} ${emp.last_name ?? ""}`.trim() || emp.email
const isClockedIn = !!emp.has_active_time_sheet
const activeId = emp.active_time_sheet?.id
const clockedInAt = emp.active_time_sheet?.clock_in
return (
<Card key={emp.id}>
<CardContent className="flex items-center justify-between gap-3 p-4">
<div className="flex items-center gap-3 min-w-0">
<Avatar size="lg">
<AvatarFallback>{initialsOf(emp.first_name, emp.last_name)}</AvatarFallback>
</Avatar>
<div className="min-w-0">
<div className="font-medium truncate">{fullName}</div>
<div className="text-xs text-muted-foreground truncate">
{emp.designation ?? emp.department?.name ?? emp.email}
</div>
<div className="mt-1 flex items-center gap-2">
{isClockedIn ? (
<Badge variant="default" className="gap-1">
<TimerIcon className="size-3" />
Since {formatTime(clockedInAt)}
</Badge>
) : (
<Badge variant="secondary">Idle</Badge>
)}
</div>
</div>
</div>
{isClockedIn && activeId ? (
<Button
size="sm"
variant="destructive"
disabled={clockOutMutation.isPending}
onClick={() => clockOutMutation.mutate(activeId)}
>
<LogOutIcon className="size-4" />
Clock Out
</Button>
) : (
<Button
size="sm"
disabled={clockInMutation.isPending}
onClick={() => clockInMutation.mutate(emp.id)}
>
<LogInIcon className="size-4" />
Clock In
</Button>
)}
</CardContent>
</Card>
)
})}
</div>
)}
</DashboardPage>
)
}
@@ -0,0 +1,96 @@
"use client"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { Badge } from "@/shared/components/ui/badge"
import { TIME_SHEET_ROUTES } from "@garage/api"
import type { TimeSheetsClient } from "@garage/api"
import { ClockIcon } from "lucide-react"
import { formatEnum } from "@/shared/utils/formatters"
function formatDate(value: unknown) {
if (!value || typeof value !== "string") return "—"
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
}
function formatTime(value: unknown) {
if (!value || typeof value !== "string") return "—"
return value.length >= 5 ? value.slice(0, 5) : value
}
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
general: "secondary",
order: "default",
task: "outline",
}
export default function TimeSheetsPage() {
return (
<ResourcePage<TimeSheetsClient>
pageTitle="Time Sheets"
routeKey={TIME_SHEET_ROUTES.INDEX}
getClient={(api) => api.timeSheets}
statusFilter={{
statuses: ["general", "order", "task"],
paramKey: "activity_type",
allLabel: "All",
}}
columns={({ actionsColumn }) => [
{
accessorKey: "date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
cell: ({ row }) => (
<div className="flex items-center gap-2">
<ClockIcon className="size-4 text-muted-foreground" />
<span>{formatDate((row.original as any).date)}</span>
</div>
),
},
{
accessorKey: "employee",
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
cell: ({ row }) => {
const e = (row.original as any).employee
if (!e) return "—"
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
},
},
{
accessorKey: "clock_in",
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
},
{
accessorKey: "clock_out",
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
},
{
accessorKey: "duration",
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
},
{
accessorKey: "activity_type",
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
cell: ({ row }) => {
const t = (row.original as any).activity_type ?? "general"
return <Badge variant={ACTIVITY_VARIANT[t] ?? "secondary"}>{formatEnum(t)}</Badge>
},
},
{
accessorKey: "calculated_total_cost",
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
cell: ({ row }) => {
const v = (row.original as any).calculated_total_cost
if (v == null) return "—"
const n = Number(v)
return Number.isFinite(n) ? n.toFixed(2) : "—"
},
},
actionsColumn({ onEdit: undefined }),
]}
/>
)
}
@@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
import { BillActions } from '@/modules/bills/bill-actions'
import { BillProvider, type BillResponse } from '@/modules/bills/bill-context'
import BillStatusBadge from '@/modules/bills/bill-status-badge'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { ReceiptIcon } from 'lucide-react'
import React from 'react'
@@ -26,6 +27,7 @@ export default async function BillDetailLayout(props: {
actions={
<div className="flex space-x-2 items-center">
<BillStatusBadge bill={{id, status:data?.status}} />
<ShareDocumentButton type="bill" id={id} />
<BillActions billId={id} />
</div>
}
@@ -6,17 +6,26 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
import { BILL_ROUTES } from "@garage/api"
import { BILL_ROUTES, BillStatus } from "@garage/api"
import type { BillsClient } from "@garage/api"
import { formatDate } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, Printer } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
export default function BillsPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<BillsClient>
pageTitle="Bills"
routeKey={BILL_ROUTES.INDEX}
searchable
searchPlaceholder="Search bills..."
statusFilter={{ statuses: BillStatus }}
getClient={(api) => api.bills}
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -41,12 +50,18 @@ export default function BillsPage() {
{
accessorKey: "total",
header: ({ column }) => <ColumnHeader column={column} title="Total" />,
cell: ({ row }) => (row.original as any).total || "—",
cell: ({ row }) => {
const v = (row.original as any).total
return v != null && v !== "" ? <Money value={v} /> : "—"
},
},
{
accessorKey: "balance_due",
header: ({ column }) => <ColumnHeader column={column} title="Balance Due" />,
cell: ({ row }) => (row.original as any).balance_due || "—",
cell: ({ row }) => {
const v = (row.original as any).balance_due
return v != null && v !== "" ? <Money value={v} /> : "—"
},
},
{
accessorKey: "title",
@@ -55,7 +70,16 @@ export default function BillsPage() {
{
accessorKey: "vendor",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor?.name || "—",
cell: ({ row }) => {
const vendor = (row.original as any).vendor
return (
<RelationLink
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
icon={Building2}
label={vendor?.company_name || getFullName(vendor)}
/>
)
},
},
{
accessorKey: "bill_date",
@@ -74,12 +98,20 @@ export default function BillsPage() {
const status = (row.original as any).status
return (
<Badge variant={status === "paid" ? "default" : "secondary"}>
{status?.replace(/_/g, " ") || "—"}
{formatEnum(status)}
</Badge>
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("bill", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -5,17 +5,26 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { ExpenseForm } from "@/modules/expenses/expense-form"
import { Badge } from "@/shared/components/ui/badge"
import { EXPENSE_ROUTES } from "@garage/api"
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
import type { ExpensesClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, Printer } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
export default function ExpensesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<ExpensesClient>
pageTitle="Expenses"
routeKey={EXPENSE_ROUTES.INDEX}
searchable
searchPlaceholder="Search expenses..."
statusFilter={{ statuses: ExpenseStatus }}
getClient={(api) => api.expenses}
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -49,7 +58,13 @@ export default function ExpensesPage() {
header: () => "Vendor",
cell: ({ row }) => {
const vendor = (row.original as any).vendor
return vendor?.company_name || vendor?.name || "—"
return (
<RelationLink
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
icon={Building2}
label={vendor?.company_name || getFullName(vendor) || vendor?.name}
/>
)
},
},
{
@@ -60,12 +75,12 @@ export default function ExpensesPage() {
{
accessorKey: "total",
header: () => "Total",
cell: ({ row }) => formatCurrency((row.original as any).total ?? 0),
cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
},
{
accessorKey: "balance_due",
header: () => "Balance Due",
cell: ({ row }) => formatCurrency((row.original as any).balance_due ?? 0),
cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
},
{
accessorKey: "status",
@@ -86,7 +101,15 @@ export default function ExpensesPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("expense", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -0,0 +1,34 @@
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { PaymentMadeActions } from '@/modules/payment-mades/payment-made-actions'
import { BanknoteIcon } from 'lucide-react'
import React from 'react'
export default async function PaymentMadeDetailLayout(props: {
params: Promise<{ id: string }>
children: React.ReactNode
}) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentMades.show(id)
const data = (payment as any)?.data ?? payment
const title = data?.payment_number || 'Payment Details'
return (
<DashboardDetailsPage
title={title}
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
icon={<BanknoteIcon className="size-5" />}
backHref="/purchase/payments-made"
actions={<PaymentMadeActions paymentId={id} />}
tabs={[
{
href: `/purchase/payments-made/${id}`,
label: 'Details',
},
]}
>
{props.children}
</DashboardDetailsPage>
)
}
@@ -0,0 +1,119 @@
import { getServerApi } from '@garage/api/server'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
import {
BadgeDollarSignIcon,
BriefcaseIcon,
Building2Icon,
CalendarIcon,
CreditCardIcon,
HashIcon,
} from 'lucide-react'
export default async function PaymentMadeDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentMades.show(id)
const data = (payment as any)?.data ?? payment
if (!data) {
return <div className="text-muted-foreground">Payment not found.</div>
}
const amount = data.payment_made != null
? Number(data.payment_made).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
: '—'
const paymentDate = data.payment_date
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
: '—'
const vendorLabel = data.vendor?.company_name
?? (data.vendor?.first_name ? `${data.vendor.first_name} ${data.vendor.last_name ?? ''}`.trim() : null)
?? data.vendor_name
?? (data.employee?.first_name ? `${data.employee.first_name} ${data.employee.last_name ?? ''}`.trim() : null)
?? data.employee_name
?? '—'
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
return (
<DashboardPage header={null}>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="flex items-center gap-3 rounded-lg border p-4">
<HashIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Number</p>
<p className="font-medium">{data.payment_number || '—'}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<Building2Icon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Vendor / Employee</p>
<p className="font-medium">{vendorLabel}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<BriefcaseIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment For</p>
<p className="font-medium capitalize">{data.payment_for || '—'}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
<div>
<p className="text-xs text-muted-foreground">Amount</p>
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CreditCardIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Mode</p>
<p className="font-medium capitalize">{paymentMode}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CalendarIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Date</p>
<p className="font-medium">{paymentDate}</p>
</div>
</div>
{data.payment_reference && (
<div className="flex items-center gap-3 rounded-lg border p-4">
<HashIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Reference</p>
<p className="font-medium">{data.payment_reference}</p>
</div>
</div>
)}
{data.paid_through && (
<div className="flex items-center gap-3 rounded-lg border p-4">
<CreditCardIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Paid Through</p>
<p className="font-medium">{data.paid_through}</p>
</div>
</div>
)}
{data.notes && (
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
<p className="text-xs text-muted-foreground mb-1">Notes</p>
<p className="text-sm">{data.notes}</p>
</div>
)}
</div>
</DashboardPage>
)
}
@@ -1,6 +1,7 @@
"use client"
import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import {
Paperclip,
@@ -32,8 +33,12 @@ import {
} from "@/shared/components/ui/dialog"
import { confirm } from "@/shared/components/confirm-dialog"
import { useAuthApi } from "@/shared/useApi"
import { getFullName } from "@/shared/utils/getFullName"
import { PAYMENT_MADE_ROUTES } from "@garage/api"
import type { PaymentMadesClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, Printer } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
// ── Attachment helpers ──
@@ -208,10 +213,13 @@ function AttachmentsDialog({
type PaymentMadeItem = {
id: number
payment_number?: string
vendor?: { id?: number | string; company_name?: string | null; first_name?: string | null; last_name?: string | null; name?: string | null } | null
vendor_name?: string
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
employee_name?: string
payment_for?: string
payment_made?: string | number
payment_mode?: { name?: string | null; title?: string | null } | null
payment_mode_name?: string
payment_date?: string
paid_through?: string
@@ -220,6 +228,8 @@ type PaymentMadeItem = {
}
export default function PaymentsMadePage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const [attachmentTarget, setAttachmentTarget] = useState<{
id: string
ref: string
@@ -230,14 +240,21 @@ export default function PaymentsMadePage() {
<ResourcePage<PaymentMadesClient>
pageTitle="Payments Made"
routeKey={PAYMENT_MADE_ROUTES.INDEX}
searchable
searchPlaceholder="Search payments..."
getClient={(api) => api.paymentMades}
headerProps={({ invalidateQuery }) => ({
onRowClick={(row) => router.push(`/purchase/payments-made/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Record Payment">
{(resourceId) => (
{(resourceId, { close }) => (
<PaymentMadeForm
resourceId={resourceId}
onSuccess={invalidateQuery}
initialData={selectedItem}
onSuccess={() => {
invalidateQuery()
close()
}}
/>
)}
</FormDialog>
@@ -262,11 +279,27 @@ export default function PaymentsMadePage() {
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => {
const item = row.original as unknown as PaymentMadeItem
const isVendor =
item.vendor?.company_name ||
getFullName(item.vendor) ||
item.vendor?.name ||
item.vendor_name
const label =
isVendor ||
getFullName(item.employee) ||
item.employee?.name ||
item.employee_name
const href = isVendor && item.vendor?.id
? `/purchase/vendor/${item.vendor.id}`
: item.employee?.id
? `/productivity/employees/${item.employee.id}`
: null
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{item.vendor_name || "—"}</span>
</div>
<RelationLink
href={href}
icon={isVendor ? Building2 : UserIcon}
label={label}
/>
)
},
},
@@ -309,10 +342,15 @@ export default function PaymentsMadePage() {
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
cell: ({ row }) => {
const item = row.original as unknown as PaymentMadeItem
const label =
item.payment_mode?.name ||
item.payment_mode?.title ||
item.payment_mode_name ||
"—"
return (
<div className="flex items-center gap-2">
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
<span className="capitalize">{item.payment_mode_name || "—"}</span>
<span className="capitalize">{label}</span>
</div>
)
},
@@ -360,7 +398,15 @@ export default function PaymentsMadePage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("payment_made", String(r.id), "print"),
},
],
}),
]}
/>
@@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
import { PurchaseOrderActions } from '@/modules/purchase-orders/purchase-order-actions'
import { PurchaseOrderProvider } from '@/modules/purchase-orders/purchase-order-context'
import { CreateBillFromPOButton } from '@/modules/purchase-orders/create-bill-from-po-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { ClipboardList } from 'lucide-react'
import React from 'react'
@@ -30,6 +31,7 @@ export default async function layout(props: {
actions={
<div className="flex items-center gap-2">
<CreateBillFromPOButton />
<ShareDocumentButton type="purchase_order" id={id} />
<PurchaseOrderActions purchaseOrderId={id} />
</div>
}
@@ -7,14 +7,21 @@ import FormDialog from "@/shared/components/form-dialog"
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
import type { PurchaseOrdersClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, Printer } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
export default function PurchaseOrdersPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<PurchaseOrdersClient>
pageTitle="Purchase Orders"
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
searchable
searchPlaceholder="Search purchase orders..."
getClient={(api) => api.purchaseOrders}
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -43,7 +50,16 @@ export default function PurchaseOrdersPage() {
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "order_date",
@@ -69,7 +85,15 @@ export default function PurchaseOrdersPage() {
return val ? new Date(val).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("purchase_order", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -5,14 +5,21 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
import { VENDOR_CREDIT_ROUTES, VendorCreditStatus } from "@garage/api"
import type { VendorCreditsClient } from "@garage/api"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { formatEnum } from "@/shared/utils/formatters"
export default function VendorCreditsPage() {
return (
<ResourcePage<VendorCreditsClient>
pageTitle="Vendor Credits"
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
searchable
searchPlaceholder="Search vendor credits..."
statusFilter={{ statuses: VendorCreditStatus }}
getClient={(api) => api.vendorCredits}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -35,12 +42,30 @@ export default function VendorCreditsPage() {
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "bill_number",
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
cell: ({ row }) => (row.original as any).bill_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.bill?.id ? `/purchase/bill/${item.bill.id}` : null}
icon={FileTextIcon}
label={item.bill?.bill_number || item.bill_number}
/>
)
},
},
{
accessorKey: "vendor_credit_date",
@@ -55,7 +80,7 @@ export default function VendorCreditsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
return <Badge variant={status === "closed" ? "secondary" : "default"}>{status || "—"}</Badge>
return <Badge variant={status === "closed" ? "secondary" : "default"}>{formatEnum(status)}</Badge>
},
},
actionsColumn(),
@@ -0,0 +1,37 @@
import { DashboardDetailsPage } from "@/base/components/layout/dashboard"
import { getServerApi } from "@garage/api/server"
import { VendorActions } from "@/modules/vendors/vendor-actions"
import { VendorProvider } from "@/modules/vendors/vendor-context"
import React from "react"
export default async function layout(props: {
params: Promise<{ id: string }>
children: React.ReactNode
}) {
const { id } = await props.params
const api = await getServerApi()
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data
const company = vendor?.company_name as string | undefined
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
const title = company || fullName || "Vendor Details"
const isActive = vendor?.is_active ?? vendor?.status === "active"
return (
<VendorProvider vendor={{ id, label: title }}>
<DashboardDetailsPage
className="p-0 lg:p-0"
title={title}
description={vendor?.email ?? vendor?.phone ?? undefined}
backHref="/purchase/vendor"
actions={<VendorActions vendorId={id} isActive={Boolean(isActive)} />}
tabs={[
{ href: `/purchase/vendor/${id}`, label: "Details" },
]}
>
{props.children}
</DashboardDetailsPage>
</VendorProvider>
)
}
@@ -0,0 +1,17 @@
import { getServerApi } from "@garage/api/server"
import { VendorGeneralInfo } from "@/modules/vendors/vendor-general-info"
export default async function VendorDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
// so cast through `any` here until the schema is regenerated.
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data
if (!vendor) {
return <div className="text-muted-foreground p-6">Vendor not found.</div>
}
return <VendorGeneralInfo vendor={vendor} />
}
+42 -1
View File
@@ -1,18 +1,28 @@
"use client"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Power } from "lucide-react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { VendorForm } from "@/modules/vendors/vendor-form"
import { useAuthApi } from "@/shared/useApi"
import { VENDOR_ROUTES } from "@garage/api"
import type { VendorsClient } from "@garage/api"
export default function VendorsPage() {
const router = useRouter()
const api = useAuthApi()
return (
<ResourcePage<VendorsClient>
pageTitle="Vendors"
routeKey={VENDOR_ROUTES.INDEX}
searchable
searchPlaceholder="Search vendors..."
getClient={(api) => api.vendors}
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Vendor">
@@ -46,6 +56,18 @@ export default function VendorsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
cell: ({ row }) => (row.original as any).email || "—",
},
{
accessorKey: "is_active",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const isActive = Boolean((row.original as any).is_active)
return (
<Badge variant={isActive ? "default" : "outline"}>
{isActive ? "Active" : "Inactive"}
</Badge>
)
},
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
@@ -54,7 +76,26 @@ export default function VendorsPage() {
return val ? new Date(val).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => {
const isActive = Boolean((row as any).is_active)
return [
{
label: isActive ? "Deactivate" : "Activate",
icon: Power,
onClick: async () => {
try {
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
router.refresh()
} catch {
toast.error("Failed to update vendor status.")
}
},
},
]
},
}),
]}
/>
)
@@ -5,8 +5,11 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
import { CREDIT_NOTE_ROUTES } from "@garage/api"
import { CREDIT_NOTE_ROUTES, CreditNoteStatus } from "@garage/api"
import type { CreditNotesClient } from "@garage/api"
import { formatEnum } from "@/shared/utils/formatters"
import { Printer } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteItem = {
id: number
@@ -20,11 +23,15 @@ type CreditNoteItem = {
export default function CreditNotesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<CreditNotesClient>
pageTitle="Credit Notes"
routeKey={CREDIT_NOTE_ROUTES.INDEX}
searchable
searchPlaceholder="Search credit notes..."
statusFilter={{ statuses: CreditNoteStatus }}
getClient={(api) => api.creditNotes}
onRowClick={(row) => router.push(`/sales/credit-notes/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -63,7 +70,7 @@ export default function CreditNotesPage() {
}
return (
<span className={colorMap[status ?? ""] ?? ""}>
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
{formatEnum(status)}
</span>
)
},
@@ -72,7 +79,15 @@ export default function CreditNotesPage() {
accessorKey: "date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("credit_note", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
)}
pageTitle="Customer Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
extraParams={{ customer_id: customerId }}
header={null}
@@ -6,7 +6,6 @@ import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import { CustomerForm } from '@/modules/customers/customer-form'
import { CUSTOMER_ROUTES } from '@garage/api'
@@ -20,18 +19,19 @@ export default function CustomersPage() {
<ResourcePage<CustomersClient>
pageTitle='Customers'
routeKey={CUSTOMER_ROUTES.INDEX}
searchable
searchPlaceholder="Search customers..."
getClient={(api) => api.customers}
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.customers.downloadImportSample()}
fileName='customers-import-sample'
/>
<ImportDataButton
onImport={(file) => api.customers.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Customers"
onDownloadSample={() => api.customers.downloadImportSample()}
sampleFileName='customers-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.customers.exportData(filters)}
@@ -4,6 +4,7 @@ import { EstimateActions } from '@/modules/estimates/estimate-actions'
import { EstimateProvider } from '@/modules/estimates/estimate-context'
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { FileTextIcon } from 'lucide-react'
import React from 'react'
import { formatDate } from '@/shared/utils/formatters'
@@ -40,6 +41,7 @@ export default async function layout(props: {
<div className="flex items-center gap-2">
<CreateInvoiceFromEstimateButton />
<CreateJobCardFromEstimateButton />
<ShareDocumentButton type="estimate" id={id} />
<EstimateActions estimateId={id} />
</div>
}
@@ -1,24 +1,31 @@
"use client"
import { useRouter } from 'next/navigation'
import { ResourcePage } from '@/shared/data-view/resource-page'
import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
import { Button } from '@/shared/components/ui/button'
import { Car, FileTextIcon, Printer, UserIcon } from 'lucide-react'
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
import Link from 'next/link'
import { formatDate } from '@/shared/utils/formatters'
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function EstimatesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<EstimatesClient>
pageTitle="Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Estimate">
@@ -39,7 +46,7 @@ export default function EstimatesPage() {
const item = row.original
return (
<div className="flex items-center gap-2">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
<FileTextIcon className="text-muted-foreground h-4 w-4" />
<span>{item.title}</span>
</Link>
@@ -57,24 +64,28 @@ export default function EstimatesPage() {
cell: ({ row }) => {
const item: any = row.original
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer)}
/>
)
}
},
},
{
accessorKey: "vehicle",
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item: any = row.original
return <Button variant="outline" asChild size="sm">
<Link href={`/sales/vehicles/${item.vehicle?.id}`}>
<Car/> {getVehicleLabel(item.vehicle as any) || "—"}
</Link>
</Button>
}
return (
<RelationLink
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
icon={Car}
label={getVehicleLabel(item.vehicle as any)}
meta={item.vehicle?.license_plate}
/>
)
},
},
{
accessorKey: "date",
@@ -100,7 +111,15 @@ export default function EstimatesPage() {
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("estimate", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -1,589 +1,458 @@
"use client"
import { use, useState, useRef, useCallback } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { useCallback, useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { toast } from "sonner"
import {
Plus,
Ellipsis,
Pencil,
Trash2,
CheckCircle2,
AlertTriangle,
XCircle,
MinusCircle,
CircleDot,
Paperclip,
FileUp,
FileText,
FileImage,
File,
X,
Car,
ChevronLeft,
ChevronRight,
CircleCheck,
FileSignature,
Gauge,
Image as ImageIcon,
Loader2,
Share2,
StickyNote,
User,
} from "lucide-react"
import { INSPECTION_ROUTES } from "@garage/api"
// ── Types ──
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import { Progress } from "@/shared/components/ui/progress"
import { Separator } from "@/shared/components/ui/separator"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { useAuthApi } from "@/shared/useApi"
import {
CheckpointFillDialog,
isCheckpointComplete,
type Checkpoint,
type Severity,
} from "@/modules/inspections/checkpoint-fill-dialog"
import { SignaturePad } from "@/modules/inspections/signature-pad"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
type CheckpointItem = {
type Inspection = {
id: number
inspection_id?: number
name?: string
description?: string
record_type?: string
condition_rate?: number
file?: string
status?: string
created_at?: string
updated_at?: string
title: string
order_number?: string | null
status?: string | null
odometer?: number | null
template?: { id: number; name: string } | null
customer?: { first_name?: string; last_name?: string } | null
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string } | null
check_points: Checkpoint[]
technician_signature_url?: string | null
customer_signature_url?: string | null
}
// ── Constants ──
const CHECKPOINT_STATUSES = [
{ value: "passed", label: "Passed", icon: CheckCircle2, color: "bg-green-100 text-green-800" },
{ value: "need_attention", label: "Need Attention", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800" },
{ value: "failed", label: "Failed", icon: XCircle, color: "bg-red-100 text-red-800" },
{ value: "not_applicable", label: "Not Applicable", icon: MinusCircle, color: "bg-gray-100 text-gray-800" },
{ value: "not_inspected", label: "Not Inspected", icon: CircleDot, color: "bg-blue-100 text-blue-800" },
] as const
const RECORD_TYPES = [
{ value: "record_conditions", label: "Record Conditions" },
{ value: "record_audio", label: "Record Audio" },
{ value: "record_video", label: "Record Video" },
{ value: "capture_photo", label: "Capture Photo" },
] as const
function formatStatus(status?: string) {
if (!status) return "Not Inspected"
return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
const SEVERITY_DOT: Record<Severity, string> = {
good: "bg-emerald-500 shadow-emerald-500/30",
attention: "bg-amber-500 shadow-amber-500/30",
critical: "bg-rose-500 shadow-rose-500/30",
na: "bg-slate-400 shadow-slate-400/30",
not_inspected: "bg-muted shadow-none",
}
const SEVERITY_LABEL: Record<Severity, string> = {
good: "Good",
attention: "Attention",
critical: "Critical",
na: "N/A",
not_inspected: "Not inspected",
}
const SEVERITY_BADGE: Record<Severity, "default" | "secondary" | "destructive" | "outline"> = {
good: "default",
attention: "secondary",
critical: "destructive",
na: "outline",
not_inspected: "outline",
}
function getStatusConfig(status?: string) {
return CHECKPOINT_STATUSES.find((s) => s.value === status) || CHECKPOINT_STATUSES[4]
function groupBySection(cps: Checkpoint[]) {
const map = new Map<string, Checkpoint[]>()
for (const cp of cps) {
const key = cp.section_name || "Other"
if (!map.has(key)) map.set(key, [])
map.get(key)!.push(cp)
}
return Array.from(map.entries()).map(([name, items]) => ({ name, items }))
}
// ── Checkpoint Form Dialog ──
function CheckpointFormDialog({
open,
onOpenChange,
inspectionId,
checkpoint,
onSuccess,
}: {
open: boolean
onOpenChange: (open: boolean) => void
inspectionId: string
checkpoint?: CheckpointItem | null
onSuccess: () => void
}) {
export default function InspectionCheckpointsPage() {
const params = useParams<{ id: string }>()
const id = params.id
const api = useAuthApi()
const [name, setName] = useState(checkpoint?.name ?? "")
const [description, setDescription] = useState(checkpoint?.description ?? "")
const [recordType, setRecordType] = useState(checkpoint?.record_type ?? "record_conditions")
const [isPending, setIsPending] = useState(false)
const isEditing = !!checkpoint
const [data, setData] = useState<Inspection | null>(null)
const [initialLoad, setInitialLoad] = useState(true)
const [refetching, setRefetching] = useState(false)
const [activeIndex, setActiveIndex] = useState<number | null>(null)
const [shareOpen, setShareOpen] = useState(false)
const [mode, setMode] = useState<"all" | "wizard">("all")
const [wizardSectionIdx, setWizardSectionIdx] = useState(0)
const [signing, setSigning] = useState<{ who: "technician" | "customer" } | null>(null)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!name.trim()) {
toast.error("Name is required")
return
}
setIsPending(true)
const load = useCallback(async () => {
const isFirst = !data
if (isFirst) setInitialLoad(true)
else setRefetching(true)
try {
const payload = {
inspection_id: Number(inspectionId),
name: name.trim(),
description: description.trim() || undefined,
record_type: recordType,
const res = await api.inspections.showOne(id)
setData(res.data as Inspection)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to load inspection")
} finally {
setInitialLoad(false)
setRefetching(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
const patchCheckpoint = useCallback((checkpointId: number, patch: Partial<Checkpoint>) => {
setData((prev) => {
if (!prev) return prev
return {
...prev,
check_points: prev.check_points.map((c) =>
c.id === checkpointId ? { ...c, ...patch } : c
),
}
})
}, [])
useEffect(() => { load() }, [load])
const sections = useMemo(() => data ? groupBySection(data.check_points ?? []) : [], [data])
const flatCheckpoints = useMemo(() => sections.flatMap((s) => s.items), [sections])
const totals = useMemo(() => {
const t = { good: 0, attention: 0, critical: 0, na: 0, not_inspected: 0 }
for (const cp of data?.check_points ?? []) {
const s = (cp.severity as Severity) ?? "not_inspected"
t[s]++
}
return t
}, [data])
const setSeverity = async (cp: Checkpoint, severity: Severity) => {
patchCheckpoint(cp.id, { severity })
try {
await api.inspections.updateCheckpoint(String(cp.id), { severity } as any)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save")
load()
}
}
if (isEditing) {
const promise = api.inspections.updateCheckpoint(String(checkpoint.id), payload)
toast.promise(promise, {
loading: "Updating checkpoint...",
success: "Checkpoint updated",
error: "Failed to update checkpoint",
})
await promise
} else {
const promise = api.inspections.createCheckpoint(payload)
toast.promise(promise, {
loading: "Creating checkpoint...",
success: "Checkpoint created",
error: "Failed to create checkpoint",
})
await promise
}
onSuccess()
onOpenChange(false)
const handleSign = async (who: "technician" | "customer", dataUrl: string) => {
setSigning({ who })
try {
await api.inspections.sign(id, who, dataUrl)
toast.success(who === "technician" ? "Technician signature saved" : "Customer signature saved")
load()
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save signature")
} finally {
setIsPending(false)
setSigning(null)
}
}
if (initialLoad) {
return (
<div className="min-h-[60vh] flex items-center justify-center">
<div className="flex items-center gap-2 text-muted-foreground text-sm">
<Loader2 className="size-4 animate-spin" /> Loading inspection…
</div>
</div>
)
}
if (!data) return <div className="p-6 text-muted-foreground">Inspection not found</div>
const vehicleLine = data.vehicle
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
: "—"
const customerName = data.customer ? `${data.customer.first_name ?? ""} ${data.customer.last_name ?? ""}`.trim() : "—"
const totalCount = data.check_points.length
const inspectedCount = totalCount - totals.not_inspected
const progress = totalCount > 0 ? Math.round((inspectedCount / totalCount) * 100) : 0
const wizardSection = sections[wizardSectionIdx]
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Checkpoint" : "Add Checkpoint"}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="cp-name">Name *</Label>
<Input
id="cp-name"
placeholder="e.g. Engine Oil Level"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4">
{/* Header */}
<Card>
<CardHeader className="gap-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
<Link href={`/sales/inspections/${id}`}>
<Button variant="ghost" size="sm" className="-ms-2">
<ChevronLeft className="size-4" /> Back to inspection
</Button>
</Link>
<div className="flex items-center gap-2">
{refetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
<Button variant="outline" size="sm" onClick={() => setShareOpen(true)}>
<Share2 className="size-4" /> Share with customer
</Button>
</div>
<div className="grid gap-2">
<Label htmlFor="cp-description">Description</Label>
<Textarea
id="cp-description"
placeholder="Check oil level and condition"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="cp-record-type">Record Type</Label>
<Select value={recordType} onValueChange={setRecordType}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{RECORD_TYPES.map((rt) => (
<SelectItem key={rt.value} value={rt.value}>
{rt.label}
</SelectItem>
<Separator />
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="min-w-0">
<CardDescription className="uppercase tracking-wide text-[11px]">Inspection</CardDescription>
<CardTitle className="text-2xl">{data.title}</CardTitle>
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground flex-wrap">
<span className="inline-flex items-center gap-1.5"><User className="size-3.5" /> {customerName}</span>
<span className="inline-flex items-center gap-1.5"><Car className="size-3.5" /> {vehicleLine}</span>
{data.vehicle?.license_plate && (
<Badge variant="outline" className="font-mono">{data.vehicle.license_plate}</Badge>
)}
{data.odometer != null && (
<span className="inline-flex items-center gap-1.5"><Gauge className="size-3.5" /> {Number(data.odometer).toLocaleString()} km</span>
)}
</div>
</div>
</div>
</CardHeader>
<CardContent className="gap-3">
{/* Progress */}
<div className="space-y-1.5">
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>Progress</span>
<span className="tabular-nums">{inspectedCount} / {totalCount} ({progress}%)</span>
</div>
<Progress value={progress} className="h-2" />
</div>
{/* Severity tally */}
<div className="flex items-center gap-2 flex-wrap mt-3">
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
<Badge key={s} variant={SEVERITY_BADGE[s]} className="gap-1.5">
<span className={`size-1.5 rounded-full ${SEVERITY_DOT[s].split(" ")[0]}`} />
{totals[s]} {SEVERITY_LABEL[s]}
</Badge>
))}
</SelectContent>
</Select>
</div>
<Button type="submit" disabled={isPending}>
{isEditing ? <Pencil className="size-4" /> : <Plus className="size-4" />}
{isPending
? (isEditing ? "Updating..." : "Creating...")
: (isEditing ? "Update Checkpoint" : "Create Checkpoint")}
</Button>
</form>
</DialogContent>
</Dialog>
)
}
// ── Attachments Dialog ──
function getFileIcon(url: string) {
const ext = url.split(".").pop()?.toLowerCase()
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")) return FileImage
if (ext === "pdf") return FileText
return File
}
function getFileName(url: string) {
try {
return decodeURIComponent(url.split("/").pop() ?? "Attachment")
} catch {
return url.split("/").pop() ?? "Attachment"
}
}
function isImageUrl(url: string) {
const ext = url.split(".").pop()?.toLowerCase()
return ["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")
}
function CheckpointAttachmentsDialog({
open,
onOpenChange,
checkpoint,
onSuccess,
}: {
open: boolean
onOpenChange: (open: boolean) => void
checkpoint: CheckpointItem | null
onSuccess: () => void
}) {
const api = useAuthApi()
const fileInputRef = useRef<HTMLInputElement>(null)
const [isUploading, setIsUploading] = useState(false)
const handleUpload = useCallback(async (file: globalThis.File) => {
if (!checkpoint) return
setIsUploading(true)
try {
const promise = api.inspections.uploadCheckpointMedia(
String(checkpoint.id),
{ file },
)
toast.promise(promise, {
loading: "Uploading attachment...",
success: "Attachment uploaded",
error: "Failed to upload attachment",
})
await promise
onSuccess()
} finally {
setIsUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ""
}
}, [api, checkpoint, onSuccess])
const handleDelete = useCallback(async () => {
if (!checkpoint) return
const promise = api.inspections.deleteCheckpointMedia(String(checkpoint.id))
toast.promise(promise, {
loading: "Removing attachment...",
success: "Attachment removed",
error: "Failed to remove attachment",
})
await promise
onSuccess()
}, [api, checkpoint, onSuccess])
const hasFile = !!checkpoint?.file
const FileIcon = checkpoint?.file ? getFileIcon(checkpoint.file) : File
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Attachments — {checkpoint?.name}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
{/* Current attachment */}
{hasFile ? (
<div className="rounded-lg border p-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3 min-w-0 ">
{isImageUrl(checkpoint.file!) ? (
<img
src={checkpoint.file!}
alt="Checkpoint attachment"
className="size-12 rounded-md object-cover"
/>
) : (
<div className="flex size-12 shrink-0 items-center justify-center rounded-md bg-muted">
<FileIcon className="size-5 text-muted-foreground" />
</div>
)}
<div className="min-w-0 flex flex-col gap-0.5 max-w-48">
<a
href={checkpoint.file!}
target="_blank"
rel="noopener noreferrer"
className="truncate text-sm font-medium text-primary hover:underline"
>
{getFileName(checkpoint.file!)}
</a>
<span className="text-xs text-muted-foreground">
Current attachment
{/* Legend */}
<div className="mt-3 rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
<span className="font-medium text-foreground">Tap a dot to mark:</span>
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => (
<span key={s} className="inline-flex items-center gap-1.5">
<span className={`size-3 rounded-full ${SEVERITY_DOT[s].split(" ")[0]} shadow-md`} />
{SEVERITY_LABEL[s]}
</span>
))}
</div>
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 text-destructive hover:text-destructive"
onClick={handleDelete}
title="Remove attachment"
>
<Trash2 className="size-4" />
</Button>
</div>
</div>
) : (
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-muted-foreground">
<Paperclip className="size-8" />
<span className="text-sm">No attachments yet</span>
</div>
</CardContent>
</Card>
{/* Mode tabs */}
{totalCount > 0 && (
<Tabs value={mode} onValueChange={(v) => setMode(v as any)} className="w-full">
<TabsList className="w-full sm:w-auto">
<TabsTrigger value="all">All sections</TabsTrigger>
<TabsTrigger value="wizard">Wizard</TabsTrigger>
</TabsList>
</Tabs>
)}
{/* Upload area */}
<input
ref={fileInputRef}
type="file"
className="hidden"
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,audio/*,video/*"
onChange={(e) => {
const file = e.target.files?.[0]
if (file) handleUpload(file)
}}
/>
{/* Sections */}
{totalCount === 0 ? (
<Card>
<CardContent className="py-10 text-center">
<CircleCheck className="size-8 mx-auto text-muted-foreground/60 mb-3" />
<p className="text-sm text-muted-foreground">
This inspection has no checkpoints yet. It was probably created from an empty template.
</p>
</CardContent>
</Card>
) : mode === "all" ? (
sections.map((section) => (
<Card key={section.name}>
<CardHeader className="py-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">{section.name}</CardTitle>
<Badge variant="outline" className="font-normal">
{section.items.filter(isCheckpointComplete).length} / {section.items.length} done
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
<ul className="divide-y">
{section.items.map((cp) => (
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
))}
</ul>
</CardContent>
</Card>
))
) : (
wizardSection && (() => {
const pendingItems = wizardSection.items.filter((cp) => !isCheckpointComplete(cp))
const sectionDone = pendingItems.length === 0
return (
<Card>
<CardHeader className="py-3 gap-1">
<div className="flex items-center justify-between flex-wrap gap-2">
<CardTitle className="text-base">{wizardSection.name}</CardTitle>
<Badge variant="outline" className="font-normal">
Section {wizardSectionIdx + 1} / {sections.length}
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
<ul className="divide-y">
{wizardSection.items.map((cp) => (
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
))}
</ul>
</CardContent>
<div className="px-4 py-3 border-t bg-muted/30 space-y-2">
{!sectionDone && (
<div className="flex items-start gap-2 text-xs text-amber-900">
<AlertTriangle className="size-3.5 mt-0.5 shrink-0 text-amber-600" />
<div>
<span className="font-medium">{pendingItems.length} pending.</span>{' '}
Each checkpoint needs a finding and its required recording before you can move on.
</div>
</div>
)}
<div className="flex items-center justify-between">
<Button
variant="outline"
className="w-full"
disabled={isUploading}
onClick={() => fileInputRef.current?.click()}
>
<FileUp className="size-4" />
{isUploading
? "Uploading..."
: hasFile
? "Replace Attachment"
: "Add Attachment"}
</Button>
</div>
</DialogContent>
</Dialog>
)
}
// ── Main Page ──
export default function InspectionCheckpointsPage({ params }: { params: Promise<{ id: string }> }) {
const { id: inspectionId } = use(params)
const api = useAuthApi()
const queryClient = useQueryClient()
const [formOpen, setFormOpen] = useState(false)
const [editingCheckpoint, setEditingCheckpoint] = useState<CheckpointItem | null>(null)
const [attachmentsCheckpoint, setAttachmentsCheckpoint] = useState<CheckpointItem | null>(null)
const queryKey = [INSPECTION_ROUTES.CHECKPOINTS, inspectionId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.inspections.listCheckpoints({ inspection_id: inspectionId } as never),
})
const invalidate = () => {
queryClient.invalidateQueries({ queryKey })
}
// ── Status change mutation ──
const changeStatusMutation = useMutation({
mutationFn: ({ checkpointId, status }: { checkpointId: number; status: string }) =>
api.inspections.changeCheckpointStatus({
inspection_id: Number(inspectionId),
inspection_check_point_id: String(checkpointId),
name: "", // required by API type but server uses checkpoint id from context
record_type: "record_conditions",
status,
} as never),
onSuccess: () => invalidate(),
})
// ── Delete checkpoint mutation ──
const deleteMutation = useMutation({
mutationFn: (checkpointId: string) => api.inspections.destroyCheckpoint(checkpointId),
onSuccess: () => {
toast.success("Checkpoint deleted")
invalidate()
},
onError: () => toast.error("Failed to delete checkpoint"),
})
const handleEdit = (checkpoint: CheckpointItem) => {
setEditingCheckpoint(checkpoint)
setFormOpen(true)
}
const handleAdd = () => {
setEditingCheckpoint(null)
setFormOpen(true)
}
const handleStatusChange = (checkpointId: number, status: string) => {
const promise = changeStatusMutation.mutateAsync({ checkpointId, status, })
toast.promise(promise, {
loading: "Updating status...",
success: `Status changed to ${formatStatus(status)}`,
error: "Failed to update status",
})
}
const checkpoints = (data as any)?.data ?? []
const meta = (data as any)?.meta
const pagination = {
page: meta?.current_page ?? 1,
pageSize: meta?.per_page ?? 15,
pageCount: meta?.last_page ?? 1,
total: meta?.total ?? 0,
}
const columns = [
{
accessorKey: "name",
header: ({ column }: any) => <ColumnHeader column={column} title="Name" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<div className="flex flex-col gap-0.5">
<span className="font-medium">{item.name}</span>
{item.description && (
<span className="text-xs text-muted-foreground">{item.description}</span>
)}
</div>
)
},
},
{
accessorKey: "record_type",
header: ({ column }: any) => <ColumnHeader column={column} title="Record Type" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
const rt = RECORD_TYPES.find((r) => r.value === item.record_type)
return rt?.label ?? item.record_type ?? "—"
},
},
{
accessorKey: "status",
header: ({ column }: any) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
const config = getStatusConfig(item.status)
return (
<Badge className={config.color}>
<config.icon className="mr-1 size-3" />
{formatStatus(item.status)}
</Badge>
)
},
},
{
accessorKey: "condition_rate",
header: ({ column }: any) => <ColumnHeader column={column} title="Condition" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return item.condition_rate != null ? `${item.condition_rate}/10` : "—"
},
},
{
id: "attachments",
header: () => <span className="text-xs">Attachments</span>,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<Button
variant="ghost"
size="sm"
className="gap-1.5"
onClick={() => setAttachmentsCheckpoint(item)}
disabled={wizardSectionIdx === 0}
onClick={() => setWizardSectionIdx((i) => Math.max(0, i - 1))}
>
<Paperclip className="size-3.5" />
{item.file ? (
<Badge variant="secondary" className="px-1.5 py-0 text-xs">1</Badge>
) : (
<span className="text-xs text-muted-foreground">0</span>
)}
<ChevronLeft className="size-4" /> Previous
</Button>
)
},
enableSorting: false,
},
{
id: "actions",
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{CHECKPOINT_STATUSES.map((s) => (
<DropdownMenuItem
key={s.value}
onClick={() => handleStatusChange(item.id, s.value)}
disabled={item.status === s.value}
<Button
size="sm"
disabled={wizardSectionIdx >= sections.length - 1 || !sectionDone}
onClick={() => setWizardSectionIdx((i) => Math.min(sections.length - 1, i + 1))}
>
<s.icon className="size-4" />
{s.label}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => handleEdit(item)}>
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => deleteMutation.mutate(String(item.id))}
>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
]
return (
<DashboardPage header={null}>
<div className="flex items-center justify-between p-4">
<h3 className="text-lg font-semibold">Checkpoints</h3>
<Button onClick={handleAdd} size="sm">
<Plus className="size-4" />
Add Checkpoint
Next <ChevronRight className="size-4" />
</Button>
</div>
<DataTable
columns={columns}
data={checkpoints}
pagination={pagination}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
</div>
</Card>
)
})()
)}
{/* Signatures */}
{totalCount > 0 && (
<Card>
<CardHeader className="py-3 flex-row items-center gap-2">
<FileSignature className="size-4 text-muted-foreground" />
<CardTitle className="text-base">Sign-off</CardTitle>
</CardHeader>
<CardContent className="gap-3 grid grid-cols-1 md:grid-cols-2">
<SignaturePad
label="Technician signature"
existingUrl={data.technician_signature_url}
saving={signing?.who === "technician"}
onSave={(d) => handleSign("technician", d)}
/>
<CheckpointFormDialog
open={formOpen}
onOpenChange={(open) => {
setFormOpen(open)
if (!open) setEditingCheckpoint(null)
}}
inspectionId={inspectionId}
checkpoint={editingCheckpoint}
onSuccess={invalidate}
<SignaturePad
label="Customer signature"
existingUrl={data.customer_signature_url}
saving={signing?.who === "customer"}
onSave={(d) => handleSign("customer", d)}
/>
<CheckpointAttachmentsDialog
open={!!attachmentsCheckpoint}
onOpenChange={(open) => {
if (!open) setAttachmentsCheckpoint(null)
}}
checkpoint={attachmentsCheckpoint}
onSuccess={invalidate}
</CardContent>
</Card>
)}
<CheckpointFillDialog
open={activeIndex !== null}
onOpenChange={(o) => { if (!o) setActiveIndex(null) }}
checkpoints={flatCheckpoints}
activeIndex={activeIndex}
onIndexChange={setActiveIndex}
onSaved={load}
onPatch={patchCheckpoint}
/>
</DashboardPage>
<InspectionShareDialog
open={shareOpen}
onOpenChange={setShareOpen}
inspectionId={id}
/>
</div>
)
}
function CheckpointRow({
cp,
onSeverity,
onOpen,
}: {
cp: Checkpoint
onSeverity: (cp: Checkpoint, s: Severity) => void
onOpen: () => void
}) {
const current = (cp.severity as Severity) ?? "not_inspected"
const attachments = cp.attachments ?? cp.media ?? []
const photoCount = attachments.filter((m) => m.media_type === "photo").length
const complete = isCheckpointComplete(cp)
return (
<li
className={`px-3 sm:px-4 py-3 transition-colors hover:bg-muted/30 ${!complete ? "bg-amber-50/40" : ""}`}
>
<div className="flex items-start gap-3 flex-wrap sm:flex-nowrap">
<button
type="button"
onClick={onOpen}
className="flex-1 min-w-0 text-left group"
>
<div className="font-medium text-sm flex items-center gap-2">
<span className="group-hover:text-primary transition">{cp.name}</span>
{!complete && (
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
Pending
</Badge>
)}
</div>
{cp.technician_notes && (
<div className="flex items-start gap-1 text-xs text-muted-foreground mt-1">
<StickyNote className="size-3 mt-0.5 shrink-0" />
<span className="italic line-clamp-1">{cp.technician_notes}</span>
</div>
)}
{photoCount > 0 && (
<div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
<ImageIcon className="size-3" /> {photoCount} photo{photoCount === 1 ? "" : "s"}
</div>
)}
</button>
<div className="flex gap-2 justify-end shrink-0 w-full sm:w-auto">
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => {
const active = current === s
return (
<button
key={s}
type="button"
onClick={(e) => { e.stopPropagation(); onSeverity(cp, s) }}
aria-label={SEVERITY_LABEL[s]}
title={SEVERITY_LABEL[s]}
className={`size-10 sm:size-9 rounded-full transition shadow-md ${SEVERITY_DOT[s]} ${active ? "ring-2 ring-offset-2 ring-foreground/40 scale-105" : "opacity-60 hover:opacity-100"}`}
/>
)
})}
</div>
</div>
</li>
)
}
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { InspectionActions } from '@/modules/inspections/inspection-actions'
import { InspectionProvider } from '@/modules/inspections/inspection-context'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import React from 'react'
export default async function layout(props: {
@@ -23,7 +24,12 @@ export default async function layout(props: {
title={title}
description={orderNumber ? `Order: ${orderNumber}` : undefined}
backHref="/sales/inspections"
actions={<InspectionActions inspectionId={id} status={status} />}
actions={
<div className="flex items-center gap-2">
<ShareDocumentButton type="inspection" id={id} />
<InspectionActions inspectionId={id} status={status} />
</div>
}
tabs={[
{
href: `/sales/inspections/${id}`,
@@ -1,5 +1,6 @@
import { getServerApi } from '@garage/api/server'
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
export default async function page(props: { params: Promise<{ id: string }> }) {
@@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
return <div className="text-muted-foreground">Inspection not found.</div>
}
const data = inspection.data as { title?: string }
return (
<DashboardPage header={null}>
<InspectionDetailHeader inspectionId={id} title={data.title} />
<InspectionGeneralInfo inspection={inspection.data} />
</DashboardPage>
)
@@ -1,25 +1,68 @@
"use client"
import { useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InspectionForm } from "@/modules/inspections/inspection-form"
import { INSPECTION_ROUTES } from "@garage/api"
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
import { Button } from "@/shared/components/ui/button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
import type { InspectionsClient } from "@garage/api"
import Link from "next/link"
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { RelationLink } from "@/shared/components/relation-link"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
const STATUS_BADGE_CLASS: Record<string, string> = {
in_progress: "bg-amber-100 text-amber-800",
completed: "bg-emerald-100 text-emerald-800",
cancelled: "bg-rose-100 text-rose-800",
}
const STATUS_LABEL: Record<string, string> = {
in_progress: "In Progress",
completed: "Completed",
cancelled: "Cancelled",
}
export default function InspectionsPage() {
const router = useRouter()
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
return (
<ResourcePage<InspectionsClient>
pageTitle="Inspections"
routeKey={INSPECTION_ROUTES.INDEX}
searchable
searchPlaceholder="Search inspections..."
statusFilter={{ statuses: InspectionStatus }}
getClient={(api) => api.inspections}
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Inspection">
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" asChild>
<Link href="/settings/inspection-templates">
<ListChecks className="size-4" />
Manage templates
</Link>
</Button>
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
<ClipboardList className="size-4" />
New from template
</Button>
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
{(resourceId) => (
<InspectionForm
resourceId={resourceId}
@@ -28,19 +71,55 @@ export default function InspectionsPage() {
/>
)}
</FormDialog>
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
<DialogContent className="min-w-2xl">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
New inspection from template
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<InspectionFromTemplateForm
onSuccess={(id) => {
setFromTemplateOpen(false)
invalidateQuery()
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
}}
/>
</ScrollArea>
</DialogContent>
</Dialog>
</div>
),
})}
columns={({ actionsColumn }) => [
columns={({ openEdit, deleteItem }) => [
{
accessorKey: "title",
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
cell: ({ row }) => {
const r = row.original as any
return (
<div className="flex flex-col">
<span className="font-medium">{r.title ?? "—"}</span>
{r.order_number && (
<span className="text-xs text-muted-foreground">{r.order_number}</span>
)}
</div>
)
},
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
return (
<RelationLink
href={c?.id ? `/sales/customers/${c.id}` : null}
icon={UserIcon}
label={getFullName(c)}
/>
)
},
},
{
@@ -48,27 +127,51 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
return (
<RelationLink
href={v?.id ? `/sales/vehicles/${v.id}` : null}
icon={Car}
label={getVehicleLabel(v as any)}
meta={v?.license_plate}
/>
)
},
},
{
accessorKey: "inspection_category",
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
cell: ({ row }) => {
const ic = (row.original as any).inspection_category
return ic?.inspection_name ?? ic?.name ?? "—"
},
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
const status = (row.original as any).status as string | undefined
if (!status) return "—"
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
return (
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
{status ?? "—"}
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
{STATUS_LABEL[status] ?? status}
</span>
)
},
},
actionsColumn(),
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<InspectionRowActions
inspection={row.original as any}
onEdit={() => openEdit(row.original as any)}
onDelete={() => deleteItem(String((row.original as any).id))}
/>
),
},
]}
/>
)
@@ -5,6 +5,7 @@ import { InvoiceProvider } from '@/modules/invoices/invoice-context'
import { ReceiptIcon } from 'lucide-react'
import React from 'react'
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
const { id } = await props.params
@@ -24,6 +25,7 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
<div className="flex space-x-2 items-center">
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
<ShareDocumentButton type="invoice" id={id} />
<InvoiceActions invoiceId={id} />
</div>
}
@@ -1,14 +1,18 @@
"use client"
import { Car, Printer, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InvoiceForm } from "@/modules/invoices/invoice-form"
import { Badge } from "@/shared/components/ui/badge"
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES } from "@garage/api"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
import type { InvoicesClient } from "@garage/api"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
type InvoiceItem = {
id: number
@@ -23,6 +27,7 @@ type InvoiceItem = {
total?: number | string
balance_due?: number | string
customer?: {
id?: number | string
first_name?: string
last_name?: string
company_name?: string
@@ -77,11 +82,15 @@ function getDueMeta(dueDate?: string) {
export default function InvoicesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<InvoicesClient>
pageTitle="Invoices"
routeKey={INVOICE_ROUTES.INDEX}
searchable
searchPlaceholder="Search invoices..."
statusFilter={{ statuses: InvoiceStatus }}
getClient={(api) => api.invoices}
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -133,15 +142,13 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const customerLabel = getCustomerLabel(item)
return (
<div className="min-w-[190px]">
<p className="font-medium leading-none">{customerLabel}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.customer?.phone || item.customer?.company_name || "—"}
</p>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getCustomerLabel(item)}
meta={item.customer?.phone}
/>
)
},
},
@@ -150,14 +157,14 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const vehicleId = (item.vehicle as any)?.id
return (
<div className="min-w-[220px]">
<p className="font-medium leading-none">{getVehicleLabel(item)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.vehicle?.license_plate || "—"}
</p>
</div>
<RelationLink
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
icon={Car}
label={getVehicleLabel(item)}
meta={item.vehicle?.license_plate}
/>
)
},
},
@@ -224,16 +231,24 @@ export default function InvoicesPage() {
return (
<div className="min-w-[150px]">
<p className="font-medium leading-none">
Total: {formatCurrency(item.total ?? 0)}
Total: {<Money value={item.total ?? 0} />}
</p>
<p className="mt-1 text-xs text-muted-foreground">
Due: {formatCurrency(item.balance_due ?? 0)}
Due: {<Money value={item.balance_due ?? 0} />}
</p>
</div>
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("invoice", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -7,11 +7,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
import { formatEnum } from "@/shared/utils/formatters"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
@@ -42,13 +45,34 @@ export default function JobCardAppointmentsPage({
router.replace(`${pathname}?${params.toString()}`)
}, [pathname, router, searchParams])
const defaultJobCard = jobCard
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
const jc = jobCard as any
const defaultJobCard = jc
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
: null
const appointmentDefaults = jc
? {
job_card_id: jc.id,
job_card_title: jc.title || `Job Card #${jc.id}`,
customer_id: jc.customer?.id,
customer_name: getFullName(jc.customer),
vehicle_id: jc.vehicle?.id,
vehicle_name: getVehicleLabel(jc.vehicle),
service_writer_id: jc.service_writer?.id,
service_writer_name: getFullName(jc.service_writer),
technician_id: jc.primary_technician?.id,
technician_name: getFullName(jc.primary_technician),
department_id: jc.department?.id,
department_name: jc.department?.name,
}
: { job_card: defaultJobCard }
return (
<ResourcePage<AppointmentsClient>
routeKey={APPOINTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search appointments..."
statusFilter={{ statuses: AppointmentStatus }}
getClient={(api) => api.appointments}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -59,8 +83,8 @@ export default function JobCardAppointmentsPage({
{(resourceId) => (
<AppointmentForm
resourceId={resourceId}
initialData={selectedItem ?? { job_card: defaultJobCard }}
onSuccess={() => { closeDialog(); invalidateQuery() }}
initialData={selectedItem ?? appointmentDefaults}
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
/>
)}
</FormDialog>
@@ -102,7 +126,7 @@ export default function JobCardAppointmentsPage({
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
return (
<Badge className={colorClass}>
{status?.replace("_", " ") ?? "—"}
{formatEnum(status)}
</Badge>
)
},
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { JOB_CARD_ROUTES } from "@garage/api"
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { CONSTANTS } from "@/config/constants"
@@ -22,6 +22,62 @@ function getFileIcon(mimeType?: string) {
return FileIcon
}
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
function describeAttachmentError(rawMessage: string, filename: string): string {
const msg = rawMessage.toLowerCase()
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
}
if (msg.includes("may not be greater") || msg.includes("max")) {
return `${filename}: exceeds 5 MB limit.`
}
if (msg.includes("must be a file")) {
return `${filename}: invalid file.`
}
return `${filename}: ${rawMessage}`
}
function showUploadError(err: unknown, files: File[]) {
if (!(err instanceof ApiError)) {
toast.error("Failed to upload attachment(s)")
return
}
const validation = err.validationErrors
if (!validation || Object.keys(validation).length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const messages: string[] = []
for (const [key, msgs] of Object.entries(validation)) {
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
if (!firstMsg) continue
const match = key.match(/^attachments\.(\d+)$/)
if (match) {
const idx = Number(match[1])
const filename = files[idx]?.name ?? `File #${idx + 1}`
messages.push(describeAttachmentError(firstMsg, filename))
} else if (key === "attachments") {
messages.push(firstMsg)
} else {
messages.push(firstMsg)
}
}
if (messages.length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const shown = messages.slice(0, 3)
const extra = messages.length - shown.length
shown.forEach((m) => toast.error(m))
if (extra > 0) toast.error(`...and ${extra} more`)
}
export default function JobCardAttachmentsPage() {
const { id: jobCardId } = useParams<{ id: string }>()
const api = useAuthApi()
@@ -66,18 +122,19 @@ export default function JobCardAttachmentsPage() {
const files = e.target.files
if (!files || files.length === 0) return
const fileList = Array.from(files)
setIsUploading(true)
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
toast.promise(promise, {
loading: "Uploading attachment(s)...",
success: "Attachment(s) uploaded successfully",
error: "Failed to upload attachment(s)",
})
const loadingToast = toast.loading("Uploading attachment(s)...")
try {
await promise
await api.jobCards.addAttachment(jobCardId, fileList)
toast.dismiss(loadingToast)
toast.success("Attachment(s) uploaded successfully")
queryClient.invalidateQueries({ queryKey })
startRefreshTransition(() => router.refresh())
} catch (err) {
toast.dismiss(loadingToast)
showUploadError(err, fileList)
} finally {
setIsUploading(false)
if (fileInputRef.current) {
@@ -6,9 +6,13 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
import { BILL_ROUTES } from "@garage/api"
import { BILL_ROUTES, BillStatus } from "@garage/api"
import type { BillsClient } from "@garage/api"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { formatEnum } from "@/shared/utils/formatters"
export default function JobCardBillsPage({
params,
@@ -25,6 +29,9 @@ export default function JobCardBillsPage({
return (
<ResourcePage<BillsClient>
routeKey={BILL_ROUTES.INDEX}
searchable
searchPlaceholder="Search bills..."
statusFilter={{ statuses: BillStatus }}
getClient={(api) => api.bills}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -46,7 +53,16 @@ export default function JobCardBillsPage({
{
accessorKey: "bill_number",
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
cell: ({ row }) => (row.original as any).bill_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.id ? `/purchase/bill/${item.id}` : null}
icon={FileTextIcon}
label={item.bill_number}
/>
)
},
},
{
accessorKey: "title",
@@ -55,7 +71,16 @@ export default function JobCardBillsPage({
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "bill_date",
@@ -78,7 +103,7 @@ export default function JobCardBillsPage({
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
return <Badge variant={status === "paid" ? "default" : "secondary"}>{formatEnum(status)}</Badge>
},
},
actionsColumn(),
@@ -44,6 +44,7 @@ export default function JobCardExpenseItemsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -4,10 +4,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InspectionForm } from "@/modules/inspections/inspection-form"
import { INSPECTION_ROUTES } from "@garage/api"
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
import type { InspectionsClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Car, UserIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
export default function InspectionsPage() {
const router = useRouter()
@@ -17,6 +21,9 @@ export default function InspectionsPage() {
pageTitle="Inspections"
extraParams={{job_card_id: jobCard?.id}}
routeKey={INSPECTION_ROUTES.INDEX}
searchable
searchPlaceholder="Search inspections..."
statusFilter={{ statuses: InspectionStatus }}
getClient={(api) => api.inspections}
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -42,7 +49,13 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
return (
<RelationLink
href={c?.id ? `/sales/customers/${c.id}` : null}
icon={UserIcon}
label={getFullName(c)}
/>
)
},
},
{
@@ -50,7 +63,14 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
return (
<RelationLink
href={v?.id ? `/sales/vehicles/${v.id}` : null}
icon={Car}
label={getVehicleLabel(v as any)}
meta={v?.license_plate}
/>
)
},
},
{
@@ -16,7 +16,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
const title = jobCard?.title || 'Job Card Details'
const status = jobCard?.status || 'draft'
const docs = jobCard?.documents
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
return (
<JobCardProvider jobCard={{ ...jobCard }}>
@@ -55,7 +55,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
// TODO: Needs refactor from API side then refactor in frontend
{
href: `/sales/job-cards/${id}/attachments`,
label: `Attachments (${docs?.length || 0})`
label: `Attachments (${attachmentsCount})`
},
{
@@ -1,21 +1,10 @@
import { getServerApi } from '@garage/api/server'
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
import type { JobCardShowData } from '@garage/api'
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const response = await api.jobCards.show(id)
const data = response.data
if (!data) {
return <div className="text-muted-foreground">Job card not found.</div>
}
export default async function JobCardDetailPage() {
return (
<DashboardPage header={null}>
<JobCardGeneralInfo jobCard={data} />
<JobCardGeneralInfo />
</DashboardPage>
)
}
@@ -44,6 +44,7 @@ export default function JobCardPartsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getParts(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
import type { PurchaseOrdersClient } from "@garage/api"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
export default function JobCardPurchaseOrdersPage({
params,
@@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
return (
<ResourcePage<PurchaseOrdersClient>
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
searchable
searchPlaceholder="Search purchase orders..."
getClient={(api) => api.purchaseOrders}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
{
accessorKey: "order_number",
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
cell: ({ row }) => (row.original as any).order_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.id ? `/purchase/purchase-order/${item.id}` : null}
icon={FileTextIcon}
label={item.order_number}
/>
)
},
},
{
accessorKey: "title",
@@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "order_date",
@@ -46,6 +46,7 @@ export default function JobCardServicesPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getServices(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { TaskForm } from "@/modules/tasks/task-form"
import { TASK_ROUTES } from "@garage/api"
import { TASK_ROUTES, TaskStatus } from "@garage/api"
import type { TasksClient } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
return (
<ResourcePage<TasksClient>
routeKey={TASK_ROUTES.INDEX}
searchable
searchPlaceholder="Search tasks..."
statusFilter={{ statuses: TaskStatus }}
getClient={(api) => api.tasks}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -6,12 +6,10 @@ import FormDialog from '@/shared/components/form-dialog'
import { JobCardForm } from '@/modules/job-cards/job-card-form'
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
import type { JobCardsClient } from '@garage/api'
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
import { ClipboardListIcon, Printer } from 'lucide-react'
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
import { Badge } from '@/shared/components/ui/badge'
import { Input } from '@/shared/components/ui/input'
import { useRouter } from 'next/navigation'
import { useState, useEffect, useMemo } from 'react'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
import { useFilterParams } from '@/shared/hooks/use-filter-params'
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
@@ -37,30 +35,18 @@ const statusColorMap: Record<string, string> = {
export default function JobCardsPage() {
const router = useRouter()
const [searchInput, setSearchInput] = useState("")
const [search, setSearch] = useState("")
const [statusFilter, setStatusFilter] = useState<string>("check_in")
const filter = useFilterParams(jobCardFilterConfig)
useEffect(() => {
const timer = setTimeout(() => setSearch(searchInput), 400)
return () => clearTimeout(timer)
}, [searchInput])
const extraParams = useMemo(() => {
const params: Record<string, unknown> = { ...filter.appliedParams }
if (search) params.search = search
if (statusFilter !== "all") params.status = statusFilter
return params
}, [filter.appliedParams, search, statusFilter])
const { print, isPrinting } = useDocumentPrint()
return (
<>
<ResourcePage<JobCardsClient>
routeKey={JOB_CARD_ROUTES.INDEX}
getClient={(api) => api.jobCards}
extraParams={extraParams}
searchable
searchPlaceholder="Search job cards..."
statusFilter={{ statuses: JobCardStatus }}
extraParams={filter.appliedParams}
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
title: "Job Cards",
@@ -133,32 +119,16 @@ export default function JobCardsPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("job_card", String(r.id), "print"),
},
],
}),
]}
tableHeader={
<div className="flex justify-between">
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
<TabsList variant="line">
<TabsTrigger value="all">All</TabsTrigger>
{JobCardStatus.map((status) => (
<TabsTrigger key={status} value={status}>
{formatEnum(status)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="relative w-64">
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search job cards..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-8"
/>
</div>
</div>
}
/>
<FilterDrawer
@@ -0,0 +1,34 @@
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { PaymentReceivedActions } from '@/modules/payment-received/payment-received-actions'
import { BanknoteIcon } from 'lucide-react'
import React from 'react'
export default async function PaymentReceivedDetailLayout(props: {
params: Promise<{ id: string }>
children: React.ReactNode
}) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentReceived.show(id)
const data = (payment as any)?.data ?? payment
const title = data?.payment_number || 'Payment Details'
return (
<DashboardDetailsPage
title={title}
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
icon={<BanknoteIcon className="size-5" />}
backHref="/sales/payment-received"
actions={<PaymentReceivedActions paymentId={id} />}
tabs={[
{
href: `/sales/payment-received/${id}`,
label: 'Details',
},
]}
>
{props.children}
</DashboardDetailsPage>
)
}
@@ -0,0 +1,97 @@
import { getServerApi } from '@garage/api/server'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
import {
BadgeDollarSignIcon,
CalendarIcon,
ClipboardListIcon,
CreditCardIcon,
HashIcon,
UserIcon,
} from 'lucide-react'
export default async function PaymentReceivedDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentReceived.show(id)
const data = (payment as any)?.data ?? payment
if (!data) {
return <div className="text-muted-foreground">Payment not found.</div>
}
const amount = data.amount_received != null
? Number(data.amount_received).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
: '—'
const paymentDate = data.payment_date
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
: '—'
const customerName = data.customer?.first_name
? `${data.customer.first_name} ${data.customer.last_name ?? ''}`.trim()
: data.customer?.company_name ?? data.customer_name ?? '—'
const jobCardLabel = data.job_card?.title ?? data.job_card_name ?? '—'
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
return (
<DashboardPage header={null}>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="flex items-center gap-3 rounded-lg border p-4">
<HashIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Number</p>
<p className="font-medium">{data.payment_number || '—'}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<UserIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Customer</p>
<p className="font-medium">{customerName}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<ClipboardListIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Job Card</p>
<p className="font-medium">{jobCardLabel}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
<div>
<p className="text-xs text-muted-foreground">Amount Received</p>
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CreditCardIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Mode</p>
<p className="font-medium capitalize">{paymentMode}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CalendarIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Date</p>
<p className="font-medium">{paymentDate}</p>
</div>
</div>
{data.note && (
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
<p className="text-xs text-muted-foreground mb-1">Note</p>
<p className="text-sm">{data.note}</p>
</div>
)}
</div>
</DashboardPage>
)
}
@@ -10,10 +10,14 @@ import {
CalendarIcon,
CreditCardIcon,
HashIcon,
Printer,
UserIcon,
ClipboardListIcon,
} from "lucide-react"
import { useRouter } from "next/navigation"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { getFullName } from "@/shared/utils/getFullName"
import { RelationLink } from "@/shared/components/relation-link"
type PaymentReceivedItem = {
id: number
@@ -30,13 +34,19 @@ type PaymentReceivedItem = {
}
export default function PaymentReceivedPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
searchable
searchPlaceholder="Search payments..."
getClient={(api) => ({
list: (query?: any) => api.paymentReceived.list(query),
destroy: (id: string) => api.paymentReceived.destroy(id),
})}
onRowClick={(row) => router.push(`/sales/payment-received/${(row as any).id}`)}
headerProps={({ invalidateQuery }) => ({
actions: (
<FormDialog title="Record Payment">
@@ -65,14 +75,17 @@ export default function PaymentReceivedPage() {
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item: any = row.original as unknown as PaymentReceivedItem
const customer = item.customer
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer) || item.customer_name}
/>
)
},
},
@@ -81,12 +94,13 @@ export default function PaymentReceivedPage() {
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
cell: ({ row }) => {
const item: any = row.original as unknown as PaymentReceivedItem
const label = item.job_card?.title
const jobCard = item.job_card
return (
<div className="flex items-center gap-2">
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
<span>{label || "—"}</span>
</div>
<RelationLink
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
icon={ClipboardListIcon}
label={jobCard?.title || item.job_card_name}
/>
)
},
},
@@ -159,7 +173,15 @@ export default function PaymentReceivedPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("payment_received", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { FileTextIcon } from 'lucide-react'
import { FileTextIcon, UserIcon } from 'lucide-react'
import { useVehicle } from '@/modules/vehicles/vehicle-context'
import { RelationLink } from '@/shared/components/relation-link'
import { getFullName } from '@/shared/utils/getFullName'
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
const { id: vehicleId } = use(params)
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
}
pageTitle="Vehicle Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
extraParams={{ vehicle_id: vehicleId }}
header={
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
{
accessorKey: "customer_name",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer) || item.customer_name}
/>
)
},
},
{
accessorKey: "date",
@@ -7,14 +7,14 @@ import type { ColumnDef } from '@tanstack/react-table'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
import { VEHICLE_ROUTES } from '@garage/api'
import type { VehiclesClient } from '@garage/api'
import { CarIcon } from 'lucide-react'
import { CarIcon, UserIcon } from 'lucide-react'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function VehiclesPage() {
const router = useRouter()
@@ -23,18 +23,19 @@ export default function VehiclesPage() {
<ResourcePage<VehiclesClient>
pageTitle="Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.vehicles.downloadImportSample()}
fileName='vehicles-import-sample'
/>
<ImportDataButton
onImport={(file) => api.vehicles.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Vehicles"
onDownloadSample={() => api.vehicles.downloadImportSample()}
sampleFileName='vehicles-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.vehicles.exportData(filters)}
@@ -80,8 +81,14 @@ export default function VehiclesPage() {
accessorKey: "customers",
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }: any) => {
const val = (row.original as any).customers?.[0]
return getFullName(val)
const customer = (row.original as any).customers?.[0]
return (
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer)}
/>
)
},
} as any,
{
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
<ResourcePage<DepartmentsClient>
pageTitle="Departments"
routeKey={DEPARTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search departments..."
getClient={(api) => api.departments}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -0,0 +1,264 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import { Switch } from "@/shared/components/ui/switch"
import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { prompt } from "@/shared/components/prompt-dialog"
import { TemplateCheckpointEditDialog } from "@/modules/inspections/template-checkpoint-edit-dialog"
import type {
InspectionTemplate,
InspectionTemplateSection,
InspectionTemplateCheckPoint,
InspectionSeverity,
} from "@garage/api"
const SEVERITY_BADGE: Record<InspectionSeverity, { label: string; cls: string }> = {
good: { label: "Good", cls: "bg-emerald-100 text-emerald-800" },
attention: { label: "Attention", cls: "bg-amber-100 text-amber-800" },
critical: { label: "Critical", cls: "bg-rose-100 text-rose-800" },
na: { label: "N/A", cls: "bg-slate-100 text-slate-700" },
not_inspected: { label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
}
const RECORD_TYPE_LABEL: Record<string, string> = {
capture_photo: "Photo",
record_video: "Video",
record_audio: "Audio",
record_conditions: "0–100",
wire_frame: "Wireframe",
none: "No media",
}
export default function InspectionTemplateEditorPage() {
const params = useParams<{ id: string }>()
const id = params.id
const api = useAuthApi()
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
const [loading, setLoading] = useState(true)
const [editing, setEditing] = useState<{
section: InspectionTemplateSection
checkpoint: InspectionTemplateCheckPoint | null
} | null>(null)
const load = useCallback(async () => {
setLoading(true)
try {
const res = await api.inspectionTemplates.show(id)
setTemplate(res.data)
} catch (e: any) {
toast.error(e?.message ?? "Failed to load template")
} finally {
setLoading(false)
}
}, [id])
useEffect(() => { load() }, [load])
const updateMeta = async (partial: Partial<InspectionTemplate>) => {
if (!template) return
try {
const res = await api.inspectionTemplates.update(template.id, partial)
setTemplate(res.data)
} catch (e: any) {
toast.error(e?.message ?? "Failed to save")
}
}
const addSection = async () => {
if (!template) return
const name = await prompt({
title: "New section",
label: "Section name",
placeholder: "e.g. Brakes",
confirmLabel: "Add section",
})
if (!name) return
const nextOrder = (template.sections?.length ?? 0) + 1
try {
await api.inspectionTemplates.createSection(template.id, { name, sort_order: nextOrder })
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to add section")
}
}
const deleteSection = async (section: InspectionTemplateSection) => {
if (!template) return
const confirmed = await confirm({
title: `Delete section "${section.name}"?`,
description: "This will remove the section and all its checkpoints.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroySection(template.id, section.id)
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete section")
}
}
const renameSection = async (section: InspectionTemplateSection, name: string) => {
if (!template || name === section.name) return
try {
await api.inspectionTemplates.updateSection(template.id, section.id, { name })
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to rename section")
}
}
const deleteCheckpoint = async (section: InspectionTemplateSection, cp: InspectionTemplateCheckPoint, e: React.MouseEvent) => {
e.stopPropagation()
if (!template) return
const confirmed = await confirm({
title: `Delete "${cp.name}"?`,
description: "This checkpoint will be removed from the template.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroyCheckpoint(template.id, section.id, cp.id)
await load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete checkpoint")
}
}
if (loading) return <div className="p-6 text-muted-foreground">Loading…</div>
if (!template) return <div className="p-6 text-muted-foreground">Template not found</div>
return (
<div className="p-6 space-y-6 max-w-4xl">
<div className="flex items-center gap-2">
<Link href="/settings/inspection-templates">
<Button variant="ghost" size="sm"><ChevronLeft className="size-4 mr-1" /> Back</Button>
</Link>
</div>
<div className="rounded border p-4 space-y-3">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label className="text-xs text-muted-foreground">Name</label>
<Input
defaultValue={template.name}
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
/>
</div>
<div className="flex items-center gap-3 mt-5">
<Switch
checked={template.is_active}
onCheckedChange={(checked) => updateMeta({ is_active: checked })}
/>
<span className="text-sm">{template.is_active ? "Active" : "Inactive"}</span>
</div>
</div>
<div>
<label className="text-xs text-muted-foreground">Description</label>
<Textarea
defaultValue={template.description ?? ""}
rows={2}
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
/>
</div>
</div>
<div className="flex items-center justify-between">
<h2 className="text-lg font-medium">Sections & Checkpoints</h2>
<Button onClick={addSection} size="sm"><Plus className="size-4 mr-1" /> Add section</Button>
</div>
<div className="space-y-4">
{(template.sections ?? []).length === 0 && (
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
No sections yet. Add one to start building the checklist.
</div>
)}
{(template.sections ?? []).map((section) => (
<div key={section.id} className="rounded border">
<div className="flex items-center gap-2 px-3 py-2 bg-muted/40">
<Input
defaultValue={section.name}
onBlur={(e) => renameSection(section, e.currentTarget.value)}
className="max-w-md h-8"
/>
<span className="text-xs text-muted-foreground">
{(section.check_points ?? []).length} checkpoint{(section.check_points ?? []).length === 1 ? "" : "s"}
</span>
<div className="ml-auto flex items-center gap-1">
<Button size="sm" variant="ghost" onClick={() => setEditing({ section, checkpoint: null })}>
<Plus className="size-4 mr-1" /> Checkpoint
</Button>
<Button size="sm" variant="ghost" onClick={() => deleteSection(section)}>
<Trash2 className="size-4 text-red-600" />
</Button>
</div>
</div>
<div className="divide-y">
{(section.check_points ?? []).length === 0 && (
<div className="p-3 text-sm text-muted-foreground">No checkpoints in this section.</div>
)}
{(section.check_points ?? []).map((cp) => {
const sev = SEVERITY_BADGE[cp.severity_default] ?? SEVERITY_BADGE.not_inspected
return (
<button
type="button"
key={cp.id}
onClick={() => setEditing({ section, checkpoint: cp })}
className="w-full text-left flex items-center gap-3 px-3 py-2 hover:bg-muted/30 transition"
>
<span className="text-xs text-muted-foreground w-6 text-right">
{cp.sort_order}
</span>
<span className="flex-1 min-w-0 truncate text-sm font-medium">
{cp.name}
</span>
<span className="text-xs text-muted-foreground hidden sm:inline-block">
{RECORD_TYPE_LABEL[cp.record_type] ?? cp.record_type}
</span>
<span className={`text-xs rounded-full px-2 py-0.5 ${sev.cls}`}>
{sev.label}
</span>
<Pencil className="size-3.5 text-muted-foreground" />
<button
type="button"
onClick={(e) => deleteCheckpoint(section, cp, e)}
className="text-red-600 hover:text-red-700"
aria-label="Delete checkpoint"
>
<Trash2 className="size-4" />
</button>
</button>
)
})}
</div>
</div>
))}
</div>
{editing && (
<TemplateCheckpointEditDialog
open={!!editing}
onOpenChange={(o) => { if (!o) setEditing(null) }}
templateId={template.id}
sectionId={editing.section.id}
checkpoint={editing.checkpoint}
nextSortOrder={(editing.section.check_points?.length ?? 0) + 1}
onSaved={load}
/>
)}
</div>
)
}
@@ -0,0 +1,157 @@
"use client"
import { useEffect, useState } from "react"
import Link from "next/link"
import { Copy, Pencil, Plus, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import type { InspectionTemplate } from "@garage/api"
export default function InspectionTemplatesPage() {
const api = useAuthApi()
const [items, setItems] = useState<InspectionTemplate[]>([])
const [search, setSearch] = useState("")
const [loading, setLoading] = useState(true)
const [creating, setCreating] = useState(false)
const [newName, setNewName] = useState("")
const load = async () => {
setLoading(true)
try {
const res = await api.inspectionTemplates.list(search ? { search } : undefined)
setItems(res.data ?? [])
} catch (e: any) {
toast.error(e?.message ?? "Failed to load templates")
} finally {
setLoading(false)
}
}
useEffect(() => {
load()
}, [])
const handleCreate = async () => {
if (!newName.trim()) return
try {
await api.inspectionTemplates.create({ name: newName.trim(), is_active: true })
setNewName("")
setCreating(false)
toast.success("Template created")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to create template")
}
}
const handleDuplicate = async (id: number) => {
try {
await api.inspectionTemplates.duplicate(id)
toast.success("Template duplicated")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to duplicate template")
}
}
const handleDelete = async (id: number, name: string) => {
const confirmed = await confirm({
title: `Delete "${name}"?`,
description: "This will remove the template and all its sections / checkpoints.",
confirmLabel: "Delete",
variant: "destructive",
})
if (!confirmed) return
try {
await api.inspectionTemplates.destroy(id)
toast.success("Template deleted")
load()
} catch (e: any) {
toast.error(e?.message ?? "Failed to delete template")
}
}
return (
<div className="p-6 space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-2xl font-semibold">Inspection Templates</h1>
<div className="flex items-center gap-2">
<Input
placeholder="Search…"
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && load()}
className="w-56"
/>
<Button onClick={() => setCreating((c) => !c)}>
<Plus className="size-4 mr-1" /> New template
</Button>
</div>
</div>
{creating && (
<div className="flex items-center gap-2 rounded border p-3">
<Input
autoFocus
placeholder="Template name (e.g. Annual Safety)"
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
className="max-w-md"
/>
<Button onClick={handleCreate}>Create</Button>
<Button variant="ghost" onClick={() => { setCreating(false); setNewName("") }}>Cancel</Button>
</div>
)}
<div className="rounded border">
<table className="w-full text-sm">
<thead className="bg-muted">
<tr>
<th className="text-left p-3">Name</th>
<th className="text-left p-3">Sections</th>
<th className="text-left p-3">Checkpoints</th>
<th className="text-left p-3">Status</th>
<th className="text-right p-3">Actions</th>
</tr>
</thead>
<tbody>
{loading && (
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading…</td></tr>
)}
{!loading && items.length === 0 && (
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No templates yet</td></tr>
)}
{!loading && items.map((t) => {
const sectionCount = t.sections?.length ?? 0
const cpCount = (t.sections ?? []).reduce((sum, s) => sum + (s.check_points?.length ?? 0), 0)
return (
<tr key={t.id} className="border-t hover:bg-muted/40">
<td className="p-3 font-medium">{t.name}</td>
<td className="p-3">{sectionCount}</td>
<td className="p-3">{cpCount}</td>
<td className="p-3">
<span className={`inline-block rounded-full px-2 py-0.5 text-xs ${t.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}>
{t.is_active ? "Active" : "Inactive"}
</span>
</td>
<td className="p-3 text-right space-x-1">
<Link href={`/settings/inspection-templates/${t.id}`}>
<Button size="sm" variant="ghost"><Pencil className="size-4" /></Button>
</Link>
<Button size="sm" variant="ghost" onClick={() => handleDuplicate(t.id)}><Copy className="size-4" /></Button>
<Button size="sm" variant="ghost" onClick={() => handleDelete(t.id, t.name)}><Trash2 className="size-4 text-red-600" /></Button>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
)
}
@@ -12,6 +12,8 @@ export default function InsuranceTypesPage() {
<ResourcePage<InsuranceTypesClient>
pageTitle="Insurance Types"
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
searchable
searchPlaceholder="Search insurance types..."
getClient={(api) => api.insuranceTypes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -12,6 +12,8 @@ export default function MakeAndModelsPage() {
<ResourcePage<MakeAndModelsClient>
pageTitle="Make & Models"
routeKey={MAKE_AND_MODEL_ROUTES.INDEX}
searchable
searchPlaceholder="Search makes & models..."
getClient={(api) => api.makeAndModels}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -13,6 +13,8 @@ export default function ShopTypesPage() {
<ResourcePage<ShopTypesClient>
pageTitle="Shop Types"
routeKey={SHOP_TYPE_ROUTES.INDEX}
searchable
searchPlaceholder="Search shop types..."
getClient={(api) => api.shopTypes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -55,6 +55,8 @@ export default function TaxesPage() {
<ResourcePage<TaxesClient>
pageTitle="Tax & Rates"
routeKey={TAX_ROUTES.INDEX}
searchable
searchPlaceholder="Search tax rates..."
getClient={(api) => api.taxes}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -0,0 +1,444 @@
"use client"
import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import {
AlertCircle,
Calendar,
Car,
CheckCircle2,
ChevronRight,
ClipboardList,
Gauge,
Loader2,
Printer,
ShieldAlert,
ShieldCheck,
User,
} from "lucide-react"
type Severity = "good" | "attention" | "critical" | "na" | "not_inspected"
type Photo = { id: number; url: string | null; caption?: string | null }
type CheckPoint = {
name: string
description?: string | null
severity: Severity
technician_notes?: string | null
condition_rate?: number | null
photos?: Photo[]
}
type Section = { name: string; items: CheckPoint[] }
type PublicInspection = {
title?: string
order_number?: string
date?: string
time?: string
status?: string
odometer?: number | null
note?: string | null
description?: string | null
customer?: { name?: string } | null
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string; vin?: string } | null
technician?: { name?: string } | null
department?: string | null
template?: string | null
totals: { good: number; attention: number; critical: number; na: number; not_inspected: number; considered: number; all: number }
score: number | null
sections: Section[]
share_expires_at?: string | null
}
const SEVERITY_LABEL: Record<Severity, string> = {
good: "Good",
attention: "Attention",
critical: "Critical",
na: "N/A",
not_inspected: "Not Inspected",
}
const SEVERITY_DOT_BG: Record<Severity, string> = {
good: "bg-emerald-500",
attention: "bg-amber-500",
critical: "bg-rose-500",
na: "bg-slate-400",
not_inspected: "bg-gray-300",
}
const SEVERITY_PILL: Record<Severity, string> = {
good: "bg-emerald-50 text-emerald-700 border-emerald-200",
attention: "bg-amber-50 text-amber-800 border-amber-200",
critical: "bg-rose-50 text-rose-700 border-rose-200",
na: "bg-slate-50 text-slate-700 border-slate-200",
not_inspected: "bg-gray-50 text-gray-600 border-gray-200",
}
const SEVERITY_BORDER: Record<Severity, string> = {
good: "border-l-emerald-500",
attention: "border-l-amber-500",
critical: "border-l-rose-500",
na: "border-l-slate-400",
not_inspected: "border-l-gray-300",
}
function ScoreRing({ score }: { score: number | null }) {
if (score === null) {
return (
<div className="size-32 rounded-full border-4 border-dashed border-muted-foreground/30 flex items-center justify-center text-xs text-muted-foreground">
Not scored
</div>
)
}
const color =
score >= 80 ? "text-emerald-600" : score >= 50 ? "text-amber-600" : "text-rose-600"
const stroke =
score >= 80 ? "stroke-emerald-500" : score >= 50 ? "stroke-amber-500" : "stroke-rose-500"
const r = 56
const c = 2 * Math.PI * r
const offset = c - (score / 100) * c
return (
<div className="relative size-32 shrink-0">
<svg viewBox="0 0 128 128" className="size-32 -rotate-90">
<circle cx="64" cy="64" r={r} className="fill-none stroke-muted" strokeWidth="10" />
<circle
cx="64"
cy="64"
r={r}
className={`fill-none ${stroke} transition-[stroke-dashoffset]`}
strokeWidth="10"
strokeLinecap="round"
strokeDasharray={c}
strokeDashoffset={offset}
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<div className={`text-3xl font-bold leading-none ${color}`}>{score}</div>
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mt-1">
Health
</div>
</div>
</div>
)
}
export default function PublicInspectionPage() {
const params = useParams<{ token: string }>()
const token = params.token
const [data, setData] = useState<PublicInspection | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const [lightbox, setLightbox] = useState<Photo | null>(null)
useEffect(() => {
const base = process.env.NEXT_PUBLIC_API_URL ?? ""
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}`, {
headers: { Accept: "application/json", "X-Lang": "en" },
})
.then(async (res) => {
if (!res.ok) {
const body = await res.json().catch(() => ({} as any))
throw new Error(body.message ?? `Failed (HTTP ${res.status})`)
}
return res.json()
})
.then((json: { data: PublicInspection }) => setData(json.data))
.catch((e: Error) => setError(e.message))
.finally(() => setLoading(false))
}, [token])
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="size-4 animate-spin" /> Loading inspection…
</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
<AlertCircle className="size-12 mx-auto text-rose-500" />
<h1 className="text-lg font-semibold">Can't open this inspection</h1>
<p className="text-sm text-muted-foreground">{error}</p>
</div>
</div>
)
}
if (!data) return null
const vehicleLine = data.vehicle
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
: "—"
const criticalCount = data.totals.critical
const attentionCount = data.totals.attention
const headlineStatus =
criticalCount > 0
? { Icon: ShieldAlert, color: "text-rose-600", bg: "bg-rose-50", label: `${criticalCount} critical issue${criticalCount === 1 ? "" : "s"} found` }
: attentionCount > 0
? { Icon: AlertCircle, color: "text-amber-600", bg: "bg-amber-50", label: `${attentionCount} item${attentionCount === 1 ? "" : "s"} need attention` }
: { Icon: ShieldCheck, color: "text-emerald-600", bg: "bg-emerald-50", label: "No issues found" }
return (
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
{/* Print is handled by downloading the backend-generated PDF
(see the Print button), so this page no longer needs print CSS. */}
{/* Print bar */}
<div className="no-print bg-white/80 backdrop-blur border-b sticky top-0 z-10">
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<ClipboardList className="size-4" />
<span className="font-medium text-foreground">Inspection report</span>
</div>
<a
href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition"
>
<Printer className="size-3.5" /> Print PDF
</a>
</div>
</div>
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-5">
{/* Hero card */}
<div className="rounded-2xl bg-white shadow-sm border overflow-hidden">
<div className="p-6 sm:p-8">
<div className="flex items-start justify-between gap-6 flex-wrap">
<div className="min-w-0 flex-1">
<div className="text-xs uppercase tracking-wider text-muted-foreground">
Vehicle inspection report
</div>
<h1 className="mt-1 text-2xl sm:text-3xl font-bold tracking-tight">{data.title ?? "Inspection"}</h1>
{data.order_number && (
<div className="text-sm text-muted-foreground font-mono mt-1">#{data.order_number}</div>
)}
<div className={`mt-4 inline-flex items-center gap-2 rounded-full ${headlineStatus.bg} px-4 py-1.5`}>
<headlineStatus.Icon className={`size-4 ${headlineStatus.color}`} />
<span className={`text-sm font-medium ${headlineStatus.color}`}>
{headlineStatus.label}
</span>
</div>
</div>
<ScoreRing score={data.score} />
</div>
</div>
<div className="border-t bg-gray-50/60 px-6 sm:px-8 py-4">
<div className="info-grid grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
<InfoCell icon={User} label="Customer" value={data.customer?.name ?? "—"} />
<InfoCell icon={Car} label="Vehicle" value={vehicleLine} subtitle={data.vehicle?.license_plate ?? undefined} />
<InfoCell icon={Calendar} label="Inspected" value={data.date ?? "—"} subtitle={data.time ?? undefined} />
<InfoCell icon={Gauge} label="Odometer" value={data.odometer != null ? `${Number(data.odometer).toLocaleString()} km` : "—"} />
</div>
</div>
</div>
{/* Severity summary */}
<div className="totals-grid grid grid-cols-2 sm:grid-cols-5 gap-2 pb-avoid">
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
<div
key={s}
className={`rounded-xl border px-3 py-3 text-center ${SEVERITY_PILL[s]}`}
>
<div className="text-xl font-bold leading-none tabular-nums">{data.totals[s]}</div>
<div className="text-[11px] font-medium mt-1.5">{SEVERITY_LABEL[s]}</div>
</div>
))}
</div>
{/* Sections */}
{data.sections.length === 0 ? (
<div className="rounded-2xl bg-white border p-8 text-center text-sm text-muted-foreground">
This inspection has no recorded checkpoints yet.
</div>
) : (
data.sections.map((section) => (
<section key={section.name} className="rounded-2xl bg-white shadow-sm border overflow-hidden">
<header className="px-5 sm:px-6 py-3 border-b flex items-center justify-between bg-gray-50/60">
<h2 className="font-semibold text-sm sm:text-base">{section.name}</h2>
<span className="text-xs text-muted-foreground">
{section.items.length} {section.items.length === 1 ? "item" : "items"}
</span>
</header>
<ul className="divide-y">
{section.items.map((cp, i) => (
<li
key={i}
className={`cp-row pb-avoid px-5 sm:px-6 py-4 border-l-4 ${SEVERITY_BORDER[cp.severity]}`}
>
{/* Head: dot + name + severity pill (pill stays inline next to name) */}
<div className="cp-head flex items-center gap-2">
<span className={`size-2 rounded-full ${SEVERITY_DOT_BG[cp.severity]} shrink-0`} />
<span className="font-medium text-sm flex-1 min-w-0 truncate">{cp.name}</span>
<span className={`cp-pill inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium shrink-0 ${SEVERITY_PILL[cp.severity]}`}>
{SEVERITY_LABEL[cp.severity]}
</span>
</div>
<div className="cp-body ms-4">
{cp.description && (
<p className="text-xs text-muted-foreground mt-1">{cp.description}</p>
)}
{cp.technician_notes && (
<p className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-foreground/80 italic border-l-2 border-muted-foreground/30">
"{cp.technician_notes}"
</p>
)}
{cp.condition_rate != null && (
<div className="mt-2">
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
<div
className={`h-full transition-all ${cp.severity === "critical" ? "bg-rose-500" : cp.severity === "attention" ? "bg-amber-500" : "bg-emerald-500"}`}
style={{ width: `${cp.condition_rate}%` }}
/>
</div>
<div className="text-[11px] text-muted-foreground mt-0.5 tabular-nums">{cp.condition_rate}%</div>
</div>
)}
{cp.photos && cp.photos.length > 0 && (
<div className="photo-grid mt-3 grid grid-cols-3 sm:grid-cols-4 gap-2">
{cp.photos.map((p) => (
p.url ? (
<button
type="button"
key={p.id}
onClick={() => setLightbox(p)}
className="group relative rounded-lg overflow-hidden border bg-muted aspect-square focus:outline-none focus:ring-2 focus:ring-primary/40"
aria-label="View photo"
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={p.url}
alt={p.caption ?? ""}
className="block w-full h-full object-cover transition group-hover:scale-105"
/>
</button>
) : null
))}
</div>
)}
</div>
</li>
))}
</ul>
</section>
))
)}
{(data.note || data.description) && (
<section className="rounded-2xl bg-white shadow-sm border p-5 sm:p-6">
<h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
<ChevronRight className="size-4 text-muted-foreground" />
Additional notes from your technician
</h2>
{data.note && <p className="text-sm leading-relaxed">{data.note}</p>}
{data.description && (
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">{data.description}</p>
)}
</section>
)}
{/* Technician footer */}
{data.technician?.name && (
<div className="rounded-2xl bg-white shadow-sm border px-5 sm:px-6 py-4 flex items-center justify-between gap-3 flex-wrap">
<div className="flex items-center gap-3">
<div className="size-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 text-white flex items-center justify-center font-semibold text-sm">
{data.technician.name
.split(" ")
.map((p) => p[0])
.filter(Boolean)
.slice(0, 2)
.join("")}
</div>
<div>
<div className="text-xs text-muted-foreground">Inspected by</div>
<div className="font-medium text-sm">{data.technician.name}</div>
</div>
</div>
{data.department && (
<span className="text-xs text-muted-foreground">{data.department}</span>
)}
{data.template && (
<span className="text-xs rounded-full border px-3 py-1 bg-muted/30">
{data.template}
</span>
)}
</div>
)}
<footer className="text-center text-xs text-muted-foreground py-6 no-print">
{data.share_expires_at && (
<div>Link valid until {new Date(data.share_expires_at).toLocaleDateString()}</div>
)}
</footer>
</div>
{/* Lightbox */}
{lightbox && lightbox.url && (
<div
className="no-print fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
onClick={() => setLightbox(null)}
role="dialog"
aria-modal
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={lightbox.url}
alt={lightbox.caption ?? ""}
className="max-w-full max-h-[88vh] object-contain shadow-2xl"
onClick={(e) => e.stopPropagation()}
/>
<button
type="button"
onClick={() => setLightbox(null)}
className="absolute top-4 right-4 rounded-full bg-white/10 hover:bg-white/20 text-white size-9 inline-flex items-center justify-center"
aria-label="Close"
>
×
</button>
{lightbox.caption && (
<div className="absolute bottom-4 inset-x-0 text-center text-white/90 text-sm px-4">
{lightbox.caption}
</div>
)}
</div>
)}
</div>
)
}
function InfoCell({
icon: Icon,
label,
value,
subtitle,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string
subtitle?: string
}) {
return (
<div className="flex items-start gap-2 min-w-0">
<Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" />
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</div>
<div className="font-medium truncate">{value}</div>
{subtitle && (
<div className="text-xs text-muted-foreground font-mono truncate">{subtitle}</div>
)}
</div>
</div>
)
}
+4
View File
@@ -1,10 +1,12 @@
import { Geist_Mono, Inter } from "next/font/google"
import NextTopLoader from "nextjs-toploader"
import { QueryProvider } from "@/shared/components/query-provider"
import { ThemeProvider } from "@/shared/components/theme-provider"
import { Toaster } from "@/shared/components/ui/sonner"
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
import { PromptDialog } from "@/shared/components/prompt-dialog"
import { NuqsAdapter } from "nuqs/adapters/next/app"
import { cn } from "@/shared/lib/utils"
import './globals.css'
@@ -33,11 +35,13 @@ export default function RootLayout({
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
>
<body>
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
<NuqsAdapter>
<ThemeProvider>
<QueryProvider>{children}</QueryProvider>
<Toaster />
<ConfirmDialog />
<PromptDialog />
</ThemeProvider>
</NuqsAdapter>
</body>
@@ -141,9 +141,20 @@ export function AppSidebar({ navGroups, logo, user, ...props }: AppSidebarProps)
)
}
function isPathActive(pathname: string, href: string): boolean {
if (href === '/') return pathname === '/'
return pathname === href || pathname.startsWith(href + '/')
}
function isItemActive(pathname: string, item: { href: string; matchPath?: string; isActive?: boolean }): boolean {
if (item.isActive !== undefined) return item.isActive
if (item.matchPath) return isPathActive(pathname, item.matchPath)
return isPathActive(pathname, item.href)
}
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isActive = item.isActive ?? pathname === item.href
const isActive = isItemActive(pathname, item)
return (
<SidebarMenuItem>
@@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isChildActive = item.items?.some((sub) => pathname === sub.href)
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
// Collapsed sidebar → flyout dropdown with sub-items
if (isCollapsed) {
@@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
</DropdownMenuLabel>
<DropdownMenuSeparator />
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<DropdownMenuItem key={sub.href} asChild>
<Link
@@ -272,7 +283,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
<SidebarMenuSub>
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<SidebarMenuSubItem key={sub.href}>
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
</Button>
)}
{(avatarSrc || avatarFallback) && (
<a rel="preload" target="_blank" href={avatarSrc} >
avatarSrc ? (
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
<Avatar className="size-14">
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
<AvatarImage src={avatarSrc} alt={title} />
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
</a>
) : (
<Avatar className="size-14">
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
)
)}
{!avatarSrc && !avatarFallback && icon && (
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
@@ -109,6 +117,7 @@ export default function DashboardDetailsPageLayout({
<Link
key={tab.href}
href={tab.href}
prefetch
className={cn(
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
"text-muted-foreground hover:text-foreground",
+7
View File
@@ -6,6 +6,12 @@ export type NavItem = {
href: string
icon?: ReactNode
isActive?: boolean
/**
* Optional prefix used to decide active state when the link target
* differs from the page's URL pattern (e.g. `/calendar/appointment/list`
* is the link, but the item should stay active on `/calendar/appointment/{id}`).
*/
matchPath?: string
badge?: string | number
items?: NavSubItem[]
}
@@ -15,6 +21,7 @@ export type NavSubItem = {
href: string
icon?: ReactNode
isActive?: boolean
matchPath?: string
}
export type NavGroup = {
+7 -5
View File
@@ -76,7 +76,7 @@ export const navGroups: NavGroup[] = [
icon: <CalendarIcon />,
items: [
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", matchPath: "/calendar/appointment", icon: <CalendarCheck2Icon /> },
],
},
{
@@ -144,10 +144,11 @@ export const navGroups: NavGroup[] = [
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
{ title: "Leave Requests", href: "/productivity/leave-requests", icon: <CalendarIcon /> },
{ title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
// { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
// { title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
{ title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
{ title: "Holidays", href: "/productivity/holidays", icon: <CalendarIcon /> },
{ title: "Tasks", href: "/productivity/tasks", icon: <ListTodoIcon /> },
],
@@ -176,7 +177,8 @@ export const navGroups: NavGroup[] = [
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
{ title: "Make & Models", href: "/settings/make-and-models", icon: <CarIcon /> },
{ title: "Configurations", href: "/settings/configurations/preferences/sales", icon: <SettingsIcon /> },
{ title: "Inspection Templates", href: "/settings/inspection-templates", icon: <ClipboardListIcon /> },
{ title: "Configurations", href: "/settings/configurations/preferences/sales", matchPath: "/settings/configurations", icon: <SettingsIcon /> },
// { title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
// { title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },
@@ -0,0 +1,14 @@
{
"list_pages": {
"inspection": { "url": "/sales/inspections", "type": "inspection", "api": "/api/inspections" },
"estimate": { "url": "/sales/estimates", "type": "estimate", "api": "/api/estimates" },
"job_card": { "url": "/sales/job-cards", "type": "job_card", "api": "/api/job-cards" },
"invoice": { "url": "/sales/invoice", "type": "invoice", "api": "/api/invoices" },
"payment_received": { "url": "/sales/payment-received", "type": "payment_received", "api": "/api/payment-recieved" },
"expense": { "url": "/purchase/expense", "type": "expense", "api": "/api/expenses" },
"purchase_order": { "url": "/purchase/purchase-order", "type": "purchase_order", "api": "/api/purchase-orders" },
"bill": { "url": "/purchase/bill", "type": "bill", "api": "/api/bills" },
"payment_made": { "url": "/purchase/payments-made", "type": "payment_made", "api": "/api/payment-mades" },
"credit_note": { "url": "/sales/credit-notes", "type": "credit_note", "api": "/api/credit-notes" }
}
}
@@ -19,6 +19,7 @@ import { useQueryClient } from "@tanstack/react-query"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { useFormDialog } from "@/shared/components/form-dialog"
import { AppointmentForm } from "./appointment-form"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentActionsProps = {
appointmentId: string
@@ -50,7 +51,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
setIsLoading(true)
try {
await api.appointments.changeStatus(appointmentId, { status } as any)
toast.success(`Status updated to "${status}".`)
toast.success(`Status updated to "${formatEnum(status)}".`)
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
router.refresh()
} catch {
@@ -15,6 +15,7 @@ import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentData = {
id?: number
@@ -89,7 +90,7 @@ export function AppointmentGeneralInfo({ appointment }: AppointmentGeneralInfoPr
<div className="flex items-center gap-2">
{appointment.status && (
<Badge className={statusClass}>
{appointment.status.replace("_", " ")}
{formatEnum(appointment.status)}
</Badge>
)}
</div>
@@ -10,20 +10,30 @@ const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))
const appointmentFormSchema = z.object({
title: z.string().min(1, "Title is required"),
const appointmentFormSchema = z
.object({
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
date: z.string().min(1, "Date is required"),
from_time: z.string().min(1, "Start time is required"),
to_time: z.string().min(1, "End time is required"),
customer: relationFieldSchema,
vehicle: relationFieldSchema,
service_writer: relationFieldSchema,
service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
technician: relationFieldSchema,
department: relationFieldSchema,
job_card: relationFieldSchema,
notes: z.string().optional(),
status: z.string().optional(),
})
.superRefine((val, ctx) => {
if (val.from_time && val.to_time && val.to_time <= val.from_time) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["to_time"],
message: "End time must be after start time",
})
}
})
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
@@ -2,7 +2,7 @@ import { z } from "zod"
const loginFormSchema = z.object({
email: z.string().trim().email("Enter a valid email address"),
password: z.string().min(8, "Password must be at least 8 characters"),
password: z.string().min(6, "Password must be at least 6 characters"),
})
type LoginFormValues = z.infer<typeof loginFormSchema>
+16 -1
View File
@@ -11,9 +11,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2, Share2 } from "lucide-react"
import { useState } from "react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { BillForm } from "./bill-form"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type BillActionsProps = {
billId: string
@@ -23,6 +26,8 @@ export function BillActions({ billId }: BillActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("bill-details-edit")
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
await api.bills.destroy(billId)
@@ -42,6 +47,14 @@ export function BillActions({ billId }: BillActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("bill", billId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -49,6 +62,8 @@ export function BillActions({ billId }: BillActionsProps) {
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="bill" id={billId} open={shareOpen} onOpenChange={setShareOpen} />
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
<DialogContent className="min-w-xl lg:min-w-4xl">
<DialogHeader>
@@ -3,7 +3,8 @@
import { Receipt } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillExpense = {
id: number
@@ -62,14 +63,14 @@ export function BillExpensesSection({ expenses = [] }: BillExpensesSectionProps)
{expense.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -19,9 +19,10 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"
import { formatDate, formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
function InfoItem({
icon: Icon,
@@ -3,7 +3,8 @@
import { Wrench } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillPart = {
id: number
@@ -62,14 +63,14 @@ export function BillPartsSection({ parts = [] }: BillPartsSectionProps) {
{part.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -17,7 +17,6 @@ import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
import { useBill } from "./bill-context"
import { formatDate } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { toRelation } from "@/shared/lib/utils"
export function BillPaymentsSection() {
const bill = useBill()
@@ -39,8 +38,17 @@ export function BillPaymentsSection() {
{(resourceId) => (
<PaymentMadeForm
initialData={{
amount: bill?.balance_due,
vendor: toRelation(bill?.vendor?.id, getFullName(bill?.vendor as any)),
// API-shape keys so PaymentMadeForm.mapToFormValues
// can pick them up (it reads `payment_made` / `vendor_id`
// / `vendor.*`, not the form-shape fields). bill_id +
// bill_number are required because the bill field is
// hidden when billId is supplied, but the schema still
// demands a populated bill relation.
bill_id: bill?.id,
bill_number: bill?.bill_number,
payment_made: bill?.balance_due,
vendor_id: bill?.vendor?.id,
vendor: bill?.vendor,
payment_for: "bill",
}}
billId={bill?.id}
@@ -77,7 +85,7 @@ export function BillPaymentsSection() {
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{item.vendor?.name || item.vendor_name || "—"}</span>
<span>{item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name || "—"}</span>
</div>
)
},
@@ -3,7 +3,8 @@
import { Briefcase } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillService = {
id: number
@@ -62,14 +63,14 @@ export function BillServicesSection({ services = [] }: BillServicesSectionProps)
{service.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -1,6 +1,6 @@
"use client"
import { BillStatus } from "@garage/api"
import { BillStatus, parseApiError } from "@garage/api"
import { Badge, badgeVariants } from "@/shared/components/ui/badge"
import {
Select,
@@ -60,7 +60,7 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
toast.success("Bill status updated")
router.refresh()
} catch (error) {
toast.error("Failed to update bill status")
toast.error(parseApiError(error, "Failed to update bill status"))
} finally {
setIsLoading(false)
}
@@ -71,7 +71,9 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
<SelectTrigger
className={`border-0 size-auto p-0 h-auto font-medium ${STATUS_TRIGGER_CLASS_NAMES[status]}`}
>
<SelectValue placeholder="Select status" />
<SelectValue placeholder="Select status">
{formatEnum(status)}
</SelectValue>
</SelectTrigger>
<SelectContent>
{BillStatus.map((s) => (
@@ -2,9 +2,10 @@
import { Card, CardContent } from "@/shared/components/ui/card"
import { Separator } from "@/shared/components/ui/separator"
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatEnum } from "@/shared/utils/formatters"
import { cn } from "@/shared/lib/utils"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
export function BillTotalsSummary() {
const bill = useBill()
@@ -46,70 +47,65 @@ export function BillTotalsSummary() {
{parts.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Parts ({parts.length})</span>
<span>{formatCurrency(partsTotal)}</span>
<span>{<Money value={partsTotal} />}</span>
</div>
)}
{services.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Services ({services.length})</span>
<span>{formatCurrency(servicesTotal)}</span>
<span>{<Money value={servicesTotal} />}</span>
</div>
)}
{expenses.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
<span>{formatCurrency(expensesTotal)}</span>
<span>{<Money value={expensesTotal} />}</span>
</div>
)}
<Separator />
<div className="flex justify-between text-sm font-medium">
<span>Subtotal</span>
<span>{formatCurrency(subTotal)}</span>
<span>{<Money value={subTotal} />}</span>
</div>
{discountAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""}</span>
<span className="text-muted-foreground">−{formatCurrency(discountAmount)}</span>
<span className="text-muted-foreground">−{<Money value={discountAmount} />}</span>
</div>
)}
{taxAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""}</span>
<span>{formatCurrency(taxAmount)}</span>
<span>{<Money value={taxAmount} />}</span>
</div>
)}
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-bold bg-muted/50",
)}>
<div className="flex justify-between text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(total)}</span>
<span>{<Money value={total} />}</span>
</div>
{paymentsMade > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Payments Made</span>
<span className="text-emerald-600">−{formatCurrency(paymentsMade)}</span>
<div className="flex justify-between text-sm text-muted-foreground">
<span>Amount Paid</span>
<span>– {<Money value={paymentsMade} />}</span>
</div>
)}
{paymentsMade > 0 && (
<>
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-semibold",
balanceDue > 0 ? "text-destructive bg-destructive/5" : "text-emerald-700 bg-emerald-50 dark:bg-emerald-950/20",
"flex justify-between rounded-lg px-3 py-2 text-base font-bold",
balanceDue > 0 ? "bg-primary/10 text-primary" : "bg-green-500/10 text-green-600",
)}>
<span>Balance Due</span>
<span>{formatCurrency(balanceDue)}</span>
<span>{<Money value={balanceDue} />}</span>
</div>
</>
)}
</div>
</CardContent>
</Card>
@@ -11,9 +11,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { CreditNoteForm } from "./credit-note-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteActionsProps = {
creditNoteId: string
@@ -23,6 +24,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("credit-note-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.creditNotes.destroy(creditNoteId)
@@ -42,6 +44,10 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("credit_note", creditNoteId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -14,6 +14,7 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { formatEnum } from "@/shared/utils/formatters"
type CreditNoteData = {
id?: number
@@ -84,7 +85,7 @@ export function CreditNoteGeneralInfo({ creditNote }: CreditNoteGeneralInfoProps
)}
{creditNote.status && (
<Badge variant={statusColorMap[creditNote.status] as any ?? "outline"}>
{creditNote.status.charAt(0).toUpperCase() + creditNote.status.slice(1)}
{formatEnum(creditNote.status)}
</Badge>
)}
</div>
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import {
Combobox,
ComboboxInput,
@@ -131,10 +132,17 @@ export function RhfCustomerSelectField<
const handleCreateSuccess = (data?: any) => {
const item = data?.data ?? data
if (item?.id) {
field.onChange(buildCustomerOption(item))
if (!item?.id) {
setIsCreateOpen(false)
return
}
queryClient.invalidateQueries({ queryKey: [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"] })
const newOption = buildCustomerOption(item)
const key = [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"]
queryClient.setQueryData<CustomerOption[]>(key, (prev = []) =>
prev.some((o) => o.value === newOption.value) ? prev : [newOption, ...prev],
)
field.onChange(newOption)
setIsCreateOpen(false)
}
@@ -243,7 +251,9 @@ export function RhfCustomerSelectField<
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
<CustomerForm onSuccess={handleCreateSuccess} />
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
@@ -0,0 +1,140 @@
"use client"
import { useRef, useState } from "react"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { UploadIcon } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
import { useAuthApi } from "@/shared/useApi"
const schema = z.object({
name: z.string().trim().min(1, "Name is required").max(150),
issuer: z.string().trim().max(150).optional(),
certificate_number: z.string().trim().max(100).optional(),
issued_date: z.string().optional(),
expiry_date: z.string().optional(),
notes: z.string().max(2000).optional(),
})
type FormValues = z.infer<typeof schema>
export type EmployeeCertificationFormProps = {
employeeId: string
onSuccess?: () => void
onCancel?: () => void
}
export function EmployeeCertificationForm({ employeeId, onSuccess, onCancel }: EmployeeCertificationFormProps) {
const api = useAuthApi()
const fileRef = useRef<HTMLInputElement | null>(null)
const [file, setFile] = useState<File | null>(null)
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
name: "", issuer: "", certificate_number: "",
issued_date: "", expiry_date: "", notes: "",
},
})
const mutation = useMutation({
mutationFn: (values: FormValues) => {
const promise = api.employees.createCertification(employeeId, {
name: values.name,
issuer: values.issuer || undefined,
certificate_number: values.certificate_number || undefined,
issued_date: values.issued_date || undefined,
expiry_date: values.expiry_date || undefined,
notes: values.notes || undefined,
file: file ?? undefined,
})
toast.promise(promise, {
loading: "Saving certification...",
success: "Certification added",
error: (err: any) => err?.message ?? "Failed to save",
})
return promise
},
onSuccess: () => {
reset()
setFile(null)
onSuccess?.()
},
})
return (
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
<Field>
<FieldLabel>Name</FieldLabel>
<Input {...register("name")} placeholder="e.g. ASE A1 Engine Repair" />
{errors.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel>Issuer</FieldLabel>
<Input {...register("issuer")} placeholder="ASE / SAE / ..." />
</Field>
<Field>
<FieldLabel>Certificate Number</FieldLabel>
<Input {...register("certificate_number")} placeholder="Optional" />
</Field>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel>Issued Date</FieldLabel>
<Input type="date" {...register("issued_date")} />
</Field>
<Field>
<FieldLabel>Expiry Date</FieldLabel>
<Input type="date" {...register("expiry_date")} />
</Field>
</div>
<Field>
<FieldLabel>Attachment (optional)</FieldLabel>
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
<UploadIcon className="size-4" />
Choose file
</Button>
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
<input
ref={fileRef}
type="file"
className="hidden"
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
</div>
</Field>
<Field>
<FieldLabel>Notes</FieldLabel>
<Textarea rows={3} {...register("notes")} />
</Field>
<div className="flex justify-end gap-2">
{onCancel && (
<Button type="button" variant="outline" onClick={onCancel}>Cancel</Button>
)}
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? "Saving..." : "Save Certification"}
</Button>
</div>
</form>
)
}
@@ -6,6 +6,7 @@ import { Loader2 } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import { EMPLOYEE_ROUTES } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { formatEnum } from "@/shared/utils/formatters"
import {
Combobox,
ComboboxInput,
@@ -149,16 +150,16 @@ export function EmployeeCombobox({
{opt.type && (
<Badge
variant="secondary"
className="h-4 px-1.5 text-xs font-normal capitalize"
className="h-4 px-1.5 text-xs font-normal"
>
{opt.type}
{formatEnum(opt.type)}
</Badge>
)}
{opt.status && (
<span
className={`text-xs capitalize ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
className={`text-xs ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
>
{opt.status}
{formatEnum(opt.status)}
</span>
)}
</div>
@@ -0,0 +1,165 @@
"use client"
import { useRef, useState } from "react"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { UploadIcon } from "lucide-react"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Textarea } from "@/shared/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
import { useAuthApi } from "@/shared/useApi"
const DOCUMENT_TYPES = [
{ value: "contract", label: "Contract" },
{ value: "id", label: "ID / Passport" },
{ value: "ase", label: "ASE" },
{ value: "certification", label: "Certification" },
{ value: "other", label: "Other" },
] as const
const schema = z.object({
name: z.string().trim().min(1, "Name is required").max(150),
type: z.enum(["contract", "id", "ase", "certification", "other"]),
issued_date: z.string().optional(),
expiry_date: z.string().optional(),
notes: z.string().max(2000).optional(),
})
type FormValues = z.infer<typeof schema>
export type EmployeeDocumentFormProps = {
employeeId: string
onSuccess?: () => void
onCancel?: () => void
}
export function EmployeeDocumentForm({ employeeId, onSuccess, onCancel }: EmployeeDocumentFormProps) {
const api = useAuthApi()
const fileRef = useRef<HTMLInputElement | null>(null)
const [file, setFile] = useState<File | null>(null)
const {
register,
handleSubmit,
setValue,
watch,
formState: { errors },
reset,
} = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { name: "", type: "other", issued_date: "", expiry_date: "", notes: "" },
})
const type = watch("type")
const mutation = useMutation({
mutationFn: (values: FormValues) => {
if (!file) throw new Error("Select a file to upload.")
const promise = api.employees.uploadDocument(employeeId, {
file,
name: values.name,
type: values.type,
issued_date: values.issued_date || undefined,
expiry_date: values.expiry_date || undefined,
notes: values.notes || undefined,
})
toast.promise(promise, {
loading: "Uploading document...",
success: "Document uploaded",
error: (err: any) => err?.message ?? "Failed to upload",
})
return promise
},
onSuccess: () => {
reset()
setFile(null)
onSuccess?.()
},
})
return (
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
<Field>
<FieldLabel>File</FieldLabel>
<div className="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
<UploadIcon className="size-4" />
Choose file
</Button>
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
<input
ref={fileRef}
type="file"
className="hidden"
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
</div>
{!file && mutation.isError && (
<FieldError>Select a file before uploading.</FieldError>
)}
</Field>
<Field>
<FieldLabel>Name</FieldLabel>
<Input {...register("name")} placeholder="e.g. Employment contract 2026" />
{errors.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<Field>
<FieldLabel>Type</FieldLabel>
<Select value={type} onValueChange={(v) => setValue("type", v as FormValues["type"], { shouldValidate: true })}>
<SelectTrigger>
<SelectValue placeholder="Select type" />
</SelectTrigger>
<SelectContent>
{DOCUMENT_TYPES.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel>Issued Date</FieldLabel>
<Input type="date" {...register("issued_date")} />
</Field>
<Field>
<FieldLabel>Expiry Date</FieldLabel>
<Input type="date" {...register("expiry_date")} />
</Field>
</div>
<Field>
<FieldLabel>Notes</FieldLabel>
<Textarea rows={3} {...register("notes")} placeholder="Optional" />
</Field>
<div className="flex justify-end gap-2">
{onCancel && (
<Button type="button" variant="outline" onClick={onCancel}>
Cancel
</Button>
)}
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? "Uploading..." : "Upload"}
</Button>
</div>
</form>
)
}

Some files were not shown because too many files have changed in this diff Show More