30 Commits
Author SHA1 Message Date
Claude CodeandClaude Opus 4.8 7b145c1469 fix(dashboard): use /api/v1/saas path for subdomain workspace resolution
The edge middleware resolved the workspace by calling the SaaS landlord at
/api/saas/workspaces/by-subdomain/<sub>, but the landlord serves that route
under /api/v1/saas/... (the garage backend already calls it with /v1). The
missing version segment returned 404, so no workspace_uuid/api_base_url
cookies were set and the proxy responded "Workspace session not found",
blocking email/password login on a cold visit to <sub>.reparee.com/login.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 06:51:56 +00:00
aseelandClaude Opus 4.8 33da1204dd fix(api): route SSR requests to the tenant backend with workspace context
getServerApi only forwarded the auth token, using the default API base URL
and sending no workspace header. In the multi-tenant setup the per-workspace
backend URL (api_base_url) and id (workspace_uuid) live in httpOnly cookies,
and client requests reach the right tenant via the /api/proxy route. SSR
never replicated that, so server components hit the wrong/default backend and
got "not found" for resources that exist — e.g. the vendor detail page.

Read api_base_url and workspace_uuid from cookies and pass baseUrl +
X-Workspace-UUID to createApi, mirroring the proxy. Fixes every server-
rendered detail page, not just vendors.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:37:44 +04:00
aseelandClaude Opus 4.8 75e44f5b26 fix(data-table): preserve prior rows when multi-selecting
onRowSelectionChange computed the next selection from the render-time
`rowSelection` closure, which could be stale by the time a second row was
toggled. The updater then produced a selection containing only the latest
row, and the persistedMap sync deleted the earlier one — so checking a
second part unchecked the first, making multi-select behave as single-select.

Track the latest selection in a ref and derive the updater from it, so each
toggle builds on the current selection. Fixes adding multiple parts/services/
expense items in invoices, estimates, and job cards.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:28:58 +04:00
aseelandClaude Opus 4.8 29d90b5e71 fix(vendor): stop detail route crashing when vendor fetch fails
The vendor detail page and layout called api.vendors.getById without a
try/catch. The API client throws ApiError on any non-2xx, so a 404 (missing
vendor), 401, or 5xx during SSR threw out of the server component and
white-screened the whole route with a generic "server-side exception" —
the existing `if (!vendor)` fallback was never reached.

Guard both fetches: log the error and degrade gracefully (page shows
"Vendor not found", layout renders chrome with a fallback title).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 16:23:29 +04:00
aseelandClaude Opus 4.8 f9aac2db37 fix(vehicles): serialize booleans as 1/0 in multipart payload
The vehicle form uploads as multipart/form-data for the image, and the
FormData builder stringified every value, turning has_insurance=false into
the literal "false". Laravel's boolean rule rejects "true"/"false" strings,
producing "The has insurance field must be true or false." Serialize
booleans as "1"/"0" so they validate; null values remain skipped (nullable).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:45:04 +04:00
Najjar\NajjarV02andClaude Opus 4.8 11d920ba6a fix(dashboard): resolve Asma tester-reported UI issues
- 3.1 currency: replace hardcoded $ with AED <Money/> in item & job-card price cells
- 5.1 calendar: /calendars now renders the month calendar (was redirect to list)
- 7.2 nav: remove dead Time Clocks / Time Sheets links (no routes, 404)
- 5.4 check-in: enforce required department at schema level
- 5.6 payments received: add invoice picker so the invoice is marked Paid
- 5.2 share link: forward ws workspace param from the public inspection page

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 14:58:18 +04:00
Najjar\NajjarV02andClaude Opus 4.8 0171daea38 fix(dashboard): add inline department create to job-card check-in
Wire the department select to DepartmentInlineForm and align its option mapping/store-object with the shared async-select contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 14:40:56 +04:00
Najjar\NajjarV02andClaude Opus 4.8 a1c647a7b3 fix(dashboard): widen generate-invoice dialog so details sidebar fits
min-w-2xl pinned the dialog to ~672px while the default sm:max-w-md cap left the col-span-3 details sidebar too narrow, clipping the date pickers and customer/vehicle selects. Switch to sm:max-w-5xl so the two-column layout has room; mobile width unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 14:40:56 +04:00
Najjar\NajjarV02andClaude Opus 4.8 16fd7dd423 feat(shop-timings): day-of-week select and closed toggle in form
Add day_of_week dropdown and is_closed checkbox to the shop timing form.
In/out times become optional and disabled when the day is marked closed;
required otherwise via schema superRefine.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 14:39:55 +04:00
Najjar\NajjarV02andClaude Opus 4.8 baa716b8ff feat(dashboard): allow both vendor and employee on payment made
Remove the mutual-exclusion validation and update the field descriptions so a payment-made can be linked to a vendor and an employee at the same time. Previously selecting both raised a validation error.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 14:36:34 +04:00
aseelandClaude Opus 4.8 97ad275588 feat(dashboard): add onboarding gate forcing company setup before app use
After login/activation, show a full-screen loader while company settings
resolve, then force the user onto /settings/company and block navigation to
any other route until the company info is filled in. The gate releases once the
company record has a name; fails open on API error so a transient failure can
never lock the user out.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:58:37 +04:00
aseelandClaude Opus 4.8 fdce301495 fix(dashboard): resolve tutorial QA notes (clips 2–6)
- settings/company: show success toast on save (2.1)
- inspection templates: add explicit Save button (2.6)
- parts: label price fields with AED currency (3.1)
- service groups: add parts/services picker to packages (3.3)
- vehicles: add insurance (has_insurance + insurance type) field (4.2)
- appointments: add calendar view with list/calendar toggle (5.1)
- job card check-in: require department (5.4)
- job card payments: refresh job card/invoice queries so PAID shows (5.6)
- vendors: add phone + address fields (6.1)
- bill payments: surface real vendor/employee validation errors (6.4)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 11:39:07 +04:00
Najjar\NajjarV02 c71b5a19ed ui(login): remove last-email display under submit button 2026-05-22 13:55:18 +04:00
Najjar\NajjarV02 3e229d0de1 feat(middleware): resolve workspace from Host on tenant subdomain
When a visitor lands on <subdomain>.reparee.com without prior
handoff, edge middleware HMAC-signs the subdomain and calls SaaS
/api/saas/workspaces/by-subdomain/<sub> to resolve workspace_uuid
and api_base_url, sets them as HttpOnly cookies. Direct login
(skipping handoff) now works because /api/proxy/* has workspace
context from the first request.

Skips on:
- workspace_uuid cookie already present
- non-tenant hosts (apex, localhost, www, "tenant" fallback)
- SAAS_SHARED_SECRET env missing (degraded: returns to 412)

Requires SaaS endpoint /api/saas/workspaces/by-subdomain/{sub}
(new WorkspaceBySubdomainController) and SAAS_SHARED_SECRET env
in Coolify (server-side only, not NEXT_PUBLIC_).
2026-05-22 12:37:11 +04:00
Najjar\NajjarV02 a888157d33 fix(api): correct typo in comments regarding workspace API installation 2026-05-22 11:38:21 +04:00
Najjar\NajjarV02 6d6059330a fix(deploy): add curl to runner stage for Coolify healthcheck 2026-05-22 11:22:05 +04:00
Najjar\NajjarV02 cd66daa6b1 fix(deploy): force dev deps in Docker deps stage; commit prod NEXT_PUBLIC_*
Coolify injects NODE_ENV=production at build time, causing
`pnpm install --frozen-lockfile` to skip devDependencies. Next.js
build then fails on missing @tailwindcss/postcss.

Override NODE_ENV=development and pass --prod=false for the install
step only. Builder stage still runs `next build` with
NODE_ENV=production, which is the intended runtime mode.

Also commits apps/dashboard/.env.production with public URLs so
Next.js bakes NEXT_PUBLIC_* into the bundle at build time (Coolify
API rejects the is_build_time flag, so we can't mark them runtime).
2026-05-22 11:16:29 +04:00
Najjar\NajjarV02 2505fccd5f feat: add Dockerfile, .dockerignore, and deployment documentation for Coolify integration 2026-05-21 11:08:48 +04:00
Najjar\NajjarV02andClaude Opus 4.7 019ea56e6f fix(activate): move handoff handler to /activate/handoff/[token]/route.ts
Next.js disallows cookie writes inside Server Components, so the handoff
exchange had to move to a Route Handler. But a route.ts cannot coexist
with a sibling page.tsx in the same segment, so the handler now lives at
/activate/handoff/[token]/route.ts and the page.tsx at /activate/[token]
becomes a stale-link error page.

Additional fixes:

- Use an explicit relative Location header (Location: /) on the success
  redirect instead of NextResponse.redirect(new URL("/", req.url)). In
  dev, req.url resolves to the canonical host and can differ from the
  host the user came in on (127.0.0.1 vs localhost), causing cookies set
  on the response to drop on cross-host follow.

- Same fix for the error redirect to /activate/error.

- New /activate/error/page.tsx renders the failure UI from the ?reason=
  query string.

- /activate/[token]/route.ts (the original location) is preserved as
  route.ts.disabled so Next does not register it and the prior segment's
  page.tsx can take over the error UI for stale links.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:22:25 +04:00
Najjar\NajjarV02 ccb9eacd86 feat: implement workspace session management and enhance API proxy handling 2026-05-20 16:23:19 +04:00
humam 4f0a2f790f feat: add logo field to settings schema and update settings client to handle file uploads
feat: integrate dialog close context in vendor select field and CRUD dialog components

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

feat: implement form dialog context for managing dialog close actions

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

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

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

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

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

feat: implement payment made and received detail pages with actions

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

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

feat: implement dialog close context for better dialog management

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 16:22:26 +04:00
254 changed files with 9879 additions and 1624 deletions
+13
View File
@@ -0,0 +1,13 @@
{
"permissions": {
"allow": [
"Bash(pnpm --version)",
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
]
},
"enabledMcpjsonServers": [
"code-review-graph"
],
"enableAllProjectMcpServers": true
}
+30
View File
@@ -0,0 +1,30 @@
**/node_modules
**/.next
**/.turbo
**/dist
**/build
**/.git
**/.gitignore
**/.env
**/.env.local
**/.env.*.local
**/npm-debug.log
**/yarn-debug.log
**/yarn-error.log
**/*.log
**/cypress/videos
**/cypress/screenshots
**/.DS_Store
**/Thumbs.db
**/.idea
**/.vscode
**/coverage
**/.cache
**/.eslintcache
**/test-results
**/playwright-report
Dockerfile
.dockerignore
README.md
docs
*.pdf
+2
View File
@@ -0,0 +1,2 @@
NIXPACKS_NODE_VERSION=22
NEXT_PUBLIC_API_URL=http://reparee.test
+102
View File
@@ -0,0 +1,102 @@
# Garage dashboard (garage-erp) — Coolify deploy
Domain: **tenant.reparee.com**
Build: Docker (multi-stage), Next.js standalone output
Port: **3000** inside container; Coolify maps to 80/443 + TLS
---
## 1. New Application in Coolify
1. **+ New Resource → Application → Public Repository** (or GitHub App).
2. Repo: this monorepo. Branch: `main` (or whatever).
3. **Build Pack: Dockerfile**.
4. **Base Directory**: `garage-erp` (where the Dockerfile lives — relative to repo root).
- If `garage-erp` IS the repo root, leave blank.
5. **Dockerfile Location**: `Dockerfile` (default).
6. **Port**: `3000`.
## 2. Environment variables
Coolify → Application → **Environment Variables**. Add:
| Key | Value |
|---|---|
| `NEXT_PUBLIC_API_URL` | `https://api.reparee.com` |
| `NEXT_PUBLIC_SAAS_URL` | `https://reparee.com` |
| `NEXT_PUBLIC_GARAGE_HOST_PATTERN` | `*.reparee.com` |
| `NODE_ENV` | `production` |
| `HOSTNAME` | `0.0.0.0` |
| `PORT` | `3000` |
| `NEXT_TELEMETRY_DISABLED` | `1` |
> `NEXT_PUBLIC_*` values are **baked into the JS bundle at build time**. Changing them requires a redeploy, not just a restart.
## 3. Domain + TLS
Coolify → Application → **Domains** → add `https://tenant.reparee.com`. Coolify auto-provisions Let's Encrypt cert. DNS A record must already point to the Coolify server's public IP.
## 4. Healthcheck
Coolify → Application → **Healthcheck**:
- **Path**: `/api/proxy/health` — set this once the backend is reachable; otherwise `/` works for the first deploy.
- **Port**: `3000`
- **Interval**: 30s
- **Timeout**: 10s
## 5. Build options
- **Build pack**: Dockerfile
- **Custom build command**: leave blank (Dockerfile handles it)
- **Build args**: none required; all envs are runtime
## 6. Deploy
Click **Deploy**. Watch build logs:
- Stage 1 (`deps`): `pnpm install --frozen-lockfile` — ~2-4 min.
- Stage 3 (`builder`): `pnpm --filter @garage/dashboard build` — ~3-6 min. Watch for Next.js trace warnings; they are non-fatal.
- Stage 4 (`runner`): copies standalone output; tiny.
First build is slow. Subsequent builds reuse Docker layer cache.
## 7. Smoke test
```bash
curl -I https://tenant.reparee.com
# → 200 OK + Set-Cookie not yet set (no session)
# Activation: full flow goes SaaS → /activate/handoff/{token}?ws=&api=
# Cookies expected after redirect: auth_token, auth_user, workspace_uuid, api_base_url
```
## 8. CORS / cookies sanity
The dashboard only sets cookies on its own origin (`tenant.reparee.com`). The Next.js server proxy at `/api/proxy/*` strips upstream `Set-Cookie` headers — Laravel cookies never reach the browser. Workspace context is read from cookies on every server-side proxy call.
Verify in browser DevTools after handoff:
- 4 cookies on `tenant.reparee.com`, all HttpOnly + SameSite=Strict + Secure.
- Network tab: all `XHR/fetch` go to `tenant.reparee.com/api/proxy/...`. **Zero direct calls** to `api.reparee.com` from the browser.
## 9. Logs
Coolify → Application → **Logs** tab streams container stdout/stderr. Next.js logs requests as `GET / 200 in 45ms` etc.
## 10. Rollback
Coolify → **Deployments** tab → pick a previous successful deployment → **Redeploy**.
## 11. Notes on monorepo
- The Dockerfile builds **only** the `@garage/dashboard` app. `@garage/api` is built as part of dashboard's `prebuild` hook (it generates OpenAPI types from `postman/collection.json`).
- If you split apps later (e.g. a separate admin app), copy the Dockerfile and change the `--filter @garage/dashboard` line.
- `output: 'standalone'` in `apps/dashboard/next.config.mjs` is required for the runner stage to work. Do not remove.
## 12. Cypress / e2e
Out of scope for the runtime container. If you want CI e2e runs:
- Use Coolify's **GitHub Actions integration** to run `pnpm test:e2e` in CI before the deploy webhook fires.
- Update `apps/dashboard/cypress.config.ts` to read `baseUrl` from env (currently hard-coded to `https://newgarage.yslootahtech.com`).
+70
View File
@@ -0,0 +1,70 @@
# Multi-stage Dockerfile for garage-erp dashboard (Coolify).
# Monorepo: turborepo + pnpm; @garage/dashboard depends on @garage/api.
# Build context = garage-erp/ (repo root for this app).
# ────────────────────────────────────────────────────────────
# Stage 1: base — pnpm via corepack, shared layer
# ────────────────────────────────────────────────────────────
FROM node:22-alpine AS base
RUN corepack enable && corepack prepare pnpm@9.0.0 --activate
WORKDIR /app
# ────────────────────────────────────────────────────────────
# Stage 2: deps — install all workspace deps
# ────────────────────────────────────────────────────────────
FROM base AS deps
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
COPY apps/dashboard/package.json ./apps/dashboard/
COPY packages/api/package.json ./packages/api/
COPY packages/ui/package.json ./packages/ui/
COPY packages/eslint-config/package.json ./packages/eslint-config/
COPY packages/typescript-config/package.json ./packages/typescript-config/
# Force dev deps even when Coolify injects NODE_ENV=production at build time.
# Tailwind / postcss / next types are devDependencies — required by `next build`.
RUN NODE_ENV=development pnpm install --frozen-lockfile --prod=false
# ────────────────────────────────────────────────────────────
# Stage 3: builder — build dashboard with standalone output
# ────────────────────────────────────────────────────────────
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/dashboard/node_modules ./apps/dashboard/node_modules
COPY --from=deps /app/packages/api/node_modules ./packages/api/node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
# Build only the dashboard (turbo handles @garage/api codegen via prebuild hook)
RUN pnpm --filter @garage/dashboard build
# ────────────────────────────────────────────────────────────
# Stage 4: runner — minimal runtime, standalone Next.js
# ────────────────────────────────────────────────────────────
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
# curl for Coolify healthcheck (busybox wget prefers IPv6 ::1 and fails)
RUN apk add --no-cache curl
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs
# Standalone server + traced node_modules
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/standalone ./
# Static assets
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/static ./apps/dashboard/.next/static
# Public assets (logos, etc.)
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/public ./apps/dashboard/public
USER nextjs
EXPOSE 3000
# Standalone entry is at apps/dashboard/server.js after copy
CMD ["node", "apps/dashboard/server.js"]
+10
View File
@@ -0,0 +1,10 @@
# Fallback backend URL — only used if the per-session `api_base_url` cookie
# is not set. The SaaS → /activate/[token] handoff sets that cookie, and the
# server proxy at /api/proxy/* forwards to whatever URL it contains.
NEXT_PUBLIC_API_URL=http://localhost:8001
# Used by the "Workspace session not found" page to link back to the SaaS.
NEXT_PUBLIC_SAAS_URL=http://localhost:8000
# Image remotePatterns wildcard for SaaS-provisioned subdomains.
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
+6
View File
@@ -0,0 +1,6 @@
# Committed prod env — Next.js bakes NEXT_PUBLIC_* into the bundle at build time.
# Only public URLs here. Secrets stay in Coolify env vars (runtime).
NEXT_PUBLIC_API_URL=https://api.reparee.com
NEXT_PUBLIC_SAAS_URL=https://reparee.com
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
+16
View File
@@ -0,0 +1,16 @@
# Production env — Coolify provides these at deploy time.
# Fallback backend URL — only used if the per-session `api_base_url` cookie
# is not set. SaaS handoff sets that cookie; server proxy uses it.
NEXT_PUBLIC_API_URL=https://api.reparee.com
# Used by "Workspace session not found" page CTA back to SaaS.
NEXT_PUBLIC_SAAS_URL=https://reparee.com
# Image remotePatterns wildcard for SaaS-provisioned subdomains.
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
# Forces Next to bind 0.0.0.0 in Docker. Coolify normally sets this.
HOSTNAME=0.0.0.0
PORT=3000
NODE_ENV=production
@@ -1,15 +1,19 @@
"use client"
import { useState } from "react"
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 { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
import { CalendarCheck2Icon, CalendarDaysIcon, ClipboardListIcon, ClockIcon, ListIcon } 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",
@@ -21,11 +25,50 @@ const STATUS_COLORS: Record<string, string> = {
export default function AppointmentsPage() {
const router = useRouter()
const [view, setView] = useState<"list" | "calendar">("list")
const viewToggle = (
<div className="flex items-center justify-end gap-1 px-1">
<Button
type="button"
variant={view === "list" ? "default" : "outline"}
size="sm"
onClick={() => setView("list")}
>
<ListIcon className="me-1 size-4" /> List
</Button>
<Button
type="button"
variant={view === "calendar" ? "default" : "outline"}
size="sm"
onClick={() => setView("calendar")}
>
<CalendarDaysIcon className="me-1 size-4" /> Calendar
</Button>
</div>
)
if (view === "calendar") {
return (
<div className="space-y-4 p-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Appointments</h1>
{viewToggle}
</div>
<AppointmentsCalendarView />
</div>
)
}
return (
<div className="space-y-2">
{viewToggle}
<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 +120,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,27 +129,20 @@ 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)}
/>
)
},
},
actionsColumn(),
]}
/>
</div>
)
}
@@ -1,5 +1,12 @@
import { redirect } from "next/navigation"
"use client"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
export default function CalendarsPage() {
return redirect("/calendar/appointment/list")
return (
<div className="space-y-4 p-4">
<h1 className="text-xl font-semibold">Calendar</h1>
<AppointmentsCalendarView />
</div>
)
}
@@ -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>
@@ -4,6 +4,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 { ExpenseItemForm } from "@/modules/expense-items/expense-item-form"
import { Money } from "@/shared/components/money"
import { EXPENSE_ITEM_ROUTES } from "@garage/api"
import type { ExpenseItemsClient } from "@garage/api"
@@ -12,15 +13,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>
@@ -36,7 +42,7 @@ export default function ExpenseItemPage() {
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
cell: ({ row }) => {
const val = (row.original as any).purchase_price
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -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)}
@@ -4,6 +4,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 { ServiceGroupForm } from "@/modules/service-groups/service-group-form"
import { Money } from "@/shared/components/money"
import { Badge } from "@/shared/components/ui/badge"
import { SERVICE_GROUP_ROUTES } from "@garage/api"
import type { ServiceGroupsClient } from "@garage/api"
@@ -13,6 +14,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: (
@@ -48,7 +51,7 @@ export default function ServiceGroupPage() {
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
cell: ({ row }) => {
const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -5,6 +5,7 @@ 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 { Money } from "@/shared/components/money"
import { useAuthApi } from "@/shared/useApi"
import { ServiceForm } from "@/modules/services/service-form"
import { SERVICE_ROUTES } from "@garage/api"
@@ -17,6 +18,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 +27,7 @@ export default function ServicesPage() {
<ImportDataButton
onImport={(file) => api.services.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Services"
/>
<ExportDataButton
onExport={(filters) => api.services.exportData(filters)}
@@ -72,7 +76,7 @@ export default function ServicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
cell: ({ row }) => {
const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -6,6 +6,7 @@ import { DashboardLayout } from "@/base/components/layout/dashboard"
import { useAuth } from "@/shared/hooks/use-auth"
import { navGroups } from "@/config/navGroups"
import { getAuthCookies } from "@/modules/auth/auth.actions"
import { OnboardingGate } from "@/shared/components/onboarding-gate"
import { redirect } from "next/navigation"
@@ -38,7 +39,7 @@ export default async function AuthenticatedLayout({
return (
<DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}>
{children}
<OnboardingGate>{children}</OnboardingGate>
</DashboardLayout>
)
}
@@ -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> : "—"
},
},
]}
/>
)
}
@@ -28,6 +28,8 @@ 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}/permissions`, label: 'Permissions' },
]}
>
@@ -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,21 +1,71 @@
"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 { EmployeeForm } from "@/modules/employees/employee-form"
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 [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">
@@ -34,8 +84,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 +103,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 +137,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: (
@@ -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",
@@ -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,44 @@
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()
// Guard the fetch: a failed request (404/401/5xx) must not throw and crash
// the whole route — render the chrome with a fallback title instead.
let vendor: Record<string, any> | undefined
try {
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
vendor = response?.data
} catch (err) {
console.error(`Failed to load vendor ${id} (layout):`, err)
}
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,24 @@
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.
// Guard the fetch: a failed request (404/401/5xx) must degrade gracefully
// instead of throwing and white-screening the whole route.
let vendor: Record<string, any> | undefined
try {
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
vendor = response?.data
} catch (err) {
console.error(`Failed to load vendor ${id}:`, err)
}
if (!vendor) {
return <div className="text-muted-foreground p-6">Vendor not found.</div>
}
return <VendorGeneralInfo vendor={vendor} />
}
+42 -1
View File
@@ -1,18 +1,28 @@
"use client"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Power } from "lucide-react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { VendorForm } from "@/modules/vendors/vendor-form"
import { useAuthApi } from "@/shared/useApi"
import { VENDOR_ROUTES } from "@garage/api"
import type { VendorsClient } from "@garage/api"
export default function VendorsPage() {
const router = useRouter()
const api = useAuthApi()
return (
<ResourcePage<VendorsClient>
pageTitle="Vendors"
routeKey={VENDOR_ROUTES.INDEX}
searchable
searchPlaceholder="Search vendors..."
getClient={(api) => api.vendors}
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Vendor">
@@ -46,6 +56,18 @@ export default function VendorsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
cell: ({ row }) => (row.original as any).email || "—",
},
{
accessorKey: "is_active",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const isActive = Boolean((row.original as any).is_active)
return (
<Badge variant={isActive ? "default" : "outline"}>
{isActive ? "Active" : "Inactive"}
</Badge>
)
},
},
{
accessorKey: "created_at",
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
@@ -54,7 +76,26 @@ export default function VendorsPage() {
return val ? new Date(val).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => {
const isActive = Boolean((row as any).is_active)
return [
{
label: isActive ? "Deactivate" : "Activate",
icon: Power,
onClick: async () => {
try {
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
router.refresh()
} catch {
toast.error("Failed to update vendor status.")
}
},
},
]
},
}),
]}
/>
)
@@ -5,8 +5,11 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
import { CREDIT_NOTE_ROUTES } from "@garage/api"
import { CREDIT_NOTE_ROUTES, CreditNoteStatus } from "@garage/api"
import type { CreditNotesClient } from "@garage/api"
import { formatEnum } from "@/shared/utils/formatters"
import { Printer } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteItem = {
id: number
@@ -20,11 +23,15 @@ type CreditNoteItem = {
export default function CreditNotesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<CreditNotesClient>
pageTitle="Credit Notes"
routeKey={CREDIT_NOTE_ROUTES.INDEX}
searchable
searchPlaceholder="Search credit notes..."
statusFilter={{ statuses: CreditNoteStatus }}
getClient={(api) => api.creditNotes}
onRowClick={(row) => router.push(`/sales/credit-notes/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -63,7 +70,7 @@ export default function CreditNotesPage() {
}
return (
<span className={colorMap[status ?? ""] ?? ""}>
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
{formatEnum(status)}
</span>
)
},
@@ -72,7 +79,15 @@ export default function CreditNotesPage() {
accessorKey: "date",
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("credit_note", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
)}
pageTitle="Customer Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
extraParams={{ customer_id: customerId }}
header={null}
@@ -6,7 +6,6 @@ import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import { CustomerForm } from '@/modules/customers/customer-form'
import { CUSTOMER_ROUTES } from '@garage/api'
@@ -20,18 +19,19 @@ export default function CustomersPage() {
<ResourcePage<CustomersClient>
pageTitle='Customers'
routeKey={CUSTOMER_ROUTES.INDEX}
searchable
searchPlaceholder="Search customers..."
getClient={(api) => api.customers}
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.customers.downloadImportSample()}
fileName='customers-import-sample'
/>
<ImportDataButton
onImport={(file) => api.customers.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Customers"
onDownloadSample={() => api.customers.downloadImportSample()}
sampleFileName='customers-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.customers.exportData(filters)}
@@ -4,6 +4,7 @@ import { EstimateActions } from '@/modules/estimates/estimate-actions'
import { EstimateProvider } from '@/modules/estimates/estimate-context'
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import { FileTextIcon } from 'lucide-react'
import React from 'react'
import { formatDate } from '@/shared/utils/formatters'
@@ -40,6 +41,7 @@ export default async function layout(props: {
<div className="flex items-center gap-2">
<CreateInvoiceFromEstimateButton />
<CreateJobCardFromEstimateButton />
<ShareDocumentButton type="estimate" id={id} />
<EstimateActions estimateId={id} />
</div>
}
@@ -1,24 +1,31 @@
"use client"
import { useRouter } from 'next/navigation'
import { ResourcePage } from '@/shared/data-view/resource-page'
import { ColumnHeader } from '@/shared/data-view/table-view'
import FormDialog from '@/shared/components/form-dialog'
import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
import { Button } from '@/shared/components/ui/button'
import { Car, FileTextIcon, Printer, UserIcon } from 'lucide-react'
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
import Link from 'next/link'
import { formatDate } from '@/shared/utils/formatters'
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function EstimatesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<EstimatesClient>
pageTitle="Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Estimate">
@@ -39,7 +46,7 @@ export default function EstimatesPage() {
const item = row.original
return (
<div className="flex items-center gap-2">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
<FileTextIcon className="text-muted-foreground h-4 w-4" />
<span>{item.title}</span>
</Link>
@@ -57,24 +64,28 @@ export default function EstimatesPage() {
cell: ({ row }) => {
const item: any = row.original
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer)}
/>
)
}
},
},
{
accessorKey: "vehicle",
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item: any = row.original
return <Button variant="outline" asChild size="sm">
<Link href={`/sales/vehicles/${item.vehicle?.id}`}>
<Car/> {getVehicleLabel(item.vehicle as any) || "—"}
</Link>
</Button>
}
return (
<RelationLink
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
icon={Car}
label={getVehicleLabel(item.vehicle as any)}
meta={item.vehicle?.license_plate}
/>
)
},
},
{
accessorKey: "date",
@@ -100,7 +111,15 @@ export default function EstimatesPage() {
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("estimate", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -1,589 +1,458 @@
"use client"
import { use, useState, useRef, useCallback } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/components/ui/select"
import { useCallback, useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { toast } from "sonner"
import {
Plus,
Ellipsis,
Pencil,
Trash2,
CheckCircle2,
AlertTriangle,
XCircle,
MinusCircle,
CircleDot,
Paperclip,
FileUp,
FileText,
FileImage,
File,
X,
Car,
ChevronLeft,
ChevronRight,
CircleCheck,
FileSignature,
Gauge,
Image as ImageIcon,
Loader2,
Share2,
StickyNote,
User,
} from "lucide-react"
import { INSPECTION_ROUTES } from "@garage/api"
// ── Types ──
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card"
import { Progress } from "@/shared/components/ui/progress"
import { Separator } from "@/shared/components/ui/separator"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { useAuthApi } from "@/shared/useApi"
import {
CheckpointFillDialog,
isCheckpointComplete,
type Checkpoint,
type Severity,
} from "@/modules/inspections/checkpoint-fill-dialog"
import { SignaturePad } from "@/modules/inspections/signature-pad"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
type CheckpointItem = {
type Inspection = {
id: number
inspection_id?: number
name?: string
description?: string
record_type?: string
condition_rate?: number
file?: string
status?: string
created_at?: string
updated_at?: string
title: string
order_number?: string | null
status?: string | null
odometer?: number | null
template?: { id: number; name: string } | null
customer?: { first_name?: string; last_name?: string } | null
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string } | null
check_points: Checkpoint[]
technician_signature_url?: string | null
customer_signature_url?: string | null
}
// ── Constants ──
const CHECKPOINT_STATUSES = [
{ value: "passed", label: "Passed", icon: CheckCircle2, color: "bg-green-100 text-green-800" },
{ value: "need_attention", label: "Need Attention", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800" },
{ value: "failed", label: "Failed", icon: XCircle, color: "bg-red-100 text-red-800" },
{ value: "not_applicable", label: "Not Applicable", icon: MinusCircle, color: "bg-gray-100 text-gray-800" },
{ value: "not_inspected", label: "Not Inspected", icon: CircleDot, color: "bg-blue-100 text-blue-800" },
] as const
const RECORD_TYPES = [
{ value: "record_conditions", label: "Record Conditions" },
{ value: "record_audio", label: "Record Audio" },
{ value: "record_video", label: "Record Video" },
{ value: "capture_photo", label: "Capture Photo" },
] as const
function formatStatus(status?: string) {
if (!status) return "Not Inspected"
return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
const SEVERITY_DOT: Record<Severity, string> = {
good: "bg-emerald-500 shadow-emerald-500/30",
attention: "bg-amber-500 shadow-amber-500/30",
critical: "bg-rose-500 shadow-rose-500/30",
na: "bg-slate-400 shadow-slate-400/30",
not_inspected: "bg-muted shadow-none",
}
const SEVERITY_LABEL: Record<Severity, string> = {
good: "Good",
attention: "Attention",
critical: "Critical",
na: "N/A",
not_inspected: "Not inspected",
}
const SEVERITY_BADGE: Record<Severity, "default" | "secondary" | "destructive" | "outline"> = {
good: "default",
attention: "secondary",
critical: "destructive",
na: "outline",
not_inspected: "outline",
}
function getStatusConfig(status?: string) {
return CHECKPOINT_STATUSES.find((s) => s.value === status) || CHECKPOINT_STATUSES[4]
function groupBySection(cps: Checkpoint[]) {
const map = new Map<string, Checkpoint[]>()
for (const cp of cps) {
const key = cp.section_name || "Other"
if (!map.has(key)) map.set(key, [])
map.get(key)!.push(cp)
}
return Array.from(map.entries()).map(([name, items]) => ({ name, items }))
}
// ── Checkpoint Form Dialog ──
function CheckpointFormDialog({
open,
onOpenChange,
inspectionId,
checkpoint,
onSuccess,
}: {
open: boolean
onOpenChange: (open: boolean) => void
inspectionId: string
checkpoint?: CheckpointItem | null
onSuccess: () => void
}) {
export default function InspectionCheckpointsPage() {
const params = useParams<{ id: string }>()
const id = params.id
const api = useAuthApi()
const [name, setName] = useState(checkpoint?.name ?? "")
const [description, setDescription] = useState(checkpoint?.description ?? "")
const [recordType, setRecordType] = useState(checkpoint?.record_type ?? "record_conditions")
const [isPending, setIsPending] = useState(false)
const isEditing = !!checkpoint
const [data, setData] = useState<Inspection | null>(null)
const [initialLoad, setInitialLoad] = useState(true)
const [refetching, setRefetching] = useState(false)
const [activeIndex, setActiveIndex] = useState<number | null>(null)
const [shareOpen, setShareOpen] = useState(false)
const [mode, setMode] = useState<"all" | "wizard">("all")
const [wizardSectionIdx, setWizardSectionIdx] = useState(0)
const [signing, setSigning] = useState<{ who: "technician" | "customer" } | null>(null)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!name.trim()) {
toast.error("Name is required")
return
}
setIsPending(true)
const load = useCallback(async () => {
const isFirst = !data
if (isFirst) setInitialLoad(true)
else setRefetching(true)
try {
const payload = {
inspection_id: Number(inspectionId),
name: name.trim(),
description: description.trim() || undefined,
record_type: recordType,
const res = await api.inspections.showOne(id)
setData(res.data as Inspection)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to load inspection")
} finally {
setInitialLoad(false)
setRefetching(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
const patchCheckpoint = useCallback((checkpointId: number, patch: Partial<Checkpoint>) => {
setData((prev) => {
if (!prev) return prev
return {
...prev,
check_points: prev.check_points.map((c) =>
c.id === checkpointId ? { ...c, ...patch } : c
),
}
})
}, [])
useEffect(() => { load() }, [load])
const sections = useMemo(() => data ? groupBySection(data.check_points ?? []) : [], [data])
const flatCheckpoints = useMemo(() => sections.flatMap((s) => s.items), [sections])
const totals = useMemo(() => {
const t = { good: 0, attention: 0, critical: 0, na: 0, not_inspected: 0 }
for (const cp of data?.check_points ?? []) {
const s = (cp.severity as Severity) ?? "not_inspected"
t[s]++
}
return t
}, [data])
const setSeverity = async (cp: Checkpoint, severity: Severity) => {
patchCheckpoint(cp.id, { severity })
try {
await api.inspections.updateCheckpoint(String(cp.id), { severity } as any)
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save")
load()
}
}
if (isEditing) {
const promise = api.inspections.updateCheckpoint(String(checkpoint.id), payload)
toast.promise(promise, {
loading: "Updating checkpoint...",
success: "Checkpoint updated",
error: "Failed to update checkpoint",
})
await promise
} else {
const promise = api.inspections.createCheckpoint(payload)
toast.promise(promise, {
loading: "Creating checkpoint...",
success: "Checkpoint created",
error: "Failed to create checkpoint",
})
await promise
}
onSuccess()
onOpenChange(false)
const handleSign = async (who: "technician" | "customer", dataUrl: string) => {
setSigning({ who })
try {
await api.inspections.sign(id, who, dataUrl)
toast.success(who === "technician" ? "Technician signature saved" : "Customer signature saved")
load()
} catch (e: any) {
toast.error(e?.payload?.message ?? "Failed to save signature")
} finally {
setIsPending(false)
setSigning(null)
}
}
if (initialLoad) {
return (
<div className="min-h-[60vh] flex items-center justify-center">
<div className="flex items-center gap-2 text-muted-foreground text-sm">
<Loader2 className="size-4 animate-spin" /> Loading inspection…
</div>
</div>
)
}
if (!data) return <div className="p-6 text-muted-foreground">Inspection not found</div>
const vehicleLine = data.vehicle
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
: "—"
const customerName = data.customer ? `${data.customer.first_name ?? ""} ${data.customer.last_name ?? ""}`.trim() : "—"
const totalCount = data.check_points.length
const inspectedCount = totalCount - totals.not_inspected
const progress = totalCount > 0 ? Math.round((inspectedCount / totalCount) * 100) : 0
const wizardSection = sections[wizardSectionIdx]
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Checkpoint" : "Add Checkpoint"}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="cp-name">Name *</Label>
<Input
id="cp-name"
placeholder="e.g. Engine Oil Level"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4">
{/* Header */}
<Card>
<CardHeader className="gap-3">
<div className="flex items-center justify-between gap-2 flex-wrap">
<Link href={`/sales/inspections/${id}`}>
<Button variant="ghost" size="sm" className="-ms-2">
<ChevronLeft className="size-4" /> Back to inspection
</Button>
</Link>
<div className="flex items-center gap-2">
{refetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
<Button variant="outline" size="sm" onClick={() => setShareOpen(true)}>
<Share2 className="size-4" /> Share with customer
</Button>
</div>
<div className="grid gap-2">
<Label htmlFor="cp-description">Description</Label>
<Textarea
id="cp-description"
placeholder="Check oil level and condition"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="cp-record-type">Record Type</Label>
<Select value={recordType} onValueChange={setRecordType}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{RECORD_TYPES.map((rt) => (
<SelectItem key={rt.value} value={rt.value}>
{rt.label}
</SelectItem>
<Separator />
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="min-w-0">
<CardDescription className="uppercase tracking-wide text-[11px]">Inspection</CardDescription>
<CardTitle className="text-2xl">{data.title}</CardTitle>
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground flex-wrap">
<span className="inline-flex items-center gap-1.5"><User className="size-3.5" /> {customerName}</span>
<span className="inline-flex items-center gap-1.5"><Car className="size-3.5" /> {vehicleLine}</span>
{data.vehicle?.license_plate && (
<Badge variant="outline" className="font-mono">{data.vehicle.license_plate}</Badge>
)}
{data.odometer != null && (
<span className="inline-flex items-center gap-1.5"><Gauge className="size-3.5" /> {Number(data.odometer).toLocaleString()} km</span>
)}
</div>
</div>
</div>
</CardHeader>
<CardContent className="gap-3">
{/* Progress */}
<div className="space-y-1.5">
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>Progress</span>
<span className="tabular-nums">{inspectedCount} / {totalCount} ({progress}%)</span>
</div>
<Progress value={progress} className="h-2" />
</div>
{/* Severity tally */}
<div className="flex items-center gap-2 flex-wrap mt-3">
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
<Badge key={s} variant={SEVERITY_BADGE[s]} className="gap-1.5">
<span className={`size-1.5 rounded-full ${SEVERITY_DOT[s].split(" ")[0]}`} />
{totals[s]} {SEVERITY_LABEL[s]}
</Badge>
))}
</SelectContent>
</Select>
</div>
<Button type="submit" disabled={isPending}>
{isEditing ? <Pencil className="size-4" /> : <Plus className="size-4" />}
{isPending
? (isEditing ? "Updating..." : "Creating...")
: (isEditing ? "Update Checkpoint" : "Create Checkpoint")}
</Button>
</form>
</DialogContent>
</Dialog>
)
}
// ── Attachments Dialog ──
function getFileIcon(url: string) {
const ext = url.split(".").pop()?.toLowerCase()
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")) return FileImage
if (ext === "pdf") return FileText
return File
}
function getFileName(url: string) {
try {
return decodeURIComponent(url.split("/").pop() ?? "Attachment")
} catch {
return url.split("/").pop() ?? "Attachment"
}
}
function isImageUrl(url: string) {
const ext = url.split(".").pop()?.toLowerCase()
return ["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")
}
function CheckpointAttachmentsDialog({
open,
onOpenChange,
checkpoint,
onSuccess,
}: {
open: boolean
onOpenChange: (open: boolean) => void
checkpoint: CheckpointItem | null
onSuccess: () => void
}) {
const api = useAuthApi()
const fileInputRef = useRef<HTMLInputElement>(null)
const [isUploading, setIsUploading] = useState(false)
const handleUpload = useCallback(async (file: globalThis.File) => {
if (!checkpoint) return
setIsUploading(true)
try {
const promise = api.inspections.uploadCheckpointMedia(
String(checkpoint.id),
{ file },
)
toast.promise(promise, {
loading: "Uploading attachment...",
success: "Attachment uploaded",
error: "Failed to upload attachment",
})
await promise
onSuccess()
} finally {
setIsUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ""
}
}, [api, checkpoint, onSuccess])
const handleDelete = useCallback(async () => {
if (!checkpoint) return
const promise = api.inspections.deleteCheckpointMedia(String(checkpoint.id))
toast.promise(promise, {
loading: "Removing attachment...",
success: "Attachment removed",
error: "Failed to remove attachment",
})
await promise
onSuccess()
}, [api, checkpoint, onSuccess])
const hasFile = !!checkpoint?.file
const FileIcon = checkpoint?.file ? getFileIcon(checkpoint.file) : File
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Attachments — {checkpoint?.name}</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4">
{/* Current attachment */}
{hasFile ? (
<div className="rounded-lg border p-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3 min-w-0 ">
{isImageUrl(checkpoint.file!) ? (
<img
src={checkpoint.file!}
alt="Checkpoint attachment"
className="size-12 rounded-md object-cover"
/>
) : (
<div className="flex size-12 shrink-0 items-center justify-center rounded-md bg-muted">
<FileIcon className="size-5 text-muted-foreground" />
</div>
)}
<div className="min-w-0 flex flex-col gap-0.5 max-w-48">
<a
href={checkpoint.file!}
target="_blank"
rel="noopener noreferrer"
className="truncate text-sm font-medium text-primary hover:underline"
>
{getFileName(checkpoint.file!)}
</a>
<span className="text-xs text-muted-foreground">
Current attachment
{/* Legend */}
<div className="mt-3 rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
<span className="font-medium text-foreground">Tap a dot to mark:</span>
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => (
<span key={s} className="inline-flex items-center gap-1.5">
<span className={`size-3 rounded-full ${SEVERITY_DOT[s].split(" ")[0]} shadow-md`} />
{SEVERITY_LABEL[s]}
</span>
))}
</div>
</div>
<Button
variant="ghost"
size="icon"
className="shrink-0 text-destructive hover:text-destructive"
onClick={handleDelete}
title="Remove attachment"
>
<Trash2 className="size-4" />
</Button>
</div>
</div>
) : (
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-muted-foreground">
<Paperclip className="size-8" />
<span className="text-sm">No attachments yet</span>
</div>
</CardContent>
</Card>
{/* Mode tabs */}
{totalCount > 0 && (
<Tabs value={mode} onValueChange={(v) => setMode(v as any)} className="w-full">
<TabsList className="w-full sm:w-auto">
<TabsTrigger value="all">All sections</TabsTrigger>
<TabsTrigger value="wizard">Wizard</TabsTrigger>
</TabsList>
</Tabs>
)}
{/* Upload area */}
<input
ref={fileInputRef}
type="file"
className="hidden"
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,audio/*,video/*"
onChange={(e) => {
const file = e.target.files?.[0]
if (file) handleUpload(file)
}}
/>
{/* Sections */}
{totalCount === 0 ? (
<Card>
<CardContent className="py-10 text-center">
<CircleCheck className="size-8 mx-auto text-muted-foreground/60 mb-3" />
<p className="text-sm text-muted-foreground">
This inspection has no checkpoints yet. It was probably created from an empty template.
</p>
</CardContent>
</Card>
) : mode === "all" ? (
sections.map((section) => (
<Card key={section.name}>
<CardHeader className="py-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">{section.name}</CardTitle>
<Badge variant="outline" className="font-normal">
{section.items.filter(isCheckpointComplete).length} / {section.items.length} done
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
<ul className="divide-y">
{section.items.map((cp) => (
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
))}
</ul>
</CardContent>
</Card>
))
) : (
wizardSection && (() => {
const pendingItems = wizardSection.items.filter((cp) => !isCheckpointComplete(cp))
const sectionDone = pendingItems.length === 0
return (
<Card>
<CardHeader className="py-3 gap-1">
<div className="flex items-center justify-between flex-wrap gap-2">
<CardTitle className="text-base">{wizardSection.name}</CardTitle>
<Badge variant="outline" className="font-normal">
Section {wizardSectionIdx + 1} / {sections.length}
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
<ul className="divide-y">
{wizardSection.items.map((cp) => (
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
))}
</ul>
</CardContent>
<div className="px-4 py-3 border-t bg-muted/30 space-y-2">
{!sectionDone && (
<div className="flex items-start gap-2 text-xs text-amber-900">
<AlertTriangle className="size-3.5 mt-0.5 shrink-0 text-amber-600" />
<div>
<span className="font-medium">{pendingItems.length} pending.</span>{' '}
Each checkpoint needs a finding and its required recording before you can move on.
</div>
</div>
)}
<div className="flex items-center justify-between">
<Button
variant="outline"
className="w-full"
disabled={isUploading}
onClick={() => fileInputRef.current?.click()}
>
<FileUp className="size-4" />
{isUploading
? "Uploading..."
: hasFile
? "Replace Attachment"
: "Add Attachment"}
</Button>
</div>
</DialogContent>
</Dialog>
)
}
// ── Main Page ──
export default function InspectionCheckpointsPage({ params }: { params: Promise<{ id: string }> }) {
const { id: inspectionId } = use(params)
const api = useAuthApi()
const queryClient = useQueryClient()
const [formOpen, setFormOpen] = useState(false)
const [editingCheckpoint, setEditingCheckpoint] = useState<CheckpointItem | null>(null)
const [attachmentsCheckpoint, setAttachmentsCheckpoint] = useState<CheckpointItem | null>(null)
const queryKey = [INSPECTION_ROUTES.CHECKPOINTS, inspectionId]
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.inspections.listCheckpoints({ inspection_id: inspectionId } as never),
})
const invalidate = () => {
queryClient.invalidateQueries({ queryKey })
}
// ── Status change mutation ──
const changeStatusMutation = useMutation({
mutationFn: ({ checkpointId, status }: { checkpointId: number; status: string }) =>
api.inspections.changeCheckpointStatus({
inspection_id: Number(inspectionId),
inspection_check_point_id: String(checkpointId),
name: "", // required by API type but server uses checkpoint id from context
record_type: "record_conditions",
status,
} as never),
onSuccess: () => invalidate(),
})
// ── Delete checkpoint mutation ──
const deleteMutation = useMutation({
mutationFn: (checkpointId: string) => api.inspections.destroyCheckpoint(checkpointId),
onSuccess: () => {
toast.success("Checkpoint deleted")
invalidate()
},
onError: () => toast.error("Failed to delete checkpoint"),
})
const handleEdit = (checkpoint: CheckpointItem) => {
setEditingCheckpoint(checkpoint)
setFormOpen(true)
}
const handleAdd = () => {
setEditingCheckpoint(null)
setFormOpen(true)
}
const handleStatusChange = (checkpointId: number, status: string) => {
const promise = changeStatusMutation.mutateAsync({ checkpointId, status, })
toast.promise(promise, {
loading: "Updating status...",
success: `Status changed to ${formatStatus(status)}`,
error: "Failed to update status",
})
}
const checkpoints = (data as any)?.data ?? []
const meta = (data as any)?.meta
const pagination = {
page: meta?.current_page ?? 1,
pageSize: meta?.per_page ?? 15,
pageCount: meta?.last_page ?? 1,
total: meta?.total ?? 0,
}
const columns = [
{
accessorKey: "name",
header: ({ column }: any) => <ColumnHeader column={column} title="Name" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<div className="flex flex-col gap-0.5">
<span className="font-medium">{item.name}</span>
{item.description && (
<span className="text-xs text-muted-foreground">{item.description}</span>
)}
</div>
)
},
},
{
accessorKey: "record_type",
header: ({ column }: any) => <ColumnHeader column={column} title="Record Type" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
const rt = RECORD_TYPES.find((r) => r.value === item.record_type)
return rt?.label ?? item.record_type ?? "—"
},
},
{
accessorKey: "status",
header: ({ column }: any) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
const config = getStatusConfig(item.status)
return (
<Badge className={config.color}>
<config.icon className="mr-1 size-3" />
{formatStatus(item.status)}
</Badge>
)
},
},
{
accessorKey: "condition_rate",
header: ({ column }: any) => <ColumnHeader column={column} title="Condition" />,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return item.condition_rate != null ? `${item.condition_rate}/10` : "—"
},
},
{
id: "attachments",
header: () => <span className="text-xs">Attachments</span>,
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<Button
variant="ghost"
size="sm"
className="gap-1.5"
onClick={() => setAttachmentsCheckpoint(item)}
disabled={wizardSectionIdx === 0}
onClick={() => setWizardSectionIdx((i) => Math.max(0, i - 1))}
>
<Paperclip className="size-3.5" />
{item.file ? (
<Badge variant="secondary" className="px-1.5 py-0 text-xs">1</Badge>
) : (
<span className="text-xs text-muted-foreground">0</span>
)}
<ChevronLeft className="size-4" /> Previous
</Button>
)
},
enableSorting: false,
},
{
id: "actions",
cell: ({ row }: any) => {
const item = row.original as CheckpointItem
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="size-8">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{CHECKPOINT_STATUSES.map((s) => (
<DropdownMenuItem
key={s.value}
onClick={() => handleStatusChange(item.id, s.value)}
disabled={item.status === s.value}
<Button
size="sm"
disabled={wizardSectionIdx >= sections.length - 1 || !sectionDone}
onClick={() => setWizardSectionIdx((i) => Math.min(sections.length - 1, i + 1))}
>
<s.icon className="size-4" />
{s.label}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => handleEdit(item)}>
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
onClick={() => deleteMutation.mutate(String(item.id))}
>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
]
return (
<DashboardPage header={null}>
<div className="flex items-center justify-between p-4">
<h3 className="text-lg font-semibold">Checkpoints</h3>
<Button onClick={handleAdd} size="sm">
<Plus className="size-4" />
Add Checkpoint
Next <ChevronRight className="size-4" />
</Button>
</div>
<DataTable
columns={columns}
data={checkpoints}
pagination={pagination}
sorting={[]}
onChange={() => {}}
isLoading={isLoading}
</div>
</Card>
)
})()
)}
{/* Signatures */}
{totalCount > 0 && (
<Card>
<CardHeader className="py-3 flex-row items-center gap-2">
<FileSignature className="size-4 text-muted-foreground" />
<CardTitle className="text-base">Sign-off</CardTitle>
</CardHeader>
<CardContent className="gap-3 grid grid-cols-1 md:grid-cols-2">
<SignaturePad
label="Technician signature"
existingUrl={data.technician_signature_url}
saving={signing?.who === "technician"}
onSave={(d) => handleSign("technician", d)}
/>
<CheckpointFormDialog
open={formOpen}
onOpenChange={(open) => {
setFormOpen(open)
if (!open) setEditingCheckpoint(null)
}}
inspectionId={inspectionId}
checkpoint={editingCheckpoint}
onSuccess={invalidate}
<SignaturePad
label="Customer signature"
existingUrl={data.customer_signature_url}
saving={signing?.who === "customer"}
onSave={(d) => handleSign("customer", d)}
/>
<CheckpointAttachmentsDialog
open={!!attachmentsCheckpoint}
onOpenChange={(open) => {
if (!open) setAttachmentsCheckpoint(null)
}}
checkpoint={attachmentsCheckpoint}
onSuccess={invalidate}
</CardContent>
</Card>
)}
<CheckpointFillDialog
open={activeIndex !== null}
onOpenChange={(o) => { if (!o) setActiveIndex(null) }}
checkpoints={flatCheckpoints}
activeIndex={activeIndex}
onIndexChange={setActiveIndex}
onSaved={load}
onPatch={patchCheckpoint}
/>
</DashboardPage>
<InspectionShareDialog
open={shareOpen}
onOpenChange={setShareOpen}
inspectionId={id}
/>
</div>
)
}
function CheckpointRow({
cp,
onSeverity,
onOpen,
}: {
cp: Checkpoint
onSeverity: (cp: Checkpoint, s: Severity) => void
onOpen: () => void
}) {
const current = (cp.severity as Severity) ?? "not_inspected"
const attachments = cp.attachments ?? cp.media ?? []
const photoCount = attachments.filter((m) => m.media_type === "photo").length
const complete = isCheckpointComplete(cp)
return (
<li
className={`px-3 sm:px-4 py-3 transition-colors hover:bg-muted/30 ${!complete ? "bg-amber-50/40" : ""}`}
>
<div className="flex items-start gap-3 flex-wrap sm:flex-nowrap">
<button
type="button"
onClick={onOpen}
className="flex-1 min-w-0 text-left group"
>
<div className="font-medium text-sm flex items-center gap-2">
<span className="group-hover:text-primary transition">{cp.name}</span>
{!complete && (
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
Pending
</Badge>
)}
</div>
{cp.technician_notes && (
<div className="flex items-start gap-1 text-xs text-muted-foreground mt-1">
<StickyNote className="size-3 mt-0.5 shrink-0" />
<span className="italic line-clamp-1">{cp.technician_notes}</span>
</div>
)}
{photoCount > 0 && (
<div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
<ImageIcon className="size-3" /> {photoCount} photo{photoCount === 1 ? "" : "s"}
</div>
)}
</button>
<div className="flex gap-2 justify-end shrink-0 w-full sm:w-auto">
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => {
const active = current === s
return (
<button
key={s}
type="button"
onClick={(e) => { e.stopPropagation(); onSeverity(cp, s) }}
aria-label={SEVERITY_LABEL[s]}
title={SEVERITY_LABEL[s]}
className={`size-10 sm:size-9 rounded-full transition shadow-md ${SEVERITY_DOT[s]} ${active ? "ring-2 ring-offset-2 ring-foreground/40 scale-105" : "opacity-60 hover:opacity-100"}`}
/>
)
})}
</div>
</div>
</li>
)
}
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { InspectionActions } from '@/modules/inspections/inspection-actions'
import { InspectionProvider } from '@/modules/inspections/inspection-context'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
import React from 'react'
export default async function layout(props: {
@@ -23,7 +24,12 @@ export default async function layout(props: {
title={title}
description={orderNumber ? `Order: ${orderNumber}` : undefined}
backHref="/sales/inspections"
actions={<InspectionActions inspectionId={id} status={status} />}
actions={
<div className="flex items-center gap-2">
<ShareDocumentButton type="inspection" id={id} />
<InspectionActions inspectionId={id} status={status} />
</div>
}
tabs={[
{
href: `/sales/inspections/${id}`,
@@ -1,5 +1,6 @@
import { getServerApi } from '@garage/api/server'
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
export default async function page(props: { params: Promise<{ id: string }> }) {
@@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
return <div className="text-muted-foreground">Inspection not found.</div>
}
const data = inspection.data as { title?: string }
return (
<DashboardPage header={null}>
<InspectionDetailHeader inspectionId={id} title={data.title} />
<InspectionGeneralInfo inspection={inspection.data} />
</DashboardPage>
)
@@ -1,25 +1,68 @@
"use client"
import { useState } from "react"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InspectionForm } from "@/modules/inspections/inspection-form"
import { INSPECTION_ROUTES } from "@garage/api"
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
import { Button } from "@/shared/components/ui/button"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
import type { InspectionsClient } from "@garage/api"
import Link from "next/link"
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { RelationLink } from "@/shared/components/relation-link"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
const STATUS_BADGE_CLASS: Record<string, string> = {
in_progress: "bg-amber-100 text-amber-800",
completed: "bg-emerald-100 text-emerald-800",
cancelled: "bg-rose-100 text-rose-800",
}
const STATUS_LABEL: Record<string, string> = {
in_progress: "In Progress",
completed: "Completed",
cancelled: "Cancelled",
}
export default function InspectionsPage() {
const router = useRouter()
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
return (
<ResourcePage<InspectionsClient>
pageTitle="Inspections"
routeKey={INSPECTION_ROUTES.INDEX}
searchable
searchPlaceholder="Search inspections..."
statusFilter={{ statuses: InspectionStatus }}
getClient={(api) => api.inspections}
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Inspection">
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" asChild>
<Link href="/settings/inspection-templates">
<ListChecks className="size-4" />
Manage templates
</Link>
</Button>
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
<ClipboardList className="size-4" />
New from template
</Button>
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
{(resourceId) => (
<InspectionForm
resourceId={resourceId}
@@ -28,19 +71,55 @@ export default function InspectionsPage() {
/>
)}
</FormDialog>
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
<DialogContent className="min-w-2xl">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
New inspection from template
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<InspectionFromTemplateForm
onSuccess={(id) => {
setFromTemplateOpen(false)
invalidateQuery()
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
}}
/>
</ScrollArea>
</DialogContent>
</Dialog>
</div>
),
})}
columns={({ actionsColumn }) => [
columns={({ openEdit, deleteItem }) => [
{
accessorKey: "title",
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
cell: ({ row }) => {
const r = row.original as any
return (
<div className="flex flex-col">
<span className="font-medium">{r.title ?? "—"}</span>
{r.order_number && (
<span className="text-xs text-muted-foreground">{r.order_number}</span>
)}
</div>
)
},
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const c = (row.original as any).customer
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
return (
<RelationLink
href={c?.id ? `/sales/customers/${c.id}` : null}
icon={UserIcon}
label={getFullName(c)}
/>
)
},
},
{
@@ -48,27 +127,51 @@ export default function InspectionsPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const v = (row.original as any).vehicle
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
return (
<RelationLink
href={v?.id ? `/sales/vehicles/${v.id}` : null}
icon={Car}
label={getVehicleLabel(v as any)}
meta={v?.license_plate}
/>
)
},
},
{
accessorKey: "inspection_category",
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
cell: ({ row }) => {
const ic = (row.original as any).inspection_category
return ic?.inspection_name ?? ic?.name ?? "—"
},
},
{
accessorKey: "status",
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
const status = (row.original as any).status as string | undefined
if (!status) return "—"
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
return (
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
{status ?? "—"}
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
{STATUS_LABEL[status] ?? status}
</span>
)
},
},
actionsColumn(),
{
id: "actions",
header: () => <span className="sr-only">Actions</span>,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<InspectionRowActions
inspection={row.original as any}
onEdit={() => openEdit(row.original as any)}
onDelete={() => deleteItem(String((row.original as any).id))}
/>
),
},
]}
/>
)
@@ -5,6 +5,7 @@ import { InvoiceProvider } from '@/modules/invoices/invoice-context'
import { ReceiptIcon } from 'lucide-react'
import React from 'react'
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
import { ShareDocumentButton } from '@/shared/components/share-document-button'
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
const { id } = await props.params
@@ -24,6 +25,7 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
<div className="flex space-x-2 items-center">
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
<ShareDocumentButton type="invoice" id={id} />
<InvoiceActions invoiceId={id} />
</div>
}
@@ -1,14 +1,18 @@
"use client"
import { Car, Printer, UserIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { InvoiceForm } from "@/modules/invoices/invoice-form"
import { Badge } from "@/shared/components/ui/badge"
import { formatCurrency, formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES } from "@garage/api"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
import type { InvoicesClient } from "@garage/api"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
type InvoiceItem = {
id: number
@@ -23,6 +27,7 @@ type InvoiceItem = {
total?: number | string
balance_due?: number | string
customer?: {
id?: number | string
first_name?: string
last_name?: string
company_name?: string
@@ -77,11 +82,15 @@ function getDueMeta(dueDate?: string) {
export default function InvoicesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<InvoicesClient>
pageTitle="Invoices"
routeKey={INVOICE_ROUTES.INDEX}
searchable
searchPlaceholder="Search invoices..."
statusFilter={{ statuses: InvoiceStatus }}
getClient={(api) => api.invoices}
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
@@ -133,15 +142,13 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const customerLabel = getCustomerLabel(item)
return (
<div className="min-w-[190px]">
<p className="font-medium leading-none">{customerLabel}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.customer?.phone || item.customer?.company_name || "—"}
</p>
</div>
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getCustomerLabel(item)}
meta={item.customer?.phone}
/>
)
},
},
@@ -150,14 +157,14 @@ export default function InvoicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
cell: ({ row }) => {
const item = row.original as unknown as InvoiceItem
const vehicleId = (item.vehicle as any)?.id
return (
<div className="min-w-[220px]">
<p className="font-medium leading-none">{getVehicleLabel(item)}</p>
<p className="mt-1 text-xs text-muted-foreground">
{item.vehicle?.license_plate || "—"}
</p>
</div>
<RelationLink
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
icon={Car}
label={getVehicleLabel(item)}
meta={item.vehicle?.license_plate}
/>
)
},
},
@@ -224,16 +231,24 @@ export default function InvoicesPage() {
return (
<div className="min-w-[150px]">
<p className="font-medium leading-none">
Total: {formatCurrency(item.total ?? 0)}
Total: {<Money value={item.total ?? 0} />}
</p>
<p className="mt-1 text-xs text-muted-foreground">
Due: {formatCurrency(item.balance_due ?? 0)}
Due: {<Money value={item.balance_due ?? 0} />}
</p>
</div>
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("invoice", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -7,11 +7,14 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { getFullName } from "@/shared/utils/getFullName"
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
import { formatEnum } from "@/shared/utils/formatters"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
@@ -42,13 +45,34 @@ export default function JobCardAppointmentsPage({
router.replace(`${pathname}?${params.toString()}`)
}, [pathname, router, searchParams])
const defaultJobCard = jobCard
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
const jc = jobCard as any
const defaultJobCard = jc
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
: null
const appointmentDefaults = jc
? {
job_card_id: jc.id,
job_card_title: jc.title || `Job Card #${jc.id}`,
customer_id: jc.customer?.id,
customer_name: getFullName(jc.customer),
vehicle_id: jc.vehicle?.id,
vehicle_name: getVehicleLabel(jc.vehicle),
service_writer_id: jc.service_writer?.id,
service_writer_name: getFullName(jc.service_writer),
technician_id: jc.primary_technician?.id,
technician_name: getFullName(jc.primary_technician),
department_id: jc.department?.id,
department_name: jc.department?.name,
}
: { job_card: defaultJobCard }
return (
<ResourcePage<AppointmentsClient>
routeKey={APPOINTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search appointments..."
statusFilter={{ statuses: AppointmentStatus }}
getClient={(api) => api.appointments}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -59,8 +83,8 @@ export default function JobCardAppointmentsPage({
{(resourceId) => (
<AppointmentForm
resourceId={resourceId}
initialData={selectedItem ?? { job_card: defaultJobCard }}
onSuccess={() => { closeDialog(); invalidateQuery() }}
initialData={selectedItem ?? appointmentDefaults}
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
/>
)}
</FormDialog>
@@ -102,7 +126,7 @@ export default function JobCardAppointmentsPage({
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
return (
<Badge className={colorClass}>
{status?.replace("_", " ") ?? "—"}
{formatEnum(status)}
</Badge>
)
},
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent } from "@/shared/components/ui/card"
import { JOB_CARD_ROUTES } from "@garage/api"
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { CONSTANTS } from "@/config/constants"
@@ -22,6 +22,62 @@ function getFileIcon(mimeType?: string) {
return FileIcon
}
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
function describeAttachmentError(rawMessage: string, filename: string): string {
const msg = rawMessage.toLowerCase()
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
}
if (msg.includes("may not be greater") || msg.includes("max")) {
return `${filename}: exceeds 5 MB limit.`
}
if (msg.includes("must be a file")) {
return `${filename}: invalid file.`
}
return `${filename}: ${rawMessage}`
}
function showUploadError(err: unknown, files: File[]) {
if (!(err instanceof ApiError)) {
toast.error("Failed to upload attachment(s)")
return
}
const validation = err.validationErrors
if (!validation || Object.keys(validation).length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const messages: string[] = []
for (const [key, msgs] of Object.entries(validation)) {
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
if (!firstMsg) continue
const match = key.match(/^attachments\.(\d+)$/)
if (match) {
const idx = Number(match[1])
const filename = files[idx]?.name ?? `File #${idx + 1}`
messages.push(describeAttachmentError(firstMsg, filename))
} else if (key === "attachments") {
messages.push(firstMsg)
} else {
messages.push(firstMsg)
}
}
if (messages.length === 0) {
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
return
}
const shown = messages.slice(0, 3)
const extra = messages.length - shown.length
shown.forEach((m) => toast.error(m))
if (extra > 0) toast.error(`...and ${extra} more`)
}
export default function JobCardAttachmentsPage() {
const { id: jobCardId } = useParams<{ id: string }>()
const api = useAuthApi()
@@ -66,18 +122,19 @@ export default function JobCardAttachmentsPage() {
const files = e.target.files
if (!files || files.length === 0) return
const fileList = Array.from(files)
setIsUploading(true)
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
toast.promise(promise, {
loading: "Uploading attachment(s)...",
success: "Attachment(s) uploaded successfully",
error: "Failed to upload attachment(s)",
})
const loadingToast = toast.loading("Uploading attachment(s)...")
try {
await promise
await api.jobCards.addAttachment(jobCardId, fileList)
toast.dismiss(loadingToast)
toast.success("Attachment(s) uploaded successfully")
queryClient.invalidateQueries({ queryKey })
startRefreshTransition(() => router.refresh())
} catch (err) {
toast.dismiss(loadingToast)
showUploadError(err, fileList)
} finally {
setIsUploading(false)
if (fileInputRef.current) {
@@ -6,9 +6,13 @@ import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
import { BILL_ROUTES } from "@garage/api"
import { BILL_ROUTES, BillStatus } from "@garage/api"
import type { BillsClient } from "@garage/api"
import { useJobCard } from "@/modules/job-cards/job-card-context"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, FileTextIcon } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { formatEnum } from "@/shared/utils/formatters"
export default function JobCardBillsPage({
params,
@@ -25,6 +29,9 @@ export default function JobCardBillsPage({
return (
<ResourcePage<BillsClient>
routeKey={BILL_ROUTES.INDEX}
searchable
searchPlaceholder="Search bills..."
statusFilter={{ statuses: BillStatus }}
getClient={(api) => api.bills}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -46,7 +53,16 @@ export default function JobCardBillsPage({
{
accessorKey: "bill_number",
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
cell: ({ row }) => (row.original as any).bill_number || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.id ? `/purchase/bill/${item.id}` : null}
icon={FileTextIcon}
label={item.bill_number}
/>
)
},
},
{
accessorKey: "title",
@@ -55,7 +71,16 @@ export default function JobCardBillsPage({
{
accessorKey: "vendor_name",
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
cell: ({ row }) => (row.original as any).vendor_name || "—",
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
icon={Building2}
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
/>
)
},
},
{
accessorKey: "bill_date",
@@ -78,7 +103,7 @@ export default function JobCardBillsPage({
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const status = (row.original as any).status
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
return <Badge variant={status === "paid" ? "default" : "secondary"}>{formatEnum(status)}</Badge>
},
},
actionsColumn(),
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table"
import { JobCardExpenseItemForm } from "@/modules/job-cards/job-card-expense-item-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters"
// TODO: expense items invalidation is not working properly when create new expense item line. Need to investigate why and fix it.
@@ -44,6 +45,7 @@ export default function JobCardExpenseItemsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -92,7 +94,7 @@ export default function JobCardExpenseItemsPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => {
const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -100,7 +102,7 @@ export default function JobCardExpenseItemsPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => {
const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
return val != null && val > 0 ? <Money value={val} /> : "—"
},
},
{
@@ -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>
)
}
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table"
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters"
import { JOB_CARD_ROUTES } from "@garage/api"
@@ -44,6 +45,7 @@ export default function JobCardPartsPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getParts(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -92,7 +94,7 @@ export default function JobCardPartsPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => {
const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -100,7 +102,7 @@ export default function JobCardPartsPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => {
const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
return val != null && val > 0 ? <Money value={val} /> : "—"
},
},
{
@@ -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",
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table"
import { JobCardServiceForm } from "@/modules/job-cards/job-card-service-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters"
import { Badge } from "@/shared/components/ui/badge"
@@ -46,6 +47,7 @@ export default function JobCardServicesPage({
const { data, isLoading } = useQuery({
queryKey,
queryFn: () => api.jobCards.getServices(jobCardId),
staleTime: 30_000,
})
const rows = (data as any)?.data ?? []
@@ -107,7 +109,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => {
const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—"
return val != null ? <Money value={val} /> : "—"
},
},
{
@@ -115,7 +117,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />,
cell: ({ row }) => {
const lr = row.original.labor_rate
return lr ? `${lr.title} ($${Number(lr.rate).toFixed(2)})` : "—"
return lr ? <span>{lr.title} (<Money value={lr.rate} />)</span> : "—"
},
},
{
@@ -133,7 +135,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => {
const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
return val != null && val > 0 ? <Money value={val} /> : "—"
},
},
{
@@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { TaskForm } from "@/modules/tasks/task-form"
import { TASK_ROUTES } from "@garage/api"
import { TASK_ROUTES, TaskStatus } from "@garage/api"
import type { TasksClient } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { useJobCard } from "@/modules/job-cards/job-card-context"
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
return (
<ResourcePage<TasksClient>
routeKey={TASK_ROUTES.INDEX}
searchable
searchPlaceholder="Search tasks..."
statusFilter={{ statuses: TaskStatus }}
getClient={(api) => api.tasks}
extraParams={{ job_card_id: jobCardId }}
header={null}
@@ -6,12 +6,10 @@ import FormDialog from '@/shared/components/form-dialog'
import { JobCardForm } from '@/modules/job-cards/job-card-form'
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
import type { JobCardsClient } from '@garage/api'
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
import { ClipboardListIcon, Printer } from 'lucide-react'
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
import { Badge } from '@/shared/components/ui/badge'
import { Input } from '@/shared/components/ui/input'
import { useRouter } from 'next/navigation'
import { useState, useEffect, useMemo } from 'react'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
import { useFilterParams } from '@/shared/hooks/use-filter-params'
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
@@ -37,30 +35,18 @@ const statusColorMap: Record<string, string> = {
export default function JobCardsPage() {
const router = useRouter()
const [searchInput, setSearchInput] = useState("")
const [search, setSearch] = useState("")
const [statusFilter, setStatusFilter] = useState<string>("check_in")
const filter = useFilterParams(jobCardFilterConfig)
useEffect(() => {
const timer = setTimeout(() => setSearch(searchInput), 400)
return () => clearTimeout(timer)
}, [searchInput])
const extraParams = useMemo(() => {
const params: Record<string, unknown> = { ...filter.appliedParams }
if (search) params.search = search
if (statusFilter !== "all") params.status = statusFilter
return params
}, [filter.appliedParams, search, statusFilter])
const { print, isPrinting } = useDocumentPrint()
return (
<>
<ResourcePage<JobCardsClient>
routeKey={JOB_CARD_ROUTES.INDEX}
getClient={(api) => api.jobCards}
extraParams={extraParams}
searchable
searchPlaceholder="Search job cards..."
statusFilter={{ statuses: JobCardStatus }}
extraParams={filter.appliedParams}
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
title: "Job Cards",
@@ -133,32 +119,16 @@ export default function JobCardsPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("job_card", String(r.id), "print"),
},
],
}),
]}
tableHeader={
<div className="flex justify-between">
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
<TabsList variant="line">
<TabsTrigger value="all">All</TabsTrigger>
{JobCardStatus.map((status) => (
<TabsTrigger key={status} value={status}>
{formatEnum(status)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div className="relative w-64">
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search job cards..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-8"
/>
</div>
</div>
}
/>
<FilterDrawer
@@ -0,0 +1,34 @@
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
import { getServerApi } from '@garage/api/server'
import { PaymentReceivedActions } from '@/modules/payment-received/payment-received-actions'
import { BanknoteIcon } from 'lucide-react'
import React from 'react'
export default async function PaymentReceivedDetailLayout(props: {
params: Promise<{ id: string }>
children: React.ReactNode
}) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentReceived.show(id)
const data = (payment as any)?.data ?? payment
const title = data?.payment_number || 'Payment Details'
return (
<DashboardDetailsPage
title={title}
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
icon={<BanknoteIcon className="size-5" />}
backHref="/sales/payment-received"
actions={<PaymentReceivedActions paymentId={id} />}
tabs={[
{
href: `/sales/payment-received/${id}`,
label: 'Details',
},
]}
>
{props.children}
</DashboardDetailsPage>
)
}
@@ -0,0 +1,97 @@
import { getServerApi } from '@garage/api/server'
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
import {
BadgeDollarSignIcon,
CalendarIcon,
ClipboardListIcon,
CreditCardIcon,
HashIcon,
UserIcon,
} from 'lucide-react'
export default async function PaymentReceivedDetailPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params
const api = await getServerApi()
const payment = await api.paymentReceived.show(id)
const data = (payment as any)?.data ?? payment
if (!data) {
return <div className="text-muted-foreground">Payment not found.</div>
}
const amount = data.amount_received != null
? Number(data.amount_received).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
: '—'
const paymentDate = data.payment_date
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
: '—'
const customerName = data.customer?.first_name
? `${data.customer.first_name} ${data.customer.last_name ?? ''}`.trim()
: data.customer?.company_name ?? data.customer_name ?? '—'
const jobCardLabel = data.job_card?.title ?? data.job_card_name ?? '—'
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
return (
<DashboardPage header={null}>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div className="flex items-center gap-3 rounded-lg border p-4">
<HashIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Number</p>
<p className="font-medium">{data.payment_number || '—'}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<UserIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Customer</p>
<p className="font-medium">{customerName}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<ClipboardListIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Job Card</p>
<p className="font-medium">{jobCardLabel}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
<div>
<p className="text-xs text-muted-foreground">Amount Received</p>
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CreditCardIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Mode</p>
<p className="font-medium capitalize">{paymentMode}</p>
</div>
</div>
<div className="flex items-center gap-3 rounded-lg border p-4">
<CalendarIcon className="size-5 text-muted-foreground" />
<div>
<p className="text-xs text-muted-foreground">Payment Date</p>
<p className="font-medium">{paymentDate}</p>
</div>
</div>
{data.note && (
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
<p className="text-xs text-muted-foreground mb-1">Note</p>
<p className="text-sm">{data.note}</p>
</div>
)}
</div>
</DashboardPage>
)
}
@@ -10,10 +10,14 @@ import {
CalendarIcon,
CreditCardIcon,
HashIcon,
Printer,
UserIcon,
ClipboardListIcon,
} from "lucide-react"
import { useRouter } from "next/navigation"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { getFullName } from "@/shared/utils/getFullName"
import { RelationLink } from "@/shared/components/relation-link"
type PaymentReceivedItem = {
id: number
@@ -30,13 +34,19 @@ type PaymentReceivedItem = {
}
export default function PaymentReceivedPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
searchable
searchPlaceholder="Search payments..."
getClient={(api) => ({
list: (query?: any) => api.paymentReceived.list(query),
destroy: (id: string) => api.paymentReceived.destroy(id),
})}
onRowClick={(row) => router.push(`/sales/payment-received/${(row as any).id}`)}
headerProps={({ invalidateQuery }) => ({
actions: (
<FormDialog title="Record Payment">
@@ -65,14 +75,17 @@ export default function PaymentReceivedPage() {
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item: any = row.original as unknown as PaymentReceivedItem
const customer = item.customer
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{getFullName(item.customer) || "—"}</span>
</div>
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer) || item.customer_name}
/>
)
},
},
@@ -81,12 +94,13 @@ export default function PaymentReceivedPage() {
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
cell: ({ row }) => {
const item: any = row.original as unknown as PaymentReceivedItem
const label = item.job_card?.title
const jobCard = item.job_card
return (
<div className="flex items-center gap-2">
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
<span>{label || "—"}</span>
</div>
<RelationLink
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
icon={ClipboardListIcon}
label={jobCard?.title || item.job_card_name}
/>
)
},
},
@@ -159,7 +173,15 @@ export default function PaymentReceivedPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("payment_received", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
import { EstimateForm } from '@/modules/estimates/estimate-form'
import { ESTIMATE_ROUTES } from '@garage/api'
import type { EstimatesClient } from '@garage/api'
import { FileTextIcon } from 'lucide-react'
import { FileTextIcon, UserIcon } from 'lucide-react'
import { useVehicle } from '@/modules/vehicles/vehicle-context'
import { RelationLink } from '@/shared/components/relation-link'
import { getFullName } from '@/shared/utils/getFullName'
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
const { id: vehicleId } = use(params)
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
}
pageTitle="Vehicle Estimates"
routeKey={ESTIMATE_ROUTES.INDEX}
searchable
searchPlaceholder="Search estimates..."
getClient={(api) => api.estimates}
extraParams={{ vehicle_id: vehicleId }}
header={
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
{
accessorKey: "customer_name",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item = row.original as any
return (
<RelationLink
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
icon={UserIcon}
label={getFullName(item.customer) || item.customer_name}
/>
)
},
},
{
accessorKey: "date",
@@ -7,14 +7,14 @@ import type { ColumnDef } from '@tanstack/react-table'
import FormDialog from '@/shared/components/form-dialog'
import { ImportDataButton } from '@/shared/components/import-data-button'
import { ExportDataButton } from '@/shared/components/export-data-button'
import { DownloadSampleButton } from '@/shared/components/download-sample-button'
import { useAuthApi } from '@/shared/useApi'
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
import { VEHICLE_ROUTES } from '@garage/api'
import type { VehiclesClient } from '@garage/api'
import { CarIcon } from 'lucide-react'
import { CarIcon, UserIcon } from 'lucide-react'
import { getFullName } from '@/shared/utils/getFullName'
import { RelationLink } from '@/shared/components/relation-link'
export default function VehiclesPage() {
const router = useRouter()
@@ -23,18 +23,19 @@ export default function VehiclesPage() {
<ResourcePage<VehiclesClient>
pageTitle="Vehicles"
routeKey={VEHICLE_ROUTES.INDEX}
searchable
searchPlaceholder="Search vehicles..."
getClient={(api) => api.vehicles}
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<div className='flex items-center gap-2'>
<DownloadSampleButton
onDownload={() => api.vehicles.downloadImportSample()}
fileName='vehicles-import-sample'
/>
<ImportDataButton
onImport={(file) => api.vehicles.importData(file)}
onSuccess={invalidateQuery}
entityLabel="Vehicles"
onDownloadSample={() => api.vehicles.downloadImportSample()}
sampleFileName='vehicles-import-sample'
/>
<ExportDataButton
onExport={(filters) => api.vehicles.exportData(filters)}
@@ -80,8 +81,14 @@ export default function VehiclesPage() {
accessorKey: "customers",
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }: any) => {
const val = (row.original as any).customers?.[0]
return getFullName(val)
const customer = (row.original as any).customers?.[0]
return (
<RelationLink
href={customer?.id ? `/sales/customers/${customer.id}` : null}
icon={UserIcon}
label={getFullName(customer)}
/>
)
},
} as any,
{
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
<ResourcePage<DepartmentsClient>
pageTitle="Departments"
routeKey={DEPARTMENT_ROUTES.INDEX}
searchable
searchPlaceholder="Search departments..."
getClient={(api) => api.departments}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
@@ -0,0 +1,290 @@
"use client"
import { useCallback, useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Pencil, Plus, Save, 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 [name, setName] = useState("")
const [description, setDescription] = useState("")
const [saving, setSaving] = useState(false)
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)
setName(res.data.name ?? "")
setDescription(res.data.description ?? "")
} 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 saveTemplate = async () => {
if (!template) return
setSaving(true)
try {
const res = await api.inspectionTemplates.update(template.id, { name, description })
setTemplate(res.data)
toast.success("Template saved")
} catch (e: any) {
toast.error(e?.message ?? "Failed to save")
} finally {
setSaving(false)
}
}
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
value={name}
onChange={(e) => setName(e.target.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
value={description}
rows={2}
onChange={(e) => setDescription(e.target.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 className="sticky bottom-0 flex justify-end gap-2 border-t bg-background py-3">
<Button onClick={saveTemplate} disabled={saving}>
<Save className="size-4 mr-1" />
{saving ? "Saving…" : "Save"}
</Button>
</div>
</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,40 @@
import Link from "next/link"
import { AlertCircle, ShieldCheck } from "lucide-react"
/**
* Error UI for failed activation handoffs. The success path is handled by
* the sibling route.ts handler at /activate/[token] — it sets cookies on the
* response and redirects to "/". Errors redirect here with ?reason=… in the
* query string.
*
* The route.ts file takes precedence over this page for matching requests,
* but the page is still reachable via a redirect to
* /activate/[token]?error=1&reason=…
*/
export default async function ActivateErrorPage(props: {
searchParams: Promise<{ reason?: string; error?: string }>
}) {
const { reason } = await props.searchParams
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">Activation failed</h1>
<p className="text-sm text-muted-foreground">
{reason ?? "Could not exchange the handoff token."}
</p>
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
<ShieldCheck className="size-3.5" />
Re-open the garage from the SaaS dashboard to get a fresh link.
</p>
<Link
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
className="inline-block text-sm underline text-primary"
>
Back to SaaS
</Link>
</div>
</div>
)
}
@@ -0,0 +1,98 @@
import { NextRequest, NextResponse } from "next/server"
/**
* SaaS → garage-erp handoff landing.
*
* URL shape:
* /activate/{handoff_token}?ws={workspace_uuid}&api={backend_url}
*
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
* api_base_url) on the redirect response and lands the user on /.
*
* Implemented as a Route Handler (not a Page) because Next.js disallows
* cookie writes inside Server Components — only Server Actions and Route
* Handlers can mutate cookies.
*/
export async function GET(
req: NextRequest,
ctx: { params: Promise<{ token: string }> },
) {
const { token } = await ctx.params
const url = new URL(req.url)
const ws = url.searchParams.get("ws")
const api = url.searchParams.get("api")
if (!ws || !api) {
return redirectToError(req, "Activation link is missing workspace or backend URL.")
}
let parsed: URL
try {
parsed = new URL(api)
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("Backend URL must be http(s).")
}
} catch {
return redirectToError(req, "Activation link has a malformed backend URL.")
}
const apiBase = parsed.toString().replace(/\/$/, "")
const endpoint = `${apiBase}/api/saas/handoff/exchange`
let response: Response
try {
response = await fetch(endpoint, {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Workspace-UUID": ws,
},
body: JSON.stringify({
handoff_token: token,
saas_workspace_uuid: ws,
}),
})
} catch (err) {
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
}
let payload: { token?: string; user?: any; message?: string } = {}
try {
payload = await response.json()
} catch {
// body is not JSON — fall through to error path
}
if (!response.ok || !payload.token || !payload.user) {
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
}
const dest = new URL("/", req.url)
const res = NextResponse.redirect(dest, 302)
const isProd = process.env.NODE_ENV === "production"
const sevenDays = 60 * 60 * 24 * 7
const cookieOptions = {
path: "/",
sameSite: "strict" as const,
httpOnly: true,
secure: isProd,
maxAge: sevenDays,
}
res.cookies.set("auth_token", payload.token, cookieOptions)
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
res.cookies.set("workspace_uuid", ws, cookieOptions)
res.cookies.set("api_base_url", apiBase, cookieOptions)
return res
}
function redirectToError(req: NextRequest, reason: string) {
const url = new URL("/activate/error", req.url)
url.searchParams.set("reason", reason)
return NextResponse.redirect(url, 302)
}
@@ -0,0 +1,30 @@
import Link from "next/link"
import { AlertCircle, ShieldCheck } from "lucide-react"
export default async function ActivateErrorPage(props: {
searchParams: Promise<{ reason?: string }>
}) {
const { reason } = await props.searchParams
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">Activation failed</h1>
<p className="text-sm text-muted-foreground">
{reason ?? "Could not exchange the handoff token."}
</p>
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
<ShieldCheck className="size-3.5" />
Re-open the garage from the SaaS dashboard to get a fresh link.
</p>
<Link
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
className="inline-block text-sm underline text-primary"
>
Back to SaaS
</Link>
</div>
</div>
)
}
@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from "next/server"
/**
* SaaS → garage-erp handoff landing.
*
* URL shape:
* /activate/handoff/{handoff_token}?ws={workspace_uuid}&api={backend_url}
*
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
* api_base_url) on the redirect response and lands the user on /.
*
* Implemented as a Route Handler (not a Page) because Next.js disallows
* cookie writes inside Server Components — only Server Actions and Route
* Handlers can mutate cookies.
*/
export async function GET(
req: NextRequest,
ctx: { params: Promise<{ token: string }> },
) {
const { token } = await ctx.params
const url = new URL(req.url)
const ws = url.searchParams.get("ws")
const api = url.searchParams.get("api")
if (!ws || !api) {
return redirectToError(req, "Activation link is missing workspace or backend URL.")
}
let parsed: URL
try {
parsed = new URL(api)
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("Backend URL must be http(s).")
}
} catch {
return redirectToError(req, "Activation link has a malformed backend URL.")
}
const apiBase = parsed.toString().replace(/\/$/, "")
const endpoint = `${apiBase}/api/saas/handoff/exchange`
let response: Response
try {
response = await fetch(endpoint, {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Workspace-UUID": ws,
},
body: JSON.stringify({
handoff_token: token,
saas_workspace_uuid: ws,
}),
})
} catch (err) {
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
}
let payload: { token?: string; user?: any; message?: string } = {}
try {
payload = await response.json()
} catch {
// body is not JSON — fall through to error path
}
if (!response.ok || !payload.token || !payload.user) {
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
}
// Use a relative Location to keep the user on whichever host they came
// in on (127.0.0.1 vs localhost). NextResponse.redirect(new URL("/", req.url))
// resolves to the Next dev server's canonical host which can differ from
// the request's actual host, and cookies set here would not survive that
// cross-host redirect.
const res = new NextResponse(null, {
status: 302,
headers: { Location: "/" },
})
const isProd = process.env.NODE_ENV === "production"
const sevenDays = 60 * 60 * 24 * 7
const cookieOptions = {
path: "/",
sameSite: "strict" as const,
httpOnly: true,
secure: isProd,
maxAge: sevenDays,
}
res.cookies.set("auth_token", payload.token, cookieOptions)
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
res.cookies.set("workspace_uuid", ws, cookieOptions)
res.cookies.set("api_base_url", apiBase, cookieOptions)
return res
}
function redirectToError(req: NextRequest, reason: string) {
const location = "/activate/error?reason=" + encodeURIComponent(reason)
return new NextResponse(null, {
status: 302,
headers: { Location: location },
})
}
@@ -0,0 +1,97 @@
import { cookies } from "next/headers"
import { NextRequest, NextResponse } from "next/server"
const HOP_BY_HOP = new Set([
"host",
"connection",
"content-length",
"keep-alive",
"transfer-encoding",
"upgrade",
"te",
"trailer",
"proxy-authorization",
"proxy-authenticate",
])
async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
const cookieStore = await cookies()
const apiBase = cookieStore.get("api_base_url")?.value
const wsUuid = cookieStore.get("workspace_uuid")?.value
const token = cookieStore.get("auth_token")?.value
if (!apiBase || !wsUuid) {
return NextResponse.json(
{
message: "Workspace session not found. Please open your garage from the SaaS dashboard.",
code: "workspace_session_missing",
},
{ status: 412 },
)
}
const { path } = await ctx.params
const url = new URL(req.url)
// The OpenAPI clients keep `/api/...` in their route patterns, so when the
// client uses baseUrl=`/api/proxy` the resulting URL is
// `/api/proxy/api/customers`. Forward the path verbatim and rejoin so the
// upstream becomes `{apiBase}/api/customers`.
const target = `${apiBase.replace(/\/$/, "")}/${(path ?? []).join("/")}${url.search}`
const headers = new Headers()
req.headers.forEach((value, key) => {
if (!HOP_BY_HOP.has(key.toLowerCase()) && key.toLowerCase() !== "cookie") {
headers.set(key, value)
}
})
headers.set("Accept", "application/json")
headers.set("X-Workspace-UUID", wsUuid)
if (token) {
headers.set("Authorization", `Bearer ${token}`)
}
const init: RequestInit = {
method: req.method,
headers,
redirect: "manual",
}
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = await req.arrayBuffer()
}
let upstream: Response
try {
upstream = await fetch(target, init)
} catch (err) {
return NextResponse.json(
{
message: "Failed to reach garage backend.",
code: "backend_unreachable",
error: (err as Error).message,
},
{ status: 502 },
)
}
const respHeaders = new Headers()
upstream.headers.forEach((value, key) => {
const k = key.toLowerCase()
if (HOP_BY_HOP.has(k) || k === "set-cookie") return
respHeaders.set(key, value)
})
return new NextResponse(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: respHeaders,
})
}
export const GET = forward
export const POST = forward
export const PUT = forward
export const PATCH = forward
export const DELETE = forward
export const OPTIONS = forward
export const HEAD = forward
@@ -0,0 +1,465 @@
"use client"
import { Suspense, useEffect, useState } from "react"
import { useParams, useSearchParams } 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>
)
}
function PublicInspectionContent() {
const params = useParams<{ token: string }>()
const token = params.token
// Workspace UUID baked into the share URL — the public API endpoint needs it
// to resolve which tenant DB holds this inspection.
const searchParams = useSearchParams()
const ws = searchParams.get("ws") ?? ""
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 ?? ""
const wsQuery = ws ? `?ws=${encodeURIComponent(ws)}` : ""
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}${wsQuery}`, {
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, ws])
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${ws ? `?ws=${encodeURIComponent(ws)}` : ""}`}
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>
)
}
export default function PublicInspectionPage() {
return (
<Suspense
fallback={
<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>
}
>
<PublicInspectionContent />
</Suspense>
)
}
function InfoCell({
icon: Icon,
label,
value,
subtitle,
}: {
icon: React.ComponentType<{ className?: string }>
label: string
value: string
subtitle?: string
}) {
return (
<div className="flex items-start gap-2 min-w-0">
<Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" />
<div className="min-w-0">
<div className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</div>
<div className="font-medium truncate">{value}</div>
{subtitle && (
<div className="text-xs text-muted-foreground font-mono truncate">{subtitle}</div>
)}
</div>
</div>
)
}
+4
View File
@@ -1,10 +1,12 @@
import { Geist_Mono, Inter } from "next/font/google"
import NextTopLoader from "nextjs-toploader"
import { QueryProvider } from "@/shared/components/query-provider"
import { ThemeProvider } from "@/shared/components/theme-provider"
import { Toaster } from "@/shared/components/ui/sonner"
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
import { PromptDialog } from "@/shared/components/prompt-dialog"
import { NuqsAdapter } from "nuqs/adapters/next/app"
import { cn } from "@/shared/lib/utils"
import './globals.css'
@@ -33,11 +35,13 @@ export default function RootLayout({
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
>
<body>
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
<NuqsAdapter>
<ThemeProvider>
<QueryProvider>{children}</QueryProvider>
<Toaster />
<ConfirmDialog />
<PromptDialog />
</ThemeProvider>
</NuqsAdapter>
</body>
@@ -141,9 +141,20 @@ export function AppSidebar({ navGroups, logo, user, ...props }: AppSidebarProps)
)
}
function isPathActive(pathname: string, href: string): boolean {
if (href === '/') return pathname === '/'
return pathname === href || pathname.startsWith(href + '/')
}
function isItemActive(pathname: string, item: { href: string; matchPath?: string; isActive?: boolean }): boolean {
if (item.isActive !== undefined) return item.isActive
if (item.matchPath) return isPathActive(pathname, item.matchPath)
return isPathActive(pathname, item.href)
}
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isActive = item.isActive ?? pathname === item.href
const isActive = isItemActive(pathname, item)
return (
<SidebarMenuItem>
@@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
const pathname = usePathname()
const isChildActive = item.items?.some((sub) => pathname === sub.href)
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
// Collapsed sidebar → flyout dropdown with sub-items
if (isCollapsed) {
@@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
</DropdownMenuLabel>
<DropdownMenuSeparator />
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<DropdownMenuItem key={sub.href} asChild>
<Link
@@ -272,7 +283,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
<SidebarMenuSub>
{item.items?.map((sub) => {
const isSubActive = sub.isActive ?? pathname === sub.href
const isSubActive = isItemActive(pathname, sub)
return (
<SidebarMenuSubItem key={sub.href}>
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
</Button>
)}
{(avatarSrc || avatarFallback) && (
<a rel="preload" target="_blank" href={avatarSrc} >
avatarSrc ? (
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
<Avatar className="size-14">
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
<AvatarImage src={avatarSrc} alt={title} />
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
</a>
) : (
<Avatar className="size-14">
<AvatarFallback>
{avatarFallback ?? title.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
)
)}
{!avatarSrc && !avatarFallback && icon && (
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
@@ -109,6 +117,7 @@ export default function DashboardDetailsPageLayout({
<Link
key={tab.href}
href={tab.href}
prefetch
className={cn(
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
"text-muted-foreground hover:text-foreground",
+7
View File
@@ -6,6 +6,12 @@ export type NavItem = {
href: string
icon?: ReactNode
isActive?: boolean
/**
* Optional prefix used to decide active state when the link target
* differs from the page's URL pattern (e.g. `/calendar/appointment/list`
* is the link, but the item should stay active on `/calendar/appointment/{id}`).
*/
matchPath?: string
badge?: string | number
items?: NavSubItem[]
}
@@ -15,6 +21,7 @@ export type NavSubItem = {
href: string
icon?: ReactNode
isActive?: boolean
matchPath?: string
}
export type NavGroup = {
+9 -6
View File
@@ -76,7 +76,7 @@ export const navGroups: NavGroup[] = [
icon: <CalendarIcon />,
items: [
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
{ title: "Appointments", href: "/calendar/appointment/list", matchPath: "/calendar/appointment", icon: <CalendarCheck2Icon /> },
],
},
{
@@ -142,12 +142,14 @@ export const navGroups: NavGroup[] = [
icon: <UserCogIcon />,
items: [
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
// Time Clocks / Time Sheets have no routes yet — links 404. Re-enable once
// /productivity/time-clocks and /productivity/timesheet pages exist.
// { 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: "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 +178,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" }
}
}
+99
View File
@@ -0,0 +1,99 @@
import { NextRequest, NextResponse } from "next/server"
/**
* Edge middleware that establishes workspace context from the request Host
* when a visitor lands on <subdomain>.reparee.com WITHOUT a prior handoff.
*
* - Skips if the workspace_uuid cookie is already set (handoff already happened).
* - Skips for the shared fallback host `tenant.reparee.com` and any non-tenant
* host (apex, localhost, preview URLs).
* - For a tenant subdomain, HMAC-signs the subdomain and calls SaaS
* `GET /api/v1/saas/workspaces/by-subdomain/<sub>` to resolve to
* { workspace_uuid, api_base_url }, then sets those as HttpOnly cookies.
*
* Matcher excludes /api/proxy/* (proxy needs no resolution; cookies already set)
* and /activate/* (the handoff itself sets the cookies via the page handler).
*/
export const config = {
matcher: [
"/((?!api/proxy|_next/static|_next/image|favicon\\.ico|robots\\.txt|sitemap\\.xml|activate).*)",
],
}
const SUBDOMAIN_RE = /^([a-z0-9-]+)\.reparee\.com$/i
const SKIP_SUBDOMAINS = new Set(["tenant", "www"])
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export async function middleware(req: NextRequest) {
if (req.cookies.get("workspace_uuid")) {
return NextResponse.next()
}
const host = (req.headers.get("host") || "").toLowerCase()
const match = host.match(SUBDOMAIN_RE)
if (!match) return NextResponse.next()
const sub = match[1].toLowerCase()
if (SKIP_SUBDOMAINS.has(sub)) return NextResponse.next()
const saasUrl = process.env.NEXT_PUBLIC_SAAS_URL || "https://reparee.com"
const secret = process.env.SAAS_SHARED_SECRET || ""
if (!secret) {
return NextResponse.next()
}
let workspaceUuid: string | undefined
let apiBaseUrl: string | undefined
try {
const signature = await hmacSha256Hex(sub, secret)
const resolveUrl = `${saasUrl.replace(/\/$/, "")}/api/v1/saas/workspaces/by-subdomain/${encodeURIComponent(sub)}`
const res = await fetch(resolveUrl, {
headers: { "X-SaaS-Signature": signature, Accept: "application/json" },
cache: "no-store",
signal: AbortSignal.timeout(2500),
})
if (!res.ok) return NextResponse.next()
const data = (await res.json()) as { ok?: boolean; workspace_uuid?: string; api_base_url?: string }
if (!data.ok || !data.workspace_uuid || !data.api_base_url) {
return NextResponse.next()
}
workspaceUuid = data.workspace_uuid
apiBaseUrl = data.api_base_url
} catch {
return NextResponse.next()
}
const response = NextResponse.next()
response.cookies.set("workspace_uuid", workspaceUuid!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
response.cookies.set("api_base_url", apiBaseUrl!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
return response
}
async function hmacSha256Hex(message: string, key: string): Promise<string> {
const enc = new TextEncoder()
const cryptoKey = await crypto.subtle.importKey(
"raw",
enc.encode(key),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
)
const sig = await crypto.subtle.sign("HMAC", cryptoKey, enc.encode(message))
return Array.from(new Uint8Array(sig))
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
}
@@ -19,6 +19,7 @@ import { useQueryClient } from "@tanstack/react-query"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { useFormDialog } from "@/shared/components/form-dialog"
import { AppointmentForm } from "./appointment-form"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentActionsProps = {
appointmentId: string
@@ -50,7 +51,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
setIsLoading(true)
try {
await api.appointments.changeStatus(appointmentId, { status } as any)
toast.success(`Status updated to "${status}".`)
toast.success(`Status updated to "${formatEnum(status)}".`)
queryClient.invalidateQueries({ queryKey: [APPOINTMENT_ROUTES.INDEX] })
router.refresh()
} catch {
@@ -15,6 +15,7 @@ import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { formatEnum } from "@/shared/utils/formatters"
type AppointmentData = {
id?: number
@@ -89,7 +90,7 @@ export function AppointmentGeneralInfo({ appointment }: AppointmentGeneralInfoPr
<div className="flex items-center gap-2">
{appointment.status && (
<Badge className={statusClass}>
{appointment.status.replace("_", " ")}
{formatEnum(appointment.status)}
</Badge>
)}
</div>
@@ -10,20 +10,30 @@ const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))
const appointmentFormSchema = z.object({
title: z.string().min(1, "Title is required"),
const appointmentFormSchema = z
.object({
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
date: z.string().min(1, "Date is required"),
from_time: z.string().min(1, "Start time is required"),
to_time: z.string().min(1, "End time is required"),
customer: relationFieldSchema,
vehicle: relationFieldSchema,
service_writer: relationFieldSchema,
service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
technician: relationFieldSchema,
department: relationFieldSchema,
job_card: relationFieldSchema,
notes: z.string().optional(),
status: z.string().optional(),
})
.superRefine((val, ctx) => {
if (val.from_time && val.to_time && val.to_time <= val.from_time) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["to_time"],
message: "End time must be after start time",
})
}
})
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
@@ -0,0 +1,132 @@
"use client"
import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
import { Calendar } from "@/shared/components/ui/calendar"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { useAuthApi } from "@/shared/useApi"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { formatEnum } from "@/shared/utils/formatters"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
confirmed: "bg-blue-100 text-blue-800",
in_progress: "bg-purple-100 text-purple-800",
completed: "bg-green-100 text-green-800",
cancelled: "bg-red-100 text-red-800",
}
function toDateKey(d: Date): string {
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, "0")
const day = String(d.getDate()).padStart(2, "0")
return `${y}-${m}-${day}`
}
export function AppointmentsCalendarView() {
const api = useAuthApi()
const router = useRouter()
const [selected, setSelected] = useState<Date | undefined>(() => new Date())
const { data, isLoading } = useQuery({
queryKey: [APPOINTMENT_ROUTES.INDEX, "calendar"],
queryFn: () => api.appointments.list({ per_page: 100 } as any),
})
const appointments: any[] = (data as any)?.data ?? []
const byDate = useMemo(() => {
const map: Record<string, any[]> = {}
for (const a of appointments) {
const key = String(a.date ?? "").slice(0, 10)
if (!key) continue
;(map[key] ??= []).push(a)
}
return map
}, [appointments])
const bookedDays = useMemo(
() => Object.keys(byDate).map((k) => new Date(`${k}T00:00:00`)),
[byDate],
)
const selectedKey = selected ? toDateKey(selected) : ""
const dayAppointments = byDate[selectedKey] ?? []
return (
<div className="grid gap-6 lg:grid-cols-[auto_1fr]">
<Card className="w-fit">
<CardContent className="p-3">
<Calendar
mode="single"
selected={selected}
onSelect={setSelected}
modifiers={{ booked: bookedDays }}
modifiersClassNames={{
booked:
"relative after:absolute after:bottom-1 after:left-1/2 after:h-1 after:w-1 after:-translate-x-1/2 after:rounded-full after:bg-primary",
}}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm font-semibold">
{selected
? selected.toLocaleDateString(undefined, {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
})
: "Select a day"}
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{isLoading && <p className="text-muted-foreground text-sm">Loading…</p>}
{!isLoading && dayAppointments.length === 0 && (
<p className="text-muted-foreground text-sm">No appointments on this day.</p>
)}
{dayAppointments.map((a) => {
const jobCardId = a.job_card_id ?? a.job_card?.id
return (
<button
key={a.id}
type="button"
onClick={() => router.push(`/calendar/appointment/${a.id}`)}
className="hover:bg-muted/40 w-full rounded border p-3 text-left transition"
>
<div className="flex items-center justify-between">
<span className="flex items-center gap-2 font-medium">
<CalendarCheck2Icon className="text-muted-foreground size-4" />
{a.title}
</span>
<Badge className={STATUS_COLORS[a.status] ?? "bg-gray-100 text-gray-800"}>
{formatEnum(a.status)}
</Badge>
</div>
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-sm">
<span className="flex items-center gap-1">
<ClockIcon className="size-3" />
{a.from_time} – {a.to_time}
</span>
{jobCardId && (
<span className="flex items-center gap-1">
<ClipboardListIcon className="size-3" />
{a.job_card?.title || `#${jobCardId}`}
</span>
)}
</div>
</button>
)
})}
</CardContent>
</Card>
</div>
)
}
@@ -5,8 +5,12 @@ import type { AuthUser } from "@garage/api"
const TOKEN_COOKIE = "auth_token"
const USER_COOKIE = "auth_user"
const WORKSPACE_COOKIE = "workspace_uuid"
const API_BASE_COOKIE = "api_base_url"
const DEFAULT_EXPIRES_IN = 60 * 60 * 24 * 7 // 7 days in seconds
const isProd = process.env.NODE_ENV === "production"
export async function setAuthCookies(
token: string,
user: AuthUser,
@@ -19,12 +23,16 @@ export async function setAuthCookies(
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
cookieStore.set(USER_COOKIE, JSON.stringify(user), {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
}
@@ -32,6 +40,8 @@ export async function clearAuthCookies() {
const cookieStore = await cookies()
cookieStore.delete(TOKEN_COOKIE)
cookieStore.delete(USER_COOKIE)
cookieStore.delete(WORKSPACE_COOKIE)
cookieStore.delete(API_BASE_COOKIE)
}
export async function getAuthCookies(): Promise<{
@@ -53,3 +63,65 @@ export async function getAuthCookies(): Promise<{
return { token, user }
}
/**
* Set the per-session workspace context: which garage backend to proxy to,
* and which workspace UUID to send on every upstream call. Written by the
* SaaS → garage-erp activation handoff.
*/
export async function setWorkspaceContext(
apiBase: string,
workspaceUuid: string,
expiresIn: number = DEFAULT_EXPIRES_IN,
) {
const cookieStore = await cookies()
const expires = new Date(Date.now() + expiresIn * 1000)
cookieStore.set(API_BASE_COOKIE, apiBase, {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
cookieStore.set(WORKSPACE_COOKIE, workspaceUuid, {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
}
export async function getWorkspaceContext(): Promise<{
apiBase: string | undefined
workspaceUuid: string | undefined
}> {
const cookieStore = await cookies()
return {
apiBase: cookieStore.get(API_BASE_COOKIE)?.value,
workspaceUuid: cookieStore.get(WORKSPACE_COOKIE)?.value,
}
}
export async function clearWorkspaceContext() {
const cookieStore = await cookies()
cookieStore.delete(WORKSPACE_COOKIE)
cookieStore.delete(API_BASE_COOKIE)
}
/**
* Server-action used by the SaaS handoff page. Wraps cookie writes for both
* the auth token/user and the workspace context atomically (from the client's
* point of view).
*/
export async function applyHandoff(
token: string,
user: AuthUser,
apiBase: string,
workspaceUuid: string,
) {
await setAuthCookies(token, user)
await setWorkspaceContext(apiBase, workspaceUuid)
}
@@ -2,7 +2,7 @@ import { z } from "zod"
const loginFormSchema = z.object({
email: z.string().trim().email("Enter a valid email address"),
password: z.string().min(8, "Password must be at least 8 characters"),
password: z.string().min(6, "Password must be at least 6 characters"),
})
type LoginFormValues = z.infer<typeof loginFormSchema>
@@ -13,7 +13,6 @@ import {
} from "@/shared/components/ui/card"
import {
Field,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -129,15 +128,6 @@ export function LoginForm({
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Logging in..." : "Login"}
</Button>
{lastLoginEmail ? (
<FieldDescription className="text-center">
Last email used: {lastLoginEmail}
</FieldDescription>
) : null}
{/* <FieldDescription className="text-center">
Don&apos;t have an account? <a href="#">Sign up</a>
</FieldDescription> */}
</Field>
</FieldGroup>
</form>
+16 -1
View File
@@ -11,9 +11,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2, Share2 } from "lucide-react"
import { useState } from "react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { BillForm } from "./bill-form"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type BillActionsProps = {
billId: string
@@ -23,6 +26,8 @@ export function BillActions({ billId }: BillActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("bill-details-edit")
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const handleDelete = async () => {
await api.bills.destroy(billId)
@@ -42,6 +47,14 @@ export function BillActions({ billId }: BillActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("bill", billId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-4" />
Share
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -49,6 +62,8 @@ export function BillActions({ billId }: BillActionsProps) {
</DropdownMenuContent>
</DropdownMenu>
<ShareDocumentDialog type="bill" id={billId} open={shareOpen} onOpenChange={setShareOpen} />
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
<DialogContent className="min-w-xl lg:min-w-4xl">
<DialogHeader>
@@ -3,7 +3,8 @@
import { Receipt } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillExpense = {
id: number
@@ -62,14 +63,14 @@ export function BillExpensesSection({ expenses = [] }: BillExpensesSectionProps)
{expense.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -19,9 +19,10 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"
import { formatDate, formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
function InfoItem({
icon: Icon,
@@ -3,7 +3,8 @@
import { Wrench } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillPart = {
id: number
@@ -62,14 +63,14 @@ export function BillPartsSection({ parts = [] }: BillPartsSectionProps) {
{part.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -17,7 +17,6 @@ import { PaymentMadeForm } from "@/modules/payment-mades/payment-made-form"
import { useBill } from "./bill-context"
import { formatDate } from "@/shared/utils/formatters"
import { getFullName } from "@/shared/utils/getFullName"
import { toRelation } from "@/shared/lib/utils"
export function BillPaymentsSection() {
const bill = useBill()
@@ -39,8 +38,17 @@ export function BillPaymentsSection() {
{(resourceId) => (
<PaymentMadeForm
initialData={{
amount: bill?.balance_due,
vendor: toRelation(bill?.vendor?.id, getFullName(bill?.vendor as any)),
// API-shape keys so PaymentMadeForm.mapToFormValues
// can pick them up (it reads `payment_made` / `vendor_id`
// / `vendor.*`, not the form-shape fields). bill_id +
// bill_number are required because the bill field is
// hidden when billId is supplied, but the schema still
// demands a populated bill relation.
bill_id: bill?.id,
bill_number: bill?.bill_number,
payment_made: bill?.balance_due,
vendor_id: bill?.vendor?.id,
vendor: bill?.vendor,
payment_for: "bill",
}}
billId={bill?.id}
@@ -77,7 +85,7 @@ export function BillPaymentsSection() {
return (
<div className="flex items-center gap-2">
<UserIcon className="h-4 w-4 text-muted-foreground" />
<span>{item.vendor?.name || item.vendor_name || "—"}</span>
<span>{item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name || "—"}</span>
</div>
)
},
@@ -3,7 +3,8 @@
import { Briefcase } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { formatCurrency, formatNumber } from "@/shared/utils/formatters"
import { formatNumber } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
type BillService = {
id: number
@@ -62,14 +63,14 @@ export function BillServicesSection({ services = [] }: BillServicesSectionProps)
{service.description || "—"}
</TableCell>
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
<TableCell className="text-right">{formatCurrency(rate)}</TableCell>
<TableCell className="text-right font-medium">{formatCurrency(amount)}</TableCell>
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
</TableRow>
)
})}
<TableRow className="bg-muted/50 font-medium">
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
<TableCell className="text-right">{formatCurrency(subtotal)}</TableCell>
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -1,6 +1,6 @@
"use client"
import { BillStatus } from "@garage/api"
import { BillStatus, parseApiError } from "@garage/api"
import { Badge, badgeVariants } from "@/shared/components/ui/badge"
import {
Select,
@@ -60,7 +60,7 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
toast.success("Bill status updated")
router.refresh()
} catch (error) {
toast.error("Failed to update bill status")
toast.error(parseApiError(error, "Failed to update bill status"))
} finally {
setIsLoading(false)
}
@@ -71,7 +71,9 @@ export default function BillStatusBadge({ bill }: BillStatusBadgeProps) {
<SelectTrigger
className={`border-0 size-auto p-0 h-auto font-medium ${STATUS_TRIGGER_CLASS_NAMES[status]}`}
>
<SelectValue placeholder="Select status" />
<SelectValue placeholder="Select status">
{formatEnum(status)}
</SelectValue>
</SelectTrigger>
<SelectContent>
{BillStatus.map((s) => (
@@ -2,9 +2,10 @@
import { Card, CardContent } from "@/shared/components/ui/card"
import { Separator } from "@/shared/components/ui/separator"
import { formatCurrency, formatEnum } from "@/shared/utils/formatters"
import { formatEnum } from "@/shared/utils/formatters"
import { cn } from "@/shared/lib/utils"
import { useBill } from "./bill-context"
import { Money } from "@/shared/components/money"
export function BillTotalsSummary() {
const bill = useBill()
@@ -46,70 +47,65 @@ export function BillTotalsSummary() {
{parts.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Parts ({parts.length})</span>
<span>{formatCurrency(partsTotal)}</span>
<span>{<Money value={partsTotal} />}</span>
</div>
)}
{services.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Services ({services.length})</span>
<span>{formatCurrency(servicesTotal)}</span>
<span>{<Money value={servicesTotal} />}</span>
</div>
)}
{expenses.length > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Expenses ({expenses.length})</span>
<span>{formatCurrency(expensesTotal)}</span>
<span>{<Money value={expensesTotal} />}</span>
</div>
)}
<Separator />
<div className="flex justify-between text-sm font-medium">
<span>Subtotal</span>
<span>{formatCurrency(subTotal)}</span>
<span>{<Money value={subTotal} />}</span>
</div>
{discountAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""}</span>
<span className="text-muted-foreground">−{formatCurrency(discountAmount)}</span>
<span className="text-muted-foreground">−{<Money value={discountAmount} />}</span>
</div>
)}
{taxAmount > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""}</span>
<span>{formatCurrency(taxAmount)}</span>
<span>{<Money value={taxAmount} />}</span>
</div>
)}
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-bold bg-muted/50",
)}>
<div className="flex justify-between text-base font-semibold">
<span>Total</span>
<span>{formatCurrency(total)}</span>
<span>{<Money value={total} />}</span>
</div>
{paymentsMade > 0 && (
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Payments Made</span>
<span className="text-emerald-600">−{formatCurrency(paymentsMade)}</span>
<div className="flex justify-between text-sm text-muted-foreground">
<span>Amount Paid</span>
<span>– {<Money value={paymentsMade} />}</span>
</div>
)}
{paymentsMade > 0 && (
<>
<Separator />
<div className={cn(
"flex justify-between rounded-lg px-3 py-2 text-base font-semibold",
balanceDue > 0 ? "text-destructive bg-destructive/5" : "text-emerald-700 bg-emerald-50 dark:bg-emerald-950/20",
"flex justify-between rounded-lg px-3 py-2 text-base font-bold",
balanceDue > 0 ? "bg-primary/10 text-primary" : "bg-green-500/10 text-green-600",
)}>
<span>Balance Due</span>
<span>{formatCurrency(balanceDue)}</span>
<span>{<Money value={balanceDue} />}</span>
</div>
</>
)}
</div>
</CardContent>
</Card>
@@ -11,9 +11,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { CreditNoteForm } from "./credit-note-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteActionsProps = {
creditNoteId: string
@@ -23,6 +24,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("credit-note-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.creditNotes.destroy(creditNoteId)
@@ -42,6 +44,10 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("credit_note", creditNoteId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete

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