14 Commits
Author SHA1 Message Date
Najjar\NajjarV02andClaude Opus 4.8 0171daea38 fix(dashboard): add inline department create to job-card check-in
Wire the department select to DepartmentInlineForm and align its option mapping/store-object with the shared async-select contract.

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

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

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

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

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

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

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

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

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

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

Additional fixes:

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:22:25 +04:00
Najjar\NajjarV02 ccb9eacd86 feat: implement workspace session management and enhance API proxy handling 2026-05-20 16:23:19 +04:00
38 changed files with 1642 additions and 159 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"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
import { CalendarCheck2Icon, CalendarDaysIcon, ClipboardListIcon, ClockIcon, ListIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { RelationLink } from "@/shared/components/relation-link"
import { formatEnum } from "@/shared/utils/formatters"
@@ -22,8 +25,44 @@ const STATUS_COLORS: Record<string, string> = {
export default function AppointmentsPage() {
const router = useRouter()
const [view, setView] = useState<"list" | "calendar">("list")
const viewToggle = (
<div className="flex items-center justify-end gap-1 px-1">
<Button
type="button"
variant={view === "list" ? "default" : "outline"}
size="sm"
onClick={() => setView("list")}
>
<ListIcon className="me-1 size-4" /> List
</Button>
<Button
type="button"
variant={view === "calendar" ? "default" : "outline"}
size="sm"
onClick={() => setView("calendar")}
>
<CalendarDaysIcon className="me-1 size-4" /> Calendar
</Button>
</div>
)
if (view === "calendar") {
return (
<div className="space-y-4 p-4">
<div className="flex items-center justify-between">
<h1 className="text-xl font-semibold">Appointments</h1>
{viewToggle}
</div>
<AppointmentsCalendarView />
</div>
)
}
return (
<div className="space-y-2">
{viewToggle}
<ResourcePage<AppointmentsClient>
pageTitle="Appointments"
routeKey={APPOINTMENT_ROUTES.INDEX}
@@ -104,5 +143,6 @@ export default function AppointmentsPage() {
actionsColumn(),
]}
/>
</div>
)
}
@@ -6,6 +6,7 @@ import { DashboardLayout } from "@/base/components/layout/dashboard"
import { useAuth } from "@/shared/hooks/use-auth"
import { navGroups } from "@/config/navGroups"
import { getAuthCookies } from "@/modules/auth/auth.actions"
import { OnboardingGate } from "@/shared/components/onboarding-gate"
import { redirect } from "next/navigation"
@@ -38,7 +39,7 @@ export default async function AuthenticatedLayout({
return (
<DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}>
{children}
<OnboardingGate>{children}</OnboardingGate>
</DashboardLayout>
)
}
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useState } from "react"
import Link from "next/link"
import { useParams } from "next/navigation"
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
import { ChevronLeft, Pencil, Plus, Save, Trash2 } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
@@ -44,6 +44,9 @@ export default function InspectionTemplateEditorPage() {
const api = useAuthApi()
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
const [loading, setLoading] = useState(true)
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [saving, setSaving] = useState(false)
const [editing, setEditing] = useState<{
section: InspectionTemplateSection
@@ -55,6 +58,8 @@ export default function InspectionTemplateEditorPage() {
try {
const res = await api.inspectionTemplates.show(id)
setTemplate(res.data)
setName(res.data.name ?? "")
setDescription(res.data.description ?? "")
} catch (e: any) {
toast.error(e?.message ?? "Failed to load template")
} finally {
@@ -74,6 +79,20 @@ export default function InspectionTemplateEditorPage() {
}
}
const saveTemplate = async () => {
if (!template) return
setSaving(true)
try {
const res = await api.inspectionTemplates.update(template.id, { name, description })
setTemplate(res.data)
toast.success("Template saved")
} catch (e: any) {
toast.error(e?.message ?? "Failed to save")
} finally {
setSaving(false)
}
}
const addSection = async () => {
if (!template) return
const name = await prompt({
@@ -153,8 +172,8 @@ export default function InspectionTemplateEditorPage() {
<div>
<label className="text-xs text-muted-foreground">Name</label>
<Input
defaultValue={template.name}
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="flex items-center gap-3 mt-5">
@@ -168,9 +187,9 @@ export default function InspectionTemplateEditorPage() {
<div>
<label className="text-xs text-muted-foreground">Description</label>
<Textarea
defaultValue={template.description ?? ""}
value={description}
rows={2}
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
</div>
@@ -259,6 +278,13 @@ export default function InspectionTemplateEditorPage() {
onSaved={load}
/>
)}
<div className="sticky bottom-0 flex justify-end gap-2 border-t bg-background py-3">
<Button onClick={saveTemplate} disabled={saving}>
<Save className="size-4 mr-1" />
{saving ? "Saving…" : "Save"}
</Button>
</div>
</div>
)
}
@@ -0,0 +1,40 @@
import Link from "next/link"
import { AlertCircle, ShieldCheck } from "lucide-react"
/**
* Error UI for failed activation handoffs. The success path is handled by
* the sibling route.ts handler at /activate/[token] — it sets cookies on the
* response and redirects to "/". Errors redirect here with ?reason=… in the
* query string.
*
* The route.ts file takes precedence over this page for matching requests,
* but the page is still reachable via a redirect to
* /activate/[token]?error=1&reason=…
*/
export default async function ActivateErrorPage(props: {
searchParams: Promise<{ reason?: string; error?: string }>
}) {
const { reason } = await props.searchParams
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
<AlertCircle className="size-12 mx-auto text-rose-500" />
<h1 className="text-lg font-semibold">Activation failed</h1>
<p className="text-sm text-muted-foreground">
{reason ?? "Could not exchange the handoff token."}
</p>
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
<ShieldCheck className="size-3.5" />
Re-open the garage from the SaaS dashboard to get a fresh link.
</p>
<Link
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
className="inline-block text-sm underline text-primary"
>
Back to SaaS
</Link>
</div>
</div>
)
}
@@ -0,0 +1,98 @@
import { NextRequest, NextResponse } from "next/server"
/**
* SaaS → garage-erp handoff landing.
*
* URL shape:
* /activate/{handoff_token}?ws={workspace_uuid}&api={backend_url}
*
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
* api_base_url) on the redirect response and lands the user on /.
*
* Implemented as a Route Handler (not a Page) because Next.js disallows
* cookie writes inside Server Components — only Server Actions and Route
* Handlers can mutate cookies.
*/
export async function GET(
req: NextRequest,
ctx: { params: Promise<{ token: string }> },
) {
const { token } = await ctx.params
const url = new URL(req.url)
const ws = url.searchParams.get("ws")
const api = url.searchParams.get("api")
if (!ws || !api) {
return redirectToError(req, "Activation link is missing workspace or backend URL.")
}
let parsed: URL
try {
parsed = new URL(api)
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("Backend URL must be http(s).")
}
} catch {
return redirectToError(req, "Activation link has a malformed backend URL.")
}
const apiBase = parsed.toString().replace(/\/$/, "")
const endpoint = `${apiBase}/api/saas/handoff/exchange`
let response: Response
try {
response = await fetch(endpoint, {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Workspace-UUID": ws,
},
body: JSON.stringify({
handoff_token: token,
saas_workspace_uuid: ws,
}),
})
} catch (err) {
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
}
let payload: { token?: string; user?: any; message?: string } = {}
try {
payload = await response.json()
} catch {
// body is not JSON — fall through to error path
}
if (!response.ok || !payload.token || !payload.user) {
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
}
const dest = new URL("/", req.url)
const res = NextResponse.redirect(dest, 302)
const isProd = process.env.NODE_ENV === "production"
const sevenDays = 60 * 60 * 24 * 7
const cookieOptions = {
path: "/",
sameSite: "strict" as const,
httpOnly: true,
secure: isProd,
maxAge: sevenDays,
}
res.cookies.set("auth_token", payload.token, cookieOptions)
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
res.cookies.set("workspace_uuid", ws, cookieOptions)
res.cookies.set("api_base_url", apiBase, cookieOptions)
return res
}
function redirectToError(req: NextRequest, reason: string) {
const url = new URL("/activate/error", req.url)
url.searchParams.set("reason", reason)
return NextResponse.redirect(url, 302)
}
@@ -0,0 +1,30 @@
import Link from "next/link"
import { AlertCircle, ShieldCheck } from "lucide-react"
export default async function ActivateErrorPage(props: {
searchParams: Promise<{ reason?: string }>
}) {
const { reason } = await props.searchParams
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
<AlertCircle className="size-12 mx-auto text-rose-500" />
<h1 className="text-lg font-semibold">Activation failed</h1>
<p className="text-sm text-muted-foreground">
{reason ?? "Could not exchange the handoff token."}
</p>
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
<ShieldCheck className="size-3.5" />
Re-open the garage from the SaaS dashboard to get a fresh link.
</p>
<Link
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
className="inline-block text-sm underline text-primary"
>
Back to SaaS
</Link>
</div>
</div>
)
}
@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from "next/server"
/**
* SaaS → garage-erp handoff landing.
*
* URL shape:
* /activate/handoff/{handoff_token}?ws={workspace_uuid}&api={backend_url}
*
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
* api_base_url) on the redirect response and lands the user on /.
*
* Implemented as a Route Handler (not a Page) because Next.js disallows
* cookie writes inside Server Components — only Server Actions and Route
* Handlers can mutate cookies.
*/
export async function GET(
req: NextRequest,
ctx: { params: Promise<{ token: string }> },
) {
const { token } = await ctx.params
const url = new URL(req.url)
const ws = url.searchParams.get("ws")
const api = url.searchParams.get("api")
if (!ws || !api) {
return redirectToError(req, "Activation link is missing workspace or backend URL.")
}
let parsed: URL
try {
parsed = new URL(api)
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("Backend URL must be http(s).")
}
} catch {
return redirectToError(req, "Activation link has a malformed backend URL.")
}
const apiBase = parsed.toString().replace(/\/$/, "")
const endpoint = `${apiBase}/api/saas/handoff/exchange`
let response: Response
try {
response = await fetch(endpoint, {
method: "POST",
cache: "no-store",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Workspace-UUID": ws,
},
body: JSON.stringify({
handoff_token: token,
saas_workspace_uuid: ws,
}),
})
} catch (err) {
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
}
let payload: { token?: string; user?: any; message?: string } = {}
try {
payload = await response.json()
} catch {
// body is not JSON — fall through to error path
}
if (!response.ok || !payload.token || !payload.user) {
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
}
// Use a relative Location to keep the user on whichever host they came
// in on (127.0.0.1 vs localhost). NextResponse.redirect(new URL("/", req.url))
// resolves to the Next dev server's canonical host which can differ from
// the request's actual host, and cookies set here would not survive that
// cross-host redirect.
const res = new NextResponse(null, {
status: 302,
headers: { Location: "/" },
})
const isProd = process.env.NODE_ENV === "production"
const sevenDays = 60 * 60 * 24 * 7
const cookieOptions = {
path: "/",
sameSite: "strict" as const,
httpOnly: true,
secure: isProd,
maxAge: sevenDays,
}
res.cookies.set("auth_token", payload.token, cookieOptions)
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
res.cookies.set("workspace_uuid", ws, cookieOptions)
res.cookies.set("api_base_url", apiBase, cookieOptions)
return res
}
function redirectToError(req: NextRequest, reason: string) {
const location = "/activate/error?reason=" + encodeURIComponent(reason)
return new NextResponse(null, {
status: 302,
headers: { Location: location },
})
}
@@ -0,0 +1,97 @@
import { cookies } from "next/headers"
import { NextRequest, NextResponse } from "next/server"
const HOP_BY_HOP = new Set([
"host",
"connection",
"content-length",
"keep-alive",
"transfer-encoding",
"upgrade",
"te",
"trailer",
"proxy-authorization",
"proxy-authenticate",
])
async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) {
const cookieStore = await cookies()
const apiBase = cookieStore.get("api_base_url")?.value
const wsUuid = cookieStore.get("workspace_uuid")?.value
const token = cookieStore.get("auth_token")?.value
if (!apiBase || !wsUuid) {
return NextResponse.json(
{
message: "Workspace session not found. Please open your garage from the SaaS dashboard.",
code: "workspace_session_missing",
},
{ status: 412 },
)
}
const { path } = await ctx.params
const url = new URL(req.url)
// The OpenAPI clients keep `/api/...` in their route patterns, so when the
// client uses baseUrl=`/api/proxy` the resulting URL is
// `/api/proxy/api/customers`. Forward the path verbatim and rejoin so the
// upstream becomes `{apiBase}/api/customers`.
const target = `${apiBase.replace(/\/$/, "")}/${(path ?? []).join("/")}${url.search}`
const headers = new Headers()
req.headers.forEach((value, key) => {
if (!HOP_BY_HOP.has(key.toLowerCase()) && key.toLowerCase() !== "cookie") {
headers.set(key, value)
}
})
headers.set("Accept", "application/json")
headers.set("X-Workspace-UUID", wsUuid)
if (token) {
headers.set("Authorization", `Bearer ${token}`)
}
const init: RequestInit = {
method: req.method,
headers,
redirect: "manual",
}
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = await req.arrayBuffer()
}
let upstream: Response
try {
upstream = await fetch(target, init)
} catch (err) {
return NextResponse.json(
{
message: "Failed to reach garage backend.",
code: "backend_unreachable",
error: (err as Error).message,
},
{ status: 502 },
)
}
const respHeaders = new Headers()
upstream.headers.forEach((value, key) => {
const k = key.toLowerCase()
if (HOP_BY_HOP.has(k) || k === "set-cookie") return
respHeaders.set(key, value)
})
return new NextResponse(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: respHeaders,
})
}
export const GET = forward
export const POST = forward
export const PUT = forward
export const PATCH = forward
export const DELETE = forward
export const OPTIONS = forward
export const HEAD = forward
+99
View File
@@ -0,0 +1,99 @@
import { NextRequest, NextResponse } from "next/server"
/**
* Edge middleware that establishes workspace context from the request Host
* when a visitor lands on <subdomain>.reparee.com WITHOUT a prior handoff.
*
* - Skips if the workspace_uuid cookie is already set (handoff already happened).
* - Skips for the shared fallback host `tenant.reparee.com` and any non-tenant
* host (apex, localhost, preview URLs).
* - For a tenant subdomain, HMAC-signs the subdomain and calls SaaS
* `GET /api/saas/workspaces/by-subdomain/<sub>` to resolve to
* { workspace_uuid, api_base_url }, then sets those as HttpOnly cookies.
*
* Matcher excludes /api/proxy/* (proxy needs no resolution; cookies already set)
* and /activate/* (the handoff itself sets the cookies via the page handler).
*/
export const config = {
matcher: [
"/((?!api/proxy|_next/static|_next/image|favicon\\.ico|robots\\.txt|sitemap\\.xml|activate).*)",
],
}
const SUBDOMAIN_RE = /^([a-z0-9-]+)\.reparee\.com$/i
const SKIP_SUBDOMAINS = new Set(["tenant", "www"])
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
export async function middleware(req: NextRequest) {
if (req.cookies.get("workspace_uuid")) {
return NextResponse.next()
}
const host = (req.headers.get("host") || "").toLowerCase()
const match = host.match(SUBDOMAIN_RE)
if (!match) return NextResponse.next()
const sub = match[1].toLowerCase()
if (SKIP_SUBDOMAINS.has(sub)) return NextResponse.next()
const saasUrl = process.env.NEXT_PUBLIC_SAAS_URL || "https://reparee.com"
const secret = process.env.SAAS_SHARED_SECRET || ""
if (!secret) {
return NextResponse.next()
}
let workspaceUuid: string | undefined
let apiBaseUrl: string | undefined
try {
const signature = await hmacSha256Hex(sub, secret)
const resolveUrl = `${saasUrl.replace(/\/$/, "")}/api/saas/workspaces/by-subdomain/${encodeURIComponent(sub)}`
const res = await fetch(resolveUrl, {
headers: { "X-SaaS-Signature": signature, Accept: "application/json" },
cache: "no-store",
signal: AbortSignal.timeout(2500),
})
if (!res.ok) return NextResponse.next()
const data = (await res.json()) as { ok?: boolean; workspace_uuid?: string; api_base_url?: string }
if (!data.ok || !data.workspace_uuid || !data.api_base_url) {
return NextResponse.next()
}
workspaceUuid = data.workspace_uuid
apiBaseUrl = data.api_base_url
} catch {
return NextResponse.next()
}
const response = NextResponse.next()
response.cookies.set("workspace_uuid", workspaceUuid!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
response.cookies.set("api_base_url", apiBaseUrl!, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
maxAge: COOKIE_MAX_AGE,
})
return response
}
async function hmacSha256Hex(message: string, key: string): Promise<string> {
const enc = new TextEncoder()
const cryptoKey = await crypto.subtle.importKey(
"raw",
enc.encode(key),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
)
const sig = await crypto.subtle.sign("HMAC", cryptoKey, enc.encode(message))
return Array.from(new Uint8Array(sig))
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
}
@@ -0,0 +1,132 @@
"use client"
import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
import { Calendar } from "@/shared/components/ui/calendar"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { useAuthApi } from "@/shared/useApi"
import { APPOINTMENT_ROUTES } from "@garage/api"
import { formatEnum } from "@/shared/utils/formatters"
const STATUS_COLORS: Record<string, string> = {
requested: "bg-yellow-100 text-yellow-800",
confirmed: "bg-blue-100 text-blue-800",
in_progress: "bg-purple-100 text-purple-800",
completed: "bg-green-100 text-green-800",
cancelled: "bg-red-100 text-red-800",
}
function toDateKey(d: Date): string {
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, "0")
const day = String(d.getDate()).padStart(2, "0")
return `${y}-${m}-${day}`
}
export function AppointmentsCalendarView() {
const api = useAuthApi()
const router = useRouter()
const [selected, setSelected] = useState<Date | undefined>(() => new Date())
const { data, isLoading } = useQuery({
queryKey: [APPOINTMENT_ROUTES.INDEX, "calendar"],
queryFn: () => api.appointments.list({ per_page: 100 } as any),
})
const appointments: any[] = (data as any)?.data ?? []
const byDate = useMemo(() => {
const map: Record<string, any[]> = {}
for (const a of appointments) {
const key = String(a.date ?? "").slice(0, 10)
if (!key) continue
;(map[key] ??= []).push(a)
}
return map
}, [appointments])
const bookedDays = useMemo(
() => Object.keys(byDate).map((k) => new Date(`${k}T00:00:00`)),
[byDate],
)
const selectedKey = selected ? toDateKey(selected) : ""
const dayAppointments = byDate[selectedKey] ?? []
return (
<div className="grid gap-6 lg:grid-cols-[auto_1fr]">
<Card className="w-fit">
<CardContent className="p-3">
<Calendar
mode="single"
selected={selected}
onSelect={setSelected}
modifiers={{ booked: bookedDays }}
modifiersClassNames={{
booked:
"relative after:absolute after:bottom-1 after:left-1/2 after:h-1 after:w-1 after:-translate-x-1/2 after:rounded-full after:bg-primary",
}}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-sm font-semibold">
{selected
? selected.toLocaleDateString(undefined, {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
})
: "Select a day"}
</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{isLoading && <p className="text-muted-foreground text-sm">Loading…</p>}
{!isLoading && dayAppointments.length === 0 && (
<p className="text-muted-foreground text-sm">No appointments on this day.</p>
)}
{dayAppointments.map((a) => {
const jobCardId = a.job_card_id ?? a.job_card?.id
return (
<button
key={a.id}
type="button"
onClick={() => router.push(`/calendar/appointment/${a.id}`)}
className="hover:bg-muted/40 w-full rounded border p-3 text-left transition"
>
<div className="flex items-center justify-between">
<span className="flex items-center gap-2 font-medium">
<CalendarCheck2Icon className="text-muted-foreground size-4" />
{a.title}
</span>
<Badge className={STATUS_COLORS[a.status] ?? "bg-gray-100 text-gray-800"}>
{formatEnum(a.status)}
</Badge>
</div>
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-sm">
<span className="flex items-center gap-1">
<ClockIcon className="size-3" />
{a.from_time} – {a.to_time}
</span>
{jobCardId && (
<span className="flex items-center gap-1">
<ClipboardListIcon className="size-3" />
{a.job_card?.title || `#${jobCardId}`}
</span>
)}
</div>
</button>
)
})}
</CardContent>
</Card>
</div>
)
}
@@ -5,8 +5,12 @@ import type { AuthUser } from "@garage/api"
const TOKEN_COOKIE = "auth_token"
const USER_COOKIE = "auth_user"
const WORKSPACE_COOKIE = "workspace_uuid"
const API_BASE_COOKIE = "api_base_url"
const DEFAULT_EXPIRES_IN = 60 * 60 * 24 * 7 // 7 days in seconds
const isProd = process.env.NODE_ENV === "production"
export async function setAuthCookies(
token: string,
user: AuthUser,
@@ -19,12 +23,16 @@ export async function setAuthCookies(
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
cookieStore.set(USER_COOKIE, JSON.stringify(user), {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
}
@@ -32,6 +40,8 @@ export async function clearAuthCookies() {
const cookieStore = await cookies()
cookieStore.delete(TOKEN_COOKIE)
cookieStore.delete(USER_COOKIE)
cookieStore.delete(WORKSPACE_COOKIE)
cookieStore.delete(API_BASE_COOKIE)
}
export async function getAuthCookies(): Promise<{
@@ -53,3 +63,65 @@ export async function getAuthCookies(): Promise<{
return { token, user }
}
/**
* Set the per-session workspace context: which garage backend to proxy to,
* and which workspace UUID to send on every upstream call. Written by the
* SaaS → garage-erp activation handoff.
*/
export async function setWorkspaceContext(
apiBase: string,
workspaceUuid: string,
expiresIn: number = DEFAULT_EXPIRES_IN,
) {
const cookieStore = await cookies()
const expires = new Date(Date.now() + expiresIn * 1000)
cookieStore.set(API_BASE_COOKIE, apiBase, {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
cookieStore.set(WORKSPACE_COOKIE, workspaceUuid, {
expires,
path: "/",
sameSite: "strict",
httpOnly: true,
secure: isProd,
})
}
export async function getWorkspaceContext(): Promise<{
apiBase: string | undefined
workspaceUuid: string | undefined
}> {
const cookieStore = await cookies()
return {
apiBase: cookieStore.get(API_BASE_COOKIE)?.value,
workspaceUuid: cookieStore.get(WORKSPACE_COOKIE)?.value,
}
}
export async function clearWorkspaceContext() {
const cookieStore = await cookies()
cookieStore.delete(WORKSPACE_COOKIE)
cookieStore.delete(API_BASE_COOKIE)
}
/**
* Server-action used by the SaaS handoff page. Wraps cookie writes for both
* the auth token/user and the workspace context atomically (from the client's
* point of view).
*/
export async function applyHandoff(
token: string,
user: AuthUser,
apiBase: string,
workspaceUuid: string,
) {
await setAuthCookies(token, user)
await setWorkspaceContext(apiBase, workspaceUuid)
}
@@ -13,7 +13,6 @@ import {
} from "@/shared/components/ui/card"
import {
Field,
FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -129,15 +128,6 @@ export function LoginForm({
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Logging in..." : "Login"}
</Button>
{lastLoginEmail ? (
<FieldDescription className="text-center">
Last email used: {lastLoginEmail}
</FieldDescription>
) : null}
{/* <FieldDescription className="text-center">
Don&apos;t have an account? <a href="#">Sign up</a>
</FieldDescription> */}
</Field>
</FieldGroup>
</form>
@@ -124,7 +124,7 @@ export function CreateInvoiceFromEstimateButton() {
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="min-w-2xl">
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>Generate Invoice from Estimate</DialogTitle>
</DialogHeader>
@@ -24,6 +24,7 @@ import {
import { DEPARTMENT_ROUTES } from "@garage/api"
import { FUEL_LEVEL_OPTIONS } from "./job-card.schema"
import { toId } from "@/shared/lib/utils"
import { DepartmentInlineForm } from "@/modules/services/inline-forms/department-inline-form"
// ── Schema ──
@@ -46,7 +47,7 @@ const mapLookupOption = (item: any) => ({
label: item.name,
})
const STORE_OBJECT = { storeObject: true } as const
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label } as const
// ── Props ──
@@ -87,6 +88,10 @@ export function JobCardCheckInDialog({
})
const handleSubmit = async (values: CheckInFormValues) => {
if (!values.department) {
form.setError("department", { message: "Department is required" })
return
}
try {
await api.jobCards.checkIn(jobCardId, {
check_in_date: values.check_in_date || undefined,
@@ -131,13 +136,13 @@ export function JobCardCheckInDialog({
name="department"
label="Department"
placeholder="Select department"
required
queryKey={[DEPARTMENT_ROUTES.INDEX]}
listFn={() => api.departments.list()}
mapOption={(op:any)=> ({value: op.id, label: op.name})}
mapOption={(item: any) => ({ value: String(item.id), label: item.name ?? String(item.id) })}
createForm={(props) => <DepartmentInlineForm {...props} />}
createLabel="Department"
{...STORE_OBJECT}
getOptionLabel={op=>op.label}
getOptionValue={op=>op}
/>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfDateField name="delivery_date" label="Delivery Date" />
@@ -1,5 +1,6 @@
"use client"
import { useQueryClient } from "@tanstack/react-query"
import { CrudResource } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
@@ -22,6 +23,7 @@ import { Money } from "@/shared/components/money"
export default function JobCardPaymentsReceived() {
const jobCard = useJobCard()
const queryClient = useQueryClient()
const [hasOpened, setHasOpened] = useState(false)
return (
@@ -60,7 +62,12 @@ export default function JobCardPaymentsReceived() {
invoiceCustomer={jobCard?.customer as any}
lockJobCard
lockCustomer
onSuccess={invalidateQuery}
onSuccess={() => {
// Refresh the payments list AND the job card / invoice
// queries so the PAID status reflects the new payment.
invalidateQuery()
queryClient.invalidateQueries()
}}
/>
)}
</FormDialog>
+2 -2
View File
@@ -212,14 +212,14 @@ export function PartForm({ resourceId, initialData, onSuccess }: PartFormProps)
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
name="selling_price"
label="Selling Price"
label="Selling Price (AED)"
placeholder="0.00"
type="number"
/>
<RhfTextField
name="purchase_price"
label="Purchase Price"
label="Purchase Price (AED)"
placeholder="0.00"
type="number"
/>
@@ -213,21 +213,24 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
return
}
const vendorError = error.validationErrors.vendor_id?.[0]
const employeeError = error.validationErrors.employee_id?.[0]
const billError = error.validationErrors.bill_id?.[0]
// Surface the actual backend validation messages on each field
// instead of blanket-replacing them with the "not both" message —
// that masked unrelated errors and showed the wrong text when only
// one of vendor/employee was selected.
const errors = error.validationErrors
const billError = errors.bill_id?.[0]
const vendorError = errors.vendor_id?.[0]
const employeeError = errors.employee_id?.[0]
if (billError) {
form.setError("bill", { message: billError })
}
if (!vendorError && !employeeError) {
return
if (vendorError) {
form.setError("vendor", { message: vendorError })
}
if (employeeError) {
form.setError("employee", { message: employeeError })
}
const message = "Select either a vendor or an employee, not both"
form.setError("vendor", { message })
form.setError("employee", { message })
},
onSuccess: () => {
form.reset()
@@ -265,14 +268,14 @@ export function PaymentMadeForm({ resourceId, initialData, onSuccess, billId, ex
name="vendor"
label="Vendor"
required={vendorRequired}
description="Select either a vendor or an employee."
description="Select a vendor, an employee, or both."
/>
<RhfAsyncSelectField
name="employee"
label="Employee"
placeholder="Select employee"
required={employeeRequired}
description="Select either a vendor or an employee."
description="Select a vendor, an employee, or both."
queryKey={[EMPLOYEE_ROUTES.INDEX]}
listFn={() => api.employees.list()}
mapOption={mapEmployeeOption}
@@ -66,19 +66,6 @@ const paymentMadeFormSchema = z.object({
message: "Vendor or employee is required",
})
}
if (hasVendor && hasEmployee) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["vendor"],
message: "Select either a vendor or an employee, not both",
})
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["employee"],
message: "Select either a vendor or an employee, not both",
})
}
})
type PaymentMadeFormValues = z.infer<typeof paymentMadeFormSchema>
@@ -1,6 +1,7 @@
"use client"
import { AlertTriangle, Plus, Save } from "lucide-react"
import { AlertTriangle, Plus, Save, Trash2 } from "lucide-react"
import { useFieldArray } from "react-hook-form"
import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
@@ -49,6 +50,8 @@ const DEFAULT_VALUES: ServiceGroupFormValues = {
mark_as_recommended: false,
set_packaged_pricing: false,
is_active: true,
parts: [],
services: [],
}
// ── Mapping helpers ──
@@ -60,6 +63,20 @@ const mapLookupOption = (item: any) => ({
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
const partLineToForm = (r: any) => ({
id: r.id,
part: r.part ? { value: String(r.part.id), label: r.part.title ?? r.part.name ?? `#${r.part.id}` } : null,
quantity: r.quantity != null ? Number(r.quantity) : 1,
rate: r.rate != null ? Number(r.rate) : 0,
})
const serviceLineToForm = (r: any) => ({
id: r.id,
service: r.service ? { value: String(r.service.id), label: r.service.title ?? r.service.name ?? `#${r.service.id}` } : null,
rate: r.rate != null ? Number(r.rate) : 0,
hours: r.hours != null ? Number(r.hours) : 0,
})
function mapToFormValues(data: unknown): ServiceGroupFormValues {
const d = (data as any)?.data ?? data ?? {}
@@ -77,6 +94,8 @@ function mapToFormValues(data: unknown): ServiceGroupFormValues {
mark_as_recommended: d.mark_as_recommended ?? false,
set_packaged_pricing: d.set_packaged_pricing ?? false,
is_active: d.is_active ?? true,
parts: Array.isArray(d._parts) ? d._parts.map(partLineToForm) : [],
services: Array.isArray(d._services) ? d._services.map(serviceLineToForm) : [],
}
}
@@ -116,18 +135,87 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
defaultValues: DEFAULT_VALUES,
resourceId,
initialData,
queryKey: [SERVICE_GROUP_ROUTES.BY_ID, resourceId],
// Fetch the group together with its existing parts/services so the
// pickers can be pre-populated when editing.
initialize: async (id) => {
const [group, parts, services] = await Promise.all([
api.serviceGroups.show(id),
api.serviceGroupParts.list({ service_group_id: id } as any),
api.serviceGroupServices.list({ service_group_id: id } as any),
])
const g = (group as any)?.data ?? group ?? {}
return {
data: {
...g,
_parts: (parts as any)?.data ?? [],
_services: (services as any)?.data ?? [],
},
}
},
mapToFormValues,
})
const partsArray = useFieldArray({ control: form.control, name: "parts" })
const servicesArray = useFieldArray({ control: form.control, name: "services" })
// Replace the package's parts/services on the server with the current form
// rows: delete the existing rows, then recreate from the form. Mirrors the
// "replace details" approach used elsewhere (e.g. payments).
const syncIncludes = async (groupId: string | number, values: ServiceGroupFormValues) => {
const gid = Number(groupId)
const existingParts = await api.serviceGroupParts.list({ service_group_id: gid } as any)
const existingPartIds = (((existingParts as any)?.data) ?? []).map((r: any) => r.id)
await Promise.all(existingPartIds.map((id: any) => api.serviceGroupParts.destroy(String(id))))
await Promise.all(
(values.parts ?? [])
.filter((p) => p.part?.value)
.map((p) =>
api.serviceGroupParts.create({
service_group_id: gid,
part_id: Number(p.part!.value),
quantity: Number(p.quantity ?? 1),
rate: Number(p.rate ?? 0),
} as any),
),
)
const existingServices = await api.serviceGroupServices.list({ service_group_id: gid } as any)
const existingServiceIds = (((existingServices as any)?.data) ?? []).map((r: any) => r.id)
await Promise.all(existingServiceIds.map((id: any) => api.serviceGroupServices.destroy(String(id))))
await Promise.all(
(values.services ?? [])
.filter((s) => s.service?.value)
.map((s) =>
api.serviceGroupServices.create({
service_group_id: gid,
service_id: Number(s.service!.value),
rate: Number(s.rate ?? 0),
hours: Number(s.hours ?? 0),
} as any),
),
)
}
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ServiceGroupFormValues) => {
const promise = isEditing && resourceId
? api.serviceGroups.update(resourceId, mapUpdatePayload(values))
: api.serviceGroups.create(mapCreatePayload(values))
const run = async () => {
const groupRes: any =
isEditing && resourceId
? await api.serviceGroups.update(resourceId, mapUpdatePayload(values))
: await api.serviceGroups.create(mapCreatePayload(values))
const groupId = resourceId ?? groupRes?.data?.id ?? groupRes?.id
if (groupId) {
await syncIncludes(groupId, values)
}
return groupRes
}
const promise = run()
toast.promise(promise, {
loading: isEditing ? "Updating service group..." : "Creating service group...",
success: isEditing ? "Service group updated" : "Service group created",
error: isEditing ? "Failed to update service group" : "Failed to create service group",
loading: isEditing ? "Updating package..." : "Creating package...",
success: isEditing ? "Package updated" : "Package created",
error: isEditing ? "Failed to update package" : "Failed to create package",
})
return promise
},
@@ -221,7 +309,7 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
name="selling_price"
label="Selling Price"
label="Selling Price (AED)"
placeholder="0.00"
type="number"
/>
@@ -239,6 +327,100 @@ export function ServiceGroupForm({ resourceId, initialData, onSuccess }: Service
rows={3}
/>
{/* ── Parts in this package ── */}
<div className="border-t pt-4">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-semibold">Parts in this package</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => partsArray.append({ part: null, quantity: 1, rate: 0 })}
>
<Plus className="me-1 h-4 w-4" /> Add Part
</Button>
</div>
{partsArray.fields.length === 0 && (
<p className="text-muted-foreground text-sm">No parts added yet.</p>
)}
<div className="space-y-3">
{partsArray.fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 gap-2 sm:grid-cols-[1fr_110px_130px_auto] sm:items-end"
>
<RhfAsyncSelectField
name={`parts.${index}.part`}
label="Part"
placeholder="Select part (e.g. Engine Oil 5W-30)"
queryKey={["parts"]}
listFn={() => api.parts.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfTextField name={`parts.${index}.quantity`} label="Qty" type="number" placeholder="1" />
<RhfTextField name={`parts.${index}.rate`} label="Rate (AED)" type="number" placeholder="0.00" />
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => partsArray.remove(index)}
aria-label="Remove part"
>
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
))}
</div>
</div>
{/* ── Services in this package ── */}
<div className="border-t pt-4">
<div className="mb-2 flex items-center justify-between">
<h3 className="text-sm font-semibold">Services in this package</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => servicesArray.append({ service: null, rate: 0, hours: 0 })}
>
<Plus className="me-1 h-4 w-4" /> Add Service
</Button>
</div>
{servicesArray.fields.length === 0 && (
<p className="text-muted-foreground text-sm">No services added yet.</p>
)}
<div className="space-y-3">
{servicesArray.fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 gap-2 sm:grid-cols-[1fr_110px_130px_auto] sm:items-end"
>
<RhfAsyncSelectField
name={`services.${index}.service`}
label="Service"
placeholder="Select service (e.g. Oil change labour)"
queryKey={["services"]}
listFn={() => api.services.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfTextField name={`services.${index}.hours`} label="Hours" type="number" placeholder="0" />
<RhfTextField name={`services.${index}.rate`} label="Rate (AED)" type="number" placeholder="0.00" />
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => servicesArray.remove(index)}
aria-label="Remove service"
>
<Trash2 className="h-4 w-4 text-red-600" />
</Button>
</div>
))}
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfCheckboxField
name="show_as_lump_sum"
@@ -4,6 +4,20 @@ export const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
const packagePartSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
part: relationFieldSchema,
quantity: z.coerce.number().min(0).optional(),
rate: z.coerce.number().min(0).optional(),
})
const packageServiceSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
service: relationFieldSchema,
rate: z.coerce.number().min(0).optional(),
hours: z.coerce.number().min(0).optional(),
})
export const serviceGroupFormSchema = z.object({
shop_type: relationFieldSchema,
inventory_category: relationFieldSchema,
@@ -18,6 +32,9 @@ export const serviceGroupFormSchema = z.object({
mark_as_recommended: z.boolean().optional(),
set_packaged_pricing: z.boolean().optional(),
is_active: z.boolean().optional(),
// ── Package contents ──
parts: z.array(packagePartSchema).optional(),
services: z.array(packageServiceSchema).optional(),
})
export type ServiceGroupFormValues = z.infer<typeof serviceGroupFormSchema>
@@ -4,7 +4,7 @@ import { AlertTriangle, Save } from "lucide-react"
import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useQuery } from "@tanstack/react-query"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { Button } from "@/shared/components/ui/button"
@@ -122,6 +122,7 @@ function mapFormToPayload(values: SettingsFormValues) {
export function SettingsForm() {
const api = useAuthApi()
const queryClient = useQueryClient()
const form = useForm<SettingsFormValues>({
resolver: zodResolver(settingsFormSchema) as any,
@@ -151,15 +152,15 @@ export function SettingsForm() {
}, [data]) // eslint-disable-line react-hooks/exhaustive-deps
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: SettingsFormValues) => {
const payload = mapFormToPayload(values)
const promise = api.settings.update(payload)
toast.promise(promise, {
loading: "Saving settings...",
success: "Settings saved successfully",
error: "Failed to save settings",
})
return promise
mutationFn: (values: SettingsFormValues) => api.settings.update(mapFormToPayload(values)),
onSuccess: () => {
toast.success("Settings saved successfully")
// Refresh the settings query so the onboarding gate releases once
// the company info has been filled in.
queryClient.invalidateQueries({ queryKey: [SETTINGS_ROUTES.INDEX] })
},
onError: () => {
toast.error("Failed to save settings")
},
})
@@ -8,6 +8,7 @@ import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfSelectField,
RhfCheckboxField,
} from "@/shared/components/form"
import { toast } from "sonner"
@@ -17,6 +18,7 @@ import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import {
shopTimingFormSchema,
DAY_OF_WEEK_VALUES,
type ShopTimingFormValues,
} from "./shop-timing.schema"
import { SHOP_TIMING_ROUTES } from "@garage/api"
@@ -29,10 +31,19 @@ export type ShopTimingFormProps = {
onSuccess?: () => void
}
// ── Options ──
const DAY_OPTIONS = DAY_OF_WEEK_VALUES.map((day) => ({
value: day,
label: day.charAt(0).toUpperCase() + day.slice(1),
}))
// ── Default values ──
const DEFAULT_VALUES: ShopTimingFormValues = {
title: "",
day_of_week: "",
is_closed: false,
in_time: "",
out_time: "",
full_day_hours: "",
@@ -51,6 +62,8 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
return {
title: d.title ?? "",
day_of_week: d.day_of_week ?? "",
is_closed: d.is_closed ?? false,
in_time: d.in_time ?? "",
out_time: d.out_time ?? "",
full_day_hours: d.full_day_hours ?? "",
@@ -64,10 +77,15 @@ function mapToFormValues(data: unknown): ShopTimingFormValues {
}
function mapFormToPayload(values: ShopTimingFormValues) {
const closed = values.is_closed
return {
title: values.title,
in_time: values.in_time,
out_time: values.out_time,
day_of_week: values.day_of_week || undefined,
is_closed: closed,
// Closed days carry no opening hours.
in_time: closed ? undefined : values.in_time,
out_time: closed ? undefined : values.out_time,
full_day_hours: values.full_day_hours || undefined,
half_day_hours: values.half_day_hours || undefined,
punch_in: values.punch_in || undefined,
@@ -93,6 +111,8 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
mapToFormValues: mapToFormValues,
})
const isClosed = form.watch("is_closed")
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: ShopTimingFormValues) => {
const payload = mapFormToPayload(values)
@@ -128,8 +148,13 @@ export function ShopTimingForm({ resourceId, initialData, onSuccess }: ShopTimin
<RhfTextField name="title" label="Title" placeholder="Enter title" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="in_time" label="In Time" placeholder="HH:MM:SS" required />
<RhfTextField name="out_time" label="Out Time" placeholder="HH:MM:SS" required />
<RhfSelectField name="day_of_week" label="Day" placeholder="Select day" options={DAY_OPTIONS} />
<RhfCheckboxField name="is_closed" label="Closed (shop shut this day)" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="in_time" label="In Time" placeholder="HH:MM:SS" required={!isClosed} disabled={isClosed} />
<RhfTextField name="out_time" label="Out Time" placeholder="HH:MM:SS" required={!isClosed} disabled={isClosed} />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
@@ -6,10 +6,24 @@ const optionalTimeFormat = z
.optional()
.refine((v) => !v || timeRegex.test(v), "Time must be in HH:MM:SS format")
const shopTimingFormSchema = z.object({
export const DAY_OF_WEEK_VALUES = [
"saturday",
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
] as const
const shopTimingFormSchema = z
.object({
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
in_time: z.string().min(1, "In time is required").regex(timeRegex, "In time must be in HH:MM:SS format"),
out_time: z.string().min(1, "Out time is required").regex(timeRegex, "Out time must be in HH:MM:SS format"),
day_of_week: z.string().optional(),
is_closed: z.boolean().default(false),
// Optional at the field level; required below only when the day is open.
in_time: optionalTimeFormat,
out_time: optionalTimeFormat,
full_day_hours: optionalTimeFormat,
half_day_hours: optionalTimeFormat,
punch_in: optionalTimeFormat,
@@ -17,7 +31,18 @@ const shopTimingFormSchema = z.object({
before_time: optionalTimeFormat,
after_time: optionalTimeFormat,
is_default: z.boolean().default(false),
})
})
.superRefine((values, ctx) => {
// When the shop is open, in/out times are mandatory.
if (!values.is_closed) {
if (!values.in_time) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["in_time"], message: "In time is required" })
}
if (!values.out_time) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["out_time"], message: "Out time is required" })
}
}
})
type ShopTimingFormValues = z.infer<typeof shopTimingFormSchema>
@@ -10,6 +10,7 @@ import {
RhfTextField,
RhfTextareaField,
RhfAsyncSelectField,
RhfCheckboxField,
RhfImageField,
} from "@/shared/components/form"
import { ShopTypeInlineForm } from "./inline-forms/shop-type-inline-form"
@@ -24,7 +25,7 @@ import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toRelation, toId } from "@/shared/lib/utils"
import { formatUppercase } from "@/shared/utils/formatters"
import { VEHICLE_ROUTES } from "@garage/api"
import { VEHICLE_ROUTES, INSURANCE_TYPE_ROUTES } from "@garage/api"
import { vehicleFormSchema, type VehicleFormValues } from "./vehicle.schema"
import { CustomerForm } from "../customers/customer-form"
@@ -57,6 +58,8 @@ const DEFAULT_VALUES: VehicleFormValues = {
drivetrain: "",
mileage: "",
note: "",
has_insurance: false,
insurance_type: null,
image: null,
}
@@ -92,6 +95,8 @@ function mapToFormValues(data: unknown): VehicleFormValues {
drivetrain: toFormString(d.drivetrain),
mileage: toFormString(d.mileage),
note: toFormString(d.note),
has_insurance: Boolean(d.has_insurance),
insurance_type: toRelation(d.insurance_type_id, d.insurance_type?.title),
image: null,
}
}
@@ -115,6 +120,8 @@ function mapToPayload(values: VehicleFormValues) {
drivetrain: values.drivetrain || undefined,
mileage: values.mileage || undefined,
note: values.note || undefined,
has_insurance: values.has_insurance ?? false,
insurance_type_id: values.has_insurance ? toId(values.insurance_type) : undefined,
image: values.image instanceof File ? values.image : undefined,
}
}
@@ -137,6 +144,8 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
const existingImageUrl: string | null =
(resolvedData as any)?.data?.image_url ?? (resolvedData as any)?.image_url ?? null
const hasInsurance = form.watch("has_insurance")
const { mutate, error, isPending } = useFormMutation(form, {
mutationFn: (values: VehicleFormValues) => {
const payload = mapToPayload(values)
@@ -254,6 +263,24 @@ export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormP
/>
</div>
{/* Insurance */}
<div className="border-t pt-4">
<RhfCheckboxField name="has_insurance" label="Has Insurance?" />
{hasInsurance && (
<div className="mt-4">
<RhfAsyncSelectField
name="insurance_type"
label="Insurance Type"
placeholder="Select insurance type (e.g. Comprehensive)"
queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
listFn={() => api.insuranceTypes.list()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
)}
</div>
{/* License & identifiers */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField
@@ -31,6 +31,10 @@ export const vehicleFormSchema = z.object({
// ── Notes ──
note: z.string().optional(),
// ── Insurance ──
has_insurance: z.boolean().optional(),
insurance_type: relationFieldSchema.optional(),
// ── Image ──
image: z.any().optional(),
})
+72 -2
View File
@@ -8,11 +8,13 @@ import { FieldGroup } from "@/shared/components/ui/field"
import {
Rhform,
RhfTextField,
RhfAsyncSelectField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId, toRelation } from "@/shared/lib/utils"
import {
vendorFormSchema,
@@ -31,24 +33,44 @@ export type VendorFormProps = {
// ── Default values ──
const DEFAULT_VALUES: VendorFormValues = {
salutation:"Mr.",
salutation: "Mr.",
first_name: "",
last_name: "",
company_name: "",
email: "",
phone: "",
alternate_phone: "",
address_line_1: "",
address_line_2: "",
city: "",
zip_code: "",
country: null,
state: null,
} as any
// ── Mapping helpers ──
const mapLookupOption = (item: any) => ({ value: String(item.id), label: item.name })
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }
function mapToFormValues(data: unknown): VendorFormValues {
const d = (data as any)?.data ?? data ?? {}
const address = Array.isArray(d.addresses) ? d.addresses[0] ?? {} : {}
return {
first_name: d.first_name || "",
last_name: d.last_name || "",
company_name: d.company_name || "",
email: d.email || "",
}
phone: d.phone || "",
alternate_phone: d.alternate_phone || "",
address_line_1: address.address_line_1 || "",
address_line_2: address.address_line_2 || "",
city: address.city || "",
zip_code: address.zip_code || "",
country: toRelation(address.country_id, address.country?.name),
state: toRelation(address.state_id, address.state?.name),
} as VendorFormValues
}
function mapFormToPayload(values: VendorFormValues) {
@@ -57,6 +79,14 @@ function mapFormToPayload(values: VendorFormValues) {
last_name: values.last_name || undefined,
company_name: values.company_name || undefined,
email: values.email || undefined,
phone: values.phone || undefined,
alternate_phone: values.alternate_phone || undefined,
address_line_1: values.address_line_1 || undefined,
address_line_2: values.address_line_2 || undefined,
city: values.city || undefined,
zip_code: values.zip_code || undefined,
country_id: toId(values.country),
state_id: toId(values.state),
}
}
@@ -113,6 +143,46 @@ export function VendorForm({ resourceId, initialData, onSuccess }: VendorFormPro
<RhfTextField name="company_name" label="Company Name" placeholder="Acme Supplies" required />
<RhfTextField name="email" label="Email" placeholder="vendor@example.com" type="email" required />
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="phone" label="Phone" placeholder="+971501234567" type="tel" />
<RhfTextField name="alternate_phone" label="Alternate Phone" placeholder="+971509876543" type="tel" />
</div>
{/* ── Address ── */}
<div className="border-t pt-4">
<h3 className="mb-3 text-sm font-semibold">Address</h3>
<RhfTextField name="address_line_1" label="Address Line 1" placeholder="Street 10" />
<div className="mt-4">
<RhfTextField name="address_line_2" label="Address Line 2" placeholder="Near Central Plaza" />
</div>
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfAsyncSelectField
name="country"
label="Country"
placeholder="Select country"
queryKey={["countries"]}
listFn={() => api.geo.countries()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
<RhfAsyncSelectField
name="state"
label="State"
placeholder="Select state"
queryKey={["states"]}
listFn={() => api.geo.states()}
mapOption={mapLookupOption}
{...STORE_OBJECT}
/>
</div>
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
<RhfTextField name="city" label="City" placeholder="Dubai" />
<RhfTextField name="zip_code" label="Zip Code" placeholder="00000" />
</div>
</div>
<Button type="submit" variant="default" disabled={isPending}>
{isEditing ? <Save /> : <Plus />}
{isPending
+13
View File
@@ -11,6 +11,11 @@ const optionalNumberSchema = z.preprocess(
z.coerce.number().int().optional(),
)
const relationFieldSchema = z
.object({ value: z.string(), label: z.string() })
.nullable()
.optional()
const vendorFormSchema = z.object({
first_name: z.string().trim().min(1, "First name is required").max(50, "First name must be at most 50 characters"),
last_name: z.string().trim().min(1, "Last name is required").max(50, "Last name must be at most 50 characters"),
@@ -22,6 +27,14 @@ const vendorFormSchema = z.object({
opening_balance: optionalNumberSchema,
credit_limit: optionalNumberSchema,
website: optionalStringMaxSchema(255),
// ── Address (optional). Persisted by the backend store endpoint when
// address_line_1 + country + state are provided. ──
address_line_1: optionalStringMaxSchema(255),
address_line_2: optionalStringMaxSchema(255),
city: optionalStringMaxSchema(100),
zip_code: optionalStringMaxSchema(20),
country: relationFieldSchema,
state: relationFieldSchema,
})
type VendorFormValues = z.infer<typeof vendorFormSchema>
+25
View File
@@ -1,5 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
images: {
remotePatterns: [
@@ -20,6 +21,30 @@ const nextConfig = {
hostname: 'reparee.test',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'api.reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'tenant.reparee.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: process.env.NEXT_PUBLIC_GARAGE_HOST_PATTERN ?? '*.reparee.com',
port: '',
pathname: '/**',
}
]
}
+22 -9
View File
@@ -1,12 +1,25 @@
import { createApi, } from "@garage/api";
import { useAuthStore } from "./stores/auth-store";
import { getAuthCookies } from "@/modules/auth/auth.actions";
import { createApi } from "@garage/api"
import { getAuthCookies, getWorkspaceContext } from "@/modules/auth/auth.actions"
/**
* Returns an authenticated API client for server-side use (server actions, RSC).
*
* Server-side calls bypass the /api/proxy route — the server already has
* cookie access and can talk to the workspace's api install directly.
* Browser-side code should use the singleton `api` from @garage/api, which
* defaults to baseUrl="/api/proxy" and gets workspace context from cookies
* via the proxy route.
*/
export const getAuthApi = async () => {
const { token } = await getAuthCookies();
console.log(`Auth Token: ${token}`);
const api = createApi({ headers: token ? { Authorization: `Bearer ${token}` } : undefined });
return api;
const { token } = await getAuthCookies()
const { apiBase, workspaceUuid } = await getWorkspaceContext()
const headers: Record<string, string> = {}
if (token) headers.Authorization = `Bearer ${token}`
if (workspaceUuid) headers["X-Workspace-UUID"] = workspaceUuid
return createApi({
baseUrl: apiBase,
headers: Object.keys(headers).length ? headers : undefined,
})
}
@@ -0,0 +1,24 @@
import Link from "next/link"
import { AlertCircle, ExternalLink } from "lucide-react"
export function WorkspaceSessionMissing({ saasUrl }: { saasUrl?: string }) {
const fallbackUrl = saasUrl ?? process.env.NEXT_PUBLIC_SAAS_URL ?? "/"
return (
<div className="min-h-[60vh] flex items-center justify-center p-6">
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
<AlertCircle className="size-10 mx-auto text-amber-500" />
<h1 className="text-lg font-semibold">Workspace session not found</h1>
<p className="text-sm text-muted-foreground">
Please open your garage from the SaaS dashboard to get a fresh handoff link.
</p>
<Link
href={fallbackUrl}
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition"
>
<ExternalLink className="size-3.5" />
Back to SaaS dashboard
</Link>
</div>
</div>
)
}
@@ -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}</>
}
+79 -62
View File
@@ -60,70 +60,87 @@ import { InventoryCategoriesClient } from "./clients/inventory-categories"
import { DocumentPrintClient } from "./clients/document-print"
import { DocumentShareClient } from "./clients/document-share"
export function createApi(options?: ApiClientOptions) {
export type CreateApiOptions = ApiClientOptions & { baseUrl?: string }
/**
* Default base URL used when no explicit override is passed. The dashboard
* runs every browser call through the Next.js server proxy at /api/proxy so
* the build-time NEXT_PUBLIC_API_URL never reaches the client.
*
* Server-side callers (server actions, RSC) can opt out by passing
* `{ baseUrl: <absolute api URL> }` from a cookie.
*/
const DEFAULT_BASE_URL = "/api/proxy"
export function createApi(options?: CreateApiOptions) {
const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL
const restOptions: ApiClientOptions | undefined = options?.headers
? { headers: options.headers }
: undefined
return {
auth: new AuthClient(undefined, options),
customers: new CustomersClient(undefined, options),
referralSources: new ReferralSourcesClient(undefined, options),
vehicles: new VehiclesClient(undefined, options),
vehicleAttributes: new VehicleAttributesClient(undefined, options),
vehicleDocuments: new VehicleDocumentsClient(undefined, options),
departments: new DepartmentsClient(undefined, options),
employees: new EmployeesClient(undefined, options),
geo: new GeoClient(undefined, options),
paymentTerms: new PaymentTermsClient(undefined, options),
shopTypes: new ShopTypesClient(undefined, options),
inventory: new InventoryClient(undefined, options),
vendors: new VendorsClient(undefined, options),
inspections: new InspectionsClient(undefined, options),
inspectionTemplates: new InspectionTemplatesClient(undefined, options),
labels: new LabelsClient(undefined, options),
insuranceTypes: new InsuranceTypesClient(undefined, options),
estimates: new EstimatesClient(undefined, options),
quickRemarks: new QuickRemarksClient(undefined, options),
quickNotes: new QuickNotesClient(undefined, options),
shopRecommendations: new ShopRecommendationsClient(undefined, options),
jobCards: new JobCardsClient(undefined, options),
paymentModes: new PaymentModesClient(undefined, options),
paymentReceived: new PaymentReceivedClient(undefined, options),
parts: new PartsClient(undefined, options),
purchaseOrders: new PurchaseOrdersClient(undefined, options),
services: new ServicesClient(undefined, options),
serviceGroups: new ServiceGroupsClient(undefined, options),
expenses: new ExpensesClient(undefined, options),
tasks: new TasksClient(undefined, options),
taskTypes: new TaskTypesClient(undefined, options),
taskSections: new TaskSectionsClient(undefined, options),
appointments: new AppointmentsClient(undefined, options),
shopTimings: new ShopTimingsClient(undefined, options),
shopCalendars: new ShopCalendarsClient(undefined, options),
holidayYears: new HolidayYearsClient(undefined, options),
taxes: new TaxesClient(undefined, options),
invoices: new InvoicesClient(undefined, options),
home: new HomeClient(undefined, options),
bills: new BillsClient(undefined, options),
reasons: new ReasonsClient(undefined, options),
holidays: new HolidaysClient(undefined, options),
makeAndModels: new MakeAndModelsClient(undefined, options),
timeSheets: new TimeSheetsClient(undefined, options),
invoiceSequences: new InvoiceSequencesClient(undefined, options),
creditNotes: new CreditNotesClient(undefined, options),
paymentMades: new PaymentMadesClient(undefined, options),
vendorCredits: new VendorCreditsClient(undefined, options),
inventoryAdjustments: new InventoryAdjustmentsClient(undefined, options),
serviceGroupIncludes: new ServiceGroupIncludesClient(undefined, options),
serviceGroupPricings: new ServiceGroupPricingsClient(undefined, options),
serviceGroupServices: new ServiceGroupServicesClient(undefined, options),
serviceGroupParts: new ServiceGroupPartsClient(undefined, options),
settings: new SettingsClient(undefined, options),
configurations: new ConfigurationsClient(undefined, options),
autoGenerate: new AutoGenerateClient(undefined, options),
expenseItems: new ExpenseItemsClient(undefined, options),
inventoryCategories: new InventoryCategoriesClient(undefined, options),
documentPrint: new DocumentPrintClient(undefined, options),
documentShare: new DocumentShareClient(undefined, options),
auth: new AuthClient(baseUrl, restOptions),
customers: new CustomersClient(baseUrl, restOptions),
referralSources: new ReferralSourcesClient(baseUrl, restOptions),
vehicles: new VehiclesClient(baseUrl, restOptions),
vehicleAttributes: new VehicleAttributesClient(baseUrl, restOptions),
vehicleDocuments: new VehicleDocumentsClient(baseUrl, restOptions),
departments: new DepartmentsClient(baseUrl, restOptions),
employees: new EmployeesClient(baseUrl, restOptions),
geo: new GeoClient(baseUrl, restOptions),
paymentTerms: new PaymentTermsClient(baseUrl, restOptions),
shopTypes: new ShopTypesClient(baseUrl, restOptions),
inventory: new InventoryClient(baseUrl, restOptions),
vendors: new VendorsClient(baseUrl, restOptions),
inspections: new InspectionsClient(baseUrl, restOptions),
inspectionTemplates: new InspectionTemplatesClient(baseUrl, restOptions),
labels: new LabelsClient(baseUrl, restOptions),
insuranceTypes: new InsuranceTypesClient(baseUrl, restOptions),
estimates: new EstimatesClient(baseUrl, restOptions),
quickRemarks: new QuickRemarksClient(baseUrl, restOptions),
quickNotes: new QuickNotesClient(baseUrl, restOptions),
shopRecommendations: new ShopRecommendationsClient(baseUrl, restOptions),
jobCards: new JobCardsClient(baseUrl, restOptions),
paymentModes: new PaymentModesClient(baseUrl, restOptions),
paymentReceived: new PaymentReceivedClient(baseUrl, restOptions),
parts: new PartsClient(baseUrl, restOptions),
purchaseOrders: new PurchaseOrdersClient(baseUrl, restOptions),
services: new ServicesClient(baseUrl, restOptions),
serviceGroups: new ServiceGroupsClient(baseUrl, restOptions),
expenses: new ExpensesClient(baseUrl, restOptions),
tasks: new TasksClient(baseUrl, restOptions),
taskTypes: new TaskTypesClient(baseUrl, restOptions),
taskSections: new TaskSectionsClient(baseUrl, restOptions),
appointments: new AppointmentsClient(baseUrl, restOptions),
shopTimings: new ShopTimingsClient(baseUrl, restOptions),
shopCalendars: new ShopCalendarsClient(baseUrl, restOptions),
holidayYears: new HolidayYearsClient(baseUrl, restOptions),
taxes: new TaxesClient(baseUrl, restOptions),
invoices: new InvoicesClient(baseUrl, restOptions),
home: new HomeClient(baseUrl, restOptions),
bills: new BillsClient(baseUrl, restOptions),
reasons: new ReasonsClient(baseUrl, restOptions),
holidays: new HolidaysClient(baseUrl, restOptions),
makeAndModels: new MakeAndModelsClient(baseUrl, restOptions),
timeSheets: new TimeSheetsClient(baseUrl, restOptions),
invoiceSequences: new InvoiceSequencesClient(baseUrl, restOptions),
creditNotes: new CreditNotesClient(baseUrl, restOptions),
paymentMades: new PaymentMadesClient(baseUrl, restOptions),
vendorCredits: new VendorCreditsClient(baseUrl, restOptions),
inventoryAdjustments: new InventoryAdjustmentsClient(baseUrl, restOptions),
serviceGroupIncludes: new ServiceGroupIncludesClient(baseUrl, restOptions),
serviceGroupPricings: new ServiceGroupPricingsClient(baseUrl, restOptions),
serviceGroupServices: new ServiceGroupServicesClient(baseUrl, restOptions),
serviceGroupParts: new ServiceGroupPartsClient(baseUrl, restOptions),
settings: new SettingsClient(baseUrl, restOptions),
configurations: new ConfigurationsClient(baseUrl, restOptions),
autoGenerate: new AutoGenerateClient(baseUrl, restOptions),
expenseItems: new ExpenseItemsClient(baseUrl, restOptions),
inventoryCategories: new InventoryCategoriesClient(baseUrl, restOptions),
documentPrint: new DocumentPrintClient(baseUrl, restOptions),
documentShare: new DocumentShareClient(baseUrl, restOptions),
}
}
/** Unauthenticated singleton — use for public calls (login, register) */
/** Unauthenticated singleton — use for public calls (login, register). */
export const api = createApi()