diff --git a/.gitignore b/.gitignore index 96fab4f..67e654f 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ node_modules .env.development.local .env.test.local .env.production.local +.env.prod # Testing coverage diff --git a/FEATURE_GAP_PLAN.md b/FEATURE_GAP_PLAN.md new file mode 100644 index 0000000..77d4bdf --- /dev/null +++ b/FEATURE_GAP_PLAN.md @@ -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? diff --git a/Reparee Full Version .md b/Reparee Full Version .md new file mode 100644 index 0000000..4cf636b --- /dev/null +++ b/Reparee Full Version .md @@ -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//`. +- Each resource gets: `-form.tsx`, `.schema.ts` (Zod), optional `-actions.tsx`, optional inline section components (e.g. `-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)///page.tsx` (`"use client"` + `ResourcePage`). +- Detail page: `app/(authenticated)///[id]/page.tsx` (async server component, uses `getServerApi()` + `DashboardPage`). +- Sub-tabs of a detail (e.g. notes, documents): `[id]//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 `.schema.ts`. +- Use `useResourceForm({ 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` (path: `packages/api/src/clients/.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/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` → 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 `.` 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/.php` MUST have the matching `lang/ar/.php` key in the same change. +- Use `__('api..')` 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()` method on the controller. + 3. Add `resources/views/pdf/document-print-.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: } + ``` + - 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`: `` + - `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//page.tsx`. Each is a thin wrapper that imports and renders the existing module list component from `modules/settings//`. +4. **Edit** `config/navGroups.tsx`: add `{ title: "Master", href: "/settings/master", icon: }` 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: }` 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.tsx` data view. +2. **Routes**: + - `app/(authenticated)/reports/page.tsx` — index grid of report cards grouped by category. + - `app/(authenticated)/reports///page.tsx` — individual report view with filters + table + export buttons. +3. **Sidebar**: add a new top-level group `{ title: "Reports", href: "/reports", icon: }` 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_`. + +--- + +# 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: , 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: , 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//`. 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: , 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/`. +- 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. diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/certifications/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/certifications/page.tsx new file mode 100644 index 0000000..a54fb8a --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/certifications/page.tsx @@ -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[] = [ + { + accessorKey: "name", + header: ({ column }) => , + cell: ({ row }) => ( +
+ + {row.original.name} +
+ ), + }, + { + accessorKey: "issuer", + header: ({ column }) => , + cell: ({ row }) => row.original.issuer ?? "—", + }, + { + accessorKey: "certificate_number", + header: ({ column }) => , + cell: ({ row }) => { + const v = row.original.certificate_number + return v ? {v} : "—" + }, + }, + { + accessorKey: "issued_date", + header: ({ column }) => , + cell: ({ row }) => formatDate(row.original.issued_date), + }, + { + accessorKey: "expiry_date", + header: ({ column }) => , + cell: ({ row }) => ( +
+ {formatDate(row.original.expiry_date)} + {row.original.is_expired && Expired} +
+ ), + }, + { + id: "actions", + header: () => Actions, + cell: ({ row }) => ( +
+ {row.original.file_url && ( + + )} + +
+ ), + }, + ] + + return ( + setOpen(true)}> + + Add Certification + + ), + }} + > + {}} + isLoading={isLoading} + /> + + + + + Add Certification + + { + setOpen(false) + queryClient.invalidateQueries({ queryKey }) + }} + onCancel={() => setOpen(false)} + /> + + + + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/documents/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/documents/page.tsx new file mode 100644 index 0000000..6ddec36 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/documents/page.tsx @@ -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[] = [ + { + accessorKey: "name", + header: ({ column }) => , + cell: ({ row }) => ( +
+ + {row.original.name} +
+ ), + }, + { + accessorKey: "type", + header: ({ column }) => , + cell: ({ row }) => {formatEnum(row.original.type)}, + }, + { + accessorKey: "issued_date", + header: ({ column }) => , + cell: ({ row }) => formatDate(row.original.issued_date), + }, + { + accessorKey: "expiry_date", + header: ({ column }) => , + cell: ({ row }) => { + const v = row.original.expiry_date + if (!v) return "—" + return ( +
+ {formatDate(v)} + {isExpired(v) && Expired} +
+ ) + }, + }, + { + id: "actions", + header: () => Actions, + cell: ({ row }) => ( +
+ {row.original.file_url && ( + + )} + +
+ ), + }, + ] + + return ( + setOpen(true)}> + + Upload Document + + ), + }} + > + {}} + isLoading={isLoading} + /> + + + + + Upload Document + + { + setOpen(false) + queryClient.invalidateQueries({ queryKey }) + }} + onCancel={() => setOpen(false)} + /> + + + + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/layout.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/layout.tsx index e23463d..639a85a 100644 --- a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/layout.tsx +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/layout.tsx @@ -30,6 +30,11 @@ export default async function layout(props: { { 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' }, ]} > diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/leave/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/leave/page.tsx new file mode 100644 index 0000000..60cd2d3 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/leave/page.tsx @@ -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 ( + + + + + {label} + + + +
{remaining}/ {total}
+

{used} used

+
+
+
+ + + ) +} + +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 ( +
+ {balance && ( +
+ + +
+ )} + + + pageTitle="Leave History" + routeKey={LEAVE_REQUEST_ROUTES.INDEX} + getClient={(api) => api.leaveRequests} + extraParams={{ employee_id: employeeId }} + header={null} + headerProps={({ invalidateQuery }) => ({ + actions: ( + + {() => ( + { + invalidateQuery() + balanceQuery.refetch() + }} + /> + )} + + ), + })} + columns={() => [ + { + accessorKey: "leave_type", + header: ({ column }) => , + cell: ({ row }) => ( +
+ + {formatEnum((row.original as any).leave_type)} +
+ ), + }, + { + accessorKey: "start_date", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).start_date), + }, + { + accessorKey: "end_date", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).end_date), + }, + { + accessorKey: "days", + header: ({ column }) => , + cell: ({ row }) => (row.original as any).days ?? "—", + }, + { + accessorKey: "status", + header: ({ column }) => , + cell: ({ row }) => { + const s = (row.original as any).status as string + return {formatEnum(s)} + }, + }, + { + accessorKey: "reason", + header: ({ column }) => , + cell: ({ row }) => (row.original as any).reason ?? "—", + }, + ]} + /> +
+ ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/payroll/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/payroll/page.tsx new file mode 100644 index 0000000..7c6d359 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/payroll/page.tsx @@ -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[] = [ + { + accessorKey: "payroll_run", + header: ({ column }) => , + cell: ({ row }) => { + const r = row.original.payroll_run + return r?.reference ?? (r?.id ? `#${r.id}` : "—") + }, + }, + { + accessorKey: "period", + header: () => Period, + 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 }) => , + cell: ({ row }) => fmt(row.original.hours_worked), + }, + { + accessorKey: "base_salary", + header: ({ column }) => , + cell: ({ row }) => fmt(row.original.base_salary), + }, + { + accessorKey: "commission_amount", + header: ({ column }) => , + cell: ({ row }) => fmt(row.original.commission_amount), + }, + { + accessorKey: "deductions", + header: ({ column }) => , + cell: ({ row }) => fmt(row.original.deductions), + }, + { + accessorKey: "net_pay", + header: ({ column }) => , + cell: ({ row }) => {fmt(row.original.net_pay)}, + }, + { + id: "status", + header: ({ column }) => , + cell: ({ row }) => { + const s = row.original.payroll_run?.status + if (!s) return "—" + return {formatEnum(s)} + }, + }, + ] + + return ( + + {}} + isLoading={isLoading} + /> + + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/[id]/performance/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/performance/page.tsx new file mode 100644 index 0000000..ced76d3 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/employees/[id]/performance/page.tsx @@ -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 ( + + + + + {label} + + + +
+ {value} + {suffix && {suffix}} +
+
+
+ ) +} + +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 ( + + + From + setFromInput(e.target.value)} /> + + + To + setToInput(e.target.value)} /> + + +
+ ), + }} + > + {isLoading && !perf ? ( +

Loading...

+ ) : !perf ? ( +

No data.

+ ) : ( +
+ + + + + +
+ )} + + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/employees/page.tsx b/apps/dashboard/app/(authenticated)/productivity/employees/page.tsx index 1144e27..c2733df 100644 --- a/apps/dashboard/app/(authenticated)/productivity/employees/page.tsx +++ b/apps/dashboard/app/(authenticated)/productivity/employees/page.tsx @@ -4,7 +4,10 @@ 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" @@ -33,6 +36,7 @@ function initialsOf(first?: string | null, last?: string | null) { export default function EmployeesPage() { const router = useRouter() + const api = useAuthApi() const [typeFilter, setTypeFilter] = useState("all") const extraParams = useMemo(() => { @@ -68,15 +72,28 @@ export default function EmployeesPage() { )} headerProps={({ selectedItem, invalidateQuery }) => ({ actions: ( - - {(resourceId) => ( - - )} - +
+ api.employees.importData(file)} + onSuccess={invalidateQuery} + entityLabel="Employees" + onDownloadSample={() => api.employees.downloadImportSample() as Promise} + sampleFileName="employees-import-sample" + /> + api.employees.exportData(filters)} + fileName="employees" + /> + + {(resourceId) => ( + + )} + +
), })} columns={({ actionsColumn }) => [ diff --git a/apps/dashboard/app/(authenticated)/productivity/leave-requests/page.tsx b/apps/dashboard/app/(authenticated)/productivity/leave-requests/page.tsx new file mode 100644 index 0000000..872a5d9 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/leave-requests/page.tsx @@ -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 ( + + 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") ? ( + + {(resourceId) => ( + + )} + + ) : null, + })} + columns={({ actionsColumn }) => [ + { + accessorKey: "employee", + header: ({ column }) => , + 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 }) => , + cell: ({ row }) => {formatEnum((row.original as any).leave_type)}, + }, + { + accessorKey: "start_date", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).start_date), + }, + { + accessorKey: "end_date", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).end_date), + }, + { + accessorKey: "days", + header: ({ column }) => , + cell: ({ row }) => (row.original as any).days ?? "—", + }, + { + accessorKey: "status", + header: ({ column }) => , + cell: ({ row }) => { + const s = (row.original as any).status as string + return {formatEnum(s)} + }, + }, + { + id: "decide", + header: () => Decide, + cell: ({ row }) => { + const r = row.original as LeaveRow + if (r.status !== "pending" || !perms.canUpdate("leave_requests")) return null + return ( +
+ + +
+ ) + }, + }, + actionsColumn(), + ]} + /> + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/payroll/[id]/page.tsx b/apps/dashboard/app/(authenticated)/productivity/payroll/[id]/page.tsx new file mode 100644 index 0000000..d052bc2 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/payroll/[id]/page.tsx @@ -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 }>, + }) + + const run = (data as any)?.data as Run | undefined + const totals = (data as any)?.totals as Record | 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[] = [ + { + accessorKey: "employee", + header: ({ column }) => , + 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 }) => , + cell: ({ row }) => fmtCurrency(row.original.hours_worked), + }, + { + accessorKey: "base_salary", + header: ({ column }) => , + cell: ({ row }) => fmtCurrency(row.original.base_salary), + }, + { + accessorKey: "commission_amount", + header: ({ column }) => , + cell: ({ row }) => fmtCurrency(row.original.commission_amount), + }, + { + accessorKey: "allowances", + header: ({ column }) => , + cell: ({ row }) => fmtCurrency(row.original.allowances), + }, + { + accessorKey: "deductions", + header: ({ column }) => , + cell: ({ row }) => fmtCurrency(row.original.deductions), + }, + { + accessorKey: "net_pay", + header: ({ column }) => , + cell: ({ row }) => {fmtCurrency(row.original.net_pay)}, + }, + { + id: "slip", + header: () => Slip, + cell: ({ row }) => ( + + ), + }, + ] + + if (isLoading && !run) { + return Loading... + } + + if (!run) { + return Run not found. + } + + const entries = run.entries ?? [] + + return ( + + {formatEnum(run.status)} + {run.status === "draft" && ( + <> + + + + + )} + {run.status === "finalized" && ( + + )} + + ), + }} + > + {totals && ( +
+ {[ + { 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) => ( + + + {t.label} + + +
{fmtCurrency(t.value)}
+
+
+ ))} +
+ )} + + {}} + isLoading={false} + /> +
+ ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/payroll/page.tsx b/apps/dashboard/app/(authenticated)/productivity/payroll/page.tsx new file mode 100644 index 0000000..56feef7 --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/payroll/page.tsx @@ -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 ( + + 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: ( + + {() => ( + { + invalidateQuery() + if (runId) router.push(`/productivity/payroll/${runId}`) + }} + /> + )} + + ), + })} + columns={({ actionsColumn }) => [ + { + accessorKey: "reference", + header: ({ column }) => , + cell: ({ row }) => {(row.original as any).reference ?? `#${(row.original as any).id}`}, + }, + { + accessorKey: "period_start", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).period_start), + }, + { + accessorKey: "period_end", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).period_end), + }, + { + accessorKey: "entries_count", + header: ({ column }) => , + cell: ({ row }) => (row.original as any).entries_count ?? "—", + }, + { + accessorKey: "status", + header: ({ column }) => , + cell: ({ row }) => { + const s = (row.original as any).status as string + return {formatEnum(s)} + }, + }, + { + accessorKey: "finalized_at", + header: ({ column }) => , + cell: ({ row }) => formatDate((row.original as any).finalized_at), + }, + actionsColumn({ onEdit: undefined }), + ]} + /> + ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/time-clocks/page.tsx b/apps/dashboard/app/(authenticated)/productivity/time-clocks/page.tsx new file mode 100644 index 0000000..8c61dfb --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/time-clocks/page.tsx @@ -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 ( + + + setSearch(e.target.value)} + placeholder="Search employees..." + className="pl-8" + /> + + ), + }} + > + {employeesQuery.isLoading ? ( +

Loading...

+ ) : employees.length === 0 ? ( +

No employees found.

+ ) : ( +
+ {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 ( + + +
+ + {initialsOf(emp.first_name, emp.last_name)} + +
+
{fullName}
+
+ {emp.designation ?? emp.department?.name ?? emp.email} +
+
+ {isClockedIn ? ( + + + Since {formatTime(clockedInAt)} + + ) : ( + Idle + )} +
+
+
+ + {isClockedIn && activeId ? ( + + ) : ( + + )} +
+
+ ) + })} +
+ )} +
+ ) +} diff --git a/apps/dashboard/app/(authenticated)/productivity/timesheet/page.tsx b/apps/dashboard/app/(authenticated)/productivity/timesheet/page.tsx new file mode 100644 index 0000000..35a632d --- /dev/null +++ b/apps/dashboard/app/(authenticated)/productivity/timesheet/page.tsx @@ -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 = { + general: "secondary", + order: "default", + task: "outline", +} + +export default function TimeSheetsPage() { + return ( + + 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 }) => , + cell: ({ row }) => ( +
+ + {formatDate((row.original as any).date)} +
+ ), + }, + { + accessorKey: "employee", + header: ({ column }) => , + 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 }) => , + cell: ({ row }) => {formatTime((row.original as any).clock_in)}, + }, + { + accessorKey: "clock_out", + header: ({ column }) => , + cell: ({ row }) => {formatTime((row.original as any).clock_out)}, + }, + { + accessorKey: "duration", + header: ({ column }) => , + cell: ({ row }) => {formatTime((row.original as any).duration)}, + }, + { + accessorKey: "activity_type", + header: ({ column }) => , + cell: ({ row }) => { + const t = (row.original as any).activity_type ?? "general" + return {formatEnum(t)} + }, + }, + { + accessorKey: "calculated_total_cost", + header: ({ column }) => , + 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 }), + ]} + /> + ) +} diff --git a/apps/dashboard/config/navGroups.tsx b/apps/dashboard/config/navGroups.tsx index 90478f3..aca3a35 100644 --- a/apps/dashboard/config/navGroups.tsx +++ b/apps/dashboard/config/navGroups.tsx @@ -144,7 +144,8 @@ export const navGroups: NavGroup[] = [ { title: "Employees", href: "/productivity/employees", icon: }, { title: "Time Clocks", href: "/productivity/time-clocks", icon: }, { title: "Time Sheets", href: "/productivity/timesheet", icon: }, - // { title: "Payroll", href: "/productivity/payroll", icon: }, + { title: "Leave Requests", href: "/productivity/leave-requests", icon: }, + { title: "Payroll", href: "/productivity/payroll", icon: }, // { title: "Payments Made", href: "/productivity/employee-payments-made", icon: }, { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: }, { title: "Shop Timing", href: "/productivity/shop-timings", icon: }, diff --git a/apps/dashboard/modules/employees/employee-certification-form.tsx b/apps/dashboard/modules/employees/employee-certification-form.tsx new file mode 100644 index 0000000..616775e --- /dev/null +++ b/apps/dashboard/modules/employees/employee-certification-form.tsx @@ -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 + +export type EmployeeCertificationFormProps = { + employeeId: string + onSuccess?: () => void + onCancel?: () => void +} + +export function EmployeeCertificationForm({ employeeId, onSuccess, onCancel }: EmployeeCertificationFormProps) { + const api = useAuthApi() + const fileRef = useRef(null) + const [file, setFile] = useState(null) + + const { + register, + handleSubmit, + formState: { errors }, + reset, + } = useForm({ + 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 ( +
mutation.mutate(v))}> + + Name + + {errors.name && {errors.name.message}} + + +
+ + Issuer + + + + Certificate Number + + +
+ +
+ + Issued Date + + + + Expiry Date + + +
+ + + Attachment (optional) +
+ + {file ? file.name : "No file selected"} + setFile(e.target.files?.[0] ?? null)} + /> +
+
+ + + Notes +