Author SHA1 Message Date
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
Najjar\NajjarV02 464402f4d6 Merge fix/back-front-validation-alignment into dev 2026-05-12 17:34:16 +04:00
94 changed files with 3445 additions and 251 deletions
+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
+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 { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } 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,8 +25,44 @@ 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}
@@ -80,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>
)
},
@@ -103,5 +143,6 @@ export default function AppointmentsPage() {
actionsColumn(),
]}
/>
</div>
)
}
@@ -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,15 +1,45 @@
"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"
@@ -17,8 +47,25 @@ export default function EmployeesPage() {
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">
@@ -37,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>
)
},
},
{
@@ -48,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",
@@ -65,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>
)
},
@@ -8,14 +8,16 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
import { BillForm } from "@/modules/bills/bill-form"
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 } from "lucide-react"
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>
@@ -96,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"),
},
],
}),
]}
/>
)
@@ -11,11 +11,13 @@ import { useRouter } from "next/navigation"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2 } from "lucide-react"
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"
@@ -99,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,
@@ -36,7 +37,8 @@ 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 } from "lucide-react"
import { Building2, Printer } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
// ── Attachment helpers ──
@@ -226,6 +228,8 @@ type PaymentMadeItem = {
}
export default function PaymentsMadePage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const [attachmentTarget, setAttachmentTarget] = useState<{
id: string
ref: string
@@ -239,6 +243,7 @@ export default function PaymentsMadePage() {
searchable
searchPlaceholder="Search payments..."
getClient={(api) => api.paymentMades}
onRowClick={(row) => router.push(`/purchase/payments-made/${(row as any).id}`)}
headerProps={({ selectedItem, invalidateQuery }) => ({
actions: (
<FormDialog title="Record Payment">
@@ -393,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"),
},
],
}),
]}
/>
@@ -8,11 +8,13 @@ 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 } from "lucide-react"
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>
@@ -83,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"),
},
],
}),
]}
/>
)
@@ -10,6 +10,7 @@ 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 (
@@ -79,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(),
@@ -7,6 +7,9 @@ import FormDialog from "@/shared/components/form-dialog"
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
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,6 +23,7 @@ type CreditNoteItem = {
export default function CreditNotesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<CreditNotesClient>
@@ -66,7 +70,7 @@ export default function CreditNotesPage() {
}
return (
<span className={colorMap[status ?? ""] ?? ""}>
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
{formatEnum(status)}
</span>
)
},
@@ -75,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"),
},
],
}),
]}
/>
)
@@ -7,7 +7,8 @@ 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 { 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'
@@ -16,6 +17,7 @@ import { RelationLink } from '@/shared/components/relation-link'
export default function EstimatesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<EstimatesClient>
pageTitle="Estimates"
@@ -109,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,7 +1,8 @@
"use client"
import { Car, UserIcon } from "lucide-react"
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"
@@ -81,6 +82,7 @@ function getDueMeta(dueDate?: string) {
export default function InvoicesPage() {
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
return (
<ResourcePage<InvoicesClient>
@@ -238,7 +240,15 @@ export default function InvoicesPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("invoice", String(r.id), "print"),
},
],
}),
]}
/>
)
@@ -14,6 +14,7 @@ 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",
@@ -125,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>
)
},
@@ -12,6 +12,7 @@ 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,
@@ -102,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(),
@@ -6,7 +6,8 @@ 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 { ClipboardListIcon } 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 { useRouter } from 'next/navigation'
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
@@ -35,6 +36,7 @@ const statusColorMap: Record<string, string> = {
export default function JobCardsPage() {
const router = useRouter()
const filter = useFilterParams(jobCardFilterConfig)
const { print, isPrinting } = useDocumentPrint()
return (
<>
@@ -117,7 +119,15 @@ export default function JobCardsPage() {
)
},
},
actionsColumn(),
actionsColumn({
extraItems: (row) => [
{
label: isPrinting ? "Printing..." : "Print",
icon: Printer,
onClick: (r) => print("job_card", String(r.id), "print"),
},
],
}),
]}
/>
@@ -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,9 +10,12 @@ 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"
@@ -31,6 +34,9 @@ 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}
@@ -40,6 +46,7 @@ export default function PaymentReceivedPage() {
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">
@@ -68,6 +75,7 @@ export default function PaymentReceivedPage() {
},
{
accessorKey: "customer",
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
cell: ({ row }) => {
const item: any = row.original as unknown as PaymentReceivedItem
@@ -165,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"),
},
],
}),
]}
/>
)
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
import { ChevronLeft, Pencil, Plus, Save, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
@@ -44,6 +44,9 @@ export default function InspectionTemplateEditorPage() {
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
@@ -55,6 +58,8 @@ export default function InspectionTemplateEditorPage() {
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 {
@@ -74,6 +79,20 @@ export default function InspectionTemplateEditorPage() {
}
}
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({
@@ -153,8 +172,8 @@ export default function InspectionTemplateEditorPage() {
<div>
<label className="text-xs text-muted-foreground">Name</label>
<Input
defaultValue={template.name}
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex items-center gap-3 mt-5">
@@ -168,9 +187,9 @@ export default function InspectionTemplateEditorPage() {
<div>
<label className="text-xs text-muted-foreground">Description</label>
<Textarea
defaultValue={template.description ?? ""}
value={description}
rows={2}
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
</div>
@@ -259,6 +278,13 @@ export default function InspectionTemplateEditorPage() {
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,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
+2 -2
View File
@@ -146,8 +146,8 @@ export const navGroups: NavGroup[] = [
{ 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 /> },
],
@@ -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/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/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>
@@ -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)
}
@@ -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>
@@ -11,11 +11,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2, Share2 } 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
@@ -25,6 +26,7 @@ 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 () => {
@@ -45,6 +47,10 @@ 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
@@ -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) => (
@@ -11,9 +11,10 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { Ellipsis, Pencil, Printer, Trash2 } from "lucide-react"
import { useFormDialog } from "@/shared/components/form-dialog"
import { CreditNoteForm } from "./credit-note-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type CreditNoteActionsProps = {
creditNoteId: string
@@ -23,6 +24,7 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("credit-note-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.creditNotes.destroy(creditNoteId)
@@ -42,6 +44,10 @@ export function CreditNoteActions({ creditNoteId }: CreditNoteActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("credit_note", creditNoteId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -14,6 +14,7 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { formatEnum } from "@/shared/utils/formatters"
type CreditNoteData = {
id?: number
@@ -84,7 +85,7 @@ export function CreditNoteGeneralInfo({ creditNote }: CreditNoteGeneralInfoProps
)}
{creditNote.status && (
<Badge variant={statusColorMap[creditNote.status] as any ?? "outline"}>
{creditNote.status.charAt(0).toUpperCase() + creditNote.status.slice(1)}
{formatEnum(creditNote.status)}
</Badge>
)}
</div>
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import {
Combobox,
ComboboxInput,
@@ -131,10 +132,17 @@ export function RhfCustomerSelectField<
const handleCreateSuccess = (data?: any) => {
const item = data?.data ?? data
if (item?.id) {
field.onChange(buildCustomerOption(item))
if (!item?.id) {
setIsCreateOpen(false)
return
}
queryClient.invalidateQueries({ queryKey: [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"] })
const newOption = buildCustomerOption(item)
const key = [CUSTOMER_ROUTES.INDEX, "customer-select", customerType ?? "all"]
queryClient.setQueryData<CustomerOption[]>(key, (prev = []) =>
prev.some((o) => o.value === newOption.value) ? prev : [newOption, ...prev],
)
field.onChange(newOption)
setIsCreateOpen(false)
}
@@ -243,7 +251,9 @@ export function RhfCustomerSelectField<
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
<CustomerForm onSuccess={handleCreateSuccess} />
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
@@ -6,6 +6,7 @@ import { Loader2 } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import { EMPLOYEE_ROUTES } from "@garage/api"
import { Badge } from "@/shared/components/ui/badge"
import { formatEnum } from "@/shared/utils/formatters"
import {
Combobox,
ComboboxInput,
@@ -149,16 +150,16 @@ export function EmployeeCombobox({
{opt.type && (
<Badge
variant="secondary"
className="h-4 px-1.5 text-xs font-normal capitalize"
className="h-4 px-1.5 text-xs font-normal"
>
{opt.type}
{formatEnum(opt.type)}
</Badge>
)}
{opt.status && (
<span
className={`text-xs capitalize ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
className={`text-xs ${opt.status === "active" ? "text-green-600 dark:text-green-400" : "text-muted-foreground"}`}
>
{opt.status}
{formatEnum(opt.status)}
</span>
)}
</div>
@@ -18,6 +18,7 @@ import {
} from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { formatEnum } from "@/shared/utils/formatters"
type EmployeeData = {
id?: number
@@ -86,16 +87,15 @@ export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
{employee.type && (
<Badge variant="outline" className="capitalize">
{employee.type}
<Badge variant="outline">
{formatEnum(employee.type)}
</Badge>
)}
{employee.status && (
<Badge
variant={employee.status === "active" ? "default" : "secondary"}
className="capitalize"
>
{employee.status}
{formatEnum(employee.status)}
</Badge>
)}
</div>
@@ -124,7 +124,7 @@ export function CreateInvoiceFromEstimateButton() {
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="min-w-2xl">
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>Generate Invoice from Estimate</DialogTitle>
</DialogHeader>
@@ -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 { ExpenseForm } from "./expense-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type ExpenseActionsProps = {
expenseId: string
@@ -23,6 +24,7 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
const api = useAuthApi()
const router = useRouter()
const editDialog = useFormDialog("expense-details-edit")
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.expenses.destroy(expenseId)
@@ -42,6 +44,10 @@ export function ExpenseActions({ expenseId }: ExpenseActionsProps) {
<Pencil className="size-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("expense", expenseId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
@@ -14,6 +14,7 @@ import { ItemsTotalsCard } from "./items-totals-card"
import { CustomersTotalsCard } from "./customers-totals-card"
import { SalesPurchaseCards } from "./sales-purchase-cards"
import { VehicleStatsCards } from "./vehicle-stats-cards"
import { QuickShortcuts } from "./quick-shortcuts"
import { DashboardPeriods, type DashboardPeriod, type HomeDashboardQuery } from "@garage/api"
const DEFAULT_PERIOD: DashboardPeriod = "this_month"
@@ -66,6 +67,9 @@ export function DashboardContent() {
return (
<div className="space-y-6">
{/* Quick Shortcuts */}
<QuickShortcuts />
{/* Financial Overview */}
<FinancialTotalsCards data={data} />
@@ -0,0 +1,117 @@
"use client"
import Link from "next/link"
import {
CalendarCheck2Icon,
CarIcon,
ClipboardCheckIcon,
ClipboardListIcon,
PackageIcon,
ReceiptIcon,
ReceiptTextIcon,
UsersIcon,
WrenchIcon,
} from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
type Shortcut = {
label: string
href: string
icon: typeof CarIcon
color: string
bg: string
}
const shortcuts: Shortcut[] = [
{
label: "Job Cards",
href: "/sales/job-cards",
icon: ClipboardListIcon,
color: "text-emerald-600",
bg: "bg-emerald-500/10",
},
{
label: "Appointments",
href: "/calendar/appointment/list",
icon: CalendarCheck2Icon,
color: "text-sky-600",
bg: "bg-sky-500/10",
},
{
label: "New Estimate",
href: "/sales/estimates/new",
icon: ReceiptTextIcon,
color: "text-violet-600",
bg: "bg-violet-500/10",
},
{
label: "Invoices",
href: "/sales/invoice",
icon: ReceiptIcon,
color: "text-amber-600",
bg: "bg-amber-500/10",
},
{
label: "Inspections",
href: "/sales/inspections",
icon: ClipboardCheckIcon,
color: "text-rose-600",
bg: "bg-rose-500/10",
},
{
label: "Customers",
href: "/sales/customers",
icon: UsersIcon,
color: "text-blue-600",
bg: "bg-blue-500/10",
},
{
label: "Vehicles",
href: "/sales/vehicles",
icon: CarIcon,
color: "text-indigo-600",
bg: "bg-indigo-500/10",
},
{
label: "Parts",
href: "/items/parts",
icon: PackageIcon,
color: "text-orange-600",
bg: "bg-orange-500/10",
},
{
label: "Services",
href: "/items/services",
icon: WrenchIcon,
color: "text-teal-600",
bg: "bg-teal-500/10",
},
]
export function QuickShortcuts() {
return (
<Card>
<CardHeader>
<CardTitle className="text-sm font-medium">Quick Shortcuts</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-2 sm:grid-cols-4 lg:grid-cols-9">
{shortcuts.map((shortcut) => (
<Link
key={shortcut.label}
href={shortcut.href}
className="flex flex-col items-center gap-2 rounded-lg border p-3 text-center transition-colors hover:bg-muted/50"
>
<div className={`rounded-md p-2 ${shortcut.bg}`}>
<shortcut.icon className={`h-5 w-5 ${shortcut.color}`} />
</div>
<span className="text-[11px] font-medium leading-tight">
{shortcut.label}
</span>
</Link>
))}
</div>
</CardContent>
</Card>
)
}
@@ -4,6 +4,7 @@ import { Calendar, Clock } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { formatEnum } from "@/shared/utils/formatters"
import type { DashboardData } from "./use-dashboard-data"
type Props = { data: DashboardData }
@@ -36,7 +37,7 @@ function AppointmentRow({ appt }: { appt: AppointmentDetail }) {
{appt.from_time?.slice(0, 5)} - {appt.to_time?.slice(0, 5)}
</div>
<Badge variant="secondary" className={statusBadge[appt.status ?? ""] ?? ""}>
{appt.status}
{formatEnum(appt.status)}
</Badge>
</div>
</div>
@@ -2,6 +2,7 @@
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { parseApiError } from "@garage/api"
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"
@@ -50,17 +51,18 @@ export function InspectionActions({ inspectionId, status, onStatusChange }: Insp
}
const handleStatusChange = async (newStatus: string) => {
const promise = api.inspections.changeStatus({
const loadingToast = toast.loading("Updating status...")
try {
await api.inspections.changeStatus({
id: Number(inspectionId),
status: newStatus,
} as never)
toast.promise(promise, {
loading: "Updating status...",
success: "Status updated successfully",
error: "Failed to update status",
})
await promise
toast.success("Status updated successfully", { id: loadingToast })
onStatusChange?.()
router.refresh()
} catch (e) {
toast.error(parseApiError(e, "Failed to update status"), { id: loadingToast })
}
}
const transition = status ? STATUS_TRANSITIONS[status] : undefined
@@ -10,6 +10,7 @@ import {
MoreHorizontal,
Pencil,
PlayCircle,
Printer,
Share2,
Trash2,
XCircle,
@@ -28,6 +29,7 @@ import { useAuthApi } from "@/shared/useApi"
import { confirm } from "@/shared/components/confirm-dialog"
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
import { INSPECTION_ROUTES } from "@garage/api"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type InspectionStatus = "in_progress" | "completed" | "cancelled"
@@ -48,6 +50,7 @@ export function InspectionRowActions({
const router = useRouter()
const api = useAuthApi()
const queryClient = useQueryClient()
const { print, isPrinting } = useDocumentPrint()
const [shareOpen, setShareOpen] = useState(false)
const inspectionId = String(inspection.id)
@@ -125,6 +128,9 @@ export function InspectionRowActions({
<Pencil className="size-3.5 text-muted-foreground" /> Edit
</DropdownMenuItem>
<DropdownMenuItem onClick={() => print("inspection", inspectionId, "print")} disabled={isPrinting}>
<Printer className="size-3.5 text-muted-foreground" /> {isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShareOpen(true)}>
<Share2 className="size-3.5 text-muted-foreground" /> Share with customer
</DropdownMenuItem>
@@ -3,7 +3,7 @@
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { InvoiceStatus } from "@garage/api"
import { InvoiceStatus, parseApiError } from "@garage/api"
import { confirm } from "@/shared/components/confirm-dialog"
import { badgeVariants } from "@/shared/components/ui/badge"
import {
@@ -71,18 +71,13 @@ export default function InvoiceStatusBadge({ invoice }: InvoiceStatusBadgeProps)
setIsUpdating(true)
const loadingToast = toast.loading(`Updating invoice status to ${formatEnum(nextStatus)}...`)
try {
const promise = api.invoices.update(String(invoice.id), { status: nextStatus })
toast.promise(promise, {
loading: `Updating invoice status to ${formatEnum(nextStatus)}...`,
success: "Invoice status updated successfully.",
error: "Failed to update invoice status.",
})
await promise
setStatus(nextStatus)
await api.invoices.update(String(invoice.id), { status: nextStatus })
toast.success("Invoice status updated successfully.", { id: loadingToast })
router.refresh()
} catch (e) {
toast.error(parseApiError(e, "Failed to update invoice status."), { id: loadingToast })
} finally {
setIsUpdating(false)
}
@@ -24,6 +24,7 @@ import {
import { DEPARTMENT_ROUTES } from "@garage/api"
import { FUEL_LEVEL_OPTIONS } from "./job-card.schema"
import { toId } from "@/shared/lib/utils"
import { DepartmentInlineForm } from "@/modules/services/inline-forms/department-inline-form"
// ── Schema ──
@@ -46,7 +47,7 @@ const mapLookupOption = (item: any) => ({
label: item.name,
})
const STORE_OBJECT = { storeObject: true } as const
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label } as const
// ── Props ──
@@ -87,6 +88,10 @@ export function JobCardCheckInDialog({
})
const handleSubmit = async (values: CheckInFormValues) => {
if (!values.department) {
form.setError("department", { message: "Department is required" })
return
}
try {
await api.jobCards.checkIn(jobCardId, {
check_in_date: values.check_in_date || undefined,
@@ -131,13 +136,13 @@ export function JobCardCheckInDialog({
name="department"
label="Department"
placeholder="Select department"
required
queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list()}
mapOption={(op:any)=> ({value: op.id, label: op.name})}
mapOption={(item: any) => ({ value: String(item.id), label: item.name ?? String(item.id) })}
createForm={(props) => <DepartmentInlineForm {...props} />}
createLabel="Department"
{...STORE_OBJECT}
getOptionLabel={op=>op.label}
getOptionValue={op=>op}
/>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfDateField name="delivery_date" label="Delivery Date" />
@@ -1,5 +1,6 @@
"use client"
import { useQueryClient } from "@tanstack/react-query"
import { CrudResource } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
@@ -22,6 +23,7 @@ import { Money } from "@/shared/components/money"
export default function JobCardPaymentsReceived() {
const jobCard = useJobCard()
const queryClient = useQueryClient()
const [hasOpened, setHasOpened] = useState(false)
return (
@@ -60,7 +62,12 @@ export default function JobCardPaymentsReceived() {
invoiceCustomer={jobCard?.customer as any}
lockJobCard
lockCustomer
onSuccess={invalidateQuery}
onSuccess={() => {
// Refresh the payments list AND the job card / invoice
// queries so the PAID status reflects the new payment.
invalidateQuery()
queryClient.invalidateQueries()
}}
/>
)}
</FormDialog>
+2 -2
View File
@@ -212,14 +212,14 @@ export function PartForm({ resourceId, initialData, onSuccess }: PartFormProps)
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
name="selling_price"
label="Selling Price"
label="Selling Price (AED)"
placeholder="0.00"
type="number"
/>
<RhfTextField
name="purchase_price"
label="Purchase Price"
label="Purchase Price (AED)"
placeholder="0.00"
type="number"
/>
@@ -0,0 +1,48 @@
"use client"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Printer, Trash2 } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type PaymentMadeActionsProps = {
paymentId: string
}
export function PaymentMadeActions({ paymentId }: PaymentMadeActionsProps) {
const api = useAuthApi()
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.paymentMades.destroy(paymentId)
router.push("/purchase/payments-made")
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => print("payment_made", paymentId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -30,6 +30,7 @@ import {
BILL_ROUTES,
PAYMENT_MODE_ROUTES,
EMPLOYEE_ROUTES,
PAYMENT_MADE_ROUTES,
PaymentFor,
} from "@garage/api"
import { RhfVendorSelectField } from "@/modules/vendors/rhf-vendor-select-field"
@@ -182,6 +183,8 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
defaultValues: DEFAULT_VALUES,
resourceId,
initialData: resolvedInitialData,
initialize: (id) => api.paymentMades.show(id),
queryKey: [PAYMENT_MADE_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
@@ -210,21 +213,24 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
return
}
const vendorError = error.validationErrors.vendor_id?.[0]
const employeeError = error.validationErrors.employee_id?.[0]
const billError = error.validationErrors.bill_id?.[0]
// Surface the actual backend validation messages on each field
// instead of blanket-replacing them with the "not both" message —
// that masked unrelated errors and showed the wrong text when only
// one of vendor/employee was selected.
const errors = error.validationErrors
const billError = errors.bill_id?.[0]
const vendorError = errors.vendor_id?.[0]
const employeeError = errors.employee_id?.[0]
if (billError) {
form.setError("bill", { message: billError })
}
if (!vendorError && !employeeError) {
return
if (vendorError) {
form.setError("vendor", { message: vendorError })
}
if (employeeError) {
form.setError("employee", { message: employeeError })
}
const message = "Select either a vendor or an employee, not both"
form.setError("vendor", { message })
form.setError("employee", { message })
},
onSuccess: () => {
form.reset()
@@ -262,14 +268,14 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
name="vendor"
label="Vendor"
required={vendorRequired}
description="Select either a vendor or an employee."
description="Select a vendor, an employee, or both."
/>
<RhfAsyncSelectField
name="employee"
label="Employee"
placeholder="Select employee"
required={employeeRequired}
description="Select either a vendor or an employee."
description="Select a vendor, an employee, or both."
queryKey={[EMPLOYEE_ROUTES.INDEX]}
listFn={() => api.employees.list()}
mapOption={mapEmployeeOption}
@@ -66,19 +66,6 @@ const paymentMadeFormSchema = z.object({
message: "Vendor or employee is required",
})
}
if (hasVendor && hasEmployee) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["vendor"],
message: "Select either a vendor or an employee, not both",
})
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["employee"],
message: "Select either a vendor or an employee, not both",
})
}
})
type PaymentMadeFormValues = z.infer<typeof paymentMadeFormSchema>
@@ -0,0 +1,48 @@
"use client"
import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Printer, Trash2 } from "lucide-react"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
type PaymentReceivedActionsProps = {
paymentId: string
}
export function PaymentReceivedActions({ paymentId }: PaymentReceivedActionsProps) {
const api = useAuthApi()
const router = useRouter()
const { print, isPrinting } = useDocumentPrint()
const handleDelete = async () => {
await api.paymentReceived.destroy(paymentId)
router.push("/sales/payment-received")
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<Ellipsis className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => print("payment_received", paymentId, "print")} disabled={isPrinting}>
<Printer className="size-4" />
{isPrinting ? "Printing..." : "Print"}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
<Trash2 className="size-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
@@ -25,7 +25,7 @@ import {
paymentReceivedFormSchema,
type PaymentReceivedFormValues,
} from "./payment-received.schema"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES } from "@garage/api"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES, PAYMENT_RECEIVED_ROUTES } from "@garage/api"
// ── Props ──
@@ -58,13 +58,29 @@ const DEFAULT_VALUES: PaymentReceivedFormValues = {
function mapToFormValues(data: unknown): PaymentReceivedFormValues {
const d = (data as any)?.data ?? data ?? {}
const jobCardId = d.job_card_id ?? d.job_card?.id
const jobCardLabel = d.job_card?.title ?? d.job_card_name
const paymentModeId = d.payment_mode_id ?? d.payment_mode?.id
const paymentModeLabel = d.payment_mode?.title ?? d.payment_mode?.name ?? d.payment_mode_name
const customerId = d.customer_id ?? d.customer?.id
const customerLabel = d.customer?.first_name
? `${d.customer.first_name} ${d.customer.last_name ?? ""}`.trim()
: d.customer?.company_name ?? d.customer?.name ?? d.customer_name
const rawDate = d.payment_date
const payment_date = typeof rawDate === "string" && rawDate
? rawDate.slice(0, 10)
: new Date().toISOString().split("T")[0]
return {
job_card: toRelation(d.job_card_id, d.job_card_name),
payment_mode: toRelation(d.payment_mode_id, d.payment_mode_name),
customer: toRelation(d.customer_id, d.customer_name),
job_card: toRelation(jobCardId, jobCardLabel),
payment_mode: toRelation(paymentModeId, paymentModeLabel),
customer: toRelation(customerId, customerLabel),
amount_received: d.amount_received != null ? Number(d.amount_received) : 0,
payment_number: d.payment_number || "",
payment_date: d.payment_date || new Date().toISOString().split("T")[0],
payment_date,
note: d.note || "",
}
}
@@ -126,6 +142,8 @@ export function PaymentReceivedForm({ resourceId, initialData, onSuccess, defaul
defaultValues: DEFAULT_VALUES,
resourceId,
initialData: resolvedInitialData,
initialize: (id) => api.paymentReceived.show(id),
queryKey: [PAYMENT_RECEIVED_ROUTES.BY_ID, resourceId],
mapToFormValues,
})
@@ -1,6 +1,7 @@
"use client"
import { AlertTriangle, Plus, Save } from "lucide-react"
import { AlertTriangle, Plus, Save, Trash2 } from "lucide-react"
import { useFieldArray } from "react-hook-form"
import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
@@ -49,6 +50,8 @@ const DEFAULT_VALUES: ServiceGroupFormValues = {
mark_as_recommended: false,
set_packaged_pricing: false,
is_active: true,
parts: [],
services: [],
}
// ── Mapping helpers ──
@@ -60,6 +63,20 @@ const mapLookupOption = (item: any) => ({
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
const partLineToForm = (r: any) => ({
id: r.id,
part: r.part ? { value: String(r.part.id), label: r.part.title ?? r.part.name ?? `#${r.part.id}` } : null,
quantity: r.quantity != null ? Number(r.quantity) : 1,
rate: r.rate != null ? Number(r.rate) : 0,
})
const serviceLineToForm = (r: any) => ({
id: r.id,
service: r.service ? { value: String(r.service.id), label: r.service.title ?? r.service.name ?? `#${r.service.id}` } : null,
rate: r.rate != null ? Number(r.rate) : 0,
hours: r.hours != null ? Number(r.hours) : 0,
})
function mapToFormValues(data: unknown): ServiceGroupFormValues {
const d = (data as any)?.data ?? data ?? {}
@@ -77,6 +94,8 @@ function mapToFormValues(data: unknown): ServiceGroupFormValues {
mark_as_recommended: d.mark_as_recommended ?? false,
set_packaged_pricing: d.set_packaged_pricing ?? false,
is_active: d.is_active ?? true,
parts: Array.isArray(d._parts) ? d._parts.map(partLineToForm) : [],
services: Array.isArray(d._services) ? d._services.map(serviceLineToForm) : [],
}
}
@@ -116,18 +135,87 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
queryKey: [SERVICE_GROUP_ROUTES.BY_ID, resourceId],
// Fetch the group together with its existing parts/services so the
// pickers can be pre-populated when editing.
initialize: async (id) => {
const [group, parts, services] = await Promise.all([
api.serviceGroups.show(id),
api.serviceGroupParts.list({ service_group_id: id } as any),
api.serviceGroupServices.list({ service_group_id: id } as any),
])
const g = (group as any)?.data ?? group ?? {}
return {
data: {
...g,
_parts: (parts as any)?.data ?? [],
_services: (services as any)?.data ?? [],
},
}
},
mapToFormValues,
})
const partsArray = useFieldArray({ control: form.control, name: "parts" })
const servicesArray = useFieldArray({ control: form.control, name: "services" })
// Replace the package's parts/services on the server with the current form
// rows: delete the existing rows, then recreate from the form. Mirrors the
// "replace details" approach used elsewhere (e.g. payments).
const syncIncludes = async (groupId: string | number, values: ServiceGroupFormValues) => {
const gid = Number(groupId)
const existingParts = await api.serviceGroupParts.list({ service_group_id: gid } as any)
const existingPartIds = (((existingParts as any)?.data) ?? []).map((r: any) => r.id)
await Promise.all(existingPartIds.map((id: any) => api.serviceGroupParts.destroy(String(id))))
await Promise.all(
(values.parts ?? [])
.filter((p) => p.part?.value)
.map((p) =>
api.serviceGroupParts.create({
service_group_id: gid,
part_id: Number(p.part!.value),
quantity: Number(p.quantity ?? 1),
rate: Number(p.rate ?? 0),
} as any),
),
)
const existingServices = await api.serviceGroupServices.list({ service_group_id: gid } as any)
const existingServiceIds = (((existingServices as any)?.data) ?? []).map((r: any) => r.id)
await Promise.all(existingServiceIds.map((id: any) => api.serviceGroupServices.destroy(String(id))))
await Promise.all(
(values.services ?? [])
.filter((s) => s.service?.value)
.map((s) =>
api.serviceGroupServices.create({
service_group_id: gid,
service_id: Number(s.service!.value),
rate: Number(s.rate ?? 0),
hours: Number(s.hours ?? 0),
} as any),
),
)
}
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ServiceGroupFormValues) => {
const promise = isEditing && resourceId
? api.serviceGroups.update(resourceId, mapUpdatePayload(values))
: api.serviceGroups.create(mapCreatePayload(values))
const run = async () => {
const groupRes: any =
isEditing && resourceId
? await api.serviceGroups.update(resourceId, mapUpdatePayload(values))
: await api.serviceGroups.create(mapCreatePayload(values))
const groupId = resourceId ?? groupRes?.data?.id ?? groupRes?.id
if (groupId) {
await syncIncludes(groupId, values)
}
return groupRes
}
const promise = run()
toast.promise(promise, {
loading: isEditing ? "Updating service group..." : "Creating service group...",
success: isEditing ? "Service group updated" : "Service group created",
error: isEditing ? "Failed to update service group" : "Failed to create service group",
loading: isEditing ? "Updating package..." : "Creating package...",
success: isEditing ? "Package updated" : "Package created",
error: isEditing ? "Failed to update package" : "Failed to create package",
})
return promise
},
@@ -221,7 +309,7 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
name="selling_price"
label="Selling Price"
label="Selling Price (AED)"
placeholder="0.00"
type="number"
/>
@@ -239,6 +327,100 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
rows={3}
/>
{/* ── Parts in this package ── */}
<div className="border-t pt-4">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-semibold">Parts in this package</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => partsArray.append({ part: null, quantity: 1, rate: 0 })}
>
<Plus className="me-1 h-4 w-4" /> Add Part
</Button>
</div>
{partsArray.fields.length === 0 && (
<p className="text-muted-foreground text-sm">No parts added yet.</p>
)}
<div className="space-y-3">
{partsArray.fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 gap-2 sm:grid-cols-[1fr_110px_130px_auto] sm:items-end"
>
<RhfAsyncSelectField
name={`parts.${index}.part`}
label="Part"
placeholder="Select part (e.g. Engine Oil 5W-30)"
queryKey={["parts"]}
listFn={() => api.parts.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfTextField name={`parts.${index}.quantity`} label="Qty" type="number" placeholder="1" />
<RhfTextField name={`parts.${index}.rate`} label="Rate (AED)" type="number" placeholder="0.00" />
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => partsArray.remove(index)}
aria-label="Remove part"
>
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
))}
</div>
</div>
{/* ── Services in this package ── */}
<div className="border-t pt-4">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-semibold">Services in this package</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => servicesArray.append({ service: null, rate: 0, hours: 0 })}
>
<Plus className="me-1 h-4 w-4" /> Add Service
</Button>
</div>
{servicesArray.fields.length === 0 && (
<p className="text-muted-foreground text-sm">No services added yet.</p>
)}
<div className="space-y-3">
{servicesArray.fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 gap-2 sm:grid-cols-[1fr_110px_130px_auto] sm:items-end"
>
<RhfAsyncSelectField
name={`services.${index}.service`}
label="Service"
placeholder="Select service (e.g. Oil change labour)"
queryKey={["services"]}
listFn={() => api.services.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfTextField name={`services.${index}.hours`} label="Hours" type="number" placeholder="0" />
<RhfTextField name={`services.${index}.rate`} label="Rate (AED)" type="number" placeholder="0.00" />
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => servicesArray.remove(index)}
aria-label="Remove service"
>
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
))}
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCheckboxField
name="show_as_lump_sum"
@@ -4,6 +4,20 @@ export const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
const packagePartSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
part: relationFieldSchema,
quantity: z.coerce.number().min(0).optional(),
rate: z.coerce.number().min(0).optional(),
})
const packageServiceSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
service: relationFieldSchema,
rate: z.coerce.number().min(0).optional(),
hours: z.coerce.number().min(0).optional(),
})
export const serviceGroupFormSchema = z.object({
shop_type: relationFieldSchema,
inventory_category: relationFieldSchema,
@@ -18,6 +32,9 @@ export const serviceGroupFormSchema = z.object({
mark_as_recommended: z.boolean().optional(),
set_packaged_pricing: z.boolean().optional(),
is_active: z.boolean().optional(),
// ── Package contents ──
parts: z.array(packagePartSchema).optional(),
services: z.array(packageServiceSchema).optional(),
})
export type ServiceGroupFormValues = z.infer<typeof serviceGroupFormSchema>
@@ -4,7 +4,7 @@ import { AlertTriangle, Save } from "lucide-react"
import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useQuery } from "@tanstack/react-query"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
@@ -17,9 +17,11 @@ import {
RhfAsyncSelectField,
RhfTextareaField,
} from "@/shared/components/form"
import { RhfImageField } from "@/shared/components/form/fields/rhf-image-field"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId } from "@/shared/lib/utils"
import { CONSTANTS } from "@/config/constants"
import { FirstDayOfWork } from "@garage/api"
import { SETTINGS_ROUTES } from "@garage/api"
@@ -58,6 +60,7 @@ const DEFAULT_VALUES: SettingsFormValues = {
description: "",
security: "",
privacy_policy: "",
logo: null,
}
// ── Mapping helpers ──
@@ -85,6 +88,7 @@ function mapToFormValues(data: unknown): SettingsFormValues {
description: d.description ?? "",
security: d.security ?? "",
privacy_policy: d.privacy_policy ?? "",
logo: null,
}
}
@@ -93,11 +97,24 @@ function mapFormToPayload(values: SettingsFormValues) {
name: values.name,
email: values.email || undefined,
phone: values.phone || undefined,
alternative_phone: values.alternative_phone || undefined,
website: values.website || undefined,
time_zone: values.time_zone || undefined,
upi_id: values.upi_id || undefined,
first_day_of_work: values.first_day_of_work || undefined,
latitude: values.latitude || undefined,
longitude: values.longitude || undefined,
bank_details: values.bank_details || undefined,
first_address_line: values.first_address_line || undefined,
second_address_line: values.second_address_line || undefined,
country_id: toId(values.country),
state_id: toId(values.state),
city: values.city || undefined,
zip_code: values.zip_code || undefined,
description: values.description || undefined,
security: values.security || undefined,
privacy_policy: values.privacy_policy || undefined,
logo: values.logo instanceof File ? values.logo : undefined,
}
}
@@ -105,6 +122,7 @@ function mapFormToPayload(values: SettingsFormValues) {
export function SettingsForm() {
const api = useAuthApi()
const queryClient = useQueryClient()
const form = useForm<SettingsFormValues>({
resolver: zodResolver(settingsFormSchema) as any,
@@ -116,6 +134,14 @@ export function SettingsForm() {
queryFn: () => api.settings.fetch(),
})
const existingLogoPath: string | null = (() => {
const raw = (data as any)?.data
const record = Array.isArray(raw) ? raw[0] : raw
const logo = record?.logo
if (!logo || typeof logo !== "string") return null
return logo.startsWith("http") ? logo : CONSTANTS.getAssetUrl(`storage/${logo.replace(/^\/+/, "")}`)
})()
useEffect(() => {
if (!data) return
const raw = (data as any)?.data
@@ -126,15 +152,15 @@ export function SettingsForm() {
}, [data]) // eslint-disable-line react-hooks/exhaustive-deps
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: SettingsFormValues) => {
const payload = mapFormToPayload(values)
const promise = api.settings.update(payload)
toast.promise(promise, {
loading: "Saving settings...",
success: "Settings saved successfully",
error: "Failed to save settings",
})
return promise
mutationFn: (values: SettingsFormValues) => api.settings.update(mapFormToPayload(values)),
onSuccess: () => {
toast.success("Settings saved successfully")
// Refresh the settings query so the onboarding gate releases once
// the company info has been filled in.
queryClient.invalidateQueries({ queryKey: [SETTINGS_ROUTES.INDEX] })
},
onError: () => {
toast.error("Failed to save settings")
},
})
@@ -286,6 +312,20 @@ export function SettingsForm() {
{/* Sidebar - 4/12 */}
<div className="lg:col-span-4">
<FieldGroup className="sticky top-24 space-y-6">
{/* Logo Section */}
<div className="rounded-lg border bg-card p-4">
<h3 className="mb-1 text-base font-semibold">Workshop Logo</h3>
<p className="text-muted-foreground mb-3 text-xs">
Shown on printed invoices, estimates, job cards and other documents.
</p>
<RhfImageField
name="logo"
accept="image/png,image/jpeg,image/jpg,image/webp,image/svg+xml"
disabled={isLoading}
initialPreviewUrl={existingLogoPath}
/>
</div>
{/* Location & Time Section */}
<div className="rounded-lg border bg-card p-4">
<h3 className="mb-4 text-base font-semibold">Location & Time</h3>
@@ -340,8 +380,8 @@ export function SettingsForm() {
<div className="mt-4">
<RhfTextareaField
name="privacy_policy"
label="Privacy Policy"
placeholder="Privacy policy text..."
label="Terms and Conditions"
placeholder="Terms and conditions text..."
disabled={isLoading}
/>
</div>
@@ -51,6 +51,14 @@ export const settingsFormSchema = z.object({
description: z.string().optional(),
security: z.string().optional(),
privacy_policy: z.string().optional(),
logo: z
.any()
.nullable()
.optional()
.refine(
(v) => v == null || v instanceof File,
"Logo must be an image file",
),
})
export type SettingsFormValues = z.infer<typeof settingsFormSchema>
@@ -8,6 +8,7 @@ import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfSelectField,
RhfCheckboxField,
} from "@/shared/components/form"
import { toast } from "sonner"
@@ -17,6 +18,7 @@ import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import {
shopTimingFormSchema,
DAY_OF_WEEK_VALUES,
type ShopTimingFormValues,
} from "./shop-timing.schema"
import { SHOP_TIMING_ROUTES } from "@garage/api"
@@ -29,10 +31,19 @@ export type ShopTimingFormProps = {
onSuccess?: () => void
}
// ── Options ──
const DAY_OPTIONS = DAY_OF_WEEK_VALUES.map((day) => ({
value: day,
label: day.charAt(0).toUpperCase() + day.slice(1),
}))
// ── Default values ──
const DEFAULT_VALUES: ShopTimingFormValues = {
title: "",
day_of_week: "",
is_closed: false,
in_time: "",
out_time: "",
full_day_hours: "",
@@ -51,6 +62,8 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
return {
title: d.title ?? "",
day_of_week: d.day_of_week ?? "",
is_closed: d.is_closed ?? false,
in_time: d.in_time ?? "",
out_time: d.out_time ?? "",
full_day_hours: d.full_day_hours ?? "",
@@ -64,10 +77,15 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
}
function mapFormToPayload(values: ShopTimingFormValues) {
const closed = values.is_closed
return {
title: values.title,
in_time: values.in_time,
out_time: values.out_time,
day_of_week: values.day_of_week || undefined,
is_closed: closed,
// Closed days carry no opening hours.
in_time: closed ? undefined : values.in_time,
out_time: closed ? undefined : values.out_time,
full_day_hours: values.full_day_hours || undefined,
half_day_hours: values.half_day_hours || undefined,
punch_in: values.punch_in || undefined,
@@ -93,6 +111,8 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
mapToFormValues: mapToFormValues,
})
const isClosed = form.watch("is_closed")
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ShopTimingFormValues) => {
const payload = mapFormToPayload(values)
@@ -128,8 +148,13 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
<RhfTextField name="title" label="Title" placeholder="Enter title" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="in_time" label="In Time" placeholder="HH:MM:SS" required />
<RhfTextField name="out_time" label="Out Time" placeholder="HH:MM:SS" required />
<RhfSelectField name="day_of_week" label="Day" placeholder="Select day" options={DAY_OPTIONS} />
<RhfCheckboxField name="is_closed" label="Closed (shop shut this day)" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="in_time" label="In Time" placeholder="HH:MM:SS" required={!isClosed} disabled={isClosed} />
<RhfTextField name="out_time" label="Out Time" placeholder="HH:MM:SS" required={!isClosed} disabled={isClosed} />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
@@ -6,10 +6,24 @@ const optionalTimeFormat = z
.optional()
.refine((v) => !v || timeRegex.test(v), "Time must be in HH:MM:SS format")
const shopTimingFormSchema = z.object({
export const DAY_OF_WEEK_VALUES = [
"saturday",
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
] as const
const shopTimingFormSchema = z
.object({
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
in_time: z.string().min(1, "In time is required").regex(timeRegex, "In time must be in HH:MM:SS format"),
out_time: z.string().min(1, "Out time is required").regex(timeRegex, "Out time must be in HH:MM:SS format"),
day_of_week: z.string().optional(),
is_closed: z.boolean().default(false),
// Optional at the field level; required below only when the day is open.
in_time: optionalTimeFormat,
out_time: optionalTimeFormat,
full_day_hours: optionalTimeFormat,
half_day_hours: optionalTimeFormat,
punch_in: optionalTimeFormat,
@@ -17,7 +31,18 @@ const shopTimingFormSchema = z.object({
before_time: optionalTimeFormat,
after_time: optionalTimeFormat,
is_default: z.boolean().default(false),
})
})
.superRefine((values, ctx) => {
// When the shop is open, in/out times are mandatory.
if (!values.is_closed) {
if (!values.in_time) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["in_time"], message: "In time is required" })
}
if (!values.out_time) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["out_time"], message: "Out time is required" })
}
}
})
type ShopTimingFormValues = z.infer<typeof shopTimingFormSchema>
@@ -10,6 +10,7 @@ import {
RhfTextField,
RhfTextareaField,
RhfAsyncSelectField,
RhfCheckboxField,
RhfImageField,
} from "@/shared/components/form"
import { ShopTypeInlineForm } from "./inline-forms/shop-type-inline-form"
@@ -24,7 +25,7 @@ import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toRelation, toId } from "@/shared/lib/utils"
import { formatUppercase } from "@/shared/utils/formatters"
import { VEHICLE_ROUTES } from "@garage/api"
import { VEHICLE_ROUTES, INSURANCE_TYPE_ROUTES } from "@garage/api"
import { vehicleFormSchema, type VehicleFormValues } from "./vehicle.schema"
import { CustomerForm } from "../customers/customer-form"
@@ -57,6 +58,8 @@ const DEFAULT_VALUES: VehicleFormValues = {
drivetrain: "",
mileage: "",
note: "",
has_insurance: false,
insurance_type: null,
image: null,
}
@@ -92,6 +95,8 @@ function mapToFormValues(data: unknown): VehicleFormValues {
drivetrain: toFormString(d.drivetrain),
mileage: toFormString(d.mileage),
note: toFormString(d.note),
has_insurance: Boolean(d.has_insurance),
insurance_type: toRelation(d.insurance_type_id, d.insurance_type?.title),
image: null,
}
}
@@ -115,6 +120,8 @@ function mapToPayload(values: VehicleFormValues) {
drivetrain: values.drivetrain || undefined,
mileage: values.mileage || undefined,
note: values.note || undefined,
has_insurance: values.has_insurance ?? false,
insurance_type_id: values.has_insurance ? toId(values.insurance_type) : undefined,
image: values.image instanceof File ? values.image : undefined,
}
}
@@ -137,6 +144,8 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
const existingImageUrl: string | null =
(resolvedData as any)?.data?.image_url ?? (resolvedData as any)?.image_url ?? null
const hasInsurance = form.watch("has_insurance")
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: VehicleFormValues) => {
const payload = mapToPayload(values)
@@ -254,6 +263,24 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
/>
</div>
{/* Insurance */}
<div className="border-t pt-4">
<RhfCheckboxField name="has_insurance" label="Has Insurance?" />
{hasInsurance && (
<div className="mt-4">
<RhfAsyncSelectField
name="insurance_type"
label="Insurance Type"
placeholder="Select insurance type (e.g. Comprehensive)"
queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
listFn={() => api.insuranceTypes.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
)}
</div>
{/* License & identifiers */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
@@ -31,6 +31,10 @@ export const vehicleFormSchema = z.object({
// ── Notes ──
note: z.string().optional(),
// ── Insurance ──
has_insurance: z.boolean().optional(),
insurance_type: relationFieldSchema.optional(),
// ── Image ──
image: z.any().optional(),
})
@@ -10,6 +10,7 @@ import { Field, FieldLabel, FieldError, FieldDescription } from "@/shared/compon
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import {
Combobox,
ComboboxInput,
@@ -228,7 +229,9 @@ export function RhfVendorSelectField<
<DialogTitle className="text-2xl font-bold">Add Vendor</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
<VendorForm onSuccess={handleCreateSuccess} />
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
+72 -2
View File
@@ -8,11 +8,13 @@ import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfAsyncSelectField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId, toRelation } from "@/shared/lib/utils"
import {
vendorFormSchema,
@@ -31,24 +33,44 @@ export type VendorFormProps = {
// ── Default values ──
const DEFAULT_VALUES: VendorFormValues = {
salutation:"Mr.",
salutation: "Mr.",
first_name: "",
last_name: "",
company_name: "",
email: "",
phone: "",
alternate_phone: "",
address_line_1: "",
address_line_2: "",
city: "",
zip_code: "",
country: null,
state: null,
} as any
// ── Mapping helpers ──
const mapLookupOption = (item: any) => ({ value: String(item.id), label: item.name })
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
function mapToFormValues(data: unknown): VendorFormValues {
const d = (data as any)?.data ?? data ?? {}
const address = Array.isArray(d.addresses) ? d.addresses[0] ?? {} : {}
return {
first_name: d.first_name || "",
last_name: d.last_name || "",
company_name: d.company_name || "",
email: d.email || "",
}
phone: d.phone || "",
alternate_phone: d.alternate_phone || "",
address_line_1: address.address_line_1 || "",
address_line_2: address.address_line_2 || "",
city: address.city || "",
zip_code: address.zip_code || "",
country: toRelation(address.country_id, address.country?.name),
state: toRelation(address.state_id, address.state?.name),
} as VendorFormValues
}
function mapFormToPayload(values: VendorFormValues) {
@@ -57,6 +79,14 @@ function mapFormToPayload(values: VendorFormValues) {
last_name: values.last_name || undefined,
company_name: values.company_name || undefined,
email: values.email || undefined,
phone: values.phone || undefined,
alternate_phone: values.alternate_phone || undefined,
address_line_1: values.address_line_1 || undefined,
address_line_2: values.address_line_2 || undefined,
city: values.city || undefined,
zip_code: values.zip_code || undefined,
country_id: toId(values.country),
state_id: toId(values.state),
}
}
@@ -113,6 +143,46 @@ export function VendorForm({ resourceId, initialData, onSuccess }: VendorFormPro
<RhfTextField name="company_name" label="Company Name" placeholder="Acme Supplies" required />
<RhfTextField name="email" label="Email" placeholder="vendor@example.com" type="email" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="phone" label="Phone" placeholder="+971501234567" type="tel" />
<RhfTextField name="alternate_phone" label="Alternate Phone" placeholder="+971509876543" type="tel" />
</div>
{/* ── Address ── */}
<div className="border-t pt-4">
<h3 className="mb-3 text-sm font-semibold">Address</h3>
<RhfTextField name="address_line_1" label="Address Line 1" placeholder="Street 10" />
<div className="mt-4">
<RhfTextField name="address_line_2" label="Address Line 2" placeholder="Near Central Plaza" />
</div>
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfAsyncSelectField
name="country"
label="Country"
placeholder="Select country"
queryKey={["countries"]}
listFn={() => api.geo.countries()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="state"
label="State"
placeholder="Select state"
queryKey={["states"]}
listFn={() => api.geo.states()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="city" label="City" placeholder="Dubai" />
<RhfTextField name="zip_code" label="Zip Code" placeholder="00000" />
</div>
</div>
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />}
{isPending
+3 -2
View File
@@ -16,6 +16,7 @@ import {
import { Badge } from "@/shared/components/ui/badge"
import { Separator } from "@/shared/components/ui/separator"
import { Money } from "@/shared/components/money"
import { formatEnum } from "@/shared/utils/formatters"
type VendorData = {
id?: number
@@ -82,8 +83,8 @@ export function VendorGeneralInfo({ vendor }: VendorGeneralInfoProps) {
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{vendor.company_name || fullName || "Unknown vendor"}</Badge>
{vendor.status && (
<Badge variant={vendor.status === "active" ? "default" : "outline"} className="capitalize">
{vendor.status}
<Badge variant={vendor.status === "active" ? "default" : "outline"}>
{formatEnum(vendor.status)}
</Badge>
)}
</div>
+13
View File
@@ -11,6 +11,11 @@ const optionalNumberSchema = z.preprocess(
z.coerce.number().int().optional(),
)
const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
.optional()
const vendorFormSchema = z.object({
first_name: z.string().trim().min(1, "First name is required").max(50, "First name must be at most 50 characters"),
last_name: z.string().trim().min(1, "Last name is required").max(50, "Last name must be at most 50 characters"),
@@ -22,6 +27,14 @@ const vendorFormSchema = z.object({
opening_balance: optionalNumberSchema,
credit_limit: optionalNumberSchema,
website: optionalStringMaxSchema(255),
// ── Address (optional). Persisted by the backend store endpoint when
// address_line_1 + country + state are provided. ──
address_line_1: optionalStringMaxSchema(255),
address_line_2: optionalStringMaxSchema(255),
city: optionalStringMaxSchema(100),
zip_code: optionalStringMaxSchema(20),
country: relationFieldSchema,
state: relationFieldSchema,
})
type VendorFormValues = z.infer<typeof vendorFormSchema>
+25
View File
@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
images: {
remotePatterns: [
@@ -20,6 +21,30 @@ const nextConfig = {
hostname: 'reparee.test',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'api.reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'tenant.reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: process.env.NEXT_PUBLIC_GARAGE_HOST_PATTERN ?? '*.reparee.com',
port: '',
pathname: '/**',
}
]
}
+22 -9
View File
@@ -1,12 +1,25 @@
import { createApi, } from "@garage/api";
import { useAuthStore } from "./stores/auth-store";
import { getAuthCookies } from "@/modules/auth/auth.actions";
import { createApi } from "@garage/api"
import { getAuthCookies, getWorkspaceContext } from "@/modules/auth/auth.actions"
/**
* Returns an authenticated API client for server-side use (server actions, RSC).
*
* Server-side calls bypass the /api/proxy route — the server already has
* cookie access and can talk to the workspace's api install directly.
* Browser-side code should use the singleton `api` from @garage/api, which
* defaults to baseUrl="/api/proxy" and gets workspace context from cookies
* via the proxy route.
*/
export const getAuthApi = async () => {
const { token } = await getAuthCookies();
console.log(`Auth Token: ${token}`);
const api = createApi({ headers: token ? { Authorization: `Bearer ${token}` } : undefined });
return api;
const { token } = await getAuthCookies()
const { apiBase, workspaceUuid } = await getWorkspaceContext()
const headers: Record<string, string> = {}
if (token) headers.Authorization = `Bearer ${token}`
if (workspaceUuid) headers["X-Workspace-UUID"] = workspaceUuid
return createApi({
baseUrl: apiBase,
headers: Object.keys(headers).length ? headers : undefined,
})
}
@@ -0,0 +1,24 @@
import Link from "next/link"
import { AlertCircle, ExternalLink } from "lucide-react"
export function WorkspaceSessionMissing({ saasUrl }: { saasUrl?: string }) {
const fallbackUrl = saasUrl ?? process.env.NEXT_PUBLIC_SAAS_URL ?? "/"
return (
<div className="min-h-[60vh] flex items-center justify-center 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-10 mx-auto text-amber-500" />
<h1 className="text-lg font-semibold">Workspace session not found</h1>
<p className="text-sm text-muted-foreground">
Please open your garage from the SaaS dashboard to get a fresh handoff link.
</p>
<Link
href={fallbackUrl}
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"
>
<ExternalLink className="size-3.5" />
Back to SaaS dashboard
</Link>
</div>
</div>
)
}
@@ -13,6 +13,7 @@ import {
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { DataTable } from "@/shared/data-view/table-view"
import { createActionsColumn } from "@/shared/data-view/table-view"
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
import { useCrudDialog, type CrudDialogClient, type UseCrudDialogOptions } from "./use-crud-dialog"
// ── Types ──
@@ -89,6 +90,11 @@ export function CrudDialog<TClient extends CrudDialogClient>({
<Dialog open={isOpen} onOpenChange={(v) => { if (!v) handleClose() }}>
<DialogContent className="min-w-2xl max-w-3xl">
{/* Inner forms manage their own close via `onSuccess` → */}
{/* `crud.handleFormSuccess`. Shadow the parent dialog's */}
{/* close so a CrudDialog opened from inside a FormDialog */}
{/* doesn't dismiss the outer dialog on every save. */}
<DialogCloseContext.Provider value={crud.closeForm}>
<DialogHeader>
<div className="flex items-center gap-2">
{crud.isFormOpen && (
@@ -142,6 +148,7 @@ export function CrudDialog<TClient extends CrudDialogClient>({
</div>
)}
</ScrollArea>
</DialogCloseContext.Provider>
</DialogContent>
</Dialog>
</>
@@ -5,6 +5,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/shared/compo
import { ScrollArea } from '@/shared/components/ui/scroll-area'
import { Plus } from 'lucide-react'
import { cn } from '../lib/utils'
import { DialogCloseContext } from '@/shared/hooks/use-dialog-close'
export const formDialogParams = {
dialog: parseAsBoolean.withDefault(false),
@@ -87,7 +88,9 @@ export default function FormDialog(props: {
</DialogTitle>
</DialogHeader>
<ScrollArea className={`max-h-[80vh] px-4 ${cn(props.classNames?.scrollArea)}`}>
{props.children(resourceId, { open, close , isOpen})}
<DialogCloseContext.Provider value={close}>
{props.children(resourceId, { open, close, isOpen })}
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
@@ -24,6 +24,7 @@ import {
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { PlusIcon } from "lucide-react"
import { DialogCloseContext } from "@/shared/hooks/use-dialog-close"
// ── Inline create types ──
@@ -199,7 +200,9 @@ export function RhfAsyncSelectField<
</DialogTitle>
</DialogHeader>
<ScrollArea className="max-h-[80vh] px-4">
<DialogCloseContext.Provider value={() => setIsCreateOpen(false)}>
{createForm({ onSuccess: handleCreateSuccess })}
</DialogCloseContext.Provider>
</ScrollArea>
</DialogContent>
</Dialog>
@@ -0,0 +1,72 @@
"use client"
import { useEffect, useMemo } from "react"
import { usePathname, useRouter } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import { Loader2 } from "lucide-react"
import { useAuthApi } from "@/shared/useApi"
import { SETTINGS_ROUTES } from "@garage/api"
const COMPANY_SETUP_PATH = "/settings/company"
function FullScreenLoader({ label }: { label: string }) {
return (
<div className="bg-background fixed inset-0 z-50 flex flex-col items-center justify-center gap-3">
<Loader2 className="text-primary size-8 animate-spin" />
<p className="text-muted-foreground text-sm">{label}</p>
</div>
)
}
/**
* Onboarding gate.
*
* After login/activation the workspace's company information must be filled in
* before the rest of the app is usable. While the settings record loads we show
* a full-screen loader; if the company isn't set up yet we force the user onto
* the company-settings page and block navigation to any other route until it is.
*/
export function OnboardingGate({ children }: { children: React.ReactNode }) {
const api = useAuthApi()
const router = useRouter()
const pathname = usePathname()
const { data, isLoading, isError } = useQuery({
queryKey: [SETTINGS_ROUTES.INDEX],
queryFn: () => api.settings.fetch(),
staleTime: 5 * 60 * 1000,
retry: 1,
})
const isCompanyFilled = useMemo(() => {
const raw = (data as any)?.data
const record = Array.isArray(raw) ? raw[0] : raw
return Boolean(record?.id) && Boolean(String(record?.name ?? "").trim())
}, [data])
const onCompanyPage = pathname?.startsWith(COMPANY_SETUP_PATH) ?? false
// Onboarding is required once we know (loaded, no error) the company isn't set up.
// Fail open on error so a transient API failure can never lock the user out.
const mustOnboard = !isLoading && !isError && !isCompanyFilled
useEffect(() => {
if (mustOnboard && !onCompanyPage) {
router.replace(COMPANY_SETUP_PATH)
}
}, [mustOnboard, onCompanyPage, router])
// Initial load — determine onboarding status before showing anything.
if (isLoading) {
return <FullScreenLoader label="Loading your workspace…" />
}
// Needs onboarding and not yet on the company page → show loader while redirecting,
// so other pages never flash or become usable.
if (mustOnboard && !onCompanyPage) {
return <FullScreenLoader label="Let's set up your company first…" />
}
return <>{children}</>
}
@@ -0,0 +1,12 @@
"use client"
import { createContext, useContext } from "react"
// Closes the nearest dialog/sheet wrapper. `null` means the form is not
// inside a dialog that should auto-close (or a parent has explicitly
// shadowed the context, e.g. CrudDialog).
export const DialogCloseContext = createContext<(() => void) | null>(null)
export function useDialogClose(): (() => void) | null {
return useContext(DialogCloseContext)
}
@@ -3,14 +3,25 @@
import { useMutation, type UseMutationOptions } from "@tanstack/react-query"
import type { FieldValues, UseFormReturn } from "react-hook-form"
import { ApiError } from "@garage/api"
import { useDialogClose } from "./use-dialog-close"
export function useFormMutation<TValues extends FieldValues, TResponse = unknown>(
form: UseFormReturn<TValues>,
options: UseMutationOptions<TResponse, Error, TValues>,
) {
const closeDialog = useDialogClose()
return useMutation<TResponse, Error, TValues>({
...options,
onError: (err, vars,values, ctx) => {
onSuccess: async (data, vars, onMutateResult, ctx) => {
await options.onSuccess?.(data, vars, onMutateResult, ctx)
// If this form is rendered inside a dialog wrapper that registers
// a close handler (e.g. FormDialog), dismiss the dialog after a
// successful submit. Plain pages render the form without the
// provider, so this is a no-op there.
closeDialog?.()
},
onError: (err, vars, values, ctx) => {
if (err instanceof ApiError && err.validationErrors) {
Object.entries(err.validationErrors).forEach(([field, msgs]) => {
form.setError(field as any, { message: msgs[0] })
+241
View File
@@ -368,6 +368,9 @@
},
{
"name": "Document print / download"
},
{
"name": "Document share"
}
],
"paths": {
@@ -18229,6 +18232,169 @@
}
}
},
"/api/inspections/from-template": {
"post": {
"tags": [
"Inspections"
],
"summary": "Create inspection from a template (DVI flow).",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"template_id": {
"type": "integer"
},
"title": {
"type": "string"
},
"customer_id": {
"type": "integer"
},
"vehicle_id": {
"type": "integer"
},
"department_id": {
"type": "integer"
},
"employee_id": {
"type": "integer"
},
"order_number": {
"type": "string"
},
"date": {
"type": "string"
},
"time": {
"type": "string"
},
"odometer": {
"type": "integer"
},
"note": {
"type": "string"
},
"inspection_category_id": {
"type": "integer"
}
}
},
"example": {
"template_id": 1,
"title": "Pre-Service Inspection",
"customer_id": 1,
"vehicle_id": 1,
"department_id": 1,
"employee_id": 1,
"order_number": "INSP-001",
"date": "2026-03-31",
"time": "09:00:00",
"odometer": 12500,
"note": "Initial walk-around notes.",
"inspection_category_id": 1
}
}
}
},
"responses": {
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string"
},
"data": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "string"
},
"customer_id": {
"type": "integer"
},
"vehicle_id": {
"type": "integer"
},
"department_id": {
"type": "integer"
},
"employee_id": {
"type": "integer"
},
"order_number": {
"type": "string"
},
"date": {
"type": "string"
},
"time": {
"type": "string"
},
"odometer": {
"type": "integer"
},
"note": {
"type": "string"
},
"inspection_category_id": {
"type": "integer"
},
"template_id": {
"type": "integer"
},
"status": {
"type": "string"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
}
}
}
}
},
"example": {
"message": "Inspection created successfully",
"data": {
"id": 1,
"title": "Pre-Service Inspection",
"customer_id": 1,
"vehicle_id": 1,
"department_id": 1,
"employee_id": 1,
"order_number": "INSP-001",
"date": "2026-03-31",
"time": "09:00:00",
"odometer": 12500,
"note": "Initial walk-around notes.",
"inspection_category_id": 1,
"template_id": 1,
"status": "in_progress",
"created_at": "2026-03-31T10:00:00.000000Z",
"updated_at": "2026-03-31T10:00:00.000000Z"
}
}
}
}
}
}
}
},
"/api/inspections/{id}": {
"put": {
"tags": [
@@ -56330,6 +56496,81 @@
}
}
}
},
"/api/documents/share": {
"post": {
"tags": [
"Document share"
],
"summary": "POST /api/documents/share",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"document_type": {
"type": "string"
},
"document_id": {
"type": "integer"
},
"channel": {
"type": "string"
},
"email": {
"type": "string"
},
"phone": {
"type": "string"
},
"message": {
"type": "string"
}
}
},
"example": {
"document_type": "invoice",
"document_id": 1,
"channel": "email",
"email": "customer@example.com",
"phone": "+971500000000",
"message": "Please find your document."
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"share_url": {
"type": "string"
},
"whatsapp_url": {
"type": "string"
},
"expires_at": {
"type": "string",
"format": "date-time"
}
}
},
"example": {
"share_url": "https://example.com/share/abc",
"whatsapp_url": "https://wa.me/971500000000?text=...",
"expires_at": "2026-05-19T12:00:00+00:00"
}
}
}
}
}
}
}
}
}
+159
View File
@@ -11624,6 +11624,84 @@
}
]
},
{
"name": "Create inspection from a template (DVI flow).",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{auth_token}}",
"type": "string"
}
]
},
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"template_id\": 1,\n \"title\": \"Pre-Service Inspection\",\n \"customer_id\": 1,\n \"vehicle_id\": 1,\n \"department_id\": 1,\n \"employee_id\": 1,\n \"order_number\": \"INSP-001\",\n \"date\": \"2026-03-31\",\n \"time\": \"09:00:00\",\n \"odometer\": 12500,\n \"note\": \"Initial walk-around notes.\",\n \"inspection_category_id\": 1\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/inspections/from-template",
"host": [
"{{base_url}}"
],
"path": [
"api",
"inspections",
"from-template"
]
},
"description": "Required: template_id, title, customer_id, vehicle_id, department_id, employee_id, order_number, date, time (H:i:s). Optional: odometer, note, inspection_category_id. Available only when inspections.use_dvi_flow is enabled."
},
"response": [
{
"name": "201 Created",
"originalRequest": {
"method": "POST",
"header": [],
"url": {
"raw": "{{base_url}}/api/inspections/from-template",
"host": [
"{{base_url}}"
],
"path": [
"api",
"inspections",
"from-template"
]
}
},
"status": "Created",
"code": 201,
"_postman_previewlanguage": "json",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"cookie": [],
"body": "{\n \"message\": \"Inspection created successfully\",\n \"data\": {\n \"id\": 1,\n \"title\": \"Pre-Service Inspection\",\n \"customer_id\": 1,\n \"vehicle_id\": 1,\n \"department_id\": 1,\n \"employee_id\": 1,\n \"order_number\": \"INSP-001\",\n \"date\": \"2026-03-31\",\n \"time\": \"09:00:00\",\n \"odometer\": 12500,\n \"note\": \"Initial walk-around notes.\",\n \"inspection_category_id\": 1,\n \"template_id\": 1,\n \"status\": \"in_progress\",\n \"created_at\": \"2026-03-31T10:00:00.000000Z\",\n \"updated_at\": \"2026-03-31T10:00:00.000000Z\"\n }\n}"
}
]
},
{
"name": "Update the specified inspection.",
"request": {
@@ -43839,6 +43917,87 @@
}
],
"description": "Unified PDF endpoint. Query/body: type = inspection | estimate | job_card | invoice | payment_received | expense | purchase_order | bill | payment_made; id = record id; mode = print (inline) | download (attachment)."
},
{
"name": "Document share",
"item": [
{
"name": "POST /api/documents/share",
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{auth_token}}",
"type": "string"
}
]
},
"method": "POST",
"header": [
{
"key": "Accept",
"value": "application/json"
},
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"document_type\": \"invoice\",\n \"document_id\": 1,\n \"channel\": \"email\",\n \"email\": \"customer@example.com\",\n \"phone\": \"+971500000000\",\n \"message\": \"Please find your document.\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{base_url}}/api/documents/share",
"host": [
"{{base_url}}"
],
"path": [
"api",
"documents",
"share"
]
}
},
"response": [
{
"name": "200 OK",
"originalRequest": {
"method": "POST",
"header": [],
"url": {
"raw": "{{base_url}}/api/documents/share",
"host": [
"{{base_url}}"
],
"path": [
"api",
"documents",
"share"
]
}
},
"status": "OK",
"code": 200,
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": "{\n \"share_url\": \"https://example.com/share/abc\",\n \"whatsapp_url\": \"https://wa.me/971500000000?text=...\",\n \"expires_at\": \"2026-05-19T12:00:00+00:00\"\n}"
}
]
}
],
"description": "Generates a tokenized share URL (and WhatsApp link) for a document; optionally emails it. Body: document_type, document_id, channel (email|link), email (required if channel=email), phone, message."
}
],
"auth": {
+79 -62
View File
@@ -60,70 +60,87 @@ import { InventoryCategoriesClient } from "./clients/inventory-categories"
import { DocumentPrintClient } from "./clients/document-print"
import { DocumentShareClient } from "./clients/document-share"
export function createApi(options?: ApiClientOptions) {
export type CreateApiOptions = ApiClientOptions & { baseUrl?: string }
/**
* Default base URL used when no explicit override is passed. The dashboard
* runs every browser call through the Next.js server proxy at /api/proxy so
* the build-time NEXT_PUBLIC_API_URL never reaches the client.
*
* Server-side callers (server actions, RSC) can opt out by passing
* `{ baseUrl: <absolute api URL> }` from a cookie.
*/
const DEFAULT_BASE_URL = "/api/proxy"
export function createApi(options?: CreateApiOptions) {
const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL
const restOptions: ApiClientOptions | undefined = options?.headers
? { headers: options.headers }
: undefined
return {
auth: new AuthClient(undefined, options),
customers: new CustomersClient(undefined, options),
referralSources: new ReferralSourcesClient(undefined, options),
vehicles: new VehiclesClient(undefined, options),
vehicleAttributes: new VehicleAttributesClient(undefined, options),
vehicleDocuments: new VehicleDocumentsClient(undefined, options),
departments: new DepartmentsClient(undefined, options),
employees: new EmployeesClient(undefined, options),
geo: new GeoClient(undefined, options),
paymentTerms: new PaymentTermsClient(undefined, options),
shopTypes: new ShopTypesClient(undefined, options),
inventory: new InventoryClient(undefined, options),
vendors: new VendorsClient(undefined, options),
inspections: new InspectionsClient(undefined, options),
inspectionTemplates: new InspectionTemplatesClient(undefined, options),
labels: new LabelsClient(undefined, options),
insuranceTypes: new InsuranceTypesClient(undefined, options),
estimates: new EstimatesClient(undefined, options),
quickRemarks: new QuickRemarksClient(undefined, options),
quickNotes: new QuickNotesClient(undefined, options),
shopRecommendations: new ShopRecommendationsClient(undefined, options),
jobCards: new JobCardsClient(undefined, options),
paymentModes: new PaymentModesClient(undefined, options),
paymentReceived: new PaymentReceivedClient(undefined, options),
parts: new PartsClient(undefined, options),
purchaseOrders: new PurchaseOrdersClient(undefined, options),
services: new ServicesClient(undefined, options),
serviceGroups: new ServiceGroupsClient(undefined, options),
expenses: new ExpensesClient(undefined, options),
tasks: new TasksClient(undefined, options),
taskTypes: new TaskTypesClient(undefined, options),
taskSections: new TaskSectionsClient(undefined, options),
appointments: new AppointmentsClient(undefined, options),
shopTimings: new ShopTimingsClient(undefined, options),
shopCalendars: new ShopCalendarsClient(undefined, options),
holidayYears: new HolidayYearsClient(undefined, options),
taxes: new TaxesClient(undefined, options),
invoices: new InvoicesClient(undefined, options),
home: new HomeClient(undefined, options),
bills: new BillsClient(undefined, options),
reasons: new ReasonsClient(undefined, options),
holidays: new HolidaysClient(undefined, options),
makeAndModels: new MakeAndModelsClient(undefined, options),
timeSheets: new TimeSheetsClient(undefined, options),
invoiceSequences: new InvoiceSequencesClient(undefined, options),
creditNotes: new CreditNotesClient(undefined, options),
paymentMades: new PaymentMadesClient(undefined, options),
vendorCredits: new VendorCreditsClient(undefined, options),
inventoryAdjustments: new InventoryAdjustmentsClient(undefined, options),
serviceGroupIncludes: new ServiceGroupIncludesClient(undefined, options),
serviceGroupPricings: new ServiceGroupPricingsClient(undefined, options),
serviceGroupServices: new ServiceGroupServicesClient(undefined, options),
serviceGroupParts: new ServiceGroupPartsClient(undefined, options),
settings: new SettingsClient(undefined, options),
configurations: new ConfigurationsClient(undefined, options),
autoGenerate: new AutoGenerateClient(undefined, options),
expenseItems: new ExpenseItemsClient(undefined, options),
inventoryCategories: new InventoryCategoriesClient(undefined, options),
documentPrint: new DocumentPrintClient(undefined, options),
documentShare: new DocumentShareClient(undefined, options),
auth: new AuthClient(baseUrl, restOptions),
customers: new CustomersClient(baseUrl, restOptions),
referralSources: new ReferralSourcesClient(baseUrl, restOptions),
vehicles: new VehiclesClient(baseUrl, restOptions),
vehicleAttributes: new VehicleAttributesClient(baseUrl, restOptions),
vehicleDocuments: new VehicleDocumentsClient(baseUrl, restOptions),
departments: new DepartmentsClient(baseUrl, restOptions),
employees: new EmployeesClient(baseUrl, restOptions),
geo: new GeoClient(baseUrl, restOptions),
paymentTerms: new PaymentTermsClient(baseUrl, restOptions),
shopTypes: new ShopTypesClient(baseUrl, restOptions),
inventory: new InventoryClient(baseUrl, restOptions),
vendors: new VendorsClient(baseUrl, restOptions),
inspections: new InspectionsClient(baseUrl, restOptions),
inspectionTemplates: new InspectionTemplatesClient(baseUrl, restOptions),
labels: new LabelsClient(baseUrl, restOptions),
insuranceTypes: new InsuranceTypesClient(baseUrl, restOptions),
estimates: new EstimatesClient(baseUrl, restOptions),
quickRemarks: new QuickRemarksClient(baseUrl, restOptions),
quickNotes: new QuickNotesClient(baseUrl, restOptions),
shopRecommendations: new ShopRecommendationsClient(baseUrl, restOptions),
jobCards: new JobCardsClient(baseUrl, restOptions),
paymentModes: new PaymentModesClient(baseUrl, restOptions),
paymentReceived: new PaymentReceivedClient(baseUrl, restOptions),
parts: new PartsClient(baseUrl, restOptions),
purchaseOrders: new PurchaseOrdersClient(baseUrl, restOptions),
services: new ServicesClient(baseUrl, restOptions),
serviceGroups: new ServiceGroupsClient(baseUrl, restOptions),
expenses: new ExpensesClient(baseUrl, restOptions),
tasks: new TasksClient(baseUrl, restOptions),
taskTypes: new TaskTypesClient(baseUrl, restOptions),
taskSections: new TaskSectionsClient(baseUrl, restOptions),
appointments: new AppointmentsClient(baseUrl, restOptions),
shopTimings: new ShopTimingsClient(baseUrl, restOptions),
shopCalendars: new ShopCalendarsClient(baseUrl, restOptions),
holidayYears: new HolidayYearsClient(baseUrl, restOptions),
taxes: new TaxesClient(baseUrl, restOptions),
invoices: new InvoicesClient(baseUrl, restOptions),
home: new HomeClient(baseUrl, restOptions),
bills: new BillsClient(baseUrl, restOptions),
reasons: new ReasonsClient(baseUrl, restOptions),
holidays: new HolidaysClient(baseUrl, restOptions),
makeAndModels: new MakeAndModelsClient(baseUrl, restOptions),
timeSheets: new TimeSheetsClient(baseUrl, restOptions),
invoiceSequences: new InvoiceSequencesClient(baseUrl, restOptions),
creditNotes: new CreditNotesClient(baseUrl, restOptions),
paymentMades: new PaymentMadesClient(baseUrl, restOptions),
vendorCredits: new VendorCreditsClient(baseUrl, restOptions),
inventoryAdjustments: new InventoryAdjustmentsClient(baseUrl, restOptions),
serviceGroupIncludes: new ServiceGroupIncludesClient(baseUrl, restOptions),
serviceGroupPricings: new ServiceGroupPricingsClient(baseUrl, restOptions),
serviceGroupServices: new ServiceGroupServicesClient(baseUrl, restOptions),
serviceGroupParts: new ServiceGroupPartsClient(baseUrl, restOptions),
settings: new SettingsClient(baseUrl, restOptions),
configurations: new ConfigurationsClient(baseUrl, restOptions),
autoGenerate: new AutoGenerateClient(baseUrl, restOptions),
expenseItems: new ExpenseItemsClient(baseUrl, restOptions),
inventoryCategories: new InventoryCategoriesClient(baseUrl, restOptions),
documentPrint: new DocumentPrintClient(baseUrl, restOptions),
documentShare: new DocumentShareClient(baseUrl, restOptions),
}
}
/** Unauthenticated singleton — use for public calls (login, register) */
/** Unauthenticated singleton — use for public calls (login, register). */
export const api = createApi()
+3 -1
View File
@@ -11,9 +11,11 @@ export type DocumentPrintType =
| "job_card"
| "invoice"
| "payment_received"
| "expense"
| "purchase_order"
| "bill"
| string
| "payment_made"
| "credit_note"
export type DocumentPrintMode = "print" | "download"
+43 -3
View File
@@ -1,10 +1,34 @@
import { ApiClient, type ApiClientOptions } from "../infra/client"
import type { ApiPath, ApiRequestBody } from "../infra/types"
import type { ApiPath } from "../infra/types"
export const SETTINGS_ROUTES = {
INDEX: "/api/settings",
} as const satisfies Record<string, ApiPath>
export type SettingsUpdatePayload = {
name?: string
email?: string
phone?: string
alternative_phone?: string
website?: string
time_zone?: string
upi_id?: string
first_day_of_work?: string
latitude?: string | number
longitude?: string | number
bank_details?: string
first_address_line?: string
second_address_line?: string
country_id?: number | string
state_id?: number | string
city?: string
zip_code?: string
description?: string
security?: string
privacy_policy?: string
logo?: File | null
}
export class SettingsClient extends ApiClient {
constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
super(baseUrl, defaultOptions)
@@ -14,7 +38,23 @@ export class SettingsClient extends ApiClient {
return this.get(SETTINGS_ROUTES.INDEX)
}
async update(payload: ApiRequestBody<typeof SETTINGS_ROUTES.INDEX, "put">) {
return this.put(SETTINGS_ROUTES.INDEX, payload)
async update(payload: SettingsUpdatePayload) {
const hasFile = payload && (payload as any).logo instanceof File
if (!hasFile) {
const { logo: _logo, ...rest } = (payload ?? {}) as Record<string, unknown>
return this.put(SETTINGS_ROUTES.INDEX, rest as any)
}
const fd = new FormData()
for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
if (value === undefined || value === null) continue
if (value instanceof File) {
fd.append(key, value)
} else {
fd.append(key, String(value))
}
}
fd.append("_method", "PUT")
return this.postFormData(SETTINGS_ROUTES.INDEX, fd)
}
}
+1
View File
@@ -19,4 +19,5 @@ export {
export { ApiClient, ApiError, type ApiClientOptions } from "./client"
export { DEFAULT_PER_PAGE } from "./crud-client"
export * from "./crud-client"
export { parseApiError } from "./parse-error"
export type { AuthUser } from "./token"
+35
View File
@@ -0,0 +1,35 @@
import { ApiError } from "./client"
/**
* Extract a user-facing error message from a thrown ApiError (or any unknown error).
* Order: first Laravel field error → payload.message → error.message → fallback.
*/
export function parseApiError(error: unknown, fallback = "Request failed"): string {
const e = error as { payload?: { errors?: unknown; message?: string }; message?: string } | undefined
if (!e) return fallback
const errors = e.payload?.errors
if (errors && typeof errors === "object" && !Array.isArray(errors)) {
const first = Object.values(errors as Record<string, unknown>)[0]
if (Array.isArray(first) && typeof first[0] === "string") {
return first[0]
}
if (typeof first === "string") {
return first
}
}
if (typeof e.payload?.message === "string" && e.payload.message.length > 0) {
return e.payload.message
}
if (error instanceof ApiError && error.message) {
return error.message
}
if (typeof e.message === "string" && e.message.length > 0) {
return e.message
}
return fallback
}
+183
View File
@@ -11786,6 +11786,120 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/inspections/from-template": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/** Create inspection from a template (DVI flow). */
post: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
/**
* @example {
* "template_id": 1,
* "title": "Pre-Service Inspection",
* "customer_id": 1,
* "vehicle_id": 1,
* "department_id": 1,
* "employee_id": 1,
* "order_number": "INSP-001",
* "date": "2026-03-31",
* "time": "09:00:00",
* "odometer": 12500,
* "note": "Initial walk-around notes.",
* "inspection_category_id": 1
* }
*/
"application/json": {
template_id?: number;
title?: string;
customer_id?: number;
vehicle_id?: number;
department_id?: number;
employee_id?: number;
order_number?: string;
date?: string;
time?: string;
odometer?: number;
note?: string;
inspection_category_id?: number;
};
};
};
responses: {
/** @description Created */
201: {
headers: {
[name: string]: unknown;
};
content: {
/**
* @example {
* "message": "Inspection created successfully",
* "data": {
* "id": 1,
* "title": "Pre-Service Inspection",
* "customer_id": 1,
* "vehicle_id": 1,
* "department_id": 1,
* "employee_id": 1,
* "order_number": "INSP-001",
* "date": "2026-03-31",
* "time": "09:00:00",
* "odometer": 12500,
* "note": "Initial walk-around notes.",
* "inspection_category_id": 1,
* "template_id": 1,
* "status": "in_progress",
* "created_at": "2026-03-31T10:00:00.000000Z",
* "updated_at": "2026-03-31T10:00:00.000000Z"
* }
* }
*/
"application/json": {
message?: string;
data?: {
id?: number;
title?: string;
customer_id?: number;
vehicle_id?: number;
department_id?: number;
employee_id?: number;
order_number?: string;
date?: string;
time?: string;
odometer?: number;
note?: string;
inspection_category_id?: number;
template_id?: number;
status?: string;
/** Format: date-time */
created_at?: string;
/** Format: date-time */
updated_at?: string;
};
};
};
};
};
};
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/inspections/{id}": {
parameters: {
query?: never;
@@ -38964,6 +39078,75 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/documents/share": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/** POST /api/documents/share */
post: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
/**
* @example {
* "document_type": "invoice",
* "document_id": 1,
* "channel": "email",
* "email": "customer@example.com",
* "phone": "+971500000000",
* "message": "Please find your document."
* }
*/
"application/json": {
document_type?: string;
document_id?: number;
channel?: string;
email?: string;
phone?: string;
message?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
/**
* @example {
* "share_url": "https://example.com/share/abc",
* "whatsapp_url": "https://wa.me/971500000000?text=...",
* "expires_at": "2026-05-19T12:00:00+00:00"
* }
*/
"application/json": {
share_url?: string;
whatsapp_url?: string;
/** Format: date-time */
expires_at?: string;
};
};
};
};
};
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {