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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Additional fixes:

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:22:25 +04:00
Najjar\NajjarV02 ccb9eacd86 feat: implement workspace session management and enhance API proxy handling 2026-05-20 16:23:19 +04:00
57 changed files with 1794 additions and 194 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,14 +1,17 @@
"use client" "use client"
import { useState } from "react"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { ResourcePage } from "@/shared/data-view/resource-page" import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog" import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form" import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api" import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } 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 { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { RelationLink } from "@/shared/components/relation-link" import { RelationLink } from "@/shared/components/relation-link"
import { formatEnum } from "@/shared/utils/formatters" import { formatEnum } from "@/shared/utils/formatters"
@@ -22,8 +25,44 @@ const STATUS_COLORS: Record<string, string> = {
export default function AppointmentsPage() { export default function AppointmentsPage() {
const router = useRouter() 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 ( return (
<div className="space-y-2">
{viewToggle}
<ResourcePage<AppointmentsClient> <ResourcePage<AppointmentsClient>
pageTitle="Appointments" pageTitle="Appointments"
routeKey={APPOINTMENT_ROUTES.INDEX} routeKey={APPOINTMENT_ROUTES.INDEX}
@@ -104,5 +143,6 @@ export default function AppointmentsPage() {
actionsColumn(), actionsColumn(),
]} ]}
/> />
</div>
) )
} }
@@ -1,5 +1,12 @@
import { redirect } from "next/navigation" "use client"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
export default function CalendarsPage() { export default function CalendarsPage() {
return redirect("/calendar/appointment/list") return (
<div className="space-y-4 p-4">
<h1 className="text-xl font-semibold">Calendar</h1>
<AppointmentsCalendarView />
</div>
)
} }
@@ -4,6 +4,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog" import FormDialog from "@/shared/components/form-dialog"
import { ExpenseItemForm } from "@/modules/expense-items/expense-item-form" import { ExpenseItemForm } from "@/modules/expense-items/expense-item-form"
import { Money } from "@/shared/components/money"
import { EXPENSE_ITEM_ROUTES } from "@garage/api" import { EXPENSE_ITEM_ROUTES } from "@garage/api"
import type { ExpenseItemsClient } from "@garage/api" import type { ExpenseItemsClient } from "@garage/api"
@@ -41,7 +42,7 @@ export default function ExpenseItemPage() {
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />, header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).purchase_price const val = (row.original as any).purchase_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -4,6 +4,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog" import FormDialog from "@/shared/components/form-dialog"
import { ServiceGroupForm } from "@/modules/service-groups/service-group-form" import { ServiceGroupForm } from "@/modules/service-groups/service-group-form"
import { Money } from "@/shared/components/money"
import { Badge } from "@/shared/components/ui/badge" import { Badge } from "@/shared/components/ui/badge"
import { SERVICE_GROUP_ROUTES } from "@garage/api" import { SERVICE_GROUP_ROUTES } from "@garage/api"
import type { ServiceGroupsClient } from "@garage/api" import type { ServiceGroupsClient } from "@garage/api"
@@ -50,7 +51,7 @@ export default function ServiceGroupPage() {
header: ({ column }) => <ColumnHeader column={column} title="Price" />, header: ({ column }) => <ColumnHeader column={column} title="Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).selling_price const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -5,6 +5,7 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog" import FormDialog from "@/shared/components/form-dialog"
import { ImportDataButton } from "@/shared/components/import-data-button" import { ImportDataButton } from "@/shared/components/import-data-button"
import { ExportDataButton } from "@/shared/components/export-data-button" import { ExportDataButton } from "@/shared/components/export-data-button"
import { Money } from "@/shared/components/money"
import { useAuthApi } from "@/shared/useApi" import { useAuthApi } from "@/shared/useApi"
import { ServiceForm } from "@/modules/services/service-form" import { ServiceForm } from "@/modules/services/service-form"
import { SERVICE_ROUTES } from "@garage/api" import { SERVICE_ROUTES } from "@garage/api"
@@ -75,7 +76,7 @@ export default function ServicesPage() {
header: ({ column }) => <ColumnHeader column={column} title="Price" />, header: ({ column }) => <ColumnHeader column={column} title="Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).selling_price const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -6,6 +6,7 @@ import { DashboardLayout } from "@/base/components/layout/dashboard"
import { useAuth } from "@/shared/hooks/use-auth" import { useAuth } from "@/shared/hooks/use-auth"
import { navGroups } from "@/config/navGroups" import { navGroups } from "@/config/navGroups"
import { getAuthCookies } from "@/modules/auth/auth.actions" import { getAuthCookies } from "@/modules/auth/auth.actions"
import { OnboardingGate } from "@/shared/components/onboarding-gate"
import { redirect } from "next/navigation" import { redirect } from "next/navigation"
@@ -38,7 +39,7 @@ export default async function AuthenticatedLayout({
return ( return (
<DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}> <DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}>
{children} <OnboardingGate>{children}</OnboardingGate>
</DashboardLayout> </DashboardLayout>
) )
} }
@@ -10,8 +10,15 @@ export default async function layout(props: {
}) { }) {
const { id } = await props.params const { id } = await props.params
const api = await getServerApi() const api = await getServerApi()
// Guard the fetch: a failed request (404/401/5xx) must not throw and crash
// the whole route — render the chrome with a fallback title instead.
let vendor: Record<string, any> | undefined
try {
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> } const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data vendor = response?.data
} catch (err) {
console.error(`Failed to load vendor ${id} (layout):`, err)
}
const company = vendor?.company_name as string | undefined const company = vendor?.company_name as string | undefined
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim() const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
@@ -6,8 +6,15 @@ export default async function VendorDetailPage(props: { params: Promise<{ id: st
const api = await getServerApi() const api = await getServerApi()
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE), // The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
// so cast through `any` here until the schema is regenerated. // so cast through `any` here until the schema is regenerated.
// Guard the fetch: a failed request (404/401/5xx) must degrade gracefully
// instead of throwing and white-screening the whole route.
let vendor: Record<string, any> | undefined
try {
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> } const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
const vendor = response?.data vendor = response?.data
} catch (err) {
console.error(`Failed to load vendor ${id}:`, err)
}
if (!vendor) { if (!vendor) {
return <div className="text-muted-foreground p-6">Vendor not found.</div> return <div className="text-muted-foreground p-6">Vendor not found.</div>
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react" import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
import { JobCardExpenseItemForm } from "@/modules/job-cards/job-card-expense-item-form" import { JobCardExpenseItemForm } from "@/modules/job-cards/job-card-expense-item-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters" import { formatDate } from "@/shared/utils/formatters"
// TODO: expense items invalidation is not working properly when create new expense item line. Need to investigate why and fix it. // TODO: expense items invalidation is not working properly when create new expense item line. Need to investigate why and fix it.
@@ -93,7 +94,7 @@ export default function JobCardExpenseItemsPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />, header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.rate const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -101,7 +102,7 @@ export default function JobCardExpenseItemsPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />, header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.discount_amount const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—" return val != null && val > 0 ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react" import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form" import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters" import { formatDate } from "@/shared/utils/formatters"
import { JOB_CARD_ROUTES } from "@garage/api" import { JOB_CARD_ROUTES } from "@garage/api"
@@ -93,7 +94,7 @@ export default function JobCardPartsPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />, header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.rate const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -101,7 +102,7 @@ export default function JobCardPartsPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />, header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.discount_amount const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—" return val != null && val > 0 ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -24,6 +24,7 @@ import { toast } from "sonner"
import { Ellipsis, Plus } from "lucide-react" import { Ellipsis, Plus } from "lucide-react"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
import { JobCardServiceForm } from "@/modules/job-cards/job-card-service-form" import { JobCardServiceForm } from "@/modules/job-cards/job-card-service-form"
import { Money } from "@/shared/components/money"
import { formatDate } from "@/shared/utils/formatters" import { formatDate } from "@/shared/utils/formatters"
import { Badge } from "@/shared/components/ui/badge" import { Badge } from "@/shared/components/ui/badge"
@@ -108,7 +109,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Rate" />, header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.rate const val = row.original.rate
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -116,7 +117,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />, header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />,
cell: ({ row }) => { cell: ({ row }) => {
const lr = row.original.labor_rate const lr = row.original.labor_rate
return lr ? `${lr.title} ($${Number(lr.rate).toFixed(2)})` : "—" return lr ? <span>{lr.title} (<Money value={lr.rate} />)</span> : "—"
}, },
}, },
{ {
@@ -134,7 +135,7 @@ export default function JobCardServicesPage({
header: ({ column }) => <ColumnHeader column={column} title="Discount" />, header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = row.original.discount_amount const val = row.original.discount_amount
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—" return val != null && val > 0 ? <Money value={val} /> : "—"
}, },
}, },
{ {
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useState } from "react" import { useCallback, useEffect, useState } from "react"
import Link from "next/link" import Link from "next/link"
import { useParams } from "next/navigation" 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 { toast } from "sonner"
import { Button } from "@/shared/components/ui/button" import { Button } from "@/shared/components/ui/button"
@@ -44,6 +44,9 @@ export default function InspectionTemplateEditorPage() {
const api = useAuthApi() const api = useAuthApi()
const [template, setTemplate] = useState<InspectionTemplate | null>(null) const [template, setTemplate] = useState<InspectionTemplate | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [saving, setSaving] = useState(false)
const [editing, setEditing] = useState<{ const [editing, setEditing] = useState<{
section: InspectionTemplateSection section: InspectionTemplateSection
@@ -55,6 +58,8 @@ export default function InspectionTemplateEditorPage() {
try { try {
const res = await api.inspectionTemplates.show(id) const res = await api.inspectionTemplates.show(id)
setTemplate(res.data) setTemplate(res.data)
setName(res.data.name ?? "")
setDescription(res.data.description ?? "")
} catch (e: any) { } catch (e: any) {
toast.error(e?.message ?? "Failed to load template") toast.error(e?.message ?? "Failed to load template")
} finally { } 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 () => { const addSection = async () => {
if (!template) return if (!template) return
const name = await prompt({ const name = await prompt({
@@ -153,8 +172,8 @@ export default function InspectionTemplateEditorPage() {
<div> <div>
<label className="text-xs text-muted-foreground">Name</label> <label className="text-xs text-muted-foreground">Name</label>
<Input <Input
defaultValue={template.name} value={name}
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })} onChange={(e) => setName(e.target.value)}
/> />
</div> </div>
<div className="flex items-center gap-3 mt-5"> <div className="flex items-center gap-3 mt-5">
@@ -168,9 +187,9 @@ export default function InspectionTemplateEditorPage() {
<div> <div>
<label className="text-xs text-muted-foreground">Description</label> <label className="text-xs text-muted-foreground">Description</label>
<Textarea <Textarea
defaultValue={template.description ?? ""} value={description}
rows={2} rows={2}
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })} onChange={(e) => setDescription(e.target.value)}
/> />
</div> </div>
</div> </div>
@@ -259,6 +278,13 @@ export default function InspectionTemplateEditorPage() {
onSaved={load} 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> </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
+27 -6
View File
@@ -1,7 +1,7 @@
"use client" "use client"
import { useEffect, useState } from "react" import { Suspense, useEffect, useState } from "react"
import { useParams } from "next/navigation" import { useParams, useSearchParams } from "next/navigation"
import { import {
AlertCircle, AlertCircle,
Calendar, Calendar,
@@ -125,9 +125,13 @@ function ScoreRing({ score }: { score: number | null }) {
) )
} }
export default function PublicInspectionPage() { function PublicInspectionContent() {
const params = useParams<{ token: string }>() const params = useParams<{ token: string }>()
const token = params.token const token = params.token
// Workspace UUID baked into the share URL — the public API endpoint needs it
// to resolve which tenant DB holds this inspection.
const searchParams = useSearchParams()
const ws = searchParams.get("ws") ?? ""
const [data, setData] = useState<PublicInspection | null>(null) const [data, setData] = useState<PublicInspection | null>(null)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
@@ -135,7 +139,8 @@ export default function PublicInspectionPage() {
useEffect(() => { useEffect(() => {
const base = process.env.NEXT_PUBLIC_API_URL ?? "" const base = process.env.NEXT_PUBLIC_API_URL ?? ""
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}`, { const wsQuery = ws ? `?ws=${encodeURIComponent(ws)}` : ""
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}${wsQuery}`, {
headers: { Accept: "application/json", "X-Lang": "en" }, headers: { Accept: "application/json", "X-Lang": "en" },
}) })
.then(async (res) => { .then(async (res) => {
@@ -148,7 +153,7 @@ export default function PublicInspectionPage() {
.then((json: { data: PublicInspection }) => setData(json.data)) .then((json: { data: PublicInspection }) => setData(json.data))
.catch((e: Error) => setError(e.message)) .catch((e: Error) => setError(e.message))
.finally(() => setLoading(false)) .finally(() => setLoading(false))
}, [token]) }, [token, ws])
if (loading) { if (loading) {
return ( return (
@@ -200,7 +205,7 @@ export default function PublicInspectionPage() {
<span className="font-medium text-foreground">Inspection report</span> <span className="font-medium text-foreground">Inspection report</span>
</div> </div>
<a <a
href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print`} href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print${ws ? `?ws=${encodeURIComponent(ws)}` : ""}`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition" 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"
@@ -418,6 +423,22 @@ export default function PublicInspectionPage() {
) )
} }
export default function PublicInspectionPage() {
return (
<Suspense
fallback={
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="size-4 animate-spin" /> Loading inspection…
</div>
</div>
}
>
<PublicInspectionContent />
</Suspense>
)
}
function InfoCell({ function InfoCell({
icon: Icon, icon: Icon,
label, label,
+4 -2
View File
@@ -142,8 +142,10 @@ export const navGroups: NavGroup[] = [
icon: <UserCogIcon />, icon: <UserCogIcon />,
items: [ items: [
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> }, { title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> }, // Time Clocks / Time Sheets have no routes yet — links 404. Re-enable once
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> }, // /productivity/time-clocks and /productivity/timesheet pages exist.
// { title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
// { title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> }, // { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> }, // { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
{ title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> }, { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
+99
View File
@@ -0,0 +1,99 @@
import { NextRequest, NextResponse } from "next/server"
/**
* Edge middleware that establishes workspace context from the request Host
* when a visitor lands on <subdomain>.reparee.com WITHOUT a prior handoff.
*
* - Skips if the workspace_uuid cookie is already set (handoff already happened).
* - Skips for the shared fallback host `tenant.reparee.com` and any non-tenant
* host (apex, localhost, preview URLs).
* - For a tenant subdomain, HMAC-signs the subdomain and calls SaaS
* `GET /api/v1/saas/workspaces/by-subdomain/<sub>` to resolve to
* { workspace_uuid, api_base_url }, then sets those as HttpOnly cookies.
*
* Matcher excludes /api/proxy/* (proxy needs no resolution; cookies already set)
* and /activate/* (the handoff itself sets the cookies via the page handler).
*/
export const config = {
matcher: [
"/((?!api/proxy|_next/static|_next/image|favicon\\.ico|robots\\.txt|sitemap\\.xml|activate).*)",
],
}
const SUBDOMAIN_RE = /^([a-z0-9-]+)\.reparee\.com$/i
const SKIP_SUBDOMAINS = new Set(["tenant", "www"])
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export async function middleware(req: NextRequest) {
if (req.cookies.get("workspace_uuid")) {
return NextResponse.next()
}
const host = (req.headers.get("host") || "").toLowerCase()
const match = host.match(SUBDOMAIN_RE)
if (!match) return NextResponse.next()
const sub = match[1].toLowerCase()
if (SKIP_SUBDOMAINS.has(sub)) return NextResponse.next()
const saasUrl = process.env.NEXT_PUBLIC_SAAS_URL || "https://reparee.com"
const secret = process.env.SAAS_SHARED_SECRET || ""
if (!secret) {
return NextResponse.next()
}
let workspaceUuid: string | undefined
let apiBaseUrl: string | undefined
try {
const signature = await hmacSha256Hex(sub, secret)
const resolveUrl = `${saasUrl.replace(/\/$/, "")}/api/v1/saas/workspaces/by-subdomain/${encodeURIComponent(sub)}`
const res = await fetch(resolveUrl, {
headers: { "X-SaaS-Signature": signature, Accept: "application/json" },
cache: "no-store",
signal: AbortSignal.timeout(2500),
})
if (!res.ok) return NextResponse.next()
const data = (await res.json()) as { ok?: boolean; workspace_uuid?: string; api_base_url?: string }
if (!data.ok || !data.workspace_uuid || !data.api_base_url) {
return NextResponse.next()
}
workspaceUuid = data.workspace_uuid
apiBaseUrl = data.api_base_url
} catch {
return NextResponse.next()
}
const response = NextResponse.next()
response.cookies.set("workspace_uuid", workspaceUuid!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
response.cookies.set("api_base_url", apiBaseUrl!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
return response
}
async function hmacSha256Hex(message: string, key: string): Promise<string> {
const enc = new TextEncoder()
const cryptoKey = await crypto.subtle.importKey(
"raw",
enc.encode(key),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
)
const sig = await crypto.subtle.sign("HMAC", cryptoKey, enc.encode(message))
return Array.from(new Uint8Array(sig))
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
}
@@ -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 TOKEN_COOKIE = "auth_token"
const USER_COOKIE = "auth_user" 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 DEFAULT_EXPIRES_IN = 60 * 60 * 24 * 7 // 7 days in seconds
const isProd = process.env.NODE_ENV === "production"
export async function setAuthCookies( export async function setAuthCookies(
token: string, token: string,
user: AuthUser, user: AuthUser,
@@ -19,12 +23,16 @@ export async function setAuthCookies(
expires, expires,
path: "/", path: "/",
sameSite: "strict", sameSite: "strict",
httpOnly: true,
secure: isProd,
}) })
cookieStore.set(USER_COOKIE, JSON.stringify(user), { cookieStore.set(USER_COOKIE, JSON.stringify(user), {
expires, expires,
path: "/", path: "/",
sameSite: "strict", sameSite: "strict",
httpOnly: true,
secure: isProd,
}) })
} }
@@ -32,6 +40,8 @@ export async function clearAuthCookies() {
const cookieStore = await cookies() const cookieStore = await cookies()
cookieStore.delete(TOKEN_COOKIE) cookieStore.delete(TOKEN_COOKIE)
cookieStore.delete(USER_COOKIE) cookieStore.delete(USER_COOKIE)
cookieStore.delete(WORKSPACE_COOKIE)
cookieStore.delete(API_BASE_COOKIE)
} }
export async function getAuthCookies(): Promise<{ export async function getAuthCookies(): Promise<{
@@ -53,3 +63,65 @@ export async function getAuthCookies(): Promise<{
return { token, user } 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" } from "@/shared/components/ui/card"
import { import {
Field, Field,
FieldDescription,
FieldError, FieldError,
FieldGroup, FieldGroup,
FieldLabel, FieldLabel,
@@ -129,15 +128,6 @@ export function LoginForm({
<Button type="submit" disabled={isSubmitting}> <Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Logging in..." : "Login"} {isSubmitting ? "Logging in..." : "Login"}
</Button> </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> </Field>
</FieldGroup> </FieldGroup>
</form> </form>
@@ -124,7 +124,7 @@ export function CreateInvoiceFromEstimateButton() {
</Button> </Button>
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="min-w-2xl"> <DialogContent className="sm:max-w-5xl">
<DialogHeader> <DialogHeader>
<DialogTitle>Generate Invoice from Estimate</DialogTitle> <DialogTitle>Generate Invoice from Estimate</DialogTitle>
</DialogHeader> </DialogHeader>
@@ -1,4 +1,5 @@
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import { Money } from "@/shared/components/money"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
/** Core expense-item columns shared between the expense items page and selector dialogs. */ /** Core expense-item columns shared between the expense items page and selector dialogs. */
@@ -16,7 +17,7 @@ export const expenseItemColumns = {
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />, header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).purchase_price const val = (row.original as any).purchase_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
chartOfAccount: { chartOfAccount: {
@@ -24,6 +24,7 @@ import {
import { DEPARTMENT_ROUTES } from "@garage/api" import { DEPARTMENT_ROUTES } from "@garage/api"
import { FUEL_LEVEL_OPTIONS } from "./job-card.schema" import { FUEL_LEVEL_OPTIONS } from "./job-card.schema"
import { toId } from "@/shared/lib/utils" import { toId } from "@/shared/lib/utils"
import { DepartmentInlineForm } from "@/modules/services/inline-forms/department-inline-form"
// ── Schema ── // ── Schema ──
@@ -37,6 +38,16 @@ const checkInSchema = z.object({
department: z.object({ value: z.any(), label: z.string() }).nullable().optional(), department: z.object({ value: z.any(), label: z.string() }).nullable().optional(),
delivery_date: z.string().optional(), delivery_date: z.string().optional(),
delivery_time: z.string().optional(), delivery_time: z.string().optional(),
}).superRefine((values, ctx) => {
// Department is marked required in the UI (asterisk); enforce it at the
// schema level so the form cannot be submitted without one.
if (!values.department) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["department"],
message: "Department is required",
})
}
}) })
type CheckInFormValues = z.infer<typeof checkInSchema> type CheckInFormValues = z.infer<typeof checkInSchema>
@@ -46,7 +57,7 @@ const mapLookupOption = (item: any) => ({
label: item.name, 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 ── // ── Props ──
@@ -87,6 +98,10 @@ export function JobCardCheckInDialog({
}) })
const handleSubmit = async (values: CheckInFormValues) => { const handleSubmit = async (values: CheckInFormValues) => {
if (!values.department) {
form.setError("department", { message: "Department is required" })
return
}
try { try {
await api.jobCards.checkIn(jobCardId, { await api.jobCards.checkIn(jobCardId, {
check_in_date: values.check_in_date || undefined, check_in_date: values.check_in_date || undefined,
@@ -131,13 +146,13 @@ export function JobCardCheckInDialog({
name="department" name="department"
label="Department" label="Department"
placeholder="Select department" placeholder="Select department"
required
queryKey={[DEPARTMENT_ROUTES.INDEX]} queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list()} 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} {...STORE_OBJECT}
getOptionLabel={op=>op.label}
getOptionValue={op=>op}
/> />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfDateField name="delivery_date" label="Delivery Date" /> <RhfDateField name="delivery_date" label="Delivery Date" />
@@ -1,5 +1,6 @@
"use client" "use client"
import { useQueryClient } from "@tanstack/react-query"
import { CrudResource } from "@/shared/data-view/resource-page" import { CrudResource } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog" import FormDialog from "@/shared/components/form-dialog"
@@ -22,6 +23,7 @@ import { Money } from "@/shared/components/money"
export default function JobCardPaymentsReceived() { export default function JobCardPaymentsReceived() {
const jobCard = useJobCard() const jobCard = useJobCard()
const queryClient = useQueryClient()
const [hasOpened, setHasOpened] = useState(false) const [hasOpened, setHasOpened] = useState(false)
return ( return (
@@ -60,7 +62,12 @@ export default function JobCardPaymentsReceived() {
invoiceCustomer={jobCard?.customer as any} invoiceCustomer={jobCard?.customer as any}
lockJobCard lockJobCard
lockCustomer 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> </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"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField <RhfTextField
name="selling_price" name="selling_price"
label="Selling Price" label="Selling Price (AED)"
placeholder="0.00" placeholder="0.00"
type="number" type="number"
/> />
<RhfTextField <RhfTextField
name="purchase_price" name="purchase_price"
label="Purchase Price" label="Purchase Price (AED)"
placeholder="0.00" placeholder="0.00"
type="number" type="number"
/> />
@@ -1,4 +1,5 @@
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import { Money } from "@/shared/components/money"
import { Badge } from "@/shared/components/ui/badge" import { Badge } from "@/shared/components/ui/badge"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
@@ -32,7 +33,7 @@ export const partColumns = {
header: ({ column }) => <ColumnHeader column={column} title="Sell Price" />, header: ({ column }) => <ColumnHeader column={column} title="Sell Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).selling_price const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
purchasePrice: { purchasePrice: {
@@ -40,7 +41,7 @@ export const partColumns = {
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />, header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).purchase_price const val = (row.original as any).purchase_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
stock: { stock: {
@@ -213,21 +213,24 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
return return
} }
const vendorError = error.validationErrors.vendor_id?.[0] // Surface the actual backend validation messages on each field
const employeeError = error.validationErrors.employee_id?.[0] // instead of blanket-replacing them with the "not both" message —
const billError = error.validationErrors.bill_id?.[0] // 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) { if (billError) {
form.setError("bill", { message: billError }) form.setError("bill", { message: billError })
} }
if (vendorError) {
if (!vendorError && !employeeError) { form.setError("vendor", { message: vendorError })
return }
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: () => { onSuccess: () => {
form.reset() form.reset()
@@ -265,14 +268,14 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
name="vendor" name="vendor"
label="Vendor" label="Vendor"
required={vendorRequired} required={vendorRequired}
description="Select either a vendor or an employee." description="Select a vendor, an employee, or both."
/> />
<RhfAsyncSelectField <RhfAsyncSelectField
name="employee" name="employee"
label="Employee" label="Employee"
placeholder="Select employee" placeholder="Select employee"
required={employeeRequired} required={employeeRequired}
description="Select either a vendor or an employee." description="Select a vendor, an employee, or both."
queryKey={[EMPLOYEE_ROUTES.INDEX]} queryKey={[EMPLOYEE_ROUTES.INDEX]}
listFn={() => api.employees.list()} listFn={() => api.employees.list()}
mapOption={mapEmployeeOption} mapOption={mapEmployeeOption}
@@ -66,19 +66,6 @@ const paymentMadeFormSchema = z.object({
message: "Vendor or employee is required", 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> type PaymentMadeFormValues = z.infer<typeof paymentMadeFormSchema>
@@ -25,7 +25,7 @@ import {
paymentReceivedFormSchema, paymentReceivedFormSchema,
type PaymentReceivedFormValues, type PaymentReceivedFormValues,
} from "./payment-received.schema" } from "./payment-received.schema"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES, PAYMENT_RECEIVED_ROUTES } from "@garage/api" import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES, INVOICE_ROUTES, PAYMENT_RECEIVED_ROUTES } from "@garage/api"
// ── Props ── // ── Props ──
@@ -45,6 +45,7 @@ export type PaymentReceivedFormProps = {
const DEFAULT_VALUES: PaymentReceivedFormValues = { const DEFAULT_VALUES: PaymentReceivedFormValues = {
job_card: null, job_card: null,
invoice: null,
payment_mode: null, payment_mode: null,
customer: null, customer: null,
amount_received: 0, amount_received: 0,
@@ -61,6 +62,9 @@ function mapToFormValues(data: unknown): PaymentReceivedFormValues {
const jobCardId = d.job_card_id ?? d.job_card?.id const jobCardId = d.job_card_id ?? d.job_card?.id
const jobCardLabel = d.job_card?.title ?? d.job_card_name const jobCardLabel = d.job_card?.title ?? d.job_card_name
const invoiceId = d.invoice_id ?? d.invoice?.id
const invoiceLabel = d.invoice?.invoice_number ?? d.invoice?.title ?? d.invoice_number
const paymentModeId = d.payment_mode_id ?? d.payment_mode?.id 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 paymentModeLabel = d.payment_mode?.title ?? d.payment_mode?.name ?? d.payment_mode_name
@@ -76,6 +80,7 @@ function mapToFormValues(data: unknown): PaymentReceivedFormValues {
return { return {
job_card: toRelation(jobCardId, jobCardLabel), job_card: toRelation(jobCardId, jobCardLabel),
invoice: toRelation(invoiceId, invoiceLabel),
payment_mode: toRelation(paymentModeId, paymentModeLabel), payment_mode: toRelation(paymentModeId, paymentModeLabel),
customer: toRelation(customerId, customerLabel), customer: toRelation(customerId, customerLabel),
amount_received: d.amount_received != null ? Number(d.amount_received) : 0, amount_received: d.amount_received != null ? Number(d.amount_received) : 0,
@@ -86,6 +91,9 @@ function mapToFormValues(data: unknown): PaymentReceivedFormValues {
} }
function mapFormToPayload(values: PaymentReceivedFormValues, invoiceId?: string | null) { function mapFormToPayload(values: PaymentReceivedFormValues, invoiceId?: string | null) {
// Prefer the invoice the form was opened from; otherwise the one picked in
// the standalone form. Linking invoice_id is what flips the invoice to Paid.
const resolvedInvoiceId = invoiceId ?? toId(values.invoice)
return { return {
job_card_id: toId(values.job_card), job_card_id: toId(values.job_card),
payment_mode_id: toId(values.payment_mode), payment_mode_id: toId(values.payment_mode),
@@ -94,7 +102,7 @@ function mapFormToPayload(values: PaymentReceivedFormValues, invoiceId?: string
payment_number: values.payment_number || undefined, payment_number: values.payment_number || undefined,
payment_date: values.payment_date, payment_date: values.payment_date,
note: values.note || undefined, note: values.note || undefined,
...(invoiceId ? { invoice_id: Number(invoiceId) } : {}), ...(resolvedInvoiceId ? { invoice_id: Number(resolvedInvoiceId) } : {}),
} }
} }
@@ -114,6 +122,10 @@ export function PaymentReceivedForm({ resourceId, initialData, onSuccess, defaul
const isJobCardLocked = !resourceId && (lockJobCard ?? !!defaultJobCard?.id) const isJobCardLocked = !resourceId && (lockJobCard ?? !!defaultJobCard?.id)
const isCustomerLocked = !resourceId && (lockCustomer ?? !!invoiceCustomer?.id) const isCustomerLocked = !resourceId && (lockCustomer ?? !!invoiceCustomer?.id)
// When opened from a specific invoice the link is implicit (invoiceId prop).
// Standalone (Payments Received → Add) needs a picker so the payment can be
// tied to an invoice — otherwise the invoice never shows as Paid.
const showInvoiceField = !invoiceId
const customerLabel = invoiceCustomer?.first_name const customerLabel = invoiceCustomer?.first_name
? `${invoiceCustomer.first_name} ${invoiceCustomer.last_name || ""}`.trim() ? `${invoiceCustomer.first_name} ${invoiceCustomer.last_name || ""}`.trim()
@@ -225,6 +237,22 @@ export function PaymentReceivedForm({ resourceId, initialData, onSuccess, defaul
)} )}
</div> </div>
{showInvoiceField && (
<RhfAsyncSelectField
name="invoice"
label="Invoice"
placeholder="Select invoice to mark as paid"
description="Link this payment to an invoice so it is marked paid."
queryKey={[INVOICE_ROUTES.INDEX]}
listFn={() => api.invoices.list()}
mapOption={(item: any) => ({
value: String(item.id),
label: item.invoice_number ?? item.title ?? `#${item.id}`,
})}
{...STORE_OBJECT}
/>
)}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField <RhfTextField
name="amount_received" name="amount_received"
@@ -26,6 +26,7 @@ const optionalStringMax255Schema = z.preprocess(
const paymentReceivedFormSchema = z.object({ const paymentReceivedFormSchema = z.object({
// ── Relations ── // ── Relations ──
job_card: relationFieldSchema, job_card: relationFieldSchema,
invoice: relationFieldSchema,
payment_mode: requiredRelationFieldSchema, payment_mode: requiredRelationFieldSchema,
customer: requiredRelationFieldSchema, customer: requiredRelationFieldSchema,
@@ -1,6 +1,7 @@
"use client" "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 { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert" import { Alert, AlertTitle } from "@/shared/components/ui/alert"
@@ -49,6 +50,8 @@ const DEFAULT_VALUES: ServiceGroupFormValues = {
mark_as_recommended: false, mark_as_recommended: false,
set_packaged_pricing: false, set_packaged_pricing: false,
is_active: true, is_active: true,
parts: [],
services: [],
} }
// ── Mapping helpers ── // ── Mapping helpers ──
@@ -60,6 +63,20 @@ const mapLookupOption = (item: any) => ({
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label } 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 { function mapToFormValues(data: unknown): ServiceGroupFormValues {
const d = (data as any)?.data ?? data ?? {} const d = (data as any)?.data ?? data ?? {}
@@ -77,6 +94,8 @@ function mapToFormValues(data: unknown): ServiceGroupFormValues {
mark_as_recommended: d.mark_as_recommended ?? false, mark_as_recommended: d.mark_as_recommended ?? false,
set_packaged_pricing: d.set_packaged_pricing ?? false, set_packaged_pricing: d.set_packaged_pricing ?? false,
is_active: d.is_active ?? true, 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, defaultValues: DEFAULT_VALUES,
resourceId, resourceId,
initialData, 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, 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, { const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ServiceGroupFormValues) => { mutationFn: (values: ServiceGroupFormValues) => {
const promise = isEditing && resourceId const run = async () => {
? api.serviceGroups.update(resourceId, mapUpdatePayload(values)) const groupRes: any =
: api.serviceGroups.create(mapCreatePayload(values)) 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, { toast.promise(promise, {
loading: isEditing ? "Updating service group..." : "Creating service group...", loading: isEditing ? "Updating package..." : "Creating package...",
success: isEditing ? "Service group updated" : "Service group created", success: isEditing ? "Package updated" : "Package created",
error: isEditing ? "Failed to update service group" : "Failed to create service group", error: isEditing ? "Failed to update package" : "Failed to create package",
}) })
return promise 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"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField <RhfTextField
name="selling_price" name="selling_price"
label="Selling Price" label="Selling Price (AED)"
placeholder="0.00" placeholder="0.00"
type="number" type="number"
/> />
@@ -239,6 +327,100 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
rows={3} 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"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCheckboxField <RhfCheckboxField
name="show_as_lump_sum" name="show_as_lump_sum"
@@ -4,6 +4,20 @@ export const relationFieldSchema = z
.object({ value: z.string(), label: z.string() }) .object({ value: z.string(), label: z.string() })
.nullable() .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({ export const serviceGroupFormSchema = z.object({
shop_type: relationFieldSchema, shop_type: relationFieldSchema,
inventory_category: relationFieldSchema, inventory_category: relationFieldSchema,
@@ -18,6 +32,9 @@ export const serviceGroupFormSchema = z.object({
mark_as_recommended: z.boolean().optional(), mark_as_recommended: z.boolean().optional(),
set_packaged_pricing: z.boolean().optional(), set_packaged_pricing: z.boolean().optional(),
is_active: 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> export type ServiceGroupFormValues = z.infer<typeof serviceGroupFormSchema>
@@ -1,4 +1,5 @@
import { ColumnHeader } from "@/shared/data-view/table-view" import { ColumnHeader } from "@/shared/data-view/table-view"
import { Money } from "@/shared/components/money"
import type { ColumnDef } from "@tanstack/react-table" import type { ColumnDef } from "@tanstack/react-table"
/** Core service columns shared between the services page and selector dialogs. */ /** Core service columns shared between the services page and selector dialogs. */
@@ -31,7 +32,7 @@ export const serviceColumns = {
header: ({ column }) => <ColumnHeader column={column} title="Price" />, header: ({ column }) => <ColumnHeader column={column} title="Price" />,
cell: ({ row }) => { cell: ({ row }) => {
const val = (row.original as any).selling_price const val = (row.original as any).selling_price
return val != null ? `$${Number(val).toFixed(2)}` : "—" return val != null ? <Money value={val} /> : "—"
}, },
}, },
} satisfies Record<string, ColumnDef<any, any>> } satisfies Record<string, ColumnDef<any, any>>
@@ -4,7 +4,7 @@ import { AlertTriangle, Save } from "lucide-react"
import { useEffect } from "react" import { useEffect } from "react"
import { useForm } from "react-hook-form" import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod" import { zodResolver } from "@hookform/resolvers/zod"
import { useQuery } from "@tanstack/react-query" import { useQuery, useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner" import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button" import { Button } from "@/shared/components/ui/button"
@@ -122,6 +122,7 @@ function mapFormToPayload(values: SettingsFormValues) {
export function SettingsForm() { export function SettingsForm() {
const api = useAuthApi() const api = useAuthApi()
const queryClient = useQueryClient()
const form = useForm<SettingsFormValues>({ const form = useForm<SettingsFormValues>({
resolver: zodResolver(settingsFormSchema) as any, resolver: zodResolver(settingsFormSchema) as any,
@@ -151,15 +152,15 @@ export function SettingsForm() {
}, [data]) // eslint-disable-line react-hooks/exhaustive-deps }, [data]) // eslint-disable-line react-hooks/exhaustive-deps
const { mutate, error, isPending } = useFormMutation(form, { const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: SettingsFormValues) => { mutationFn: (values: SettingsFormValues) => api.settings.update(mapFormToPayload(values)),
const payload = mapFormToPayload(values) onSuccess: () => {
const promise = api.settings.update(payload) toast.success("Settings saved successfully")
toast.promise(promise, { // Refresh the settings query so the onboarding gate releases once
loading: "Saving settings...", // the company info has been filled in.
success: "Settings saved successfully", queryClient.invalidateQueries({ queryKey: [SETTINGS_ROUTES.INDEX] })
error: "Failed to save settings", },
}) onError: () => {
return promise toast.error("Failed to save settings")
}, },
}) })
@@ -8,6 +8,7 @@ import { FieldGroup } from "@/shared/components/ui/field"
import { import {
Rhform, Rhform,
RhfTextField, RhfTextField,
RhfSelectField,
RhfCheckboxField, RhfCheckboxField,
} from "@/shared/components/form" } from "@/shared/components/form"
import { toast } from "sonner" import { toast } from "sonner"
@@ -17,6 +18,7 @@ import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { import {
shopTimingFormSchema, shopTimingFormSchema,
DAY_OF_WEEK_VALUES,
type ShopTimingFormValues, type ShopTimingFormValues,
} from "./shop-timing.schema" } from "./shop-timing.schema"
import { SHOP_TIMING_ROUTES } from "@garage/api" import { SHOP_TIMING_ROUTES } from "@garage/api"
@@ -29,10 +31,19 @@ export type ShopTimingFormProps = {
onSuccess?: () => void onSuccess?: () => void
} }
// ── Options ──
const DAY_OPTIONS = DAY_OF_WEEK_VALUES.map((day) => ({
value: day,
label: day.charAt(0).toUpperCase() + day.slice(1),
}))
// ── Default values ── // ── Default values ──
const DEFAULT_VALUES: ShopTimingFormValues = { const DEFAULT_VALUES: ShopTimingFormValues = {
title: "", title: "",
day_of_week: "",
is_closed: false,
in_time: "", in_time: "",
out_time: "", out_time: "",
full_day_hours: "", full_day_hours: "",
@@ -51,6 +62,8 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
return { return {
title: d.title ?? "", title: d.title ?? "",
day_of_week: d.day_of_week ?? "",
is_closed: d.is_closed ?? false,
in_time: d.in_time ?? "", in_time: d.in_time ?? "",
out_time: d.out_time ?? "", out_time: d.out_time ?? "",
full_day_hours: d.full_day_hours ?? "", full_day_hours: d.full_day_hours ?? "",
@@ -64,10 +77,15 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
} }
function mapFormToPayload(values: ShopTimingFormValues) { function mapFormToPayload(values: ShopTimingFormValues) {
const closed = values.is_closed
return { return {
title: values.title, title: values.title,
in_time: values.in_time, day_of_week: values.day_of_week || undefined,
out_time: values.out_time, 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, full_day_hours: values.full_day_hours || undefined,
half_day_hours: values.half_day_hours || undefined, half_day_hours: values.half_day_hours || undefined,
punch_in: values.punch_in || undefined, punch_in: values.punch_in || undefined,
@@ -93,6 +111,8 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
mapToFormValues: mapToFormValues, mapToFormValues: mapToFormValues,
}) })
const isClosed = form.watch("is_closed")
const { mutate, error, isPending } = useFormMutation(form, { const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ShopTimingFormValues) => { mutationFn: (values: ShopTimingFormValues) => {
const payload = mapFormToPayload(values) const payload = mapFormToPayload(values)
@@ -128,8 +148,13 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
<RhfTextField name="title" label="Title" placeholder="Enter title" required /> <RhfTextField name="title" label="Title" placeholder="Enter title" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="in_time" label="In Time" placeholder="HH:MM:SS" required /> <RhfSelectField name="day_of_week" label="Day" placeholder="Select day" options={DAY_OPTIONS} />
<RhfTextField name="out_time" label="Out Time" placeholder="HH:MM:SS" required /> <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>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
@@ -6,10 +6,24 @@ const optionalTimeFormat = z
.optional() .optional()
.refine((v) => !v || timeRegex.test(v), "Time must be in HH:MM:SS format") .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"), 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"), day_of_week: z.string().optional(),
out_time: z.string().min(1, "Out time is required").regex(timeRegex, "Out time must be in HH:MM:SS format"), 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, full_day_hours: optionalTimeFormat,
half_day_hours: optionalTimeFormat, half_day_hours: optionalTimeFormat,
punch_in: optionalTimeFormat, punch_in: optionalTimeFormat,
@@ -17,7 +31,18 @@ const shopTimingFormSchema = z.object({
before_time: optionalTimeFormat, before_time: optionalTimeFormat,
after_time: optionalTimeFormat, after_time: optionalTimeFormat,
is_default: z.boolean().default(false), 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> type ShopTimingFormValues = z.infer<typeof shopTimingFormSchema>
@@ -10,6 +10,7 @@ import {
RhfTextField, RhfTextField,
RhfTextareaField, RhfTextareaField,
RhfAsyncSelectField, RhfAsyncSelectField,
RhfCheckboxField,
RhfImageField, RhfImageField,
} from "@/shared/components/form" } from "@/shared/components/form"
import { ShopTypeInlineForm } from "./inline-forms/shop-type-inline-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 { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toRelation, toId } from "@/shared/lib/utils" import { toRelation, toId } from "@/shared/lib/utils"
import { formatUppercase } from "@/shared/utils/formatters" 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 { vehicleFormSchema, type VehicleFormValues } from "./vehicle.schema"
import { CustomerForm } from "../customers/customer-form" import { CustomerForm } from "../customers/customer-form"
@@ -57,6 +58,8 @@ const DEFAULT_VALUES: VehicleFormValues = {
drivetrain: "", drivetrain: "",
mileage: "", mileage: "",
note: "", note: "",
has_insurance: false,
insurance_type: null,
image: null, image: null,
} }
@@ -92,6 +95,8 @@ function mapToFormValues(data: unknown): VehicleFormValues {
drivetrain: toFormString(d.drivetrain), drivetrain: toFormString(d.drivetrain),
mileage: toFormString(d.mileage), mileage: toFormString(d.mileage),
note: toFormString(d.note), note: toFormString(d.note),
has_insurance: Boolean(d.has_insurance),
insurance_type: toRelation(d.insurance_type_id, d.insurance_type?.title),
image: null, image: null,
} }
} }
@@ -115,6 +120,8 @@ function mapToPayload(values: VehicleFormValues) {
drivetrain: values.drivetrain || undefined, drivetrain: values.drivetrain || undefined,
mileage: values.mileage || undefined, mileage: values.mileage || undefined,
note: values.note || 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, image: values.image instanceof File ? values.image : undefined,
} }
} }
@@ -137,6 +144,8 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
const existingImageUrl: string | null = const existingImageUrl: string | null =
(resolvedData as any)?.data?.image_url ?? (resolvedData as any)?.image_url ?? 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, { const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: VehicleFormValues) => { mutationFn: (values: VehicleFormValues) => {
const payload = mapToPayload(values) const payload = mapToPayload(values)
@@ -254,6 +263,24 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
/> />
</div> </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 */} {/* License & identifiers */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"> <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField <RhfTextField
@@ -31,6 +31,10 @@ export const vehicleFormSchema = z.object({
// ── Notes ── // ── Notes ──
note: z.string().optional(), note: z.string().optional(),
// ── Insurance ──
has_insurance: z.boolean().optional(),
insurance_type: relationFieldSchema.optional(),
// ── Image ── // ── Image ──
image: z.any().optional(), image: z.any().optional(),
}) })
+72 -2
View File
@@ -8,11 +8,13 @@ import { FieldGroup } from "@/shared/components/ui/field"
import { import {
Rhform, Rhform,
RhfTextField, RhfTextField,
RhfAsyncSelectField,
} from "@/shared/components/form" } from "@/shared/components/form"
import { toast } from "sonner" import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi" import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form" import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation" import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId, toRelation } from "@/shared/lib/utils"
import { import {
vendorFormSchema, vendorFormSchema,
@@ -31,24 +33,44 @@ export type VendorFormProps = {
// ── Default values ── // ── Default values ──
const DEFAULT_VALUES: VendorFormValues = { const DEFAULT_VALUES: VendorFormValues = {
salutation:"Mr.", salutation: "Mr.",
first_name: "", first_name: "",
last_name: "", last_name: "",
company_name: "", company_name: "",
email: "", email: "",
phone: "",
alternate_phone: "",
address_line_1: "",
address_line_2: "",
city: "",
zip_code: "",
country: null,
state: null,
} as any } as any
// ── Mapping helpers ── // ── 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 { function mapToFormValues(data: unknown): VendorFormValues {
const d = (data as any)?.data ?? data ?? {} const d = (data as any)?.data ?? data ?? {}
const address = Array.isArray(d.addresses) ? d.addresses[0] ?? {} : {}
return { return {
first_name: d.first_name || "", first_name: d.first_name || "",
last_name: d.last_name || "", last_name: d.last_name || "",
company_name: d.company_name || "", company_name: d.company_name || "",
email: d.email || "", 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) { function mapFormToPayload(values: VendorFormValues) {
@@ -57,6 +79,14 @@ function mapFormToPayload(values: VendorFormValues) {
last_name: values.last_name || undefined, last_name: values.last_name || undefined,
company_name: values.company_name || undefined, company_name: values.company_name || undefined,
email: values.email || 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="company_name" label="Company Name" placeholder="Acme Supplies" required />
<RhfTextField name="email" label="Email" placeholder="vendor@example.com" type="email" 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}> <Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />} {isEditing ? <Save /> : <Plus />}
{isPending {isPending
+13
View File
@@ -11,6 +11,11 @@ const optionalNumberSchema = z.preprocess(
z.coerce.number().int().optional(), z.coerce.number().int().optional(),
) )
const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
.optional()
const vendorFormSchema = z.object({ 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"), 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"), 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, opening_balance: optionalNumberSchema,
credit_limit: optionalNumberSchema, credit_limit: optionalNumberSchema,
website: optionalStringMaxSchema(255), 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> type VendorFormValues = z.infer<typeof vendorFormSchema>
+25
View File
@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
output: 'standalone',
images: { images: {
remotePatterns: [ remotePatterns: [
@@ -20,6 +21,30 @@ const nextConfig = {
hostname: 'reparee.test', hostname: 'reparee.test',
port: '', port: '',
pathname: '/**', 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 { createApi } from "@garage/api"
import { useAuthStore } from "./stores/auth-store"; import { getAuthCookies, getWorkspaceContext } from "@/modules/auth/auth.actions"
import { getAuthCookies } 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 () => { export const getAuthApi = async () => {
const { token } = await getAuthCookies(); const { token } = await getAuthCookies()
console.log(`Auth Token: ${token}`); const { apiBase, workspaceUuid } = await getWorkspaceContext()
const api = createApi({ headers: token ? { Authorization: `Bearer ${token}` } : undefined });
return api; 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>
)
}
@@ -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}</>
}
@@ -39,8 +39,13 @@ export function DataTable<TData>({
// Persisted map of id → original row data across all pages // Persisted map of id → original row data across all pages
const persistedMap = useRef<Map<string, TData>>(new Map()) const persistedMap = useRef<Map<string, TData>>(new Map())
// Current-page selection state that TanStack Table controls // Current-page selection state that TanStack Table controls.
// A ref mirrors the latest value so onRowSelectionChange never derives the
// next selection from a stale closure (which would drop previously-checked
// rows and make multi-select behave like single-select).
const [rowSelection, setRowSelection] = useState<RowSelectionState>({}) const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const rowSelectionRef = useRef<RowSelectionState>({})
rowSelectionRef.current = rowSelection
// When the page/data changes, restore selection state for the new page from the map // When the page/data changes, restore selection state for the new page from the map
useEffect(() => { useEffect(() => {
@@ -50,6 +55,7 @@ export function DataTable<TData>({
const id = String((row as Record<string, unknown>)[rowKeyStr]) const id = String((row as Record<string, unknown>)[rowKeyStr])
if (persistedMap.current.has(id)) restored[id] = true if (persistedMap.current.has(id)) restored[id] = true
}) })
rowSelectionRef.current = restored
setRowSelection(restored) setRowSelection(restored)
}, [data]) // eslint-disable-line react-hooks/exhaustive-deps }, [data]) // eslint-disable-line react-hooks/exhaustive-deps
@@ -128,7 +134,10 @@ export function DataTable<TData>({
}) })
}, },
onRowSelectionChange: (updater) => { onRowSelectionChange: (updater) => {
const next = typeof updater === "function" ? updater(rowSelection) : updater // Derive from the ref (always current), not the render-time closure,
// so toggling a second row preserves earlier selections.
const next = typeof updater === "function" ? updater(rowSelectionRef.current) : updater
rowSelectionRef.current = next
setRowSelection(next) setRowSelection(next)
if (selection) { if (selection) {
// Sync current page into the persisted map // Sync current page into the persisted map
+79 -62
View File
@@ -60,70 +60,87 @@ import { InventoryCategoriesClient } from "./clients/inventory-categories"
import { DocumentPrintClient } from "./clients/document-print" import { DocumentPrintClient } from "./clients/document-print"
import { DocumentShareClient } from "./clients/document-share" 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 { return {
auth: new AuthClient(undefined, options), auth: new AuthClient(baseUrl, restOptions),
customers: new CustomersClient(undefined, options), customers: new CustomersClient(baseUrl, restOptions),
referralSources: new ReferralSourcesClient(undefined, options), referralSources: new ReferralSourcesClient(baseUrl, restOptions),
vehicles: new VehiclesClient(undefined, options), vehicles: new VehiclesClient(baseUrl, restOptions),
vehicleAttributes: new VehicleAttributesClient(undefined, options), vehicleAttributes: new VehicleAttributesClient(baseUrl, restOptions),
vehicleDocuments: new VehicleDocumentsClient(undefined, options), vehicleDocuments: new VehicleDocumentsClient(baseUrl, restOptions),
departments: new DepartmentsClient(undefined, options), departments: new DepartmentsClient(baseUrl, restOptions),
employees: new EmployeesClient(undefined, options), employees: new EmployeesClient(baseUrl, restOptions),
geo: new GeoClient(undefined, options), geo: new GeoClient(baseUrl, restOptions),
paymentTerms: new PaymentTermsClient(undefined, options), paymentTerms: new PaymentTermsClient(baseUrl, restOptions),
shopTypes: new ShopTypesClient(undefined, options), shopTypes: new ShopTypesClient(baseUrl, restOptions),
inventory: new InventoryClient(undefined, options), inventory: new InventoryClient(baseUrl, restOptions),
vendors: new VendorsClient(undefined, options), vendors: new VendorsClient(baseUrl, restOptions),
inspections: new InspectionsClient(undefined, options), inspections: new InspectionsClient(baseUrl, restOptions),
inspectionTemplates: new InspectionTemplatesClient(undefined, options), inspectionTemplates: new InspectionTemplatesClient(baseUrl, restOptions),
labels: new LabelsClient(undefined, options), labels: new LabelsClient(baseUrl, restOptions),
insuranceTypes: new InsuranceTypesClient(undefined, options), insuranceTypes: new InsuranceTypesClient(baseUrl, restOptions),
estimates: new EstimatesClient(undefined, options), estimates: new EstimatesClient(baseUrl, restOptions),
quickRemarks: new QuickRemarksClient(undefined, options), quickRemarks: new QuickRemarksClient(baseUrl, restOptions),
quickNotes: new QuickNotesClient(undefined, options), quickNotes: new QuickNotesClient(baseUrl, restOptions),
shopRecommendations: new ShopRecommendationsClient(undefined, options), shopRecommendations: new ShopRecommendationsClient(baseUrl, restOptions),
jobCards: new JobCardsClient(undefined, options), jobCards: new JobCardsClient(baseUrl, restOptions),
paymentModes: new PaymentModesClient(undefined, options), paymentModes: new PaymentModesClient(baseUrl, restOptions),
paymentReceived: new PaymentReceivedClient(undefined, options), paymentReceived: new PaymentReceivedClient(baseUrl, restOptions),
parts: new PartsClient(undefined, options), parts: new PartsClient(baseUrl, restOptions),
purchaseOrders: new PurchaseOrdersClient(undefined, options), purchaseOrders: new PurchaseOrdersClient(baseUrl, restOptions),
services: new ServicesClient(undefined, options), services: new ServicesClient(baseUrl, restOptions),
serviceGroups: new ServiceGroupsClient(undefined, options), serviceGroups: new ServiceGroupsClient(baseUrl, restOptions),
expenses: new ExpensesClient(undefined, options), expenses: new ExpensesClient(baseUrl, restOptions),
tasks: new TasksClient(undefined, options), tasks: new TasksClient(baseUrl, restOptions),
taskTypes: new TaskTypesClient(undefined, options), taskTypes: new TaskTypesClient(baseUrl, restOptions),
taskSections: new TaskSectionsClient(undefined, options), taskSections: new TaskSectionsClient(baseUrl, restOptions),
appointments: new AppointmentsClient(undefined, options), appointments: new AppointmentsClient(baseUrl, restOptions),
shopTimings: new ShopTimingsClient(undefined, options), shopTimings: new ShopTimingsClient(baseUrl, restOptions),
shopCalendars: new ShopCalendarsClient(undefined, options), shopCalendars: new ShopCalendarsClient(baseUrl, restOptions),
holidayYears: new HolidayYearsClient(undefined, options), holidayYears: new HolidayYearsClient(baseUrl, restOptions),
taxes: new TaxesClient(undefined, options), taxes: new TaxesClient(baseUrl, restOptions),
invoices: new InvoicesClient(undefined, options), invoices: new InvoicesClient(baseUrl, restOptions),
home: new HomeClient(undefined, options), home: new HomeClient(baseUrl, restOptions),
bills: new BillsClient(undefined, options), bills: new BillsClient(baseUrl, restOptions),
reasons: new ReasonsClient(undefined, options), reasons: new ReasonsClient(baseUrl, restOptions),
holidays: new HolidaysClient(undefined, options), holidays: new HolidaysClient(baseUrl, restOptions),
makeAndModels: new MakeAndModelsClient(undefined, options), makeAndModels: new MakeAndModelsClient(baseUrl, restOptions),
timeSheets: new TimeSheetsClient(undefined, options), timeSheets: new TimeSheetsClient(baseUrl, restOptions),
invoiceSequences: new InvoiceSequencesClient(undefined, options), invoiceSequences: new InvoiceSequencesClient(baseUrl, restOptions),
creditNotes: new CreditNotesClient(undefined, options), creditNotes: new CreditNotesClient(baseUrl, restOptions),
paymentMades: new PaymentMadesClient(undefined, options), paymentMades: new PaymentMadesClient(baseUrl, restOptions),
vendorCredits: new VendorCreditsClient(undefined, options), vendorCredits: new VendorCreditsClient(baseUrl, restOptions),
inventoryAdjustments: new InventoryAdjustmentsClient(undefined, options), inventoryAdjustments: new InventoryAdjustmentsClient(baseUrl, restOptions),
serviceGroupIncludes: new ServiceGroupIncludesClient(undefined, options), serviceGroupIncludes: new ServiceGroupIncludesClient(baseUrl, restOptions),
serviceGroupPricings: new ServiceGroupPricingsClient(undefined, options), serviceGroupPricings: new ServiceGroupPricingsClient(baseUrl, restOptions),
serviceGroupServices: new ServiceGroupServicesClient(undefined, options), serviceGroupServices: new ServiceGroupServicesClient(baseUrl, restOptions),
serviceGroupParts: new ServiceGroupPartsClient(undefined, options), serviceGroupParts: new ServiceGroupPartsClient(baseUrl, restOptions),
settings: new SettingsClient(undefined, options), settings: new SettingsClient(baseUrl, restOptions),
configurations: new ConfigurationsClient(undefined, options), configurations: new ConfigurationsClient(baseUrl, restOptions),
autoGenerate: new AutoGenerateClient(undefined, options), autoGenerate: new AutoGenerateClient(baseUrl, restOptions),
expenseItems: new ExpenseItemsClient(undefined, options), expenseItems: new ExpenseItemsClient(baseUrl, restOptions),
inventoryCategories: new InventoryCategoriesClient(undefined, options), inventoryCategories: new InventoryCategoriesClient(baseUrl, restOptions),
documentPrint: new DocumentPrintClient(undefined, options), documentPrint: new DocumentPrintClient(baseUrl, restOptions),
documentShare: new DocumentShareClient(undefined, options), 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() export const api = createApi()
+4
View File
@@ -20,6 +20,10 @@ function buildVehicleFormData(payload: Record<string, any>): FormData {
if (value == null) continue if (value == null) continue
if (value instanceof File) { if (value instanceof File) {
fd.append(key, value) fd.append(key, value)
} else if (typeof value === "boolean") {
// Laravel's `boolean` rule rejects the strings "true"/"false";
// serialize as "1"/"0" so multipart payloads validate correctly.
fd.append(key, value ? "1" : "0")
} else { } else {
fd.append(key, String(value)) fd.append(key, String(value))
} }
+15 -3
View File
@@ -6,10 +6,22 @@ import type { AuthUser } from "./infra/token"
export async function getServerApi() { export async function getServerApi() {
const cookieStore = await cookies() const cookieStore = await cookies()
const token = cookieStore.get("auth_token")?.value const token = cookieStore.get("auth_token")?.value
// Multi-tenant: the workspace's backend URL and id live in httpOnly cookies
// set by middleware. Client requests reach the right tenant via the
// /api/proxy route; SSR must replicate that — point at the tenant's
// api_base_url and send X-Workspace-UUID, or the request hits the wrong
// (default) backend and resources come back "not found".
const apiBaseUrl = cookieStore.get("api_base_url")?.value
const workspaceUuid = cookieStore.get("workspace_uuid")?.value
return createApi( const headers: Record<string, string> = {}
token ? { headers: { Authorization: `Bearer ${token}` } } : undefined, if (token) headers.Authorization = `Bearer ${token}`
) if (workspaceUuid) headers["X-Workspace-UUID"] = workspaceUuid
return createApi({
...(apiBaseUrl ? { baseUrl: apiBaseUrl } : {}),
...(Object.keys(headers).length ? { headers } : {}),
})
} }
export async function getServerUser(): Promise<AuthUser | null> { export async function getServerUser(): Promise<AuthUser | null> {