Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c55be5052 | ||
|
|
0d591b9807 | ||
|
|
4f0a2f790f | ||
|
|
2d6e3c5734 | ||
|
|
5570527e69 | ||
|
|
4bfd8c84a9 | ||
|
|
54d11f01b4 | ||
|
|
fcbba6247d | ||
|
|
05b55b5721 | ||
|
|
6b356d2855 | ||
|
|
464402f4d6 |
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(pnpm --version)",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
|
||||
]
|
||||
},
|
||||
"enabledMcpjsonServers": [
|
||||
"code-review-graph"
|
||||
],
|
||||
"enableAllProjectMcpServers": true
|
||||
}
|
||||
@@ -11,6 +11,7 @@ node_modules
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.prod
|
||||
|
||||
# Testing
|
||||
coverage
|
||||
|
||||
@@ -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?
|
||||
@@ -0,0 +1,551 @@
|
||||
# Reparee → Garage Box Feature Parity — Implementation Roadmap
|
||||
|
||||
> **Purpose of this doc.** Single source of truth for closing the gap between Reparee's current dashboard and Garage Box. Captures the gap analysis, the canonical Reparee patterns to mimic, and a per-phase implementation spec detailed enough for a fresh agent to pick up any phase and ship it without re-discovering conventions.
|
||||
|
||||
> **Status (2026-05-21).** Phase 1 (Integrations placeholder) is the only phase ready to execute. Phases 2–8 are spec'd here but not started. Pick one, re-open it in a focused planning session, and implement.
|
||||
|
||||
---
|
||||
|
||||
## 0. Reading order
|
||||
|
||||
1. **Part A — Gap analysis** (what's missing and why).
|
||||
2. **Part B — Project conventions cheatsheet** (the patterns every phase MUST follow).
|
||||
3. **Part C — Phase index** (the at-a-glance table).
|
||||
4. **Part D — Per-phase implementation specs** (Phases 1–8, in recommended build order).
|
||||
|
||||
---
|
||||
|
||||
## Part A — Gap analysis (Garage Box vs Reparee)
|
||||
|
||||
Legend: ✅ exists ⚠️ partial / different location ❌ missing
|
||||
|
||||
### Already covered
|
||||
- **Sales** (Customers, Vehicles, Inspections, Estimates, Job Cards, Invoices, Payments Received, Credit Notes) — ✅
|
||||
- **Purchases** (Vendors, Expenses, POs, Bills, Payments Made, Vendor Credits) — ✅
|
||||
- **Employees / Productivity** (Employees, Time Clocks, Time Sheets, Payroll, Shop Calendars, Shop Timing, Holidays, Tasks, Leave Requests) — ✅ (Reparee adds Leave Requests beyond Garage Box)
|
||||
- **Items** (Services, Parts, Expense Item, Service Group, Inventory Adjustments) — ✅
|
||||
- **Settings** Company / Shop Types / Tax & Rates / Configurations — ✅
|
||||
|
||||
### Gaps
|
||||
| Garage Box | Status in Reparee | Phase |
|
||||
|---|---|---|
|
||||
| Settings → Integrations | ❌ → placeholder | **Phase 1** |
|
||||
| Settings → Master (hub for body types + make & model + other lookups) | ❌ as a hub (data scattered) | **Phase 2** |
|
||||
| Settings → Templates (notification template library, ~35 templates × 4 channels) | ⚠️ only inspection templates | **Phase 3** |
|
||||
| Reports (top-level module) | ❌ | **Phase 4** |
|
||||
| CRM (Leads pipeline, Calls log + calendar, Tasks pipeline) | ❌ (Reparee has only productivity tasks, not CRM tasks) | **Phase 5** |
|
||||
| Marketing (Service Reminders, Rating & Reviews, Google Business Reviews) | ❌ | **Phase 6** |
|
||||
| Settings → Integrations (real connectors: Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp) | ❌ | **Phase 7** |
|
||||
| Accountants (Chart of Accounts + Manual Journals + default account wiring) | ❌ | **Phase 8** |
|
||||
|
||||
### Cross-cutting Garage Box conventions to mimic
|
||||
- **Pipelines** (Leads, Tasks) have user-editable column **sections** (add / rename / reorder). Default sections seeded on first run.
|
||||
- **`+ Label`** chip on every record (taxonomy / colored tags).
|
||||
- **Configurable doc-number sequences** with a gear icon next to the `#` field (`LD-000001`, `CL-000001`, `TK-000001`, `JN-000001`, etc.).
|
||||
- **Notification templates** are channel-aware (SMS / WhatsApp / Email / Push) with per-channel toggles.
|
||||
- **Per-row Department filter** is universal — every list view has a Department dropdown in the toolbar.
|
||||
|
||||
---
|
||||
|
||||
## Part B — Project conventions cheatsheet (MUST follow in every phase)
|
||||
|
||||
> Every phase below assumes these patterns. Don't re-invent.
|
||||
|
||||
### B1. Frontend module structure
|
||||
- **Modules live at** `garage-erp/apps/dashboard/modules/<area>/`.
|
||||
- Each resource gets: `<resource>-form.tsx`, `<resource>.schema.ts` (Zod), optional `<resource>-actions.tsx`, optional inline section components (e.g. `<resource>-services-section.tsx`).
|
||||
- **Reference**: `garage-erp/apps/dashboard/modules/estimates/` is the canonical example. Mirror its file layout for any new resource.
|
||||
|
||||
### B2. Routes (Next.js App Router)
|
||||
- List page: `app/(authenticated)/<area>/<resource>/page.tsx` (`"use client"` + `ResourcePage<Client>`).
|
||||
- Detail page: `app/(authenticated)/<area>/<resource>/[id]/page.tsx` (async server component, uses `getServerApi()` + `DashboardPage`).
|
||||
- Sub-tabs of a detail (e.g. notes, documents): `[id]/<subroute>/page.tsx`.
|
||||
- **Reference**: `app/(authenticated)/sales/estimates/page.tsx` (list) + `[id]/page.tsx` (detail).
|
||||
|
||||
### B3. Tables & row actions
|
||||
- Use TanStack Table via `ResourcePage` wrapper.
|
||||
- Row actions via `actionsColumn({ extraItems: (row) => [...] })`.
|
||||
- Print buttons via `useDocumentPrint(type, id)` from `apps/dashboard/shared/hooks/use-document-print.ts`.
|
||||
|
||||
### B4. Forms
|
||||
- React Hook Form 7 + Zod 4. Schema lives in `<resource>.schema.ts`.
|
||||
- Use `useResourceForm<FormValues, ApiPayload>({ schema, resourceId, initialize, mapToFormValues })` from `apps/dashboard/shared/hooks/`.
|
||||
- Mutations: `useFormMutation` for create/update; invalidate via `tableQuery.invalidateQuery()` or the resource's query key.
|
||||
|
||||
### B5. Sidebar navigation
|
||||
- Single source: `garage-erp/apps/dashboard/config/navGroups.tsx` — hard-coded, **no i18n layer**.
|
||||
- Add a new group entry or a sub-item; pick a `lucide-react` icon already imported (or add to the import block at top of file).
|
||||
|
||||
### B6. API client (`@garage/api`)
|
||||
- All clients extend `CrudClient<INDEX_ROUTE, BY_ID_ROUTE>` (path: `packages/api/src/clients/<name>.ts`).
|
||||
- After backend changes, **regenerate**: `pnpm --filter @garage/api generate` (runs `generate:openapi && generate:types`).
|
||||
- The generated files in `packages/api/` are NOT hand-edited; only the thin client wrappers are.
|
||||
|
||||
### B7. Backend routes
|
||||
- **Legacy string controller resolution** in `reparee_backend/routes/api.php`:
|
||||
```php
|
||||
Route::get('/leads', 'LeadController@index');
|
||||
Route::post('/leads', 'LeadController@store');
|
||||
// etc.
|
||||
```
|
||||
- **Every route is gated** by `permission.check` middleware (auto-applied group-wide).
|
||||
|
||||
### B8. Backend controllers
|
||||
- Standard CRUD shape: `index`, `show`, `store`, `update`, `destroy` returning `JsonResponse`.
|
||||
- Path: `reparee_backend/app/Http/Controllers/Api/<Name>Controller.php`.
|
||||
- Use `vyuldashev/laravel-openapi` annotations so OpenAPI spec stays in sync (mirror `EstimateController`).
|
||||
|
||||
### B9. Models & migrations
|
||||
- Models in `reparee_backend/app/Models/`. Use `$fillable`, `$casts`, relations.
|
||||
- Migrations: `php artisan make:migration create_<table>_table` → standard `Schema::create` with `$table->id()` + `timestamps()`.
|
||||
|
||||
### B10. Permissions
|
||||
- Permissions are **columns on the `roles` table**: `can_{view|create|update|delete}_{resource}`.
|
||||
- To add a new resource:
|
||||
1. Create a migration that adds the four boolean columns to `roles` (default `false`).
|
||||
2. Update `database/seeders/RoleSeeder.php` so Super Admin gets `true` for all new columns (it auto-discovers `can_*` columns — verify).
|
||||
3. The `permission.check` middleware reads the column name from the route name; ensure route is named `<resource>.<ability>` or matches its existing convention.
|
||||
- **Reference migration**: `2026_04_06_120000_create_roles_table_and_refactor_employee_permissions.php`.
|
||||
|
||||
### B11. i18n (backend)
|
||||
- Pairs required: every new key in `lang/en/<file>.php` MUST have the matching `lang/ar/<file>.php` key in the same change.
|
||||
- Use `__('api.<area>.<key>')` in controllers and responses.
|
||||
- Dashboard nav labels are NOT translated (hard-coded in `navGroups.tsx`).
|
||||
|
||||
### B12. Document-print (PDF)
|
||||
- Single entry: `POST /api/document-print` → `DocumentPrintController@handle`.
|
||||
- To add a printable type:
|
||||
1. Add string to `DocumentPrintController::TYPES`.
|
||||
2. Add `payload<Type>()` method on the controller.
|
||||
3. Add `resources/views/pdf/document-print-<type>.blade.php`.
|
||||
4. Add the type to the `DocumentPrintType` union in `packages/api/src/clients/document-print.ts`.
|
||||
|
||||
### B13. Pipeline-with-sections precedent
|
||||
- `TaskSection` model + `task-section-form.tsx` already exist. Fields: `title`, `arrangement` (sort order), `is_default`.
|
||||
- Reuse this pattern for `LeadSection`, `CallSection` (if needed), `JournalSection`, etc.
|
||||
|
||||
### B14. House rules (from `CLAUDE.md`)
|
||||
- Never `git commit / push / tag / reset --hard / rebase` — stop at file edits.
|
||||
- Don't add new dependencies without explicit approval.
|
||||
- After edits, run `pnpm --filter dashboard typecheck`, `pnpm --filter dashboard lint`, and `php -l` on changed PHP files, then report results.
|
||||
- Match existing conventions before introducing new patterns.
|
||||
|
||||
---
|
||||
|
||||
## Part C — Phase index
|
||||
|
||||
| # | Phase | Effort | Backend changes | Frontend changes | Depends on |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Integrations placeholder | XS (1 hr) | none | 2 files | — |
|
||||
| 2 | Settings → Master hub | S (1 day) | none (regroup) | 1 layout + tabs | — |
|
||||
| 3 | Notification Templates library | M (3 days) | new table + CRUD + permission | full module | — |
|
||||
| 4 | Reports (4 reports locked) | M (1 wk) | 4 aggregation endpoints | reports module + 4 reports w/ Recharts | reads existing data |
|
||||
| 5 | CRM (Leads, Calls, Tasks-CRM) | XL (2–3 wks) | 3 resources + sections + permissions + i18n | 3 modules + pipelines | reuses TaskSection pattern |
|
||||
| 6 | Marketing (Reminders email+SMS, Reviews) | L (1–2 wks) | reminder engine + Twilio integration + reviews | 3 sub-pages | needs Phase 3 (templates); Twilio composer dep |
|
||||
| 7 | ~~Integrations (real)~~ | DEFERRED | — | — | — |
|
||||
| 8A | Accountants — COA + Manual Journals | L (1.5 wks) | ledger UI only, no auto-post | 3 sub-pages | — |
|
||||
| 8B | Accountants — auto-posting | L (1–2 wks) | observers on Invoice/Bill/Payment/Expense + reversal | linkage panels on source docs | requires 8A stable |
|
||||
|
||||
---
|
||||
|
||||
## Part D — Per-phase implementation specs
|
||||
|
||||
# Phase 1 — Settings → Integrations (Coming Soon)
|
||||
|
||||
**Goal.** Add an Integrations entry under Settings that renders a "Coming soon" placeholder.
|
||||
|
||||
### Backend
|
||||
None.
|
||||
|
||||
### Frontend
|
||||
1. **Edit** `garage-erp/apps/dashboard/config/navGroups.tsx` (around line 183):
|
||||
- There is already a commented-out entry:
|
||||
```tsx
|
||||
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> }
|
||||
```
|
||||
- Uncomment it but change `href` to `/settings/integrations` (single page, no sub-tabs yet).
|
||||
- Insert between `Inspection Templates` and `Configurations`. Confirm `PlugZapIcon` is in the top-of-file imports; if not, add `PlugZapIcon` to the `lucide-react` import.
|
||||
|
||||
2. **Create** `garage-erp/apps/dashboard/app/(authenticated)/settings/integrations/page.tsx`:
|
||||
- Use `DashboardPage` with `headerProps={{ title: "Integrations" }}` (match `settings/insurance-types/page.tsx`).
|
||||
- Centered `Empty` block (from `@/shared/components/ui/empty`):
|
||||
- `EmptyMedia`: `<PlugZapIcon className="size-12 text-muted-foreground" />`
|
||||
- `EmptyTitle`: "Coming soon"
|
||||
- `EmptyDescription`: "Connect WhatsApp, payments, accounting and email providers. Available in an upcoming release."
|
||||
|
||||
### Verification
|
||||
1. `pnpm --filter dashboard dev`.
|
||||
2. Sidebar → Settings expands → new "Integrations" entry visible between Inspection Templates and Configurations.
|
||||
3. Click → page renders with the Empty state.
|
||||
4. `pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`.
|
||||
|
||||
### Out of scope
|
||||
Sub-tabs (Providers / Integrations), any provider logic, backend.
|
||||
|
||||
---
|
||||
|
||||
# Phase 2 — Settings → Master hub
|
||||
|
||||
**Goal.** Group existing lookup data screens under one "Master" sidebar entry with tabs, matching Garage Box's UX.
|
||||
|
||||
### Tabs (in order)
|
||||
1. Body Types (existing `/settings/...`)
|
||||
2. Make & Model (existing `/settings/make-and-models`)
|
||||
3. Insurance Types (existing `/settings/insurance-types`)
|
||||
4. Departments (existing `/settings/departments`)
|
||||
5. Shop Types (move from top-level OR alias)
|
||||
6. Vehicle Transmissions, Fuel Types, Colors, Unit Types, Payment Terms, Payment Modes, Labor Rates, Reasons, Referral Sources, Document Types, Labels — surface those that currently lack a dedicated screen.
|
||||
|
||||
### Backend
|
||||
None new. Verify every tab's data source has a controller in `app/Http/Controllers/Api/` (most already do: `MakeAndModelController`, `InsuranceTypeController`, `DepartmentController`, `VehicleBodyTypeController`, `VehicleTransmissionController`, `VehicleFuelTypeController`, `VehicleColorController`, `UnitTypeController`, `PaymentTermController`, `PaymentModeController`, `LaborRateController`, `ReasonController`, `ReferralSourceController`, `DocumentTypeController`, `LabelController`).
|
||||
|
||||
### Frontend
|
||||
1. **Create** `app/(authenticated)/settings/master/layout.tsx` with a `Tabs` header (use existing `Tabs` from `packages/ui`) and the 11+ tab labels above.
|
||||
2. **Create** `app/(authenticated)/settings/master/page.tsx` that redirects to `./body-types`.
|
||||
3. **Create** `app/(authenticated)/settings/master/<each-tab>/page.tsx`. Each is a thin wrapper that imports and renders the existing module list component from `modules/settings/<existing-folder>/`.
|
||||
4. **Edit** `config/navGroups.tsx`: add `{ title: "Master", href: "/settings/master", icon: <DatabaseIcon /> }` after Integrations. **Keep** the existing top-level entries (Insurance Types, Departments, Make & Models) in the Settings list — they coexist as aliases for backwards-compat (per Part F decision).
|
||||
|
||||
### Verification
|
||||
1. Sidebar → Settings → Master → tabs render and each tab CRUDs correctly.
|
||||
2. Direct URL `/settings/master/insurance-types` works.
|
||||
3. Removed/aliased entries still resolve to the same screen.
|
||||
|
||||
---
|
||||
|
||||
# Phase 3 — Notification Templates library
|
||||
|
||||
**Goal.** Manage ~35 notification templates (per Garage Box screenshot 16) with per-channel toggles and bodies. Required for Phase 6 (Marketing) and any reminder/automation.
|
||||
|
||||
### Data model
|
||||
| Table | Columns |
|
||||
|---|---|
|
||||
| `notification_templates` | `id`, `key` (unique e.g. `appointment_created`), `title`, `description` (nullable), `created_at`, `updated_at` |
|
||||
| `notification_template_channels` | `id`, `notification_template_id` (FK), `channel` enum(`sms`,`whatsapp`,`email`,`push`), `enabled` bool, `subject` (nullable, for email), `body` text, `created_at`, `updated_at` |
|
||||
|
||||
Seed all template `key`s from this list (extracted from Garage Box image 16):
|
||||
- `appointment_assigned`, `appointment_cancelled`, `appointment_confirmed`, `appointment_create`, `appointment_no_shows`, `appointment_reminder`, `appointment_requested`, `appointment_reschedule`, `appointment_unconfirmed`
|
||||
- `attendance_details`, `attendance_reminder`
|
||||
- `call_assigned`, `call_cancelled`, `call_completed`, `call_rescheduled`, `call_scheduled`
|
||||
- `estimate_approved_by_admin`, `estimate_approved_by_customer`, `estimate_send`
|
||||
- `job_card_customer`, `job_card_technician`
|
||||
- `login_otp`
|
||||
- `new_lead_notification`
|
||||
- `part_requisition_create`
|
||||
- `purchase_order_create`
|
||||
- `ratings_reviews_link`
|
||||
- `salary_change_notification`
|
||||
- `send_customer_statement`, `send_inspection`, `send_invoice`, `send_vendor_statement`
|
||||
- `service_reminder_cancelled`, `service_reminder_reschedule`, `service_reminder_scheduled`, `service_reminder_send`
|
||||
- `work_request_form_send`, `workorder_create`
|
||||
|
||||
### Backend
|
||||
- `NotificationTemplateController` (`index`, `show`, `update` only — templates are seeded, not user-created).
|
||||
- Routes (string-resolution style):
|
||||
```php
|
||||
Route::get('/notification-templates', 'NotificationTemplateController@index');
|
||||
Route::get('/notification-templates/{key}', 'NotificationTemplateController@show');
|
||||
Route::put('/notification-templates/{key}', 'NotificationTemplateController@update');
|
||||
```
|
||||
- Permissions: `can_view_notification_templates`, `can_update_notification_templates` (skip create/delete — seed-managed).
|
||||
- Lang keys in `lang/en/api.php` + `lang/ar/api.php` under `notification_templates`.
|
||||
|
||||
### Frontend
|
||||
1. **Module** `apps/dashboard/modules/notification-templates/` with `notification-template-row.tsx`, `notification-template-edit-dialog.tsx`, `notification-template.schema.ts`.
|
||||
2. **Route** `app/(authenticated)/settings/templates/notifications/page.tsx` — TanStack Table with columns: Title, SMS (✓/—), WhatsApp, Email, Push, Actions.
|
||||
3. **Sidebar entry**: `config/navGroups.tsx` add `{ title: "Templates", href: "/settings/templates/notifications", icon: <FileTextIcon /> }` between Inspection Templates and Integrations. (Or restructure existing `/settings/templates` if free.)
|
||||
4. **Edit dialog**: tabs per channel, body editor with **variable picker** (e.g. `{{customer.name}}`, `{{vehicle.plate}}`, `{{appointment.date}}`). Variables list lives in a `notification-template-variables.ts` constants file co-located with the module.
|
||||
5. **API client**: `packages/api/src/clients/notification-templates.ts` extends `CrudClient`.
|
||||
|
||||
### Verification
|
||||
1. Seeded list shows all 35+ rows.
|
||||
2. Toggle a channel → persists.
|
||||
3. Edit body → re-render shows updated body.
|
||||
4. Backend `__('api.notification_templates.updated')` returns Arabic when locale is `ar`.
|
||||
|
||||
---
|
||||
|
||||
# Phase 4 — Reports
|
||||
|
||||
**Goal.** Top-level Reports module with categorized reports across Sales, Purchases, Inventory, Employees, Accountants.
|
||||
|
||||
### Reports to ship (v1 — locked per Part F)
|
||||
1. **Sales by Customer** — revenue grouped by customer with date range + department filter.
|
||||
2. **Invoices Aging** — outstanding invoices bucketed 0–30 / 31–60 / 61–90 / 90+ days.
|
||||
3. **Technician Productivity** — hours logged vs billable per technician, derived from `TimeSheet` + job-card service rows.
|
||||
4. **Inventory Valuation + Low-Stock** — current stock value by part + list of parts under reorder threshold.
|
||||
|
||||
All other reports candidates (Sales by Service/Vehicle, Payments Summary, Estimates Conversion, Purchases by Vendor, Bills Aging, Stock Movement, Attendance, Payroll, Job Card Turnaround/Status) are deferred to a follow-up phase. Architect the reports module so adding the 5th report is trivial.
|
||||
|
||||
### Charting
|
||||
Use **Recharts** via the already-installed wrapper `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency. Wrapper exports `ChartContainer`, `ChartTooltip`, `ChartTooltipContent`, etc. — mimic shadcn's chart usage docs.
|
||||
|
||||
### Backend
|
||||
- `app/Http/Controllers/Api/Reports/` directory — one controller per report category (`SalesReportController`, `PurchasesReportController`, etc.).
|
||||
- Each report = single GET endpoint accepting `from`, `to`, optional `department_id`, `customer_id`, etc. Returns aggregated rows.
|
||||
- Use Eloquent + `selectRaw` aggregations. Index any frequently-grouped columns via migration.
|
||||
- Routes grouped under `/api/reports/...`. New permission per category: `can_view_reports_sales`, `can_view_reports_purchases`, ...
|
||||
- **No new models or tables** — pure read aggregation over existing data.
|
||||
- Lang keys for report titles in `lang/en/reports.php` + `lang/ar/reports.php`.
|
||||
|
||||
### Frontend
|
||||
1. **Module** `apps/dashboard/modules/reports/` with:
|
||||
- `report-card.tsx` (preview tile in the index).
|
||||
- `report-filters.tsx` (date range, department, customer/vendor).
|
||||
- One subdirectory per category: `sales/`, `purchases/`, `inventory/`, `employees/`, `job-cards/`. Each contains a `<report-name>-report.tsx` data view.
|
||||
2. **Routes**:
|
||||
- `app/(authenticated)/reports/page.tsx` — index grid of report cards grouped by category.
|
||||
- `app/(authenticated)/reports/<category>/<slug>/page.tsx` — individual report view with filters + table + export buttons.
|
||||
3. **Sidebar**: add a new top-level group `{ title: "Reports", href: "/reports", icon: <BarChart3Icon /> }` after Items/Employees in `navGroups.tsx`.
|
||||
4. **Export**: reuse `useDocumentPrint` pattern for PDF; for Excel use existing `maatwebsite/excel` backend integration (add new export classes in `app/Exports/Reports/`).
|
||||
5. **Charts**: prefer `recharts` if already in `packages/ui` dependencies; otherwise propose to user before adding.
|
||||
|
||||
### Verification
|
||||
1. Each report renders with sample data filtered by date range.
|
||||
2. PDF export uses the same layout shell as other prints (`resources/views/pdf/layouts/document.blade.php`).
|
||||
3. Excel export downloads a valid `.xlsx`.
|
||||
4. Permissions block access when role lacks `can_view_reports_<category>`.
|
||||
|
||||
---
|
||||
|
||||
# Phase 5 — CRM (Leads, Calls, Tasks-CRM)
|
||||
|
||||
**Goal.** Add the missing CRM module with three pipelines: Leads, Calls, Tasks (distinct from existing productivity tasks). Mirrors Garage Box screenshots 1–8.
|
||||
|
||||
### Sub-phase 5a — Leads
|
||||
|
||||
#### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `lead_sections` | `id`, `title`, `arrangement`, `is_default`, `kind` enum(`open`,`won`,`lost`) (kind drives default behavior). Reuse `TaskSection` pattern. |
|
||||
| `leads` | `id`, `number` (unique, e.g. `LD-000001`), `title`, `date`, `lead_owner_id` (FK users), `referral_source_id` (FK), `lead_status_id` (FK), `department_id`, `description`, `lead_section_id` (FK), `customer_id` (nullable), `vehicle_id` (nullable), salutation, first/last/company name, phone, email, address fields, vehicle fields (make, model, plate, body_type_id). |
|
||||
| `lead_services` | pivot to services |
|
||||
| `lead_parts` | pivot to parts |
|
||||
| `lead_labels` | pivot to `labels` table |
|
||||
|
||||
#### Backend
|
||||
- `LeadController`, `LeadSectionController`, `LeadServiceController`, `LeadPartController` (mirror Estimate's split).
|
||||
- Permissions: `can_view_leads`, `can_create_leads`, `can_update_leads`, `can_delete_leads`, plus `can_manage_lead_sections`.
|
||||
- Number sequence: reuse `InvoiceSequenceController` pattern (add `LeadSequenceController`).
|
||||
- Lang keys under `lang/en/api.php` `leads` section + `lang/ar/api.php`.
|
||||
- OpenAPI annotations on each method.
|
||||
|
||||
#### Frontend
|
||||
- **Module** `apps/dashboard/modules/leads/` with `lead-form.tsx`, `lead.schema.ts`, `lead-pipeline.tsx` (Kanban view), `lead-actions.tsx`, inline sections for services/parts.
|
||||
- **Routes** `app/(authenticated)/crm/leads/page.tsx` (Kanban + table toggle), `[id]/page.tsx` (detail).
|
||||
- **Sidebar** new group `{ title: "CRM", icon: <UsersIcon />, items: [Leads, Calls, Tasks] }` after Purchases in `navGroups.tsx`.
|
||||
- **Pipeline UI**: Kanban with `@dnd-kit` (check if already in deps before adding). Each column = a `LeadSection`. "+ Section" button opens a section dialog (reuse `task-section-form.tsx` pattern).
|
||||
- **API client** `packages/api/src/clients/leads.ts`.
|
||||
|
||||
### Sub-phase 5b — Calls
|
||||
|
||||
#### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `calls` | `id`, `number` (`CL-000001`), `call_for` (polymorphic morphs to Customer/Lead), `vehicle_id`, `status` enum(`requested`,`scheduled`,`completed`,`cancelled`), `type` enum(`inbound`,`outbound`), `subject`, `call_owner_id`, `call_date`, `from_time`, `to_time`, `department_id`, `purpose_id` (FK to lookup), `agenda` text, `outcome_id` (nullable FK), `description`, `duration_minutes`, `duration_seconds`, `voice_recording_path`, `send_notification` bool. |
|
||||
| `call_reminders` | `id`, `call_id`, `unit` int, `unit_type` enum(`minute`,`hour`,`day`), `event` enum(`before`,`after`), `channel` enum(`sms`,`email`,`whatsapp`). |
|
||||
| `call_purposes`, `call_outcomes` | lookups |
|
||||
|
||||
#### Backend
|
||||
- `CallController` (CRUD + special endpoints: `complete`, `cancel`, `reschedule`).
|
||||
- `CallReminderController` (nested).
|
||||
- Reminder dispatcher: a Laravel scheduled job in `app/Console/Commands/SendDueCallReminders.php` runs every minute, sends pending reminders via the relevant notification template (Phase 3) through the provider configured in Phase 7. If Phase 7 not yet shipped, log-only.
|
||||
- Permissions: standard four + `can_log_calls`, `can_complete_calls`.
|
||||
|
||||
#### Frontend
|
||||
- **Module** `apps/dashboard/modules/calls/` with `call-form.tsx` (schedule), `call-log-form.tsx` (log), `call.schema.ts`, `call-calendar.tsx`.
|
||||
- **Routes** `app/(authenticated)/crm/calls/page.tsx` (table + tabs Requested/Scheduled/Completed/Cancelled), `crm/calls/calendar/page.tsx` (month view), `[id]/page.tsx`.
|
||||
|
||||
### Sub-phase 5c — Tasks (CRM)
|
||||
|
||||
**Approach locked per Part F: Option A — extend existing `tasks` table.**
|
||||
|
||||
#### Migration
|
||||
Add to the existing `tasks` table:
|
||||
- `context` enum (`productivity`, `crm`), default `productivity`, NOT NULL.
|
||||
- `customer_id` nullable FK to `customers`.
|
||||
- `vehicle_id` nullable FK to `vehicles`.
|
||||
- Index on `(context, status)` for the pipeline filter.
|
||||
|
||||
#### Backend
|
||||
- Backfill existing rows to `context = 'productivity'`.
|
||||
- All existing `TaskController` queries get a `->where('context', 'productivity')` filter so `/productivity/tasks` keeps showing only what it shows today.
|
||||
- Add `CrmTaskController` (thin) that scopes to `context = 'crm'` and exposes the same CRUD + section endpoints. Reuse the `TaskSection` table for sections (add a `context` column there too, same enum).
|
||||
- Permissions: introduce `can_view_crm_tasks`, `can_create_crm_tasks`, `can_update_crm_tasks`, `can_delete_crm_tasks` separate from the existing productivity-task permissions.
|
||||
|
||||
#### Frontend
|
||||
- New module `apps/dashboard/modules/crm-tasks/` mirroring Leads pipeline pattern (Kanban with sections).
|
||||
- Route `app/(authenticated)/crm/tasks/page.tsx` (Kanban + table toggle).
|
||||
- Re-use schema fragments from `modules/tasks/` where possible — extract shared bits to a `modules/tasks/shared/` if duplication grows.
|
||||
|
||||
### Verification (Phase 5 overall)
|
||||
1. Pipeline drag-and-drop persists section + arrangement.
|
||||
2. New lead with vehicle info creates a corresponding draft Customer + Vehicle (or links existing) — confirm desired behavior.
|
||||
3. Call scheduled with a 10-min reminder → cron job fires at expected time.
|
||||
4. Number sequences advance correctly when a record is created.
|
||||
|
||||
---
|
||||
|
||||
# Phase 6 — Marketing (Service Reminders + Reviews)
|
||||
|
||||
**Goal.** Automate service reminders based on mileage / time, plus collect and surface customer reviews.
|
||||
|
||||
### Service Reminders
|
||||
- New table `service_reminders`: `id`, `customer_id`, `vehicle_id`, `reminder_type` (`mileage` / `time`), `interval_value`, `interval_unit`, `last_triggered_at`, `next_due_at`, `status` enum(`scheduled`,`sent`,`cancelled`), `channels` JSON (subset of `['email','sms']`).
|
||||
- Scheduled command `app/Console/Commands/SendDueServiceReminders.php` runs daily; sends via Phase 3 templates (`service_reminder_send`).
|
||||
- **Channels (per Part F)**: **Email** via Laravel `Mail::to(...)->send(...)` using the configured mail sender; **SMS** via Twilio.
|
||||
- Install `twilio/sdk` (Composer) — flag this dependency add for user approval per CLAUDE.md house rules.
|
||||
- Add a `NotificationDispatcher` service in `app/Services/Notifications/` with `sendEmail()` and `sendSms()` methods. Reads Twilio credentials from `config/services.php` (`twilio.sid`, `twilio.token`, `twilio.from`) which read from `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`).
|
||||
- WhatsApp/Push channel toggles render but are disabled with a "Requires integration" tooltip — wiring up to providers happens in deferred Phase 7.
|
||||
- Frontend: `app/(authenticated)/marketing/service-reminders/page.tsx` — list with status tabs, "Create reminder" form with Email + SMS channel checkboxes.
|
||||
|
||||
### Rating & Reviews
|
||||
- New table `customer_reviews`: `id`, `customer_id`, `job_card_id`, `rating` 1–5, `comment`, `submitted_at`, `source` enum(`internal`,`google`).
|
||||
- Public-facing review form already partially served by `PublicInspectionController` pattern — extend with `PublicReviewController`.
|
||||
- After job-card completion, fire `ratings_reviews_link` template (Phase 3).
|
||||
- Frontend list at `app/(authenticated)/marketing/reviews/page.tsx`.
|
||||
|
||||
### Google Business Reviews
|
||||
- Read-only sync via Google Business Profile API (requires Phase 7 Google integration).
|
||||
- Background job polls every 6 h.
|
||||
- Render in same Reviews list with `source = google` badge.
|
||||
|
||||
### Sidebar
|
||||
- Add CRM-style group `{ title: "Marketing", icon: <MegaphoneIcon />, items: [Service Reminders, Reviews, Google Reviews] }` after CRM.
|
||||
|
||||
### Verification
|
||||
1. Create a mileage-based reminder → next_due_at calculated.
|
||||
2. Cron tick at due time → template send is recorded (or logged if Phase 7 incomplete).
|
||||
3. Submit a public review → appears in admin list.
|
||||
|
||||
---
|
||||
|
||||
# Phase 7 — Integrations (real connectors) — DEFERRED
|
||||
|
||||
**Status (per Part F decision): NOT IN ROADMAP.** The Phase 1 "Coming soon" placeholder is the long-term state for now. Twilio (SMS) and Laravel mail (email) used by Phase 6 are configured via `.env` only — no user-facing integrations UI.
|
||||
|
||||
Keep this spec as reference for when integrations become a priority later.
|
||||
|
||||
**Goal (when revived).** Replace the Phase 1 placeholder with a real Providers/Integrations page connecting Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp. Twilio also moves into the UI at that point.
|
||||
|
||||
### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `integration_providers` | seeded list: `id`, `key` (slug), `name`, `purpose`, `icon_path`, `auth_type` (`oauth2`/`api_key`/`webhook`), `is_active`. |
|
||||
| `integration_connections` | per-tenant connection: `id`, `provider_id`, `credentials` (encrypted JSON), `status` (`connected`/`disconnected`/`error`), `last_synced_at`. |
|
||||
|
||||
### Backend
|
||||
- `IntegrationProviderController` (list), `IntegrationConnectionController` (CRUD + `connect`, `disconnect`, `test`).
|
||||
- One service class per provider in `app/Services/Integrations/<Provider>/`. Each implements a common contract `IntegrationDriver` with `connect()`, `disconnect()`, `sendMessage()`, `pullData()`.
|
||||
- OAuth callback routes: `/integrations/{provider}/callback`.
|
||||
- Permissions: `can_manage_integrations`.
|
||||
- Lang keys for connection status messages.
|
||||
|
||||
### Frontend
|
||||
- **Replace** the Phase 1 placeholder page with `app/(authenticated)/settings/integrations/page.tsx` showing a `Tabs` of "Providers" (catalog) + "Integrations" (connected list).
|
||||
- **Provider catalog tile** with "Connect" button → opens OAuth popup or credentials dialog.
|
||||
- Update `navGroups.tsx`: `href: "/settings/integrations/providers"` (the original commented-out path).
|
||||
|
||||
### Verification
|
||||
1. Connect Google → OAuth popup → callback persists tokens → "Connected" badge appears.
|
||||
2. Test SMS via Vonage → message delivered (in sandbox).
|
||||
3. Disconnect → credentials zeroed.
|
||||
|
||||
### Out of scope for first cut
|
||||
Real-time webhook handlers for each provider (do them incrementally, one provider per follow-up PR).
|
||||
|
||||
---
|
||||
|
||||
# Phase 8 — Accountants
|
||||
|
||||
**Goal.** Introduce a real general ledger. Split into two sub-phases per Part F: ship the ledger UI first (8A), wire auto-posting into existing modules afterward (8B).
|
||||
|
||||
## Phase 8A — Chart of Accounts + Manual Journals + Default Configuration
|
||||
|
||||
Ship the standalone ledger. No existing controllers are touched. Users can manually post journal entries; nothing auto-posts.
|
||||
|
||||
### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `chart_of_accounts` | `id`, `name`, `code` (nullable), `account_type` enum(`asset`,`liability`,`equity`,`income`,`expense`,`cogs`), `parent_id` (nullable, for sub-accounts), `is_system` bool (lock icon in UI), `note`. |
|
||||
| `journals` | `id`, `number` (`JN-000001`), `date`, `reference`, `notes`, `total_amount` (must balance), `posted_by`, `posted_at`. |
|
||||
| `journal_lines` | `id`, `journal_id`, `account_id`, `debit`, `credit`, `description`. Constraint: sum(debit) == sum(credit) per journal. |
|
||||
| `default_account_settings` | single-row config table for: `sales_account_id`, `purchase_account_id`, `inventory_account_id`, `adjustment_account_id`, `customer_advance_account_id`, `deposit_to_account_id`, `vendor_advance_account_id`, `paid_through_account_id`, `purchase_discount_account_id`, `expense_account_id`. |
|
||||
|
||||
### Seed
|
||||
Seed ~80 standard accounts matching Garage Box screenshot 9 (Accounts Payable, Accounts Receivable, Advance Tax, … VAT Payable). Mark system accounts (`is_system = true`).
|
||||
|
||||
### Backend (8A only)
|
||||
- `ChartOfAccountController`, `JournalController`, `DefaultAccountSettingsController`.
|
||||
- Permissions: `can_view_accountants`, `can_manage_chart_of_accounts`, `can_post_journals`.
|
||||
- OpenAPI annotations.
|
||||
- **No changes to existing controllers** in this sub-phase — Invoices/Bills/Payments/Expenses are untouched.
|
||||
|
||||
### Frontend
|
||||
- **Sidebar group** `{ title: "Accountants", icon: <BookOpenIcon />, items: [Manual Journals, Chart Of Accounts] }` after Purchases.
|
||||
- **Module** `apps/dashboard/modules/accountants/` with `chart-of-account-list.tsx`, `chart-of-account-form.tsx`, `journal-form.tsx` (multi-line debit/credit with running balance check), `default-account-settings-form.tsx`.
|
||||
- **Routes**: `app/(authenticated)/accountants/chart-of-accounts/page.tsx`, `accountants/manual-journals/page.tsx`, `[id]/page.tsx`.
|
||||
|
||||
### Verification (8A)
|
||||
1. Seed list matches Garage Box exactly (account names + types).
|
||||
2. Create a manual journal with unbalanced lines → backend rejects.
|
||||
3. Default Configuration dialog persists.
|
||||
4. Invoices/Bills/Payments/Expenses still work unchanged (no regression).
|
||||
|
||||
## Phase 8B — Auto-posting + cross-doc linking
|
||||
|
||||
Wire the ledger into operational modules. **Only start after 8A is stable in production.**
|
||||
|
||||
### Backend
|
||||
- New service `app/Services/Accounting/JournalPoster.php` with methods like `postInvoice(Invoice $i)`, `postBill(Bill $b)`, `postPaymentReceived(...)`, `postPaymentMade(...)`, `postExpense(...)`.
|
||||
- Hook into existing controllers via Eloquent `created` / `updated` model observers (cleaner than editing every controller). Observers live in `app/Observers/`, registered in `EventServiceProvider`.
|
||||
- Each posted journal gets a `source_type` + `source_id` morphable pair so it links back to the originating document.
|
||||
- Reversal logic: when a source doc is deleted or voided, post the reverse journal (don't soft-delete the original).
|
||||
- New permission: `can_post_automatic_journals` (default true for finance roles).
|
||||
|
||||
### Frontend
|
||||
- On Invoice / Bill / Payment / Expense detail pages: add a "Journal Entry" panel showing the posted journal lines (read-only) with a deep link to `/accountants/manual-journals/<id>`.
|
||||
- On Journal detail: show "Source Document" link back to the originating doc.
|
||||
|
||||
### Verification (8B)
|
||||
1. Create an Invoice → Journal auto-posts (debit AR, credit Sales, credit Tax).
|
||||
2. Edit Invoice amount → existing journal reversed + new one posted.
|
||||
3. Delete Invoice → reversal posted; original journal preserved for audit.
|
||||
4. Default Configuration changes are respected on next post.
|
||||
5. Audit trail: every Journal has a non-null `source_type`/`source_id` when auto-posted.
|
||||
|
||||
---
|
||||
|
||||
## Part E — Cross-cutting follow-ups (every phase finishes with)
|
||||
|
||||
1. Run **`pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`** — must pass.
|
||||
2. Run **`php -l`** on every changed PHP file.
|
||||
3. Regenerate API client if backend changed: **`pnpm --filter @garage/api generate`**.
|
||||
4. Update lang pairs (`lang/en/*.php` + `lang/ar/*.php`).
|
||||
5. Update permission migration + seeder for any new permission columns.
|
||||
6. Use the `code-review-graph` MCP `detect_changes_tool` + `get_review_context_tool` before opening the PR to self-review.
|
||||
7. Update `claude-timeline/YYYY-MM-DD.md` with a one-line note about the phase shipped (per global memory rule).
|
||||
8. **Do not commit** — leave the diff for the user to review.
|
||||
|
||||
---
|
||||
|
||||
## Part F — Resolved decisions (2026-05-21)
|
||||
|
||||
All open questions answered by the user. These are now binding for the phases referenced.
|
||||
|
||||
- **Phase 2 (Master)** → **Keep top-level entries as aliases.** Insurance Types, Departments, Make & Models remain in the Settings sidebar AND appear under Master tabs. Backwards-compat for bookmarks. No redirects, no removals.
|
||||
- **Phase 4 (Reports) — charts** → **Use Recharts (already installed)** via the existing wrapper at `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency.
|
||||
- **Phase 4 (Reports) — v1 scope** → ship exactly these four reports:
|
||||
1. Sales by Customer
|
||||
2. Invoices Aging (0–30 / 31–60 / 61–90 / 90+ days)
|
||||
3. Technician Productivity (hours logged vs billable per technician)
|
||||
4. Inventory Valuation + Low-Stock
|
||||
All other reports listed in Phase 4 are deferred.
|
||||
- **Phase 5c (CRM Tasks)** → **Extend the existing `tasks` table** (Option A). Add `context` enum (`productivity` | `crm`), nullable `customer_id`, nullable `vehicle_id`. All existing task queries get a `context = 'productivity'` filter.
|
||||
- **Phase 6 (Marketing reminders) — channels** → **Email + SMS in v1; WhatsApp deferred.**
|
||||
- Email sends via Laravel's configured mail sender (`config/mail.php`) — works out of the box, no Integrations UI required.
|
||||
- SMS sends via **Twilio**. Configured server-side via `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`) — not surfaced in the Integrations page yet.
|
||||
- WhatsApp channel toggles are visible but disabled with a "Requires integration" tooltip.
|
||||
- **Phase 7 (Integrations real)** → **Stays "coming soon."** The Phase 1 placeholder is the long-term state for now. Twilio + Laravel mail are configured server-side only; no user-facing connector UI in this roadmap. Phase 7's detailed spec is preserved as a future reference but no work is planned.
|
||||
- **Phase 8 (Accountants)** → **Split into two sub-phases:**
|
||||
- **Phase 8A**: Chart of Accounts + Manual Journals + Default Configuration UI. No automatic posting from other modules.
|
||||
- **Phase 8B**: Auto-post journals on Invoice / Bill / Payment / Expense create + link from each source doc to its posted journal entry. Big blast radius — ship only after 8A is stable.
|
||||
@@ -5,11 +5,12 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -26,6 +27,9 @@ export default function AppointmentsPage() {
|
||||
<ResourcePage<AppointmentsClient>
|
||||
pageTitle="Appointments"
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -77,7 +81,7 @@ export default function AppointmentsPage() {
|
||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||
return (
|
||||
<Badge className={colorClass}>
|
||||
{status?.replace("_", " ") ?? "—"}
|
||||
{formatEnum(status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
@@ -86,22 +90,14 @@ export default function AppointmentsPage() {
|
||||
id: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const jobCardId = (row.original as any).job_card_id
|
||||
if (!jobCardId) return <span className="text-muted-foreground">—</span>
|
||||
const item = row.original as any
|
||||
const jobCardId = item.job_card_id ?? item.job_card?.id
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
router.push(`/sales/job-cards/${jobCardId}`)
|
||||
}}
|
||||
>
|
||||
<ClipboardListIcon className="size-3" />
|
||||
#{jobCardId}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Button>
|
||||
<RelationLink
|
||||
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -201,15 +201,20 @@ export default function InventoryAdjustmentsPage() {
|
||||
<ResourcePage<InventoryAdjustmentsClient>
|
||||
pageTitle="Inventory Adjustments"
|
||||
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search adjustments..."
|
||||
getClient={(api) => api.inventoryAdjustments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inventory Adjustment">
|
||||
{(resourceId) => (
|
||||
<FormDialog
|
||||
title="Inventory Adjustment"
|
||||
classNames={{ dialogContent: "lg:min-w-4xl" }}
|
||||
>
|
||||
{(resourceId, { close }) => (
|
||||
<InventoryAdjustmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => { invalidateQuery(); close() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
|
||||
@@ -12,15 +12,20 @@ export default function ExpenseItemPage() {
|
||||
<ResourcePage<ExpenseItemsClient>
|
||||
pageTitle="Expense Items"
|
||||
routeKey={EXPENSE_ITEM_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expense items..."
|
||||
getClient={(api) => api.expenseItems}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Expense Item">
|
||||
{(resourceId) => (
|
||||
{(resourceId, { close }) => (
|
||||
<ExpenseItemForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
|
||||
@@ -17,6 +17,8 @@ export default function PartsPage() {
|
||||
<ResourcePage<PartsClient>
|
||||
pageTitle="Parts"
|
||||
routeKey={PARTS_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search parts..."
|
||||
getClient={(api) => api.parts}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
@@ -24,6 +26,7 @@ export default function PartsPage() {
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.parts.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Parts"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.parts.exportData(filters)}
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
|
||||
<ResourcePage<ServiceGroupsClient>
|
||||
pageTitle="Service Groups"
|
||||
routeKey={SERVICE_GROUP_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search service groups..."
|
||||
getClient={(api) => api.serviceGroups}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -17,6 +17,8 @@ export default function ServicesPage() {
|
||||
<ResourcePage<ServicesClient>
|
||||
pageTitle="Services"
|
||||
routeKey={SERVICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search services..."
|
||||
getClient={(api) => api.services}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
@@ -24,6 +26,7 @@ export default function ServicesPage() {
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.services.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Services"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.services.exportData(filters)}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { TIME_SHEET_ROUTES } from "@garage/api"
|
||||
import type { TimeSheetsClient } from "@garage/api"
|
||||
import { ClockIcon } from "lucide-react"
|
||||
|
||||
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
|
||||
general: "secondary",
|
||||
order: "default",
|
||||
task: "outline",
|
||||
}
|
||||
|
||||
function formatTime(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
return value.length >= 5 ? value.slice(0, 5) : value
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function formatCost(value: unknown) {
|
||||
if (value === null || value === undefined) return "—"
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return "—"
|
||||
return n.toFixed(2)
|
||||
}
|
||||
|
||||
export default function EmployeeAttendancePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
|
||||
return (
|
||||
<ResourcePage<TimeSheetsClient>
|
||||
pageTitle="Attendance"
|
||||
routeKey={TIME_SHEET_ROUTES.INDEX}
|
||||
getClient={(api) => api.timeSheets}
|
||||
extraParams={{ employee_id: employeeId }}
|
||||
header={null}
|
||||
statusFilter={{
|
||||
statuses: ["general", "order", "task"],
|
||||
paramKey: "activity_type",
|
||||
allLabel: "All",
|
||||
}}
|
||||
columns={() => [
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClockIcon className="size-4 text-muted-foreground" />
|
||||
<span>{formatDate((row.original as any).date)}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_in",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_out",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "duration",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "activity_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
|
||||
cell: ({ row }) => {
|
||||
const type = (row.original as any).activity_type ?? "general"
|
||||
return <Badge variant={ACTIVITY_VARIANT[type] ?? "secondary"}>{type}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "calculated_total_cost",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => formatCost((row.original as any).calculated_total_cost),
|
||||
},
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).note
|
||||
return v ? <span className="text-sm">{v}</span> : "—"
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { Plus, Trash2, ExternalLinkIcon, AwardIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EmployeeCertificationForm } from "@/modules/employees/employee-certification-form"
|
||||
|
||||
type CertRow = {
|
||||
id: number
|
||||
name: string
|
||||
issuer?: string | null
|
||||
certificate_number?: string | null
|
||||
issued_date?: string | null
|
||||
expiry_date?: string | null
|
||||
file_url?: string | null
|
||||
is_expired?: boolean
|
||||
notes?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
export default function EmployeeCertificationsPage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
const queryKey = ["employee-certifications", employeeId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.employees.listCertifications(employeeId) as Promise<{ data: CertRow[] | { data: CertRow[] } }>,
|
||||
})
|
||||
|
||||
const rows: CertRow[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.employees.destroyCertification(employeeId, String(id)),
|
||||
onSuccess: () => {
|
||||
toast.success("Certification deleted")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => toast.error("Failed to delete"),
|
||||
})
|
||||
|
||||
async function handleDelete(row: CertRow) {
|
||||
const ok = await confirm({
|
||||
title: "Delete certification?",
|
||||
description: `Permanently delete "${row.name}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate(row.id)
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CertRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<AwardIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "issuer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issuer" />,
|
||||
cell: ({ row }) => row.original.issuer ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "certificate_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cert #" />,
|
||||
cell: ({ row }) => {
|
||||
const v = row.original.certificate_number
|
||||
return v ? <span className="font-mono text-xs">{v}</span> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "issued_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiry_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{formatDate(row.original.expiry_date)}</span>
|
||||
{row.original.is_expired && <Badge variant="destructive">Expired</Badge>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex justify-end gap-1">
|
||||
{row.original.file_url && (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLinkIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Certifications",
|
||||
actions: (
|
||||
<Button size="sm" onClick={() => setOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Certification
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Certification</DialogTitle>
|
||||
</DialogHeader>
|
||||
<EmployeeCertificationForm
|
||||
employeeId={employeeId}
|
||||
onSuccess={() => {
|
||||
setOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
onCancel={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { Plus, Trash2, ExternalLinkIcon, FileTextIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EmployeeDocumentForm } from "@/modules/employees/employee-document-form"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type DocRow = {
|
||||
id: number
|
||||
name: string
|
||||
type: string
|
||||
file_url?: string
|
||||
issued_date?: string | null
|
||||
expiry_date?: string | null
|
||||
notes?: string | null
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function isExpired(value: unknown) {
|
||||
if (!value || typeof value !== "string") return false
|
||||
const d = new Date(value)
|
||||
return !Number.isNaN(d.getTime()) && d.getTime() < Date.now()
|
||||
}
|
||||
|
||||
export default function EmployeeDocumentsPage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const queryKey = ["employee-documents", employeeId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.employees.listDocuments(employeeId) as Promise<{ data: DocRow[] | { data: DocRow[] } }>,
|
||||
})
|
||||
|
||||
const rows: DocRow[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.employees.destroyDocument(employeeId, String(id)),
|
||||
onSuccess: () => {
|
||||
toast.success("Document deleted")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => toast.error("Failed to delete document"),
|
||||
})
|
||||
|
||||
async function handleDelete(row: DocRow) {
|
||||
const ok = await confirm({
|
||||
title: "Delete document?",
|
||||
description: `Permanently delete "${row.name}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate(row.id)
|
||||
}
|
||||
|
||||
const columns: ColumnDef<DocRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<FileTextIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => <Badge variant="outline">{formatEnum(row.original.type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: "issued_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiry_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
||||
cell: ({ row }) => {
|
||||
const v = row.original.expiry_date
|
||||
if (!v) return "—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{formatDate(v)}</span>
|
||||
{isExpired(v) && <Badge variant="destructive">Expired</Badge>}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex justify-end gap-1">
|
||||
{row.original.file_url && (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLinkIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Documents",
|
||||
actions: (
|
||||
<Button size="sm" onClick={() => setOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Upload Document
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Document</DialogTitle>
|
||||
</DialogHeader>
|
||||
<EmployeeDocumentForm
|
||||
employeeId={employeeId}
|
||||
onSuccess={() => {
|
||||
setOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
onCancel={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -28,6 +28,13 @@ export default async function layout(props: {
|
||||
actions={<EmployeeActions employeeId={id} />}
|
||||
tabs={[
|
||||
{ href: `/productivity/employees/${id}`, label: 'Details' },
|
||||
{ href: `/productivity/employees/${id}/attendance`, label: 'Attendance' },
|
||||
{ href: `/productivity/employees/${id}/work-history`, label: 'Work History' },
|
||||
{ href: `/productivity/employees/${id}/documents`, label: 'Documents' },
|
||||
{ href: `/productivity/employees/${id}/certifications`, label: 'Certifications' },
|
||||
{ href: `/productivity/employees/${id}/leave`, label: 'Leave' },
|
||||
{ href: `/productivity/employees/${id}/payroll`, label: 'Payroll' },
|
||||
{ href: `/productivity/employees/${id}/performance`, label: 'Performance' },
|
||||
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useEmployee } from "@/modules/employees/employee-context"
|
||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
||||
import type { LeaveRequestsClient } from "@garage/api"
|
||||
import { CalendarIcon, PlaneIcon, ActivityIcon } from "lucide-react"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Balance = {
|
||||
annual_total: number
|
||||
annual_used: number
|
||||
annual_remaining: number
|
||||
sick_total: number
|
||||
sick_used: number
|
||||
sick_remaining: number
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
||||
if (status === "approved") return "default"
|
||||
if (status === "rejected") return "destructive"
|
||||
if (status === "cancelled") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
function BalanceCard({ icon: Icon, label, used, total, remaining }: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
used: number
|
||||
total: number
|
||||
remaining: number
|
||||
}) {
|
||||
const pct = total > 0 ? Math.min(100, (used / total) * 100) : 0
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<Icon className="size-4" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold">{remaining}<span className="ml-1 text-sm font-normal text-muted-foreground">/ {total}</span></div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{used} used</p>
|
||||
<div className="mt-2 h-2 w-full overflow-hidden rounded bg-muted">
|
||||
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default function EmployeeLeavePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const employee = useEmployee()
|
||||
|
||||
const balanceQuery = useQuery({
|
||||
queryKey: ["employee-leave-balance", employeeId],
|
||||
queryFn: () => api.employees.getLeaveBalance(employeeId) as Promise<{ data: Balance }>,
|
||||
})
|
||||
|
||||
const balance = (balanceQuery.data as any)?.data as Balance | undefined
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{balance && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-2 px-4 pt-4">
|
||||
<BalanceCard
|
||||
icon={PlaneIcon}
|
||||
label="Annual Leave"
|
||||
used={Number(balance.annual_used)}
|
||||
total={Number(balance.annual_total)}
|
||||
remaining={Number(balance.annual_remaining)}
|
||||
/>
|
||||
<BalanceCard
|
||||
icon={ActivityIcon}
|
||||
label="Sick Leave"
|
||||
used={Number(balance.sick_used)}
|
||||
total={Number(balance.sick_total)}
|
||||
remaining={Number(balance.sick_remaining)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ResourcePage<LeaveRequestsClient>
|
||||
pageTitle="Leave History"
|
||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
||||
getClient={(api) => api.leaveRequests}
|
||||
extraParams={{ employee_id: employeeId }}
|
||||
header={null}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="New Leave Request">
|
||||
{() => (
|
||||
<LeaveRequestForm
|
||||
presetEmployee={{ id: employeeId, label: employee?.label ?? "" }}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
balanceQuery.refetch()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={() => [
|
||||
{
|
||||
accessorKey: "leave_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="size-4 text-muted-foreground" />
|
||||
<Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "days",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "reason",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Reason" />,
|
||||
cell: ({ row }) => (row.original as any).reason ?? "—",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Slip = {
|
||||
id: number
|
||||
payroll_run?: { id?: number; reference?: string; period_start?: string; period_end?: string; status?: string }
|
||||
hours_worked: number
|
||||
base_salary: number
|
||||
commission_amount: number
|
||||
allowances: number
|
||||
deductions: number
|
||||
net_pay: number
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function fmt(v: unknown) {
|
||||
const n = Number(v)
|
||||
if (!Number.isFinite(n)) return "—"
|
||||
return n.toFixed(2)
|
||||
}
|
||||
|
||||
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function EmployeePayrollPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
const api = useAuthApi()
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["employee-payroll-slips", employeeId],
|
||||
queryFn: () => api.employees.listPayrollSlips(employeeId) as Promise<{ data: Slip[] | { data: Slip[] } }>,
|
||||
})
|
||||
|
||||
const rows: Slip[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const columns: ColumnDef<Slip>[] = [
|
||||
{
|
||||
accessorKey: "payroll_run",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Run" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.payroll_run
|
||||
return r?.reference ?? (r?.id ? `#${r.id}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "period",
|
||||
header: () => <span>Period</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.payroll_run
|
||||
if (!r) return "—"
|
||||
return `${formatDate(r.period_start)} → ${formatDate(r.period_end)}`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "hours_worked",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
||||
cell: ({ row }) => fmt(row.original.hours_worked),
|
||||
},
|
||||
{
|
||||
accessorKey: "base_salary",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
||||
cell: ({ row }) => fmt(row.original.base_salary),
|
||||
},
|
||||
{
|
||||
accessorKey: "commission_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
||||
cell: ({ row }) => fmt(row.original.commission_amount),
|
||||
},
|
||||
{
|
||||
accessorKey: "deductions",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
||||
cell: ({ row }) => fmt(row.original.deductions),
|
||||
},
|
||||
{
|
||||
accessorKey: "net_pay",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
||||
cell: ({ row }) => <span className="font-semibold">{fmt(row.original.net_pay)}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.payroll_run?.status
|
||||
if (!s) return "—"
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage headerProps={{ title: "Payroll Slips" }}>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { ClockIcon, WrenchIcon, CheckCircle2Icon, TimerIcon, PercentIcon } from "lucide-react"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Field, FieldLabel } from "@/shared/components/ui/field"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
|
||||
type PerfData = {
|
||||
period: { from: string; to: string }
|
||||
hours_worked: number
|
||||
jobs_total: number
|
||||
jobs_completed: number
|
||||
avg_job_duration_hours: number
|
||||
completion_rate: number
|
||||
}
|
||||
|
||||
function StatCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
suffix,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string | number
|
||||
suffix?: string
|
||||
}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<Icon className="size-4" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold">
|
||||
{value}
|
||||
{suffix && <span className="ml-1 text-base font-normal text-muted-foreground">{suffix}</span>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function firstOfMonth() {
|
||||
const d = new Date()
|
||||
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function lastOfMonth() {
|
||||
const d = new Date()
|
||||
return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export default function EmployeePerformancePage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const [fromInput, setFromInput] = useState(firstOfMonth())
|
||||
const [toInput, setToInput] = useState(lastOfMonth())
|
||||
const [from, setFrom] = useState(fromInput)
|
||||
const [to, setTo] = useState(toInput)
|
||||
|
||||
const { data, isLoading, isFetching } = useQuery({
|
||||
queryKey: ["employee-performance", employeeId, from, to],
|
||||
queryFn: () => api.employees.performance(employeeId, { from, to }) as Promise<{ data: PerfData }>,
|
||||
})
|
||||
|
||||
const perf = useMemo(() => (data as any)?.data as PerfData | undefined, [data])
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: perf ? `Performance · ${perf.period.from} → ${perf.period.to}` : "Performance",
|
||||
actions: (
|
||||
<div className="flex items-end gap-2">
|
||||
<Field>
|
||||
<FieldLabel>From</FieldLabel>
|
||||
<Input type="date" value={fromInput} onChange={(e) => setFromInput(e.target.value)} />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>To</FieldLabel>
|
||||
<Input type="date" value={toInput} onChange={(e) => setToInput(e.target.value)} />
|
||||
</Field>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={isFetching}
|
||||
onClick={() => {
|
||||
setFrom(fromInput)
|
||||
setTo(toInput)
|
||||
}}
|
||||
>
|
||||
{isFetching ? "Loading..." : "Apply"}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{isLoading && !perf ? (
|
||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
||||
) : !perf ? (
|
||||
<p className="text-sm text-muted-foreground">No data.</p>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
||||
<StatCard icon={ClockIcon} label="Hours Worked" value={perf.hours_worked.toFixed(2)} suffix="h" />
|
||||
<StatCard icon={WrenchIcon} label="Jobs Assigned" value={perf.jobs_total} />
|
||||
<StatCard icon={CheckCircle2Icon} label="Jobs Completed" value={perf.jobs_completed} />
|
||||
<StatCard icon={TimerIcon} label="Avg Job Duration" value={perf.avg_job_duration_hours.toFixed(2)} suffix="h" />
|
||||
<StatCard icon={PercentIcon} label="Completion Rate" value={perf.completion_rate} suffix="%" />
|
||||
</div>
|
||||
)}
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||
import type { JobCardsClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { WrenchIcon } from "lucide-react"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const ROLE_PARAM = {
|
||||
technician: "primary_technician_id",
|
||||
sales: "sales_person_id",
|
||||
writer: "service_writer_id",
|
||||
} as const
|
||||
|
||||
type RoleKey = keyof typeof ROLE_PARAM
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" | "destructive" {
|
||||
if (!status) return "secondary"
|
||||
if (status === "completed" || status === "delivered") return "default"
|
||||
if (status === "cancelled") return "destructive"
|
||||
return "outline"
|
||||
}
|
||||
|
||||
export default function EmployeeWorkHistoryPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
const router = useRouter()
|
||||
const [role, setRole] = useState<RoleKey>("technician")
|
||||
const paramKey = ROLE_PARAM[role]
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="px-4 pt-4">
|
||||
<Tabs value={role} onValueChange={(v) => setRole(v as RoleKey)}>
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="technician">As Technician</TabsTrigger>
|
||||
<TabsTrigger value="sales">As Sales Person</TabsTrigger>
|
||||
<TabsTrigger value="writer">As Service Writer</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<ResourcePage<JobCardsClient>
|
||||
key={role}
|
||||
pageTitle="Work History"
|
||||
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search by job number, plate, customer..."
|
||||
getClient={(api) => api.jobCards}
|
||||
extraParams={{ [paramKey]: employeeId }}
|
||||
header={null}
|
||||
onRowClick={(row) => router.push(`/sales/job-cards/${(row as any).id}`)}
|
||||
columns={() => [
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job #" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<WrenchIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-mono text-xs">{(row.original as any).order_number ?? "—"}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
if (!c) return "—"
|
||||
return `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() || c.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
if (!v) return "—"
|
||||
const display = `${v.make ?? ""} ${v.model ?? ""}`.trim()
|
||||
return display || v.license_plate || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status
|
||||
return s ? <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Opened" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).created_at),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,32 +1,99 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { EmployeeForm } from "@/modules/employees/employee-form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||
import type { EmployeesClient } from "@garage/api"
|
||||
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const TYPE_OPTIONS = [
|
||||
{ value: "all", label: "All types" },
|
||||
{ value: "employee", label: "Employee" },
|
||||
{ value: "sales_person", label: "Sales Person" },
|
||||
]
|
||||
|
||||
function initialsOf(first?: string | null, last?: string | null) {
|
||||
const f = (first ?? "").trim()[0] ?? ""
|
||||
const l = (last ?? "").trim()[0] ?? ""
|
||||
return (f + l).toUpperCase() || "?"
|
||||
}
|
||||
|
||||
export default function EmployeesPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
const [typeFilter, setTypeFilter] = useState<string>("all")
|
||||
|
||||
const extraParams = useMemo(() => {
|
||||
if (typeFilter === "all") return undefined
|
||||
return { type: typeFilter }
|
||||
}, [typeFilter])
|
||||
|
||||
return (
|
||||
<ResourcePage<EmployeesClient>
|
||||
pageTitle="Employees"
|
||||
routeKey={EMPLOYEE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search employees..."
|
||||
statusFilter={{ statuses: ["active", "inactive"] }}
|
||||
extraParams={extraParams}
|
||||
getClient={(api) => api.employees}
|
||||
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
|
||||
tableHeader={() => (
|
||||
<div className="flex items-center gap-2">
|
||||
<Select value={typeFilter} onValueChange={setTypeFilter}>
|
||||
<SelectTrigger className="w-44">
|
||||
<SelectValue placeholder="All types" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{TYPE_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Employee">
|
||||
{(resourceId) => (
|
||||
<EmployeeForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.employees.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Employees"
|
||||
onDownloadSample={() => api.employees.downloadImportSample() as Promise<Blob>}
|
||||
sampleFileName="employees-import-sample"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.employees.exportData(filters)}
|
||||
fileName="employees"
|
||||
/>
|
||||
<FormDialog title="Employee">
|
||||
{(resourceId) => (
|
||||
<EmployeeForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -34,8 +101,16 @@ export default function EmployeesPage() {
|
||||
accessorKey: "first_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => {
|
||||
const { first_name, last_name } = row.original
|
||||
return `${first_name ?? ""} ${last_name ?? ""}`.trim()
|
||||
const r = row.original as any
|
||||
const fullName = `${r.first_name ?? ""} ${r.last_name ?? ""}`.trim() || "—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar size="sm">
|
||||
<AvatarFallback>{initialsOf(r.first_name, r.last_name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="font-medium">{fullName}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -45,15 +120,32 @@ export default function EmployeesPage() {
|
||||
{
|
||||
accessorKey: "phone",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
|
||||
cell: ({ row }) => (row.original as any).phone ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "position",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Position" />,
|
||||
accessorKey: "type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => {
|
||||
const t = (row.original as any).type
|
||||
if (!t) return "—"
|
||||
return <Badge variant="outline">{t === "sales_person" ? "Sales Person" : "Employee"}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "department",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||
cell: ({ row }) => (row.original as any).department?.name ?? "—",
|
||||
cell: ({ row }) => {
|
||||
const d = (row.original as any).department?.name
|
||||
return d ? <Badge variant="secondary">{d}</Badge> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "role",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Role" />,
|
||||
cell: ({ row }) => {
|
||||
const r = (row.original as any).role?.name
|
||||
return r ? <Badge variant="secondary">{r}</Badge> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
@@ -62,7 +154,7 @@ export default function EmployeesPage() {
|
||||
const status = row.original.status
|
||||
return (
|
||||
<span className={status === "active" ? "text-green-600" : "text-red-600"}>
|
||||
{status}
|
||||
{formatEnum(status)}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
|
||||
<ResourcePage<HolidayYearsClient>
|
||||
pageTitle="Holiday Years"
|
||||
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search holidays..."
|
||||
getClient={(api) => api.holidayYears}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
||||
import type { LeaveRequestsClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { toast } from "sonner"
|
||||
import { CheckIcon, XIcon } from "lucide-react"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { usePermissions } from "@/shared/hooks/use-permissions"
|
||||
|
||||
type LeaveRow = {
|
||||
id: number
|
||||
leave_type: string
|
||||
start_date?: string
|
||||
end_date?: string
|
||||
days?: number
|
||||
status: string
|
||||
reason?: string | null
|
||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
||||
if (status === "approved") return "default"
|
||||
if (status === "rejected") return "destructive"
|
||||
if (status === "cancelled") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function LeaveRequestsPage() {
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const perms = usePermissions()
|
||||
|
||||
async function handleDecision(id: number, action: "approve" | "reject") {
|
||||
const ok = await confirm({
|
||||
title: action === "approve" ? "Approve request?" : "Reject request?",
|
||||
description: `This will mark the leave request as ${action}d.`,
|
||||
confirmLabel: action === "approve" ? "Approve" : "Reject",
|
||||
variant: action === "approve" ? "default" : "destructive",
|
||||
})
|
||||
if (!ok) return
|
||||
const promise = action === "approve"
|
||||
? api.leaveRequests.approve(String(id))
|
||||
: api.leaveRequests.reject(String(id))
|
||||
toast.promise(promise, {
|
||||
loading: action === "approve" ? "Approving..." : "Rejecting...",
|
||||
success: action === "approve" ? "Approved" : "Rejected",
|
||||
error: "Failed",
|
||||
})
|
||||
await promise
|
||||
queryClient.invalidateQueries({ queryKey: [LEAVE_REQUEST_ROUTES.INDEX] })
|
||||
}
|
||||
|
||||
return (
|
||||
<ResourcePage<LeaveRequestsClient>
|
||||
pageTitle="Leave Requests"
|
||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
||||
getClient={(api) => api.leaveRequests}
|
||||
statusFilter={{
|
||||
statuses: ["pending", "approved", "rejected", "cancelled"],
|
||||
paramKey: "status",
|
||||
allLabel: "All",
|
||||
}}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: perms.canCreate("leave_requests") ? (
|
||||
<FormDialog title="Leave Request">
|
||||
{(resourceId) => (
|
||||
<LeaveRequestForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
) : null,
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = (row.original as any).employee
|
||||
if (!e) return "—"
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "leave_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => <Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "days",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "decide",
|
||||
header: () => <span className="sr-only">Decide</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as LeaveRow
|
||||
if (r.status !== "pending" || !perms.canUpdate("leave_requests")) return null
|
||||
return (
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "approve")}>
|
||||
<CheckIcon className="size-4 text-green-600" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "reject")}>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { toast } from "sonner"
|
||||
import { CheckCircle2Icon, RefreshCwIcon, BanknoteIcon, Trash2, DownloadIcon } from "lucide-react"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Entry = {
|
||||
id: number
|
||||
employee_id: number
|
||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
||||
hours_worked: number
|
||||
overtime_hours: number
|
||||
base_salary: number
|
||||
commission_amount: number
|
||||
allowances: number
|
||||
deductions: number
|
||||
net_pay: number
|
||||
note?: string | null
|
||||
}
|
||||
|
||||
type Run = {
|
||||
id: number
|
||||
reference?: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
status: "draft" | "finalized" | "paid"
|
||||
entries: Entry[]
|
||||
note?: string | null
|
||||
finalized_at?: string | null
|
||||
paid_at?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function fmtCurrency(value: unknown) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return "—"
|
||||
return n.toFixed(2)
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function PayrollRunPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: runId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
|
||||
const queryKey = ["payroll-run", runId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.payroll.show(runId) as Promise<{ data: Run; totals: Record<string, number> }>,
|
||||
})
|
||||
|
||||
const run = (data as any)?.data as Run | undefined
|
||||
const totals = (data as any)?.totals as Record<string, number> | undefined
|
||||
|
||||
const refetch = () => queryClient.invalidateQueries({ queryKey })
|
||||
|
||||
const finalizeMutation = useMutation({
|
||||
mutationFn: () => api.payroll.finalize(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Run finalized")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to finalize"),
|
||||
})
|
||||
|
||||
const regenerateMutation = useMutation({
|
||||
mutationFn: () => api.payroll.regenerate(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Entries regenerated")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to regenerate"),
|
||||
})
|
||||
|
||||
const markPaidMutation = useMutation({
|
||||
mutationFn: () => api.payroll.markPaid(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Marked as paid")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to mark paid"),
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: () => api.payroll.destroy(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Run deleted")
|
||||
router.push("/productivity/payroll")
|
||||
},
|
||||
onError: () => toast.error("Failed to delete"),
|
||||
})
|
||||
|
||||
async function handleDelete() {
|
||||
const ok = await confirm({
|
||||
title: "Delete payroll run?",
|
||||
description: "This permanently removes the run and all its entries.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<Entry>[] = [
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = row.original.employee
|
||||
if (!e) return `#${row.original.employee_id}`
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "hours_worked",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.hours_worked),
|
||||
},
|
||||
{
|
||||
accessorKey: "base_salary",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.base_salary),
|
||||
},
|
||||
{
|
||||
accessorKey: "commission_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.commission_amount),
|
||||
},
|
||||
{
|
||||
accessorKey: "allowances",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Allowances" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.allowances),
|
||||
},
|
||||
{
|
||||
accessorKey: "deductions",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.deductions),
|
||||
},
|
||||
{
|
||||
accessorKey: "net_pay",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
||||
cell: ({ row }) => <span className="font-semibold">{fmtCurrency(row.original.net_pay)}</span>,
|
||||
},
|
||||
{
|
||||
id: "slip",
|
||||
header: () => <span className="sr-only">Slip</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a
|
||||
href={`/api/payroll/runs/${runId}/entries/${row.original.id}/slip`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Download slip PDF"
|
||||
>
|
||||
<DownloadIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
if (isLoading && !run) {
|
||||
return <DashboardPage>Loading...</DashboardPage>
|
||||
}
|
||||
|
||||
if (!run) {
|
||||
return <DashboardPage>Run not found.</DashboardPage>
|
||||
}
|
||||
|
||||
const entries = run.entries ?? []
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: `${run.reference ?? `Payroll #${run.id}`} · ${formatDate(run.period_start)} → ${formatDate(run.period_end)}`,
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={statusVariant(run.status)}>{formatEnum(run.status)}</Badge>
|
||||
{run.status === "draft" && (
|
||||
<>
|
||||
<Button size="sm" variant="outline" disabled={regenerateMutation.isPending} onClick={() => regenerateMutation.mutate()}>
|
||||
<RefreshCwIcon className="size-4" />
|
||||
Regenerate
|
||||
</Button>
|
||||
<Button size="sm" disabled={finalizeMutation.isPending} onClick={() => finalizeMutation.mutate()}>
|
||||
<CheckCircle2Icon className="size-4" />
|
||||
Finalize
|
||||
</Button>
|
||||
<Button size="sm" variant="destructive" disabled={deleteMutation.isPending} onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{run.status === "finalized" && (
|
||||
<Button size="sm" disabled={markPaidMutation.isPending} onClick={() => markPaidMutation.mutate()}>
|
||||
<BanknoteIcon className="size-4" />
|
||||
Mark Paid
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{totals && (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 mb-4">
|
||||
{[
|
||||
{ label: "Gross Base", value: totals.gross_base },
|
||||
{ label: "Commission", value: totals.commission },
|
||||
{ label: "Allowances", value: totals.allowances },
|
||||
{ label: "Deductions", value: totals.deductions },
|
||||
{ label: "Net Total", value: totals.net_pay },
|
||||
].map((t) => (
|
||||
<Card key={t.label}>
|
||||
<CardHeader className="pb-1">
|
||||
<CardTitle className="text-xs font-medium text-muted-foreground">{t.label}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-lg font-semibold">{fmtCurrency(t.value)}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={entries}
|
||||
pagination={{ page: 1, pageSize: entries.length || 10, pageCount: 1, total: entries.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={false}
|
||||
/>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { PayrollRunForm } from "@/modules/payroll/payroll-run-form"
|
||||
import { PAYROLL_ROUTES } from "@garage/api"
|
||||
import type { PayrollClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type RunRow = {
|
||||
id: number
|
||||
reference?: string | null
|
||||
period_start?: string
|
||||
period_end?: string
|
||||
status: string
|
||||
entries_count?: number
|
||||
generated_at?: string | null
|
||||
finalized_at?: string | null
|
||||
paid_at?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function PayrollPage() {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<ResourcePage<PayrollClient>
|
||||
pageTitle="Payroll"
|
||||
routeKey={PAYROLL_ROUTES.RUNS_INDEX}
|
||||
getClient={(api) => api.payroll}
|
||||
statusFilter={{
|
||||
statuses: ["draft", "finalized", "paid"],
|
||||
paramKey: "status",
|
||||
}}
|
||||
onRowClick={(row) => router.push(`/productivity/payroll/${(row as any).id}`)}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Payroll Run">
|
||||
{() => (
|
||||
<PayrollRunForm
|
||||
onSuccess={(runId) => {
|
||||
invalidateQuery()
|
||||
if (runId) router.push(`/productivity/payroll/${runId}`)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "reference",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Reference" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{(row.original as any).reference ?? `#${(row.original as any).id}`}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "period_start",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Period Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).period_start),
|
||||
},
|
||||
{
|
||||
accessorKey: "period_end",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Period End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).period_end),
|
||||
},
|
||||
{
|
||||
accessorKey: "entries_count",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Entries" />,
|
||||
cell: ({ row }) => (row.original as any).entries_count ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "finalized_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Finalized" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).finalized_at),
|
||||
},
|
||||
actionsColumn({ onEdit: undefined }),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
|
||||
<ResourcePage<ShopCalendarsClient>
|
||||
pageTitle="Shop Calendars"
|
||||
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop calendars..."
|
||||
getClient={(api) => api.shopCalendars}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
|
||||
<ResourcePage<ShopTimingsClient>
|
||||
pageTitle="Shop Timings"
|
||||
routeKey={SHOP_TIMING_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop timings..."
|
||||
getClient={(api) => api.shopTimings}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
|
||||
export default function TasksPage() {
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Tasks",
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { LogInIcon, LogOutIcon, TimerIcon, SearchIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||
|
||||
type Employee = {
|
||||
id: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
email?: string
|
||||
designation?: string
|
||||
department?: { id?: number; name?: string }
|
||||
track_attendance?: boolean
|
||||
has_active_time_sheet?: boolean
|
||||
active_time_sheet?: { id?: number; clock_in?: string; date?: string } | null
|
||||
status?: string
|
||||
}
|
||||
|
||||
function initialsOf(first?: string | null, last?: string | null) {
|
||||
const f = (first ?? "").trim()[0] ?? ""
|
||||
const l = (last ?? "").trim()[0] ?? ""
|
||||
return (f + l).toUpperCase() || "?"
|
||||
}
|
||||
|
||||
function formatTime(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
return value.length >= 5 ? value.slice(0, 5) : value
|
||||
}
|
||||
|
||||
export default function TimeClocksPage() {
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [search, setSearch] = useState("")
|
||||
|
||||
const employeesQuery = useQuery({
|
||||
queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }],
|
||||
queryFn: () => api.employees.list({ per_page: 100, status: "active" } as any) as Promise<{ data: Employee[] }>,
|
||||
})
|
||||
|
||||
const employees: Employee[] = useMemo(() => {
|
||||
const rows: Employee[] = (employeesQuery.data as any)?.data ?? []
|
||||
if (!search) return rows
|
||||
const q = search.toLowerCase()
|
||||
return rows.filter((e) => {
|
||||
const name = `${e.first_name ?? ""} ${e.last_name ?? ""}`.toLowerCase()
|
||||
return name.includes(q) || (e.email ?? "").toLowerCase().includes(q)
|
||||
})
|
||||
}, [employeesQuery.data, search])
|
||||
|
||||
const refetch = () => queryClient.invalidateQueries({ queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }] })
|
||||
|
||||
const clockInMutation = useMutation({
|
||||
mutationFn: (employeeId: number) => api.timeSheets.clockIn({ employee_id: employeeId } as any),
|
||||
onSuccess: () => {
|
||||
toast.success("Clocked in")
|
||||
refetch()
|
||||
},
|
||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock in"),
|
||||
})
|
||||
|
||||
const clockOutMutation = useMutation({
|
||||
mutationFn: (timeSheetId: number) => api.timeSheets.clockOut({ time_sheet_id: timeSheetId } as any),
|
||||
onSuccess: () => {
|
||||
toast.success("Clocked out")
|
||||
refetch()
|
||||
},
|
||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock out"),
|
||||
})
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Time Clocks",
|
||||
actions: (
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search employees..."
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{employeesQuery.isLoading ? (
|
||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
||||
) : employees.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No employees found.</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{employees.map((emp) => {
|
||||
const fullName = `${emp.first_name ?? ""} ${emp.last_name ?? ""}`.trim() || emp.email
|
||||
const isClockedIn = !!emp.has_active_time_sheet
|
||||
const activeId = emp.active_time_sheet?.id
|
||||
const clockedInAt = emp.active_time_sheet?.clock_in
|
||||
|
||||
return (
|
||||
<Card key={emp.id}>
|
||||
<CardContent className="flex items-center justify-between gap-3 p-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Avatar size="lg">
|
||||
<AvatarFallback>{initialsOf(emp.first_name, emp.last_name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium truncate">{fullName}</div>
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{emp.designation ?? emp.department?.name ?? emp.email}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
{isClockedIn ? (
|
||||
<Badge variant="default" className="gap-1">
|
||||
<TimerIcon className="size-3" />
|
||||
Since {formatTime(clockedInAt)}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Idle</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isClockedIn && activeId ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={clockOutMutation.isPending}
|
||||
onClick={() => clockOutMutation.mutate(activeId)}
|
||||
>
|
||||
<LogOutIcon className="size-4" />
|
||||
Clock Out
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={clockInMutation.isPending}
|
||||
onClick={() => clockInMutation.mutate(emp.id)}
|
||||
>
|
||||
<LogInIcon className="size-4" />
|
||||
Clock In
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { TIME_SHEET_ROUTES } from "@garage/api"
|
||||
import type { TimeSheetsClient } from "@garage/api"
|
||||
import { ClockIcon } from "lucide-react"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function formatTime(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
return value.length >= 5 ? value.slice(0, 5) : value
|
||||
}
|
||||
|
||||
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
|
||||
general: "secondary",
|
||||
order: "default",
|
||||
task: "outline",
|
||||
}
|
||||
|
||||
export default function TimeSheetsPage() {
|
||||
return (
|
||||
<ResourcePage<TimeSheetsClient>
|
||||
pageTitle="Time Sheets"
|
||||
routeKey={TIME_SHEET_ROUTES.INDEX}
|
||||
getClient={(api) => api.timeSheets}
|
||||
statusFilter={{
|
||||
statuses: ["general", "order", "task"],
|
||||
paramKey: "activity_type",
|
||||
allLabel: "All",
|
||||
}}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClockIcon className="size-4 text-muted-foreground" />
|
||||
<span>{formatDate((row.original as any).date)}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = (row.original as any).employee
|
||||
if (!e) return "—"
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_in",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_out",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "duration",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "activity_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
|
||||
cell: ({ row }) => {
|
||||
const t = (row.original as any).activity_type ?? "general"
|
||||
return <Badge variant={ACTIVITY_VARIANT[t] ?? "secondary"}>{formatEnum(t)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "calculated_total_cost",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).calculated_total_cost
|
||||
if (v == null) return "—"
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n.toFixed(2) : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn({ onEdit: undefined }),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
|
||||
import { BillActions } from '@/modules/bills/bill-actions'
|
||||
import { BillProvider, type BillResponse } from '@/modules/bills/bill-context'
|
||||
import BillStatusBadge from '@/modules/bills/bill-status-badge'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
@@ -26,6 +27,7 @@ export default async function BillDetailLayout(props: {
|
||||
actions={
|
||||
<div className="flex space-x-2 items-center">
|
||||
<BillStatusBadge bill={{id, status:data?.status}} />
|
||||
<ShareDocumentButton type="bill" id={id} />
|
||||
<BillActions billId={id} />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -6,17 +6,26 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
export default function BillsPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
pageTitle="Bills"
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -41,12 +50,18 @@ export default function BillsPage() {
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Total" />,
|
||||
cell: ({ row }) => (row.original as any).total || "—",
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).total
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Balance Due" />,
|
||||
cell: ({ row }) => (row.original as any).balance_due || "—",
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).balance_due
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +70,16 @@ export default function BillsPage() {
|
||||
{
|
||||
accessorKey: "vendor",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor?.name || "—",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
@@ -74,12 +98,20 @@ export default function BillsPage() {
|
||||
const status = (row.original as any).status
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status?.replace(/_/g, " ") || "—"}
|
||||
{formatEnum(status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("bill", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -5,17 +5,26 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { EXPENSE_ROUTES } from "@garage/api"
|
||||
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
|
||||
import type { ExpensesClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
export default function ExpensesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
return (
|
||||
<ResourcePage<ExpensesClient>
|
||||
pageTitle="Expenses"
|
||||
routeKey={EXPENSE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expenses..."
|
||||
statusFilter={{ statuses: ExpenseStatus }}
|
||||
getClient={(api) => api.expenses}
|
||||
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -49,7 +58,13 @@ export default function ExpensesPage() {
|
||||
header: () => "Vendor",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return vendor?.company_name || vendor?.name || "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor) || vendor?.name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -60,12 +75,12 @@ export default function ExpensesPage() {
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: () => "Total",
|
||||
cell: ({ row }) => formatCurrency((row.original as any).total ?? 0),
|
||||
cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: () => "Balance Due",
|
||||
cell: ({ row }) => formatCurrency((row.original as any).balance_due ?? 0),
|
||||
cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
@@ -86,7 +101,15 @@ export default function ExpensesPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("expense", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { PaymentMadeActions } from '@/modules/payment-mades/payment-made-actions'
|
||||
import { BanknoteIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function PaymentMadeDetailLayout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const payment = await api.paymentMades.show(id)
|
||||
const data = (payment as any)?.data ?? payment
|
||||
const title = data?.payment_number || 'Payment Details'
|
||||
|
||||
return (
|
||||
<DashboardDetailsPage
|
||||
title={title}
|
||||
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
|
||||
icon={<BanknoteIcon className="size-5" />}
|
||||
backHref="/purchase/payments-made"
|
||||
actions={<PaymentMadeActions paymentId={id} />}
|
||||
tabs={[
|
||||
{
|
||||
href: `/purchase/payments-made/${id}`,
|
||||
label: 'Details',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import {
|
||||
BadgeDollarSignIcon,
|
||||
BriefcaseIcon,
|
||||
Building2Icon,
|
||||
CalendarIcon,
|
||||
CreditCardIcon,
|
||||
HashIcon,
|
||||
} from 'lucide-react'
|
||||
|
||||
export default async function PaymentMadeDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const payment = await api.paymentMades.show(id)
|
||||
const data = (payment as any)?.data ?? payment
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Payment not found.</div>
|
||||
}
|
||||
|
||||
const amount = data.payment_made != null
|
||||
? Number(data.payment_made).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
: '—'
|
||||
|
||||
const paymentDate = data.payment_date
|
||||
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
|
||||
: '—'
|
||||
|
||||
const vendorLabel = data.vendor?.company_name
|
||||
?? (data.vendor?.first_name ? `${data.vendor.first_name} ${data.vendor.last_name ?? ''}`.trim() : null)
|
||||
?? data.vendor_name
|
||||
?? (data.employee?.first_name ? `${data.employee.first_name} ${data.employee.last_name ?? ''}`.trim() : null)
|
||||
?? data.employee_name
|
||||
?? '—'
|
||||
|
||||
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<HashIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Number</p>
|
||||
<p className="font-medium">{data.payment_number || '—'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<Building2Icon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Vendor / Employee</p>
|
||||
<p className="font-medium">{vendorLabel}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<BriefcaseIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment For</p>
|
||||
<p className="font-medium capitalize">{data.payment_for || '—'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Amount</p>
|
||||
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Mode</p>
|
||||
<p className="font-medium capitalize">{paymentMode}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<CalendarIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Date</p>
|
||||
<p className="font-medium">{paymentDate}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.payment_reference && (
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<HashIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Reference</p>
|
||||
<p className="font-medium">{data.payment_reference}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.paid_through && (
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Paid Through</p>
|
||||
<p className="font-medium">{data.paid_through}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.notes && (
|
||||
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground mb-1">Notes</p>
|
||||
<p className="text-sm">{data.notes}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import {
|
||||
Paperclip,
|
||||
@@ -32,8 +33,12 @@ import {
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { PAYMENT_MADE_ROUTES } from "@garage/api"
|
||||
import type { PaymentMadesClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
// ── Attachment helpers ──
|
||||
|
||||
@@ -208,10 +213,13 @@ function AttachmentsDialog({
|
||||
type PaymentMadeItem = {
|
||||
id: number
|
||||
payment_number?: string
|
||||
vendor?: { id?: number | string; company_name?: string | null; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
vendor_name?: string
|
||||
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
employee_name?: string
|
||||
payment_for?: string
|
||||
payment_made?: string | number
|
||||
payment_mode?: { name?: string | null; title?: string | null } | null
|
||||
payment_mode_name?: string
|
||||
payment_date?: string
|
||||
paid_through?: string
|
||||
@@ -220,6 +228,8 @@ type PaymentMadeItem = {
|
||||
}
|
||||
|
||||
export default function PaymentsMadePage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
const [attachmentTarget, setAttachmentTarget] = useState<{
|
||||
id: string
|
||||
ref: string
|
||||
@@ -230,14 +240,21 @@ export default function PaymentsMadePage() {
|
||||
<ResourcePage<PaymentMadesClient>
|
||||
pageTitle="Payments Made"
|
||||
routeKey={PAYMENT_MADE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => api.paymentMades}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
onRowClick={(row) => router.push(`/purchase/payments-made/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Record Payment">
|
||||
{(resourceId) => (
|
||||
{(resourceId, { close }) => (
|
||||
<PaymentMadeForm
|
||||
resourceId={resourceId}
|
||||
onSuccess={invalidateQuery}
|
||||
initialData={selectedItem}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -262,11 +279,27 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const isVendor =
|
||||
item.vendor?.company_name ||
|
||||
getFullName(item.vendor) ||
|
||||
item.vendor?.name ||
|
||||
item.vendor_name
|
||||
const label =
|
||||
isVendor ||
|
||||
getFullName(item.employee) ||
|
||||
item.employee?.name ||
|
||||
item.employee_name
|
||||
const href = isVendor && item.vendor?.id
|
||||
? `/purchase/vendor/${item.vendor.id}`
|
||||
: item.employee?.id
|
||||
? `/productivity/employees/${item.employee.id}`
|
||||
: null
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.vendor_name || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={href}
|
||||
icon={isVendor ? Building2 : UserIcon}
|
||||
label={label}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -309,10 +342,15 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const label =
|
||||
item.payment_mode?.name ||
|
||||
item.payment_mode?.title ||
|
||||
item.payment_mode_name ||
|
||||
"—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
||||
<span className="capitalize">{label}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
@@ -360,7 +398,15 @@ export default function PaymentsMadePage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("payment_made", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { getServerApi } from '@garage/api/server'
|
||||
import { PurchaseOrderActions } from '@/modules/purchase-orders/purchase-order-actions'
|
||||
import { PurchaseOrderProvider } from '@/modules/purchase-orders/purchase-order-context'
|
||||
import { CreateBillFromPOButton } from '@/modules/purchase-orders/create-bill-from-po-button'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { ClipboardList } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
@@ -30,6 +31,7 @@ export default async function layout(props: {
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<CreateBillFromPOButton />
|
||||
<ShareDocumentButton type="purchase_order" id={id} />
|
||||
<PurchaseOrderActions purchaseOrderId={id} />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -7,14 +7,21 @@ import FormDialog from "@/shared/components/form-dialog"
|
||||
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
export default function PurchaseOrdersPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
pageTitle="Purchase Orders"
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -43,7 +50,16 @@ export default function PurchaseOrdersPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
@@ -69,7 +85,15 @@ export default function PurchaseOrdersPage() {
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("purchase_order", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -5,14 +5,21 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
|
||||
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
|
||||
import { VENDOR_CREDIT_ROUTES, VendorCreditStatus } from "@garage/api"
|
||||
import type { VendorCreditsClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
export default function VendorCreditsPage() {
|
||||
return (
|
||||
<ResourcePage<VendorCreditsClient>
|
||||
pageTitle="Vendor Credits"
|
||||
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendor credits..."
|
||||
statusFilter={{ statuses: VendorCreditStatus }}
|
||||
getClient={(api) => api.vendorCredits}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
@@ -35,12 +42,30 @@ export default function VendorCreditsPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.bill?.id ? `/purchase/bill/${item.bill.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill?.bill_number || item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_credit_date",
|
||||
@@ -55,7 +80,7 @@ export default function VendorCreditsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return <Badge variant={status === "closed" ? "secondary" : "default"}>{status || "—"}</Badge>
|
||||
return <Badge variant={status === "closed" ? "secondary" : "default"}>{formatEnum(status)}</Badge>
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DashboardDetailsPage } from "@/base/components/layout/dashboard"
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorActions } from "@/modules/vendors/vendor-actions"
|
||||
import { VendorProvider } from "@/modules/vendors/vendor-context"
|
||||
import React from "react"
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
const company = vendor?.company_name as string | undefined
|
||||
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
|
||||
const title = company || fullName || "Vendor Details"
|
||||
const isActive = vendor?.is_active ?? vendor?.status === "active"
|
||||
|
||||
return (
|
||||
<VendorProvider vendor={{ id, label: title }}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={vendor?.email ?? vendor?.phone ?? undefined}
|
||||
backHref="/purchase/vendor"
|
||||
actions={<VendorActions vendorId={id} isActive={Boolean(isActive)} />}
|
||||
tabs={[
|
||||
{ href: `/purchase/vendor/${id}`, label: "Details" },
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</VendorProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorGeneralInfo } from "@/modules/vendors/vendor-general-info"
|
||||
|
||||
export default async function VendorDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
|
||||
// so cast through `any` here until the schema is regenerated.
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
if (!vendor) {
|
||||
return <div className="text-muted-foreground p-6">Vendor not found.</div>
|
||||
}
|
||||
|
||||
return <VendorGeneralInfo vendor={vendor} />
|
||||
}
|
||||
+42
-1
@@ -1,18 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { Power } from "lucide-react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { VendorForm } from "@/modules/vendors/vendor-form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { VENDOR_ROUTES } from "@garage/api"
|
||||
import type { VendorsClient } from "@garage/api"
|
||||
|
||||
export default function VendorsPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<VendorsClient>
|
||||
pageTitle="Vendors"
|
||||
routeKey={VENDOR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendors..."
|
||||
getClient={(api) => api.vendors}
|
||||
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Vendor">
|
||||
@@ -46,6 +56,18 @@ export default function VendorsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
|
||||
cell: ({ row }) => (row.original as any).email || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const isActive = Boolean((row.original as any).is_active)
|
||||
return (
|
||||
<Badge variant={isActive ? "default" : "outline"}>
|
||||
{isActive ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
@@ -54,7 +76,26 @@ export default function VendorsPage() {
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => {
|
||||
const isActive = Boolean((row as any).is_active)
|
||||
return [
|
||||
{
|
||||
label: isActive ? "Deactivate" : "Activate",
|
||||
icon: Power,
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
|
||||
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast.error("Failed to update vendor status.")
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -5,8 +5,11 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
|
||||
import { CREDIT_NOTE_ROUTES } from "@garage/api"
|
||||
import { CREDIT_NOTE_ROUTES, CreditNoteStatus } from "@garage/api"
|
||||
import type { CreditNotesClient } from "@garage/api"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { Printer } from "lucide-react"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
type CreditNoteItem = {
|
||||
id: number
|
||||
@@ -20,11 +23,15 @@ type CreditNoteItem = {
|
||||
|
||||
export default function CreditNotesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<CreditNotesClient>
|
||||
pageTitle="Credit Notes"
|
||||
routeKey={CREDIT_NOTE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search credit notes..."
|
||||
statusFilter={{ statuses: CreditNoteStatus }}
|
||||
getClient={(api) => api.creditNotes}
|
||||
onRowClick={(row) => router.push(`/sales/credit-notes/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -63,7 +70,7 @@ export default function CreditNotesPage() {
|
||||
}
|
||||
return (
|
||||
<span className={colorMap[status ?? ""] ?? ""}>
|
||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
||||
{formatEnum(status)}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
@@ -72,7 +79,15 @@ export default function CreditNotesPage() {
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("credit_note", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
|
||||
)}
|
||||
pageTitle="Customer Vehicles"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
extraParams={{ customer_id: customerId }}
|
||||
header={null}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import { CustomerForm } from '@/modules/customers/customer-form'
|
||||
import { CUSTOMER_ROUTES } from '@garage/api'
|
||||
@@ -20,18 +19,19 @@ export default function CustomersPage() {
|
||||
<ResourcePage<CustomersClient>
|
||||
pageTitle='Customers'
|
||||
routeKey={CUSTOMER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search customers..."
|
||||
getClient={(api) => api.customers}
|
||||
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className='flex items-center gap-2'>
|
||||
<DownloadSampleButton
|
||||
onDownload={() => api.customers.downloadImportSample()}
|
||||
fileName='customers-import-sample'
|
||||
/>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.customers.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Customers"
|
||||
onDownloadSample={() => api.customers.downloadImportSample()}
|
||||
sampleFileName='customers-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.customers.exportData(filters)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EstimateActions } from '@/modules/estimates/estimate-actions'
|
||||
import { EstimateProvider } from '@/modules/estimates/estimate-context'
|
||||
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
|
||||
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
@@ -40,6 +41,7 @@ export default async function layout(props: {
|
||||
<div className="flex items-center gap-2">
|
||||
<CreateInvoiceFromEstimateButton />
|
||||
<CreateJobCardFromEstimateButton />
|
||||
<ShareDocumentButton type="estimate" id={id} />
|
||||
<EstimateActions estimateId={id} />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,24 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
|
||||
import { Button } from '@/shared/components/ui/button'
|
||||
import { Car, FileTextIcon, Printer, UserIcon } from 'lucide-react'
|
||||
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||
import Link from 'next/link'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function EstimatesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
return (
|
||||
<ResourcePage<EstimatesClient>
|
||||
pageTitle="Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Estimate">
|
||||
@@ -39,7 +46,7 @@ export default function EstimatesPage() {
|
||||
const item = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
|
||||
<FileTextIcon className="text-muted-foreground h-4 w-4" />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
@@ -55,26 +62,30 @@ export default function EstimatesPage() {
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item:any = row.original
|
||||
const item: any = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{getFullName(item.customer) || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item :any= row.original
|
||||
return <Button variant="outline" asChild size="sm">
|
||||
<Link href={`/sales/vehicles/${item.vehicle?.id}`}>
|
||||
<Car/> {getVehicleLabel(item.vehicle as any) || "—"}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
const item: any = row.original
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item.vehicle as any)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
@@ -100,7 +111,15 @@ export default function EstimatesPage() {
|
||||
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("estimate", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionActions } from '@/modules/inspections/inspection-actions'
|
||||
import { InspectionProvider } from '@/modules/inspections/inspection-context'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import React from 'react'
|
||||
|
||||
export default async function layout(props: {
|
||||
@@ -23,7 +24,12 @@ export default async function layout(props: {
|
||||
title={title}
|
||||
description={orderNumber ? `Order: ${orderNumber}` : undefined}
|
||||
backHref="/sales/inspections"
|
||||
actions={<InspectionActions inspectionId={id} status={status} />}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<ShareDocumentButton type="inspection" id={id} />
|
||||
<InspectionActions inspectionId={id} status={status} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/inspections/${id}`,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
|
||||
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
@@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
return <div className="text-muted-foreground">Inspection not found.</div>
|
||||
}
|
||||
|
||||
const data = inspection.data as { title?: string }
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<InspectionDetailHeader inspectionId={id} title={data.title} />
|
||||
<InspectionGeneralInfo inspection={inspection.data} />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -1,46 +1,125 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
|
||||
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import Link from "next/link"
|
||||
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
const STATUS_BADGE_CLASS: Record<string, string> = {
|
||||
in_progress: "bg-amber-100 text-amber-800",
|
||||
completed: "bg-emerald-100 text-emerald-800",
|
||||
cancelled: "bg-rose-100 text-rose-800",
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
in_progress: "In Progress",
|
||||
completed: "Completed",
|
||||
cancelled: "Cancelled",
|
||||
}
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<ResourcePage<InspectionsClient>
|
||||
pageTitle="Inspections"
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inspection">
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/settings/inspection-templates">
|
||||
<ListChecks className="size-4" />
|
||||
Manage templates
|
||||
</Link>
|
||||
</Button>
|
||||
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
|
||||
<ClipboardList className="size-4" />
|
||||
New from template
|
||||
</Button>
|
||||
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
|
||||
<DialogContent className="min-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">
|
||||
New inspection from template
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<InspectionFromTemplateForm
|
||||
onSuccess={(id) => {
|
||||
setFromTemplateOpen(false)
|
||||
invalidateQuery()
|
||||
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
columns={({ openEdit, deleteItem }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{r.title ?? "—"}</span>
|
||||
{r.order_number && (
|
||||
<span className="text-xs text-muted-foreground">{r.order_number}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -48,27 +127,51 @@ export default function InspectionsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inspection_category",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
|
||||
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
|
||||
cell: ({ row }) => {
|
||||
const ic = (row.original as any).inspection_category
|
||||
return ic?.inspection_name ?? ic?.name ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
const status = (row.original as any).status as string | undefined
|
||||
if (!status) return "—"
|
||||
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
|
||||
return (
|
||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
||||
{status ?? "—"}
|
||||
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
|
||||
{STATUS_LABEL[status] ?? status}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<InspectionRowActions
|
||||
inspection={row.original as any}
|
||||
onEdit={() => openEdit(row.original as any)}
|
||||
onDelete={() => deleteItem(String((row.original as any).id))}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { InvoiceProvider } from '@/modules/invoices/invoice-context'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
|
||||
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||
const { id } = await props.params
|
||||
@@ -24,6 +25,7 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
|
||||
<div className="flex space-x-2 items-center">
|
||||
|
||||
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
|
||||
<ShareDocumentButton type="invoice" id={id} />
|
||||
<InvoiceActions invoiceId={id} />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
"use client"
|
||||
|
||||
import { Car, Printer, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InvoiceForm } from "@/modules/invoices/invoice-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { INVOICE_ROUTES } from "@garage/api"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
|
||||
import type { InvoicesClient } from "@garage/api"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
type InvoiceItem = {
|
||||
id: number
|
||||
@@ -23,6 +27,7 @@ type InvoiceItem = {
|
||||
total?: number | string
|
||||
balance_due?: number | string
|
||||
customer?: {
|
||||
id?: number | string
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
company_name?: string
|
||||
@@ -77,11 +82,15 @@ function getDueMeta(dueDate?: string) {
|
||||
|
||||
export default function InvoicesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<InvoicesClient>
|
||||
pageTitle="Invoices"
|
||||
routeKey={INVOICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search invoices..."
|
||||
statusFilter={{ statuses: InvoiceStatus }}
|
||||
getClient={(api) => api.invoices}
|
||||
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -133,15 +142,13 @@ export default function InvoicesPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const customerLabel = getCustomerLabel(item)
|
||||
|
||||
return (
|
||||
<div className="min-w-[190px]">
|
||||
<p className="font-medium leading-none">{customerLabel}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{item.customer?.phone || item.customer?.company_name || "—"}
|
||||
</p>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getCustomerLabel(item)}
|
||||
meta={item.customer?.phone}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -150,14 +157,14 @@ export default function InvoicesPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
const vehicleId = (item.vehicle as any)?.id
|
||||
return (
|
||||
<div className="min-w-[220px]">
|
||||
<p className="font-medium leading-none">{getVehicleLabel(item)}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{item.vehicle?.license_plate || "—"}
|
||||
</p>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -224,16 +231,24 @@ export default function InvoicesPage() {
|
||||
return (
|
||||
<div className="min-w-[150px]">
|
||||
<p className="font-medium leading-none">
|
||||
Total: {formatCurrency(item.total ?? 0)}
|
||||
Total: {<Money value={item.total ?? 0} />}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Due: {formatCurrency(item.balance_due ?? 0)}
|
||||
Due: {<Money value={item.balance_due ?? 0} />}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("invoice", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -7,11 +7,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -42,13 +45,34 @@ export default function JobCardAppointmentsPage({
|
||||
router.replace(`${pathname}?${params.toString()}`)
|
||||
}, [pathname, router, searchParams])
|
||||
|
||||
const defaultJobCard = jobCard
|
||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
||||
const jc = jobCard as any
|
||||
const defaultJobCard = jc
|
||||
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
|
||||
: null
|
||||
|
||||
const appointmentDefaults = jc
|
||||
? {
|
||||
job_card_id: jc.id,
|
||||
job_card_title: jc.title || `Job Card #${jc.id}`,
|
||||
customer_id: jc.customer?.id,
|
||||
customer_name: getFullName(jc.customer),
|
||||
vehicle_id: jc.vehicle?.id,
|
||||
vehicle_name: getVehicleLabel(jc.vehicle),
|
||||
service_writer_id: jc.service_writer?.id,
|
||||
service_writer_name: getFullName(jc.service_writer),
|
||||
technician_id: jc.primary_technician?.id,
|
||||
technician_name: getFullName(jc.primary_technician),
|
||||
department_id: jc.department?.id,
|
||||
department_name: jc.department?.name,
|
||||
}
|
||||
: { job_card: defaultJobCard }
|
||||
|
||||
return (
|
||||
<ResourcePage<AppointmentsClient>
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -59,8 +83,8 @@ export default function JobCardAppointmentsPage({
|
||||
{(resourceId) => (
|
||||
<AppointmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
||||
initialData={selectedItem ?? appointmentDefaults}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -102,7 +126,7 @@ export default function JobCardAppointmentsPage({
|
||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||
return (
|
||||
<Badge className={colorClass}>
|
||||
{status?.replace("_", " ") ?? "—"}
|
||||
{formatEnum(status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { CONSTANTS } from "@/config/constants"
|
||||
@@ -22,6 +22,62 @@ function getFileIcon(mimeType?: string) {
|
||||
return FileIcon
|
||||
}
|
||||
|
||||
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
|
||||
|
||||
function describeAttachmentError(rawMessage: string, filename: string): string {
|
||||
const msg = rawMessage.toLowerCase()
|
||||
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
|
||||
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
|
||||
}
|
||||
if (msg.includes("may not be greater") || msg.includes("max")) {
|
||||
return `${filename}: exceeds 5 MB limit.`
|
||||
}
|
||||
if (msg.includes("must be a file")) {
|
||||
return `${filename}: invalid file.`
|
||||
}
|
||||
return `${filename}: ${rawMessage}`
|
||||
}
|
||||
|
||||
function showUploadError(err: unknown, files: File[]) {
|
||||
if (!(err instanceof ApiError)) {
|
||||
toast.error("Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const validation = err.validationErrors
|
||||
if (!validation || Object.keys(validation).length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const messages: string[] = []
|
||||
for (const [key, msgs] of Object.entries(validation)) {
|
||||
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
|
||||
if (!firstMsg) continue
|
||||
|
||||
const match = key.match(/^attachments\.(\d+)$/)
|
||||
if (match) {
|
||||
const idx = Number(match[1])
|
||||
const filename = files[idx]?.name ?? `File #${idx + 1}`
|
||||
messages.push(describeAttachmentError(firstMsg, filename))
|
||||
} else if (key === "attachments") {
|
||||
messages.push(firstMsg)
|
||||
} else {
|
||||
messages.push(firstMsg)
|
||||
}
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const shown = messages.slice(0, 3)
|
||||
const extra = messages.length - shown.length
|
||||
shown.forEach((m) => toast.error(m))
|
||||
if (extra > 0) toast.error(`...and ${extra} more`)
|
||||
}
|
||||
|
||||
export default function JobCardAttachmentsPage() {
|
||||
const { id: jobCardId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
@@ -66,18 +122,19 @@ export default function JobCardAttachmentsPage() {
|
||||
const files = e.target.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const fileList = Array.from(files)
|
||||
setIsUploading(true)
|
||||
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment(s)...",
|
||||
success: "Attachment(s) uploaded successfully",
|
||||
error: "Failed to upload attachment(s)",
|
||||
})
|
||||
const loadingToast = toast.loading("Uploading attachment(s)...")
|
||||
|
||||
try {
|
||||
await promise
|
||||
await api.jobCards.addAttachment(jobCardId, fileList)
|
||||
toast.dismiss(loadingToast)
|
||||
toast.success("Attachment(s) uploaded successfully")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
startRefreshTransition(() => router.refresh())
|
||||
} catch (err) {
|
||||
toast.dismiss(loadingToast)
|
||||
showUploadError(err, fileList)
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) {
|
||||
|
||||
@@ -6,9 +6,13 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
export default function JobCardBillsPage({
|
||||
params,
|
||||
@@ -25,6 +29,9 @@ export default function JobCardBillsPage({
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +53,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/bill/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +71,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
@@ -78,7 +103,7 @@ export default function JobCardBillsPage({
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{formatEnum(status)}</Badge>
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
|
||||
@@ -44,6 +44,7 @@ export default function JobCardExpenseItemsPage({
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
@@ -4,10 +4,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Car, UserIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
@@ -17,6 +21,9 @@ export default function InspectionsPage() {
|
||||
pageTitle="Inspections"
|
||||
extraParams={{job_card_id: jobCard?.id}}
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -42,7 +49,13 @@ export default function InspectionsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -50,7 +63,14 @@ export default function InspectionsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -16,7 +16,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
|
||||
const title = jobCard?.title || 'Job Card Details'
|
||||
const status = jobCard?.status || 'draft'
|
||||
const docs = jobCard?.documents
|
||||
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
|
||||
|
||||
return (
|
||||
<JobCardProvider jobCard={{ ...jobCard }}>
|
||||
@@ -55,7 +55,7 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
// TODO: Needs refactor from API side then refactor in frontend
|
||||
{
|
||||
href: `/sales/job-cards/${id}/attachments`,
|
||||
label: `Attachments (${docs?.length || 0})`
|
||||
label: `Attachments (${attachmentsCount})`
|
||||
},
|
||||
|
||||
{
|
||||
|
||||
@@ -1,21 +1,10 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import type { JobCardShowData } from '@garage/api'
|
||||
|
||||
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = await api.jobCards.show(id)
|
||||
const data = response.data
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Job card not found.</div>
|
||||
}
|
||||
|
||||
export default async function JobCardDetailPage() {
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<JobCardGeneralInfo jobCard={data} />
|
||||
<JobCardGeneralInfo />
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ export default function JobCardPartsPage({
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getParts(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
@@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function JobCardPurchaseOrdersPage({
|
||||
params,
|
||||
@@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
|
||||
cell: ({ row }) => (row.original as any).order_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/purchase-order/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.order_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
|
||||
@@ -46,6 +46,7 @@ export default function JobCardServicesPage({
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getServices(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
@@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
|
||||
@@ -6,12 +6,10 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { JobCardForm } from '@/modules/job-cards/job-card-form'
|
||||
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
|
||||
import type { JobCardsClient } from '@garage/api'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
|
||||
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
|
||||
import { ClipboardListIcon, Printer } from 'lucide-react'
|
||||
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||
import { Badge } from '@/shared/components/ui/badge'
|
||||
import { Input } from '@/shared/components/ui/input'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
|
||||
import { useFilterParams } from '@/shared/hooks/use-filter-params'
|
||||
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
|
||||
@@ -37,30 +35,18 @@ const statusColorMap: Record<string, string> = {
|
||||
|
||||
export default function JobCardsPage() {
|
||||
const router = useRouter()
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<string>("check_in")
|
||||
|
||||
const filter = useFilterParams(jobCardFilterConfig)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearch(searchInput), 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
const extraParams = useMemo(() => {
|
||||
const params: Record<string, unknown> = { ...filter.appliedParams }
|
||||
if (search) params.search = search
|
||||
if (statusFilter !== "all") params.status = statusFilter
|
||||
return params
|
||||
}, [filter.appliedParams, search, statusFilter])
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourcePage<JobCardsClient>
|
||||
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||
getClient={(api) => api.jobCards}
|
||||
extraParams={extraParams}
|
||||
searchable
|
||||
searchPlaceholder="Search job cards..."
|
||||
statusFilter={{ statuses: JobCardStatus }}
|
||||
extraParams={filter.appliedParams}
|
||||
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Job Cards",
|
||||
@@ -133,32 +119,16 @@ export default function JobCardsPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("job_card", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
|
||||
tableHeader={
|
||||
<div className="flex justify-between">
|
||||
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="all">All</TabsTrigger>
|
||||
{JobCardStatus.map((status) => (
|
||||
<TabsTrigger key={status} value={status}>
|
||||
{formatEnum(status)}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search job cards..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<FilterDrawer
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { PaymentReceivedActions } from '@/modules/payment-received/payment-received-actions'
|
||||
import { BanknoteIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function PaymentReceivedDetailLayout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const payment = await api.paymentReceived.show(id)
|
||||
const data = (payment as any)?.data ?? payment
|
||||
const title = data?.payment_number || 'Payment Details'
|
||||
|
||||
return (
|
||||
<DashboardDetailsPage
|
||||
title={title}
|
||||
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
|
||||
icon={<BanknoteIcon className="size-5" />}
|
||||
backHref="/sales/payment-received"
|
||||
actions={<PaymentReceivedActions paymentId={id} />}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/payment-received/${id}`,
|
||||
label: 'Details',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import {
|
||||
BadgeDollarSignIcon,
|
||||
CalendarIcon,
|
||||
ClipboardListIcon,
|
||||
CreditCardIcon,
|
||||
HashIcon,
|
||||
UserIcon,
|
||||
} from 'lucide-react'
|
||||
|
||||
export default async function PaymentReceivedDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const payment = await api.paymentReceived.show(id)
|
||||
const data = (payment as any)?.data ?? payment
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Payment not found.</div>
|
||||
}
|
||||
|
||||
const amount = data.amount_received != null
|
||||
? Number(data.amount_received).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
: '—'
|
||||
|
||||
const paymentDate = data.payment_date
|
||||
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
|
||||
: '—'
|
||||
|
||||
const customerName = data.customer?.first_name
|
||||
? `${data.customer.first_name} ${data.customer.last_name ?? ''}`.trim()
|
||||
: data.customer?.company_name ?? data.customer_name ?? '—'
|
||||
|
||||
const jobCardLabel = data.job_card?.title ?? data.job_card_name ?? '—'
|
||||
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<HashIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Number</p>
|
||||
<p className="font-medium">{data.payment_number || '—'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<UserIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Customer</p>
|
||||
<p className="font-medium">{customerName}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<ClipboardListIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Job Card</p>
|
||||
<p className="font-medium">{jobCardLabel}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Amount Received</p>
|
||||
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Mode</p>
|
||||
<p className="font-medium capitalize">{paymentMode}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||
<CalendarIcon className="size-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">Payment Date</p>
|
||||
<p className="font-medium">{paymentDate}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.note && (
|
||||
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
|
||||
<p className="text-xs text-muted-foreground mb-1">Note</p>
|
||||
<p className="text-sm">{data.note}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -10,10 +10,14 @@ import {
|
||||
CalendarIcon,
|
||||
CreditCardIcon,
|
||||
HashIcon,
|
||||
Printer,
|
||||
UserIcon,
|
||||
ClipboardListIcon,
|
||||
} from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
type PaymentReceivedItem = {
|
||||
id: number
|
||||
@@ -30,13 +34,19 @@ type PaymentReceivedItem = {
|
||||
}
|
||||
|
||||
export default function PaymentReceivedPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
|
||||
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => ({
|
||||
list: (query?: any) => api.paymentReceived.list(query),
|
||||
destroy: (id: string) => api.paymentReceived.destroy(id),
|
||||
})}
|
||||
onRowClick={(row) => router.push(`/sales/payment-received/${(row as any).id}`)}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Record Payment">
|
||||
@@ -65,14 +75,17 @@ export default function PaymentReceivedPage() {
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item:any = row.original as unknown as PaymentReceivedItem
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const customer = item.customer
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{getFullName(item.customer) || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -80,13 +93,14 @@ export default function PaymentReceivedPage() {
|
||||
accessorKey: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const item:any = row.original as unknown as PaymentReceivedItem
|
||||
const label = item.job_card?.title
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const jobCard = item.job_card
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{label || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={jobCard?.title || item.job_card_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -159,7 +173,15 @@ export default function PaymentReceivedPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("payment_received", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import { FileTextIcon, UserIcon } from 'lucide-react'
|
||||
import { useVehicle } from '@/modules/vehicles/vehicle-context'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
|
||||
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: vehicleId } = use(params)
|
||||
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
}
|
||||
pageTitle="Vehicle Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
extraParams={{ vehicle_id: vehicleId }}
|
||||
header={
|
||||
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
|
||||
@@ -7,14 +7,14 @@ import type { ColumnDef } from '@tanstack/react-table'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
|
||||
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
|
||||
import { VEHICLE_ROUTES } from '@garage/api'
|
||||
import type { VehiclesClient } from '@garage/api'
|
||||
import { CarIcon } from 'lucide-react'
|
||||
import { CarIcon, UserIcon } from 'lucide-react'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function VehiclesPage() {
|
||||
const router = useRouter()
|
||||
@@ -23,18 +23,19 @@ export default function VehiclesPage() {
|
||||
<ResourcePage<VehiclesClient>
|
||||
pageTitle="Vehicles"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className='flex items-center gap-2'>
|
||||
<DownloadSampleButton
|
||||
onDownload={() => api.vehicles.downloadImportSample()}
|
||||
fileName='vehicles-import-sample'
|
||||
/>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.vehicles.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Vehicles"
|
||||
onDownloadSample={() => api.vehicles.downloadImportSample()}
|
||||
sampleFileName='vehicles-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.vehicles.exportData(filters)}
|
||||
@@ -80,8 +81,14 @@ export default function VehiclesPage() {
|
||||
accessorKey: "customers",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }: any) => {
|
||||
const val = (row.original as any).customers?.[0]
|
||||
return getFullName(val)
|
||||
const customer = (row.original as any).customers?.[0]
|
||||
return (
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
} as any,
|
||||
{
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
|
||||
<ResourcePage<DepartmentsClient>
|
||||
pageTitle="Departments"
|
||||
routeKey={DEPARTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search departments..."
|
||||
getClient={(api) => api.departments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Switch } from "@/shared/components/ui/switch"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { prompt } from "@/shared/components/prompt-dialog"
|
||||
import { TemplateCheckpointEditDialog } from "@/modules/inspections/template-checkpoint-edit-dialog"
|
||||
import type {
|
||||
InspectionTemplate,
|
||||
InspectionTemplateSection,
|
||||
InspectionTemplateCheckPoint,
|
||||
InspectionSeverity,
|
||||
} from "@garage/api"
|
||||
|
||||
const SEVERITY_BADGE: Record<InspectionSeverity, { label: string; cls: string }> = {
|
||||
good: { label: "Good", cls: "bg-emerald-100 text-emerald-800" },
|
||||
attention: { label: "Attention", cls: "bg-amber-100 text-amber-800" },
|
||||
critical: { label: "Critical", cls: "bg-rose-100 text-rose-800" },
|
||||
na: { label: "N/A", cls: "bg-slate-100 text-slate-700" },
|
||||
not_inspected: { label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
|
||||
}
|
||||
|
||||
const RECORD_TYPE_LABEL: Record<string, string> = {
|
||||
capture_photo: "Photo",
|
||||
record_video: "Video",
|
||||
record_audio: "Audio",
|
||||
record_conditions: "0–100",
|
||||
wire_frame: "Wireframe",
|
||||
none: "No media",
|
||||
}
|
||||
|
||||
export default function InspectionTemplateEditorPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const [editing, setEditing] = useState<{
|
||||
section: InspectionTemplateSection
|
||||
checkpoint: InspectionTemplateCheckPoint | null
|
||||
} | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.show(id)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load template")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const updateMeta = async (partial: Partial<InspectionTemplate>) => {
|
||||
if (!template) return
|
||||
try {
|
||||
const res = await api.inspectionTemplates.update(template.id, partial)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to save")
|
||||
}
|
||||
}
|
||||
|
||||
const addSection = async () => {
|
||||
if (!template) return
|
||||
const name = await prompt({
|
||||
title: "New section",
|
||||
label: "Section name",
|
||||
placeholder: "e.g. Brakes",
|
||||
confirmLabel: "Add section",
|
||||
})
|
||||
if (!name) return
|
||||
const nextOrder = (template.sections?.length ?? 0) + 1
|
||||
try {
|
||||
await api.inspectionTemplates.createSection(template.id, { name, sort_order: nextOrder })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to add section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteSection = async (section: InspectionTemplateSection) => {
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete section "${section.name}"?`,
|
||||
description: "This will remove the section and all its checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroySection(template.id, section.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete section")
|
||||
}
|
||||
}
|
||||
|
||||
const renameSection = async (section: InspectionTemplateSection, name: string) => {
|
||||
if (!template || name === section.name) return
|
||||
try {
|
||||
await api.inspectionTemplates.updateSection(template.id, section.id, { name })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to rename section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCheckpoint = async (section: InspectionTemplateSection, cp: InspectionTemplateCheckPoint, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${cp.name}"?`,
|
||||
description: "This checkpoint will be removed from the template.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroyCheckpoint(template.id, section.id, cp.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete checkpoint")
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="p-6 text-muted-foreground">Loading…</div>
|
||||
if (!template) return <div className="p-6 text-muted-foreground">Template not found</div>
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-4xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="/settings/inspection-templates">
|
||||
<Button variant="ghost" size="sm"><ChevronLeft className="size-4 mr-1" /> Back</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="rounded border p-4 space-y-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Name</label>
|
||||
<Input
|
||||
defaultValue={template.name}
|
||||
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<Switch
|
||||
checked={template.is_active}
|
||||
onCheckedChange={(checked) => updateMeta({ is_active: checked })}
|
||||
/>
|
||||
<span className="text-sm">{template.is_active ? "Active" : "Inactive"}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Description</label>
|
||||
<Textarea
|
||||
defaultValue={template.description ?? ""}
|
||||
rows={2}
|
||||
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">Sections & Checkpoints</h2>
|
||||
<Button onClick={addSection} size="sm"><Plus className="size-4 mr-1" /> Add section</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{(template.sections ?? []).length === 0 && (
|
||||
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
|
||||
No sections yet. Add one to start building the checklist.
|
||||
</div>
|
||||
)}
|
||||
{(template.sections ?? []).map((section) => (
|
||||
<div key={section.id} className="rounded border">
|
||||
<div className="flex items-center gap-2 px-3 py-2 bg-muted/40">
|
||||
<Input
|
||||
defaultValue={section.name}
|
||||
onBlur={(e) => renameSection(section, e.currentTarget.value)}
|
||||
className="max-w-md h-8"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(section.check_points ?? []).length} checkpoint{(section.check_points ?? []).length === 1 ? "" : "s"}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button size="sm" variant="ghost" onClick={() => setEditing({ section, checkpoint: null })}>
|
||||
<Plus className="size-4 mr-1" /> Checkpoint
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => deleteSection(section)}>
|
||||
<Trash2 className="size-4 text-red-600" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{(section.check_points ?? []).length === 0 && (
|
||||
<div className="p-3 text-sm text-muted-foreground">No checkpoints in this section.</div>
|
||||
)}
|
||||
{(section.check_points ?? []).map((cp) => {
|
||||
const sev = SEVERITY_BADGE[cp.severity_default] ?? SEVERITY_BADGE.not_inspected
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={cp.id}
|
||||
onClick={() => setEditing({ section, checkpoint: cp })}
|
||||
className="w-full text-left flex items-center gap-3 px-3 py-2 hover:bg-muted/30 transition"
|
||||
>
|
||||
<span className="text-xs text-muted-foreground w-6 text-right">
|
||||
{cp.sort_order}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0 truncate text-sm font-medium">
|
||||
{cp.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground hidden sm:inline-block">
|
||||
{RECORD_TYPE_LABEL[cp.record_type] ?? cp.record_type}
|
||||
</span>
|
||||
<span className={`text-xs rounded-full px-2 py-0.5 ${sev.cls}`}>
|
||||
{sev.label}
|
||||
</span>
|
||||
<Pencil className="size-3.5 text-muted-foreground" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => deleteCheckpoint(section, cp, e)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
aria-label="Delete checkpoint"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<TemplateCheckpointEditDialog
|
||||
open={!!editing}
|
||||
onOpenChange={(o) => { if (!o) setEditing(null) }}
|
||||
templateId={template.id}
|
||||
sectionId={editing.section.id}
|
||||
checkpoint={editing.checkpoint}
|
||||
nextSortOrder={(editing.section.check_points?.length ?? 0) + 1}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { Copy, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import type { InspectionTemplate } from "@garage/api"
|
||||
|
||||
export default function InspectionTemplatesPage() {
|
||||
const api = useAuthApi()
|
||||
const [items, setItems] = useState<InspectionTemplate[]>([])
|
||||
const [search, setSearch] = useState("")
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState("")
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.list(search ? { search } : undefined)
|
||||
setItems(res.data ?? [])
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load templates")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim()) return
|
||||
try {
|
||||
await api.inspectionTemplates.create({ name: newName.trim(), is_active: true })
|
||||
setNewName("")
|
||||
setCreating(false)
|
||||
toast.success("Template created")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to create template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDuplicate = async (id: number) => {
|
||||
try {
|
||||
await api.inspectionTemplates.duplicate(id)
|
||||
toast.success("Template duplicated")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to duplicate template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, name: string) => {
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${name}"?`,
|
||||
description: "This will remove the template and all its sections / checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroy(id)
|
||||
toast.success("Template deleted")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete template")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h1 className="text-2xl font-semibold">Inspection Templates</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && load()}
|
||||
className="w-56"
|
||||
/>
|
||||
<Button onClick={() => setCreating((c) => !c)}>
|
||||
<Plus className="size-4 mr-1" /> New template
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{creating && (
|
||||
<div className="flex items-center gap-2 rounded border p-3">
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder="Template name (e.g. Annual Safety)"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
|
||||
className="max-w-md"
|
||||
/>
|
||||
<Button onClick={handleCreate}>Create</Button>
|
||||
<Button variant="ghost" onClick={() => { setCreating(false); setNewName("") }}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted">
|
||||
<tr>
|
||||
<th className="text-left p-3">Name</th>
|
||||
<th className="text-left p-3">Sections</th>
|
||||
<th className="text-left p-3">Checkpoints</th>
|
||||
<th className="text-left p-3">Status</th>
|
||||
<th className="text-right p-3">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading…</td></tr>
|
||||
)}
|
||||
{!loading && items.length === 0 && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No templates yet</td></tr>
|
||||
)}
|
||||
{!loading && items.map((t) => {
|
||||
const sectionCount = t.sections?.length ?? 0
|
||||
const cpCount = (t.sections ?? []).reduce((sum, s) => sum + (s.check_points?.length ?? 0), 0)
|
||||
return (
|
||||
<tr key={t.id} className="border-t hover:bg-muted/40">
|
||||
<td className="p-3 font-medium">{t.name}</td>
|
||||
<td className="p-3">{sectionCount}</td>
|
||||
<td className="p-3">{cpCount}</td>
|
||||
<td className="p-3">
|
||||
<span className={`inline-block rounded-full px-2 py-0.5 text-xs ${t.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}>
|
||||
{t.is_active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="p-3 text-right space-x-1">
|
||||
<Link href={`/settings/inspection-templates/${t.id}`}>
|
||||
<Button size="sm" variant="ghost"><Pencil className="size-4" /></Button>
|
||||
</Link>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDuplicate(t.id)}><Copy className="size-4" /></Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDelete(t.id, t.name)}><Trash2 className="size-4 text-red-600" /></Button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export default function InsuranceTypesPage() {
|
||||
<ResourcePage<InsuranceTypesClient>
|
||||
pageTitle="Insurance Types"
|
||||
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search insurance types..."
|
||||
getClient={(api) => api.insuranceTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -12,6 +12,8 @@ export default function MakeAndModelsPage() {
|
||||
<ResourcePage<MakeAndModelsClient>
|
||||
pageTitle="Make & Models"
|
||||
routeKey={MAKE_AND_MODEL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search makes & models..."
|
||||
getClient={(api) => api.makeAndModels}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ShopTypesPage() {
|
||||
<ResourcePage<ShopTypesClient>
|
||||
pageTitle="Shop Types"
|
||||
routeKey={SHOP_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop types..."
|
||||
getClient={(api) => api.shopTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function TaxesPage() {
|
||||
<ResourcePage<TaxesClient>
|
||||
pageTitle="Tax & Rates"
|
||||
routeKey={TAX_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tax rates..."
|
||||
getClient={(api) => api.taxes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import {
|
||||
AlertCircle,
|
||||
Calendar,
|
||||
Car,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Gauge,
|
||||
Loader2,
|
||||
Printer,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
|
||||
type Severity = "good" | "attention" | "critical" | "na" | "not_inspected"
|
||||
|
||||
type Photo = { id: number; url: string | null; caption?: string | null }
|
||||
|
||||
type CheckPoint = {
|
||||
name: string
|
||||
description?: string | null
|
||||
severity: Severity
|
||||
technician_notes?: string | null
|
||||
condition_rate?: number | null
|
||||
photos?: Photo[]
|
||||
}
|
||||
|
||||
type Section = { name: string; items: CheckPoint[] }
|
||||
|
||||
type PublicInspection = {
|
||||
title?: string
|
||||
order_number?: string
|
||||
date?: string
|
||||
time?: string
|
||||
status?: string
|
||||
odometer?: number | null
|
||||
note?: string | null
|
||||
description?: string | null
|
||||
customer?: { name?: string } | null
|
||||
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string; vin?: string } | null
|
||||
technician?: { name?: string } | null
|
||||
department?: string | null
|
||||
template?: string | null
|
||||
totals: { good: number; attention: number; critical: number; na: number; not_inspected: number; considered: number; all: number }
|
||||
score: number | null
|
||||
sections: Section[]
|
||||
share_expires_at?: string | null
|
||||
}
|
||||
|
||||
const SEVERITY_LABEL: Record<Severity, string> = {
|
||||
good: "Good",
|
||||
attention: "Attention",
|
||||
critical: "Critical",
|
||||
na: "N/A",
|
||||
not_inspected: "Not Inspected",
|
||||
}
|
||||
|
||||
const SEVERITY_DOT_BG: Record<Severity, string> = {
|
||||
good: "bg-emerald-500",
|
||||
attention: "bg-amber-500",
|
||||
critical: "bg-rose-500",
|
||||
na: "bg-slate-400",
|
||||
not_inspected: "bg-gray-300",
|
||||
}
|
||||
|
||||
const SEVERITY_PILL: Record<Severity, string> = {
|
||||
good: "bg-emerald-50 text-emerald-700 border-emerald-200",
|
||||
attention: "bg-amber-50 text-amber-800 border-amber-200",
|
||||
critical: "bg-rose-50 text-rose-700 border-rose-200",
|
||||
na: "bg-slate-50 text-slate-700 border-slate-200",
|
||||
not_inspected: "bg-gray-50 text-gray-600 border-gray-200",
|
||||
}
|
||||
|
||||
const SEVERITY_BORDER: Record<Severity, string> = {
|
||||
good: "border-l-emerald-500",
|
||||
attention: "border-l-amber-500",
|
||||
critical: "border-l-rose-500",
|
||||
na: "border-l-slate-400",
|
||||
not_inspected: "border-l-gray-300",
|
||||
}
|
||||
|
||||
function ScoreRing({ score }: { score: number | null }) {
|
||||
if (score === null) {
|
||||
return (
|
||||
<div className="size-32 rounded-full border-4 border-dashed border-muted-foreground/30 flex items-center justify-center text-xs text-muted-foreground">
|
||||
Not scored
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const color =
|
||||
score >= 80 ? "text-emerald-600" : score >= 50 ? "text-amber-600" : "text-rose-600"
|
||||
const stroke =
|
||||
score >= 80 ? "stroke-emerald-500" : score >= 50 ? "stroke-amber-500" : "stroke-rose-500"
|
||||
const r = 56
|
||||
const c = 2 * Math.PI * r
|
||||
const offset = c - (score / 100) * c
|
||||
|
||||
return (
|
||||
<div className="relative size-32 shrink-0">
|
||||
<svg viewBox="0 0 128 128" className="size-32 -rotate-90">
|
||||
<circle cx="64" cy="64" r={r} className="fill-none stroke-muted" strokeWidth="10" />
|
||||
<circle
|
||||
cx="64"
|
||||
cy="64"
|
||||
r={r}
|
||||
className={`fill-none ${stroke} transition-[stroke-dashoffset]`}
|
||||
strokeWidth="10"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={c}
|
||||
strokeDashoffset={offset}
|
||||
/>
|
||||
</svg>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center">
|
||||
<div className={`text-3xl font-bold leading-none ${color}`}>{score}</div>
|
||||
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mt-1">
|
||||
Health
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PublicInspectionPage() {
|
||||
const params = useParams<{ token: string }>()
|
||||
const token = params.token
|
||||
const [data, setData] = useState<PublicInspection | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [lightbox, setLightbox] = useState<Photo | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const base = process.env.NEXT_PUBLIC_API_URL ?? ""
|
||||
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}`, {
|
||||
headers: { Accept: "application/json", "X-Lang": "en" },
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({} as any))
|
||||
throw new Error(body.message ?? `Failed (HTTP ${res.status})`)
|
||||
}
|
||||
return res.json()
|
||||
})
|
||||
.then((json: { data: PublicInspection }) => setData(json.data))
|
||||
.catch((e: Error) => setError(e.message))
|
||||
.finally(() => setLoading(false))
|
||||
}, [token])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading inspection…
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
|
||||
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
|
||||
<AlertCircle className="size-12 mx-auto text-rose-500" />
|
||||
<h1 className="text-lg font-semibold">Can't open this inspection</h1>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!data) return null
|
||||
|
||||
const vehicleLine = data.vehicle
|
||||
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
|
||||
: "—"
|
||||
|
||||
const criticalCount = data.totals.critical
|
||||
const attentionCount = data.totals.attention
|
||||
const headlineStatus =
|
||||
criticalCount > 0
|
||||
? { Icon: ShieldAlert, color: "text-rose-600", bg: "bg-rose-50", label: `${criticalCount} critical issue${criticalCount === 1 ? "" : "s"} found` }
|
||||
: attentionCount > 0
|
||||
? { Icon: AlertCircle, color: "text-amber-600", bg: "bg-amber-50", label: `${attentionCount} item${attentionCount === 1 ? "" : "s"} need attention` }
|
||||
: { Icon: ShieldCheck, color: "text-emerald-600", bg: "bg-emerald-50", label: "No issues found" }
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
|
||||
{/* Print is handled by downloading the backend-generated PDF
|
||||
(see the Print button), so this page no longer needs print CSS. */}
|
||||
|
||||
{/* Print bar */}
|
||||
<div className="no-print bg-white/80 backdrop-blur border-b sticky top-0 z-10">
|
||||
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<ClipboardList className="size-4" />
|
||||
<span className="font-medium text-foreground">Inspection report</span>
|
||||
</div>
|
||||
<a
|
||||
href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition"
|
||||
>
|
||||
<Printer className="size-3.5" /> Print PDF
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-5">
|
||||
{/* Hero card */}
|
||||
<div className="rounded-2xl bg-white shadow-sm border overflow-hidden">
|
||||
<div className="p-6 sm:p-8">
|
||||
<div className="flex items-start justify-between gap-6 flex-wrap">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs uppercase tracking-wider text-muted-foreground">
|
||||
Vehicle inspection report
|
||||
</div>
|
||||
<h1 className="mt-1 text-2xl sm:text-3xl font-bold tracking-tight">{data.title ?? "Inspection"}</h1>
|
||||
{data.order_number && (
|
||||
<div className="text-sm text-muted-foreground font-mono mt-1">#{data.order_number}</div>
|
||||
)}
|
||||
|
||||
<div className={`mt-4 inline-flex items-center gap-2 rounded-full ${headlineStatus.bg} px-4 py-1.5`}>
|
||||
<headlineStatus.Icon className={`size-4 ${headlineStatus.color}`} />
|
||||
<span className={`text-sm font-medium ${headlineStatus.color}`}>
|
||||
{headlineStatus.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<ScoreRing score={data.score} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t bg-gray-50/60 px-6 sm:px-8 py-4">
|
||||
<div className="info-grid grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
|
||||
<InfoCell icon={User} label="Customer" value={data.customer?.name ?? "—"} />
|
||||
<InfoCell icon={Car} label="Vehicle" value={vehicleLine} subtitle={data.vehicle?.license_plate ?? undefined} />
|
||||
<InfoCell icon={Calendar} label="Inspected" value={data.date ?? "—"} subtitle={data.time ?? undefined} />
|
||||
<InfoCell icon={Gauge} label="Odometer" value={data.odometer != null ? `${Number(data.odometer).toLocaleString()} km` : "—"} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Severity summary */}
|
||||
<div className="totals-grid grid grid-cols-2 sm:grid-cols-5 gap-2 pb-avoid">
|
||||
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
|
||||
<div
|
||||
key={s}
|
||||
className={`rounded-xl border px-3 py-3 text-center ${SEVERITY_PILL[s]}`}
|
||||
>
|
||||
<div className="text-xl font-bold leading-none tabular-nums">{data.totals[s]}</div>
|
||||
<div className="text-[11px] font-medium mt-1.5">{SEVERITY_LABEL[s]}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sections */}
|
||||
{data.sections.length === 0 ? (
|
||||
<div className="rounded-2xl bg-white border p-8 text-center text-sm text-muted-foreground">
|
||||
This inspection has no recorded checkpoints yet.
|
||||
</div>
|
||||
) : (
|
||||
data.sections.map((section) => (
|
||||
<section key={section.name} className="rounded-2xl bg-white shadow-sm border overflow-hidden">
|
||||
<header className="px-5 sm:px-6 py-3 border-b flex items-center justify-between bg-gray-50/60">
|
||||
<h2 className="font-semibold text-sm sm:text-base">{section.name}</h2>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{section.items.length} {section.items.length === 1 ? "item" : "items"}
|
||||
</span>
|
||||
</header>
|
||||
<ul className="divide-y">
|
||||
{section.items.map((cp, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className={`cp-row pb-avoid px-5 sm:px-6 py-4 border-l-4 ${SEVERITY_BORDER[cp.severity]}`}
|
||||
>
|
||||
{/* Head: dot + name + severity pill (pill stays inline next to name) */}
|
||||
<div className="cp-head flex items-center gap-2">
|
||||
<span className={`size-2 rounded-full ${SEVERITY_DOT_BG[cp.severity]} shrink-0`} />
|
||||
<span className="font-medium text-sm flex-1 min-w-0 truncate">{cp.name}</span>
|
||||
<span className={`cp-pill inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium shrink-0 ${SEVERITY_PILL[cp.severity]}`}>
|
||||
{SEVERITY_LABEL[cp.severity]}
|
||||
</span>
|
||||
</div>
|
||||
<div className="cp-body ms-4">
|
||||
{cp.description && (
|
||||
<p className="text-xs text-muted-foreground mt-1">{cp.description}</p>
|
||||
)}
|
||||
{cp.technician_notes && (
|
||||
<p className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-foreground/80 italic border-l-2 border-muted-foreground/30">
|
||||
"{cp.technician_notes}"
|
||||
</p>
|
||||
)}
|
||||
{cp.condition_rate != null && (
|
||||
<div className="mt-2">
|
||||
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full transition-all ${cp.severity === "critical" ? "bg-rose-500" : cp.severity === "attention" ? "bg-amber-500" : "bg-emerald-500"}`}
|
||||
style={{ width: `${cp.condition_rate}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground mt-0.5 tabular-nums">{cp.condition_rate}%</div>
|
||||
</div>
|
||||
)}
|
||||
{cp.photos && cp.photos.length > 0 && (
|
||||
<div className="photo-grid mt-3 grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{cp.photos.map((p) => (
|
||||
p.url ? (
|
||||
<button
|
||||
type="button"
|
||||
key={p.id}
|
||||
onClick={() => setLightbox(p)}
|
||||
className="group relative rounded-lg overflow-hidden border bg-muted aspect-square focus:outline-none focus:ring-2 focus:ring-primary/40"
|
||||
aria-label="View photo"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={p.url}
|
||||
alt={p.caption ?? ""}
|
||||
className="block w-full h-full object-cover transition group-hover:scale-105"
|
||||
/>
|
||||
</button>
|
||||
) : null
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
|
||||
{(data.note || data.description) && (
|
||||
<section className="rounded-2xl bg-white shadow-sm border p-5 sm:p-6">
|
||||
<h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
|
||||
<ChevronRight className="size-4 text-muted-foreground" />
|
||||
Additional notes from your technician
|
||||
</h2>
|
||||
{data.note && <p className="text-sm leading-relaxed">{data.note}</p>}
|
||||
{data.description && (
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">{data.description}</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Technician footer */}
|
||||
{data.technician?.name && (
|
||||
<div className="rounded-2xl bg-white shadow-sm border px-5 sm:px-6 py-4 flex items-center justify-between gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 text-white flex items-center justify-center font-semibold text-sm">
|
||||
{data.technician.name
|
||||
.split(" ")
|
||||
.map((p) => p[0])
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.join("")}
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Inspected by</div>
|
||||
<div className="font-medium text-sm">{data.technician.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
{data.department && (
|
||||
<span className="text-xs text-muted-foreground">{data.department}</span>
|
||||
)}
|
||||
{data.template && (
|
||||
<span className="text-xs rounded-full border px-3 py-1 bg-muted/30">
|
||||
{data.template}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<footer className="text-center text-xs text-muted-foreground py-6 no-print">
|
||||
{data.share_expires_at && (
|
||||
<div>Link valid until {new Date(data.share_expires_at).toLocaleDateString()}</div>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
{/* Lightbox */}
|
||||
{lightbox && lightbox.url && (
|
||||
<div
|
||||
className="no-print fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
|
||||
onClick={() => setLightbox(null)}
|
||||
role="dialog"
|
||||
aria-modal
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={lightbox.url}
|
||||
alt={lightbox.caption ?? ""}
|
||||
className="max-w-full max-h-[88vh] object-contain shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightbox(null)}
|
||||
className="absolute top-4 right-4 rounded-full bg-white/10 hover:bg-white/20 text-white size-9 inline-flex items-center justify-center"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{lightbox.caption && (
|
||||
<div className="absolute bottom-4 inset-x-0 text-center text-white/90 text-sm px-4">
|
||||
{lightbox.caption}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InfoCell({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
subtitle,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string
|
||||
subtitle?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-2 min-w-0">
|
||||
<Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</div>
|
||||
<div className="font-medium truncate">{value}</div>
|
||||
{subtitle && (
|
||||
<div className="text-xs text-muted-foreground font-mono truncate">{subtitle}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Geist_Mono, Inter } from "next/font/google"
|
||||
import NextTopLoader from "nextjs-toploader"
|
||||
|
||||
|
||||
import { QueryProvider } from "@/shared/components/query-provider"
|
||||
import { ThemeProvider } from "@/shared/components/theme-provider"
|
||||
import { Toaster } from "@/shared/components/ui/sonner"
|
||||
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
|
||||
import { PromptDialog } from "@/shared/components/prompt-dialog"
|
||||
import { NuqsAdapter } from "nuqs/adapters/next/app"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import './globals.css'
|
||||
@@ -33,11 +35,13 @@ export default function RootLayout({
|
||||
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
|
||||
>
|
||||
<body>
|
||||
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
|
||||
<NuqsAdapter>
|
||||
<ThemeProvider>
|
||||
<QueryProvider>{children}</QueryProvider>
|
||||
<Toaster />
|
||||
<ConfirmDialog />
|
||||
<PromptDialog />
|
||||
</ThemeProvider>
|
||||
</NuqsAdapter>
|
||||
</body>
|
||||
|
||||
@@ -141,9 +141,20 @@ export function AppSidebar({ navGroups, logo, user, ...props }: AppSidebarProps)
|
||||
)
|
||||
}
|
||||
|
||||
function isPathActive(pathname: string, href: string): boolean {
|
||||
if (href === '/') return pathname === '/'
|
||||
return pathname === href || pathname.startsWith(href + '/')
|
||||
}
|
||||
|
||||
function isItemActive(pathname: string, item: { href: string; matchPath?: string; isActive?: boolean }): boolean {
|
||||
if (item.isActive !== undefined) return item.isActive
|
||||
if (item.matchPath) return isPathActive(pathname, item.matchPath)
|
||||
return isPathActive(pathname, item.href)
|
||||
}
|
||||
|
||||
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||
const pathname = usePathname()
|
||||
const isActive = item.isActive ?? pathname === item.href
|
||||
const isActive = isItemActive(pathname, item)
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
@@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
|
||||
|
||||
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||
const pathname = usePathname()
|
||||
const isChildActive = item.items?.some((sub) => pathname === sub.href)
|
||||
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
|
||||
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
|
||||
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
|
||||
|
||||
// Collapsed sidebar → flyout dropdown with sub-items
|
||||
if (isCollapsed) {
|
||||
@@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{item.items?.map((sub) => {
|
||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
||||
const isSubActive = isItemActive(pathname, sub)
|
||||
return (
|
||||
<DropdownMenuItem key={sub.href} asChild>
|
||||
<Link
|
||||
@@ -272,7 +283,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
|
||||
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
|
||||
<SidebarMenuSub>
|
||||
{item.items?.map((sub) => {
|
||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
||||
const isSubActive = isItemActive(pathname, sub)
|
||||
return (
|
||||
<SidebarMenuSubItem key={sub.href}>
|
||||
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
|
||||
|
||||
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
|
||||
</Button>
|
||||
)}
|
||||
{(avatarSrc || avatarFallback) && (
|
||||
<a rel="preload" target="_blank" href={avatarSrc} >
|
||||
<Avatar className="size-14">
|
||||
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
|
||||
<AvatarFallback>
|
||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</a>
|
||||
avatarSrc ? (
|
||||
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
|
||||
<Avatar className="size-14">
|
||||
<AvatarImage src={avatarSrc} alt={title} />
|
||||
<AvatarFallback>
|
||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</a>
|
||||
) : (
|
||||
<Avatar className="size-14">
|
||||
<AvatarFallback>
|
||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)
|
||||
)}
|
||||
{!avatarSrc && !avatarFallback && icon && (
|
||||
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
|
||||
@@ -109,6 +117,7 @@ export default function DashboardDetailsPageLayout({
|
||||
<Link
|
||||
key={tab.href}
|
||||
href={tab.href}
|
||||
prefetch
|
||||
className={cn(
|
||||
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
|
||||
"text-muted-foreground hover:text-foreground",
|
||||
|
||||
@@ -6,6 +6,12 @@ export type NavItem = {
|
||||
href: string
|
||||
icon?: ReactNode
|
||||
isActive?: boolean
|
||||
/**
|
||||
* Optional prefix used to decide active state when the link target
|
||||
* differs from the page's URL pattern (e.g. `/calendar/appointment/list`
|
||||
* is the link, but the item should stay active on `/calendar/appointment/{id}`).
|
||||
*/
|
||||
matchPath?: string
|
||||
badge?: string | number
|
||||
items?: NavSubItem[]
|
||||
}
|
||||
@@ -15,6 +21,7 @@ export type NavSubItem = {
|
||||
href: string
|
||||
icon?: ReactNode
|
||||
isActive?: boolean
|
||||
matchPath?: string
|
||||
}
|
||||
|
||||
export type NavGroup = {
|
||||
|
||||
@@ -76,7 +76,7 @@ export const navGroups: NavGroup[] = [
|
||||
icon: <CalendarIcon />,
|
||||
items: [
|
||||
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
|
||||
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
|
||||
{ title: "Appointments", href: "/calendar/appointment/list", matchPath: "/calendar/appointment", icon: <CalendarCheck2Icon /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -144,10 +144,11 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
|
||||
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
|
||||
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
|
||||
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||
{ title: "Leave Requests", href: "/productivity/leave-requests", icon: <CalendarIcon /> },
|
||||
{ title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
||||
// { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
||||
// { title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||
{ title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
||||
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||
{ title: "Holidays", href: "/productivity/holidays", icon: <CalendarIcon /> },
|
||||
{ title: "Tasks", href: "/productivity/tasks", icon: <ListTodoIcon /> },
|
||||
],
|
||||
@@ -176,7 +177,8 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
|
||||
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
|
||||
{ title: "Make & Models", href: "/settings/make-and-models", icon: <CarIcon /> },
|
||||
{ title: "Configurations", href: "/settings/configurations/preferences/sales", icon: <SettingsIcon /> },
|
||||
{ title: "Inspection Templates", href: "/settings/inspection-templates", icon: <ClipboardListIcon /> },
|
||||
{ title: "Configurations", href: "/settings/configurations/preferences/sales", matchPath: "/settings/configurations", icon: <SettingsIcon /> },
|
||||
// { title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
|
||||
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
|
||||
// { title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"list_pages": {
|
||||
"inspection": { "url": "/sales/inspections", "type": "inspection", "api": "/api/inspections" },
|
||||
"estimate": { "url": "/sales/estimates", "type": "estimate", "api": "/api/estimates" },
|
||||
"job_card": { "url": "/sales/job-cards", "type": "job_card", "api": "/api/job-cards" },
|
||||
"invoice": { "url": "/sales/invoice", "type": "invoice", "api": "/api/invoices" },
|
||||
"payment_received": { "url": "/sales/payment-received", "type": "payment_received", "api": "/api/payment-recieved" },
|
||||
"expense": { "url": "/purchase/expense", "type": "expense", "api": "/api/expenses" },
|
||||
"purchase_order": { "url": "/purchase/purchase-order", "type": "purchase_order", "api": "/api/purchase-orders" },
|
||||
"bill": { "url": "/purchase/bill", "type": "bill", "api": "/api/bills" },
|
||||
"payment_made": { "url": "/purchase/payments-made", "type": "payment_made", "api": "/api/payment-mades" },
|
||||
"credit_note": { "url": "/sales/credit-notes", "type": "credit_note", "api": "/api/credit-notes" }
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { useQueryClient } from "@tanstack/react-query"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "./appointment-form"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type AppointmentActionsProps = {
|
||||
appointmentId: string
|
||||
@@ -50,7 +51,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await api.appointments.changeStatus(appointmentId, { status } as any)
|
||||
toast.success(`Status updated to "${status}".`)
|
||||
toast.success(`Status updated to "${formatEnum(status)}".`)
|
||||
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
|
||||
router.refresh()
|
||||
} catch {
|
||||
|
||||
@@ -15,6 +15,7 @@ import Link from "next/link"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type AppointmentData = {
|
||||
id?: number
|
||||
@@ -89,7 +90,7 @@ export function AppointmentGeneralInfo({ appointment }: AppointmentGeneralInfoPr
|
||||
<div className="flex items-center gap-2">
|
||||
{appointment.status && (
|
||||
<Badge className={statusClass}>
|
||||
{appointment.status.replace("_", " ")}
|
||||
{formatEnum(appointment.status)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -11,9 +11,12 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
import { Ellipsis, Pencil, Printer, Trash2, Share2 } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { BillForm } from "./bill-form"
|
||||
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
type BillActionsProps = {
|
||||
billId: string
|
||||
@@ -23,6 +26,8 @@ export function BillActions({ billId }: BillActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
const editDialog = useFormDialog("bill-details-edit")
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.bills.destroy(billId)
|
||||
@@ -42,6 +47,14 @@ export function BillActions({ billId }: BillActionsProps) {
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => print("bill", billId, "print")} disabled={isPrinting}>
|
||||
<Printer className="size-4" />
|
||||
{isPrinting ? "Printing..." : "Print"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShareOpen(true)}>
|
||||
<Share2 className="size-4" />
|
||||
Share
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
@@ -49,6 +62,8 @@ export function BillActions({ billId }: BillActionsProps) {
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<ShareDocumentDialog type="bill" id={billId} open={shareOpen} onOpenChange={setShareOpen} />
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { Receipt } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillExpense = {
|
||||
id: number
|
||||
@@ -62,14 +63,14 @@ export function BillExpensesSection({ expenses = [] }: BillExpensesSectionProps)
|
||||
{expense.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
|
||||
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { formatDate, formatCurrency, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useBill } from "./bill-context"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { Wrench } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillPart = {
|
||||
id: number
|
||||
@@ -62,14 +63,14 @@ export function BillPartsSection({ parts = [] }: BillPartsSectionProps) {
|
||||
{part.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
|
||||
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
@@ -17,7 +17,6 @@ import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
|
||||
import { useBill } from "./bill-context"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { toRelation } from "@/shared/lib/utils"
|
||||
|
||||
export function BillPaymentsSection() {
|
||||
const bill = useBill()
|
||||
@@ -39,8 +38,17 @@ export function BillPaymentsSection() {
|
||||
{(resourceId) => (
|
||||
<PaymentMadeForm
|
||||
initialData={{
|
||||
amount: bill?.balance_due,
|
||||
vendor: toRelation(bill?.vendor?.id, getFullName(bill?.vendor as any)),
|
||||
// API-shape keys so PaymentMadeForm.mapToFormValues
|
||||
// can pick them up (it reads `payment_made` / `vendor_id`
|
||||
// / `vendor.*`, not the form-shape fields). bill_id +
|
||||
// bill_number are required because the bill field is
|
||||
// hidden when billId is supplied, but the schema still
|
||||
// demands a populated bill relation.
|
||||
bill_id: bill?.id,
|
||||
bill_number: bill?.bill_number,
|
||||
payment_made: bill?.balance_due,
|
||||
vendor_id: bill?.vendor?.id,
|
||||
vendor: bill?.vendor,
|
||||
payment_for: "bill",
|
||||
}}
|
||||
billId={bill?.id}
|
||||
@@ -77,7 +85,7 @@ export function BillPaymentsSection() {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.vendor?.name || item.vendor_name || "—"}</span>
|
||||
<span>{item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name || "—"}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { Briefcase } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillService = {
|
||||
id: number
|
||||
@@ -62,14 +63,14 @@ export function BillServicesSection({ services = [] }: BillServicesSectionProps)
|
||||
{service.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
|
||||
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { BillStatus } from "@garage/api"
|
||||
import { BillStatus, parseApiError } from "@garage/api"
|
||||
import { Badge, badgeVariants } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Select,
|
||||
@@ -60,7 +60,7 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
|
||||
toast.success("Bill status updated")
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast.error("Failed to update bill status")
|
||||
toast.error(parseApiError(error, "Failed to update bill status"))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -71,7 +71,9 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
|
||||
<SelectTrigger
|
||||
className={`border-0 size-auto p-0 h-auto font-medium ${STATUS_TRIGGER_CLASS_NAMES[status]}`}
|
||||
>
|
||||
<SelectValue placeholder="Select status" />
|
||||
<SelectValue placeholder="Select status">
|
||||
{formatEnum(status)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BillStatus.map((s) => (
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import { useBill } from "./bill-context"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
export function BillTotalsSummary() {
|
||||
const bill = useBill()
|
||||
@@ -46,70 +47,65 @@ export function BillTotalsSummary() {
|
||||
{parts.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Parts ({parts.length})</span>
|
||||
<span>{formatCurrency(partsTotal)}</span>
|
||||
<span>{<Money value={partsTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{services.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Services ({services.length})</span>
|
||||
<span>{formatCurrency(servicesTotal)}</span>
|
||||
<span>{<Money value={servicesTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
{expenses.length > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
|
||||
<span>{formatCurrency(expensesTotal)}</span>
|
||||
<span>{<Money value={expensesTotal} />}</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
|
||||
<div className="flex justify-between text-sm font-medium">
|
||||
<span>Subtotal</span>
|
||||
<span>{formatCurrency(subTotal)}</span>
|
||||
<span>{<Money value={subTotal} />}</span>
|
||||
</div>
|
||||
|
||||
{discountAmount > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""}</span>
|
||||
<span className="text-muted-foreground">−{formatCurrency(discountAmount)}</span>
|
||||
<span className="text-muted-foreground">−{<Money value={discountAmount} />}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{taxAmount > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""}</span>
|
||||
<span>{formatCurrency(taxAmount)}</span>
|
||||
<span>{<Money value={taxAmount} />}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex justify-between text-base font-semibold">
|
||||
<span>Total</span>
|
||||
<span>{<Money value={total} />}</span>
|
||||
</div>
|
||||
|
||||
{paymentsMade > 0 && (
|
||||
<div className="flex justify-between text-sm text-muted-foreground">
|
||||
<span>Amount Paid</span>
|
||||
<span>– {<Money value={paymentsMade} />}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className={cn(
|
||||
"flex justify-between rounded-lg px-3 py-2 text-base font-bold bg-muted/50",
|
||||
"flex justify-between rounded-lg px-3 py-2 text-base font-bold",
|
||||
balanceDue > 0 ? "bg-primary/10 text-primary" : "bg-green-500/10 text-green-600",
|
||||
)}>
|
||||
<span>Total</span>
|
||||
<span>{formatCurrency(total)}</span>
|
||||
<span>Balance Due</span>
|
||||
<span>{<Money value={balanceDue} />}</span>
|
||||
</div>
|
||||
|
||||
{paymentsMade > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Payments Made</span>
|
||||
<span className="text-emerald-600">−{formatCurrency(paymentsMade)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paymentsMade > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className={cn(
|
||||
"flex justify-between rounded-lg px-3 py-2 text-base font-semibold",
|
||||
balanceDue > 0 ? "text-destructive bg-destructive/5" : "text-emerald-700 bg-emerald-50 dark:bg-emerald-950/20",
|
||||
)}>
|
||||
<span>Balance Due</span>
|
||||
<span>{formatCurrency(balanceDue)}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -11,9 +11,10 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
|
||||
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { CreditNoteForm } from "./credit-note-form"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
type CreditNoteActionsProps = {
|
||||
creditNoteId: string
|
||||
@@ -23,6 +24,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
const editDialog = useFormDialog("credit-note-details-edit")
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.creditNotes.destroy(creditNoteId)
|
||||
@@ -42,6 +44,10 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => print("credit_note", creditNoteId, "print")} disabled={isPrinting}>
|
||||
<Printer className="size-4" />
|
||||
{isPrinting ? "Printing..." : "Print"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type CreditNoteData = {
|
||||
id?: number
|
||||
@@ -84,7 +85,7 @@ export function CreditNoteGeneralInfo({ creditNote }: CreditNoteGeneralInfoProps
|
||||
)}
|
||||
{creditNote.status && (
|
||||
<Badge variant={statusColorMap[creditNote.status] as any ?? "outline"}>
|
||||
{creditNote.status.charAt(0).toUpperCase() + creditNote.status.slice(1)}
|
||||
{formatEnum(creditNote.status)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
@@ -131,10 +132,17 @@ export function RhfCustomerSelectField<
|
||||
|
||||
const handleCreateSuccess = (data?: any) => {
|
||||
const item = data?.data ?? data
|
||||
if (item?.id) {
|
||||
field.onChange(buildCustomerOption(item))
|
||||
if (!item?.id) {
|
||||
setIsCreateOpen(false)
|
||||
return
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"] })
|
||||
const newOption = buildCustomerOption(item)
|
||||
const key = [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"]
|
||||
|
||||
queryClient.setQueryData<CustomerOption[]>(key, (prev = []) =>
|
||||
prev.some((o) => o.value === newOption.value) ? prev : [newOption, ...prev],
|
||||
)
|
||||
field.onChange(newOption)
|
||||
setIsCreateOpen(false)
|
||||
}
|
||||
|
||||
@@ -243,7 +251,9 @@ export function RhfCustomerSelectField<
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<CustomerForm onSuccess={handleCreateSuccess} />
|
||||
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
|
||||
<CustomerForm onSuccess={handleCreateSuccess} />
|
||||
</DialogCloseContext.Provider>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useState } from "react"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { toast } from "sonner"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { z } from "zod"
|
||||
import { UploadIcon } from "lucide-react"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1, "Name is required").max(150),
|
||||
issuer: z.string().trim().max(150).optional(),
|
||||
certificate_number: z.string().trim().max(100).optional(),
|
||||
issued_date: z.string().optional(),
|
||||
expiry_date: z.string().optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
export type EmployeeCertificationFormProps = {
|
||||
employeeId: string
|
||||
onSuccess?: () => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
export function EmployeeCertificationForm({ employeeId, onSuccess, onCancel }: EmployeeCertificationFormProps) {
|
||||
const api = useAuthApi()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
reset,
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
name: "", issuer: "", certificate_number: "",
|
||||
issued_date: "", expiry_date: "", notes: "",
|
||||
},
|
||||
})
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: FormValues) => {
|
||||
const promise = api.employees.createCertification(employeeId, {
|
||||
name: values.name,
|
||||
issuer: values.issuer || undefined,
|
||||
certificate_number: values.certificate_number || undefined,
|
||||
issued_date: values.issued_date || undefined,
|
||||
expiry_date: values.expiry_date || undefined,
|
||||
notes: values.notes || undefined,
|
||||
file: file ?? undefined,
|
||||
})
|
||||
toast.promise(promise, {
|
||||
loading: "Saving certification...",
|
||||
success: "Certification added",
|
||||
error: (err: any) => err?.message ?? "Failed to save",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
reset()
|
||||
setFile(null)
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
|
||||
<Field>
|
||||
<FieldLabel>Name</FieldLabel>
|
||||
<Input {...register("name")} placeholder="e.g. ASE A1 Engine Repair" />
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field>
|
||||
<FieldLabel>Issuer</FieldLabel>
|
||||
<Input {...register("issuer")} placeholder="ASE / SAE / ..." />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Certificate Number</FieldLabel>
|
||||
<Input {...register("certificate_number")} placeholder="Optional" />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field>
|
||||
<FieldLabel>Issued Date</FieldLabel>
|
||||
<Input type="date" {...register("issued_date")} />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Expiry Date</FieldLabel>
|
||||
<Input type="date" {...register("expiry_date")} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Attachment (optional)</FieldLabel>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
|
||||
<UploadIcon className="size-4" />
|
||||
Choose file
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"
|
||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Notes</FieldLabel>
|
||||
<Textarea rows={3} {...register("notes")} />
|
||||
</Field>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
{onCancel && (
|
||||
<Button type="button" variant="outline" onClick={onCancel}>Cancel</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? "Saving..." : "Save Certification"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { Loader2 } from "lucide-react"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxInput,
|
||||
@@ -149,16 +150,16 @@ export function EmployeeCombobox({
|
||||
{opt.type && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="h-4 px-1.5 text-xs font-normal capitalize"
|
||||
className="h-4 px-1.5 text-xs font-normal"
|
||||
>
|
||||
{opt.type}
|
||||
{formatEnum(opt.type)}
|
||||
</Badge>
|
||||
)}
|
||||
{opt.status && (
|
||||
<span
|
||||
className={`text-xs capitalize ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
|
||||
className={`text-xs ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
|
||||
>
|
||||
{opt.status}
|
||||
{formatEnum(opt.status)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client"
|
||||
|
||||
import { useRef, useState } from "react"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { toast } from "sonner"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { z } from "zod"
|
||||
import { UploadIcon } from "lucide-react"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
|
||||
const DOCUMENT_TYPES = [
|
||||
{ value: "contract", label: "Contract" },
|
||||
{ value: "id", label: "ID / Passport" },
|
||||
{ value: "ase", label: "ASE" },
|
||||
{ value: "certification", label: "Certification" },
|
||||
{ value: "other", label: "Other" },
|
||||
] as const
|
||||
|
||||
const schema = z.object({
|
||||
name: z.string().trim().min(1, "Name is required").max(150),
|
||||
type: z.enum(["contract", "id", "ase", "certification", "other"]),
|
||||
issued_date: z.string().optional(),
|
||||
expiry_date: z.string().optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
export type EmployeeDocumentFormProps = {
|
||||
employeeId: string
|
||||
onSuccess?: () => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
export function EmployeeDocumentForm({ employeeId, onSuccess, onCancel }: EmployeeDocumentFormProps) {
|
||||
const api = useAuthApi()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
watch,
|
||||
formState: { errors },
|
||||
reset,
|
||||
} = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { name: "", type: "other", issued_date: "", expiry_date: "", notes: "" },
|
||||
})
|
||||
|
||||
const type = watch("type")
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: (values: FormValues) => {
|
||||
if (!file) throw new Error("Select a file to upload.")
|
||||
const promise = api.employees.uploadDocument(employeeId, {
|
||||
file,
|
||||
name: values.name,
|
||||
type: values.type,
|
||||
issued_date: values.issued_date || undefined,
|
||||
expiry_date: values.expiry_date || undefined,
|
||||
notes: values.notes || undefined,
|
||||
})
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading document...",
|
||||
success: "Document uploaded",
|
||||
error: (err: any) => err?.message ?? "Failed to upload",
|
||||
})
|
||||
return promise
|
||||
},
|
||||
onSuccess: () => {
|
||||
reset()
|
||||
setFile(null)
|
||||
onSuccess?.()
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
|
||||
<Field>
|
||||
<FieldLabel>File</FieldLabel>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
|
||||
<UploadIcon className="size-4" />
|
||||
Choose file
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
|
||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</div>
|
||||
{!file && mutation.isError && (
|
||||
<FieldError>Select a file before uploading.</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Name</FieldLabel>
|
||||
<Input {...register("name")} placeholder="e.g. Employment contract 2026" />
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Type</FieldLabel>
|
||||
<Select value={type} onValueChange={(v) => setValue("type", v as FormValues["type"], { shouldValidate: true })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DOCUMENT_TYPES.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field>
|
||||
<FieldLabel>Issued Date</FieldLabel>
|
||||
<Input type="date" {...register("issued_date")} />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>Expiry Date</FieldLabel>
|
||||
<Input type="date" {...register("expiry_date")} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>Notes</FieldLabel>
|
||||
<Textarea rows={3} {...register("notes")} placeholder="Optional" />
|
||||
</Field>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
{onCancel && (
|
||||
<Button type="button" variant="outline" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
{mutation.isPending ? "Uploading..." : "Upload"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
"use client"
|
||||
|
||||
import { AlertTriangle, Plus, Save } from "lucide-react"
|
||||
import { AlertTriangle, ImageIcon, Plus, Save, UploadIcon } from "lucide-react"
|
||||
import { useRef, useState } from "react"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
|
||||
import { FieldGroup } from "@/shared/components/ui/field"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import {
|
||||
Rhform,
|
||||
RhfTextField,
|
||||
RhfSelectField,
|
||||
RhfAsyncSelectField,
|
||||
RhfCheckboxField,
|
||||
RhfTextareaField,
|
||||
} from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -24,27 +28,18 @@ import {
|
||||
STATUS_OPTIONS,
|
||||
TYPE_OPTIONS,
|
||||
WAGE_TYPE_OPTIONS,
|
||||
GENDER_OPTIONS,
|
||||
MARITAL_OPTIONS,
|
||||
} from "./employee.schema"
|
||||
import { EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, SHOP_TIMING_ROUTES, SHOP_CALENDAR_ROUTES, GEO_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
const titleCase = (v: string) => v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
|
||||
const STATUS_SELECT_OPTIONS = STATUS_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const TYPE_SELECT_OPTIONS = TYPE_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const WAGE_TYPE_SELECT_OPTIONS = WAGE_TYPE_OPTIONS.map((v) => ({
|
||||
value: v,
|
||||
label: v,
|
||||
}))
|
||||
|
||||
// ── Props ──
|
||||
const STATUS_SELECT_OPTIONS = STATUS_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
||||
const TYPE_SELECT_OPTIONS = TYPE_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
||||
const WAGE_TYPE_SELECT_OPTIONS = WAGE_TYPE_OPTIONS.map((v) => ({ value: v, label: v }))
|
||||
const GENDER_SELECT_OPTIONS = GENDER_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
||||
const MARITAL_SELECT_OPTIONS = MARITAL_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
||||
|
||||
export type EmployeeFormProps = {
|
||||
resourceId?: string | null
|
||||
@@ -52,8 +47,6 @@ export type EmployeeFormProps = {
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
// ── Default values ──
|
||||
|
||||
const DEFAULT_VALUES: EmployeeFormValues = {
|
||||
department: null,
|
||||
country: null,
|
||||
@@ -73,12 +66,28 @@ const DEFAULT_VALUES: EmployeeFormValues = {
|
||||
track_attendance: true,
|
||||
notify_owner_when_punch_in_out: false,
|
||||
geo_fence_radius: null,
|
||||
address: "",
|
||||
date_of_birth: "",
|
||||
gender: null,
|
||||
marital_status: null,
|
||||
national_id: "",
|
||||
hire_date: "",
|
||||
emergency_contact_name: "",
|
||||
emergency_contact_phone: "",
|
||||
bank_name: "",
|
||||
bank_account_number: "",
|
||||
bank_iban: "",
|
||||
hourly_rate: null,
|
||||
commission_rate: null,
|
||||
}
|
||||
|
||||
// ── Mapping helpers ──
|
||||
|
||||
function mapToFormValues(data: unknown): EmployeeFormValues {
|
||||
const d = (data as any)?.data ?? data ?? {}
|
||||
const formatDate = (v: unknown): string => {
|
||||
if (!v) return ""
|
||||
const s = String(v)
|
||||
return s.length >= 10 ? s.slice(0, 10) : s
|
||||
}
|
||||
|
||||
return {
|
||||
department: toRelation(d.department_id, d.department?.name),
|
||||
@@ -99,6 +108,19 @@ function mapToFormValues(data: unknown): EmployeeFormValues {
|
||||
track_attendance: d.track_attendance ?? true,
|
||||
notify_owner_when_punch_in_out: d.notify_owner_when_punch_in_out ?? false,
|
||||
geo_fence_radius: d.geo_fence_radius ?? null,
|
||||
address: d.address || "",
|
||||
date_of_birth: formatDate(d.date_of_birth),
|
||||
gender: d.gender ?? null,
|
||||
marital_status: d.marital_status ?? null,
|
||||
national_id: d.national_id || "",
|
||||
hire_date: formatDate(d.hire_date),
|
||||
emergency_contact_name: d.emergency_contact_name || "",
|
||||
emergency_contact_phone: d.emergency_contact_phone || "",
|
||||
bank_name: d.bank_name || "",
|
||||
bank_account_number: d.bank_account_number || "",
|
||||
bank_iban: d.bank_iban || "",
|
||||
hourly_rate: d.hourly_rate ?? null,
|
||||
commission_rate: d.commission_rate ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +134,7 @@ function mapFormToPayload(values: EmployeeFormValues) {
|
||||
first_name: values.first_name,
|
||||
last_name: values.last_name,
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
password: values.password || undefined,
|
||||
phone: values.phone || undefined,
|
||||
designation: values.designation || undefined,
|
||||
salary: values.salary ?? undefined,
|
||||
@@ -122,11 +144,22 @@ function mapFormToPayload(values: EmployeeFormValues) {
|
||||
track_attendance: values.track_attendance,
|
||||
notify_owner_when_punch_in_out: values.notify_owner_when_punch_in_out,
|
||||
geo_fence_radius: values.geo_fence_radius ?? undefined,
|
||||
address: values.address || undefined,
|
||||
date_of_birth: values.date_of_birth || undefined,
|
||||
gender: values.gender ?? undefined,
|
||||
marital_status: values.marital_status ?? undefined,
|
||||
national_id: values.national_id || undefined,
|
||||
hire_date: values.hire_date || undefined,
|
||||
emergency_contact_name: values.emergency_contact_name || undefined,
|
||||
emergency_contact_phone: values.emergency_contact_phone || undefined,
|
||||
bank_name: values.bank_name || undefined,
|
||||
bank_account_number: values.bank_account_number || undefined,
|
||||
bank_iban: values.bank_iban || undefined,
|
||||
hourly_rate: values.hourly_rate ?? undefined,
|
||||
commission_rate: values.commission_rate ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared mapOption for async selects ──
|
||||
|
||||
const mapLookupOption = (item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.name ?? item.title ?? String(item.id),
|
||||
@@ -134,7 +167,71 @@ const mapLookupOption = (item: any) => ({
|
||||
|
||||
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
|
||||
|
||||
// ── Component ──
|
||||
function SectionHeading({ title, description }: { title: string; description?: string }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-semibold">{title}</h3>
|
||||
{description && <p className="text-xs text-muted-foreground">{description}</p>}
|
||||
<Separator className="mt-2" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarUpload({ employeeId, initialUrl }: { employeeId: string; initialUrl?: string | null }) {
|
||||
const api = useAuthApi()
|
||||
const inputRef = useRef<HTMLInputElement | null>(null)
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(initialUrl ?? null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
|
||||
async function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
setUploading(true)
|
||||
try {
|
||||
const res: any = await api.employees.uploadAvatar(employeeId, file)
|
||||
const url = res?.data?.avatar_url ?? URL.createObjectURL(file)
|
||||
setPreviewUrl(url)
|
||||
toast.success("Avatar updated")
|
||||
} catch (err: any) {
|
||||
toast.error(err?.message ?? "Failed to upload avatar")
|
||||
} finally {
|
||||
setUploading(false)
|
||||
e.target.value = ""
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar size="lg">
|
||||
{previewUrl ? <AvatarImage src={previewUrl} alt="Avatar" /> : null}
|
||||
<AvatarFallback>
|
||||
<ImageIcon className="size-5 text-muted-foreground" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
<UploadIcon className="size-4" />
|
||||
{uploading ? "Uploading..." : "Upload photo"}
|
||||
</Button>
|
||||
<p className="mt-1 text-xs text-muted-foreground">JPG, PNG, WEBP. Max 5 MB.</p>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFormProps) {
|
||||
const api = useAuthApi()
|
||||
@@ -168,6 +265,9 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
},
|
||||
})
|
||||
|
||||
const initialAvatarUrl = (initialData as any)?.avatar_url
|
||||
?? ((initialData as any)?.avatar_path ? `/storage/${(initialData as any).avatar_path}` : null)
|
||||
|
||||
return (
|
||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||
{error && (
|
||||
@@ -181,19 +281,67 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
{/* Personal */}
|
||||
<SectionHeading title="Personal" />
|
||||
|
||||
{isEditing && resourceId ? (
|
||||
<AvatarUpload employeeId={resourceId} initialUrl={initialAvatarUrl} />
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="first_name" label="First Name" placeholder="Jane" required />
|
||||
<RhfTextField name="last_name" label="Last Name" placeholder="Smith" required />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="email" label="Email" placeholder="jane@example.com" type="email" />
|
||||
<RhfTextField name="password" label="Password" placeholder="At least 6 characters" type="password" required />
|
||||
<RhfTextField name="date_of_birth" label="Date of Birth" type="date" />
|
||||
<RhfTextField name="national_id" label="National ID" placeholder="A1234567" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="phone" label="Phone" placeholder="0501234567" type="tel" />
|
||||
<RhfTextField name="designation" label="Designation" placeholder="Technician" />
|
||||
<RhfSelectField name="gender" label="Gender" placeholder="Select gender" options={GENDER_SELECT_OPTIONS} />
|
||||
<RhfSelectField name="marital_status" label="Marital Status" placeholder="Select status" options={MARITAL_SELECT_OPTIONS} />
|
||||
</div>
|
||||
|
||||
{/* Contact */}
|
||||
<SectionHeading title="Contact" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="email" label="Email" placeholder="jane@example.com" type="email" required />
|
||||
<RhfTextField name="password" label="Password" placeholder={isEditing ? "Leave blank to keep" : "At least 6 characters"} type="password" required={!isEditing} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="phone" label="Phone" placeholder="+971501234567" type="tel" />
|
||||
<RhfAsyncSelectField
|
||||
name="country"
|
||||
label="Country"
|
||||
placeholder="Select country"
|
||||
queryKey={[GEO_ROUTES.COUNTRIES]}
|
||||
listFn={() => api.geo.countries()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<RhfTextareaField name="address" label="Address" placeholder="Street, city, region..." rows={2} />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="emergency_contact_name" label="Emergency Contact Name" placeholder="Full name" />
|
||||
<RhfTextField name="emergency_contact_phone" label="Emergency Contact Phone" type="tel" />
|
||||
</div>
|
||||
|
||||
{/* Employment */}
|
||||
<SectionHeading title="Employment" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="hire_date" label="Hire Date" type="date" />
|
||||
<RhfTextField name="designation" label="Designation" placeholder="Senior Technician" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField name="type" label="Type" placeholder="Select type" options={TYPE_SELECT_OPTIONS} />
|
||||
<RhfSelectField name="status" label="Status" placeholder="Select status" options={STATUS_SELECT_OPTIONS} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
@@ -209,41 +357,32 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
||||
<RhfTextField name="role_id" label="Role ID" placeholder="1" type="number" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField
|
||||
name="status"
|
||||
label="Status"
|
||||
placeholder="Select status"
|
||||
options={STATUS_SELECT_OPTIONS}
|
||||
/>
|
||||
<RhfSelectField
|
||||
name="type"
|
||||
label="Type"
|
||||
placeholder="Select type"
|
||||
options={TYPE_SELECT_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
{/* Compensation */}
|
||||
<SectionHeading title="Compensation" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfSelectField name="wage_type" label="Wage Type" placeholder="Select wage type" options={WAGE_TYPE_SELECT_OPTIONS} />
|
||||
<RhfTextField name="salary" label="Salary" placeholder="0" type="number" />
|
||||
<RhfSelectField
|
||||
name="wage_type"
|
||||
label="Wage Type"
|
||||
placeholder="Select wage type"
|
||||
options={WAGE_TYPE_SELECT_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="country"
|
||||
label="Country"
|
||||
placeholder="Select country"
|
||||
queryKey={[GEO_ROUTES.COUNTRIES]}
|
||||
listFn={() => api.geo.countries()}
|
||||
mapOption={mapLookupOption}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
<RhfTextField name="hourly_rate" label="Hourly Rate" placeholder="0.00" type="number" />
|
||||
<RhfTextField name="commission_rate" label="Commission (%)" placeholder="0" type="number" />
|
||||
</div>
|
||||
|
||||
{/* Bank */}
|
||||
<SectionHeading title="Bank" description="Used for payroll payouts." />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfTextField name="bank_name" label="Bank Name" placeholder="Bank of ..." />
|
||||
<RhfTextField name="bank_account_number" label="Account Number" placeholder="000123456789" />
|
||||
</div>
|
||||
<RhfTextField name="bank_iban" label="IBAN" placeholder="AE00 0000 0000 0000 0000 000" />
|
||||
|
||||
{/* Tracking */}
|
||||
<SectionHeading title="Attendance Tracking" />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<RhfAsyncSelectField
|
||||
name="shop_calender"
|
||||
label="Shop Calendar"
|
||||
|
||||
@@ -9,6 +9,15 @@ import {
|
||||
Calendar,
|
||||
BadgeCheck,
|
||||
CircleDot,
|
||||
Cake,
|
||||
Heart,
|
||||
IdCard,
|
||||
Home,
|
||||
PhoneCall,
|
||||
Landmark,
|
||||
Wallet,
|
||||
PercentIcon,
|
||||
DollarSign,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
Card,
|
||||
@@ -16,8 +25,10 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type EmployeeData = {
|
||||
id?: number
|
||||
@@ -37,6 +48,22 @@ type EmployeeData = {
|
||||
department?: { id?: number; name?: string } | null
|
||||
shop_calender?: { id?: number; title?: string } | null
|
||||
shop_timing?: { id?: number; title?: string } | null
|
||||
role?: { id?: number; name?: string } | null
|
||||
avatar_url?: string | null
|
||||
avatar_path?: string | null
|
||||
address?: string | null
|
||||
date_of_birth?: string | null
|
||||
gender?: string | null
|
||||
marital_status?: string | null
|
||||
national_id?: string | null
|
||||
hire_date?: string | null
|
||||
emergency_contact_name?: string | null
|
||||
emergency_contact_phone?: string | null
|
||||
bank_name?: string | null
|
||||
bank_account_number?: string | null
|
||||
bank_iban?: string | null
|
||||
hourly_rate?: string | number | null
|
||||
commission_rate?: string | number | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
@@ -45,6 +72,19 @@ type EmployeeGeneralInfoProps = {
|
||||
employee: EmployeeData
|
||||
}
|
||||
|
||||
function formatDate(value?: string | null): string | null {
|
||||
if (!value) return null
|
||||
const d = new Date(value)
|
||||
if (Number.isNaN(d.getTime())) return value
|
||||
return d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function initialsOf(first?: string | null, last?: string | null) {
|
||||
const f = (first ?? "").trim()[0] ?? ""
|
||||
const l = (last ?? "").trim()[0] ?? ""
|
||||
return (f + l).toUpperCase() || "?"
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
icon: Icon,
|
||||
label,
|
||||
@@ -52,7 +92,7 @@ function InfoItem({
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value?: string | null
|
||||
value?: string | number | null
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-3">
|
||||
@@ -62,7 +102,7 @@ function InfoItem({
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<span className="text-sm font-medium">
|
||||
{value || <span className="text-muted-foreground">—</span>}
|
||||
{value != null && value !== "" ? value : <span className="text-muted-foreground">—</span>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -71,6 +111,7 @@ function InfoItem({
|
||||
|
||||
export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
||||
const fullName = [employee.first_name, employee.last_name].filter(Boolean).join(" ")
|
||||
const avatarSrc = employee.avatar_url ?? (employee.avatar_path ? `/storage/${employee.avatar_path}` : null)
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
@@ -83,62 +124,77 @@ export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
|
||||
{employee.type && (
|
||||
<Badge variant="outline" className="capitalize">
|
||||
{employee.type}
|
||||
</Badge>
|
||||
)}
|
||||
{employee.status && (
|
||||
<Badge
|
||||
variant={employee.status === "active" ? "default" : "secondary"}
|
||||
className="capitalize"
|
||||
>
|
||||
{employee.status}
|
||||
</Badge>
|
||||
)}
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar size="lg">
|
||||
{avatarSrc ? <AvatarImage src={avatarSrc} alt={fullName} /> : null}
|
||||
<AvatarFallback>{initialsOf(employee.first_name, employee.last_name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
|
||||
{employee.type && (
|
||||
<Badge variant="outline">
|
||||
{formatEnum(employee.type)}
|
||||
</Badge>
|
||||
)}
|
||||
{employee.status && (
|
||||
<Badge
|
||||
variant={employee.status === "active" ? "default" : "secondary"}
|
||||
>
|
||||
{formatEnum(employee.status)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Mail} label="Email" value={employee.email} />
|
||||
<InfoItem icon={Phone} label="Phone" value={employee.phone} />
|
||||
<InfoItem icon={Briefcase} label="Position" value={employee.position} />
|
||||
<InfoItem icon={BadgeCheck} label="Designation" value={employee.designation} />
|
||||
<InfoItem icon={Cake} label="Date of Birth" value={formatDate(employee.date_of_birth)} />
|
||||
<InfoItem icon={Heart} label="Marital Status" value={employee.marital_status ? formatEnum(employee.marital_status) : null} />
|
||||
<InfoItem icon={User} label="Gender" value={employee.gender ? formatEnum(employee.gender) : null} />
|
||||
<InfoItem icon={IdCard} label="National ID" value={employee.national_id} />
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Home} label="Address" value={employee.address} />
|
||||
<InfoItem icon={PhoneCall} label="Emergency Contact" value={[employee.emergency_contact_name, employee.emergency_contact_phone].filter(Boolean).join(" • ")} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Work Details */}
|
||||
{/* Employment + Compensation */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Building2 className="size-4" />
|
||||
Work Details
|
||||
Employment
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem
|
||||
icon={Building2}
|
||||
label="Department"
|
||||
value={employee.department?.name}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Calendar}
|
||||
label="Shop Calendar"
|
||||
value={employee.shop_calender?.title}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={Clock}
|
||||
label="Shop Timing"
|
||||
value={employee.shop_timing?.title}
|
||||
/>
|
||||
<InfoItem
|
||||
icon={MapPin}
|
||||
label="Geo Fence Radius"
|
||||
value={employee.geo_fence_radius != null ? String(employee.geo_fence_radius) : null}
|
||||
/>
|
||||
<InfoItem icon={Briefcase} label="Designation" value={employee.designation} />
|
||||
<InfoItem icon={Calendar} label="Hire Date" value={formatDate(employee.hire_date)} />
|
||||
<InfoItem icon={Building2} label="Department" value={employee.department?.name} />
|
||||
<InfoItem icon={BadgeCheck} label="Role" value={employee.role?.name} />
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={DollarSign} label="Salary" value={employee.salary ? Number(employee.salary).toFixed(2) : null} />
|
||||
<InfoItem icon={Wallet} label="Wage Type" value={employee.wage_type} />
|
||||
<InfoItem icon={Clock} label="Hourly Rate" value={employee.hourly_rate != null ? Number(employee.hourly_rate).toFixed(2) : null} />
|
||||
<InfoItem icon={PercentIcon} label="Commission %" value={employee.commission_rate != null ? Number(employee.commission_rate).toFixed(2) : null} />
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Landmark} label="Bank" value={employee.bank_name} />
|
||||
<InfoItem icon={Wallet} label="Account #" value={employee.bank_account_number} />
|
||||
<InfoItem icon={Landmark} label="IBAN" value={employee.bank_iban} />
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<InfoItem icon={Calendar} label="Shop Calendar" value={employee.shop_calender?.title} />
|
||||
<InfoItem icon={Clock} label="Shop Timing" value={employee.shop_timing?.title} />
|
||||
<InfoItem icon={MapPin} label="Geo Fence Radius (m)" value={employee.geo_fence_radius != null ? String(employee.geo_fence_radius) : null} />
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user