Compare commits
20
Commits
3c55be5052
..
dev
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
NIXPACKS_NODE_VERSION=22
|
||||||
|
NEXT_PUBLIC_API_URL=http://reparee.test
|
||||||
@@ -11,7 +11,6 @@ node_modules
|
|||||||
.env.development.local
|
.env.development.local
|
||||||
.env.test.local
|
.env.test.local
|
||||||
.env.production.local
|
.env.production.local
|
||||||
.env.prod
|
|
||||||
|
|
||||||
# Testing
|
# Testing
|
||||||
coverage
|
coverage
|
||||||
|
|||||||
@@ -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
@@ -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"]
|
||||||
@@ -1,486 +0,0 @@
|
|||||||
# Garage ERP — Feature Gap Plan vs. Industry Leaders
|
|
||||||
|
|
||||||
> Comparison of the current Reparee Garage ERP against established automotive
|
|
||||||
> workshop management platforms (GarageBox, Tekmetric, Shopmonkey, AutoLeap,
|
|
||||||
> Garage Hive, Mitchell 1 Manager SE, MaxxTraxx, Workshop Software).
|
|
||||||
>
|
|
||||||
> Goal: list what does **not** yet exist in this codebase, group it by impact,
|
|
||||||
> and give each gap an implementation hint so it can be picked up later.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. What Reparee already has (baseline)
|
|
||||||
|
|
||||||
Captured from the current backend (`reparee_backend/`) controllers/models and
|
|
||||||
dashboard navigation (`apps/dashboard/config/navGroups.tsx`):
|
|
||||||
|
|
||||||
**Sales & service workflow**
|
|
||||||
- Customers (with notes, types, referral sources, import/export)
|
|
||||||
- Vehicles (owners, makes/models, body types, fuel, transmission, colors,
|
|
||||||
documents, mileage history, import/export)
|
|
||||||
- Inspections + Inspection Templates (categories, checkpoints, labels)
|
|
||||||
- Public share link for inspections (token-based, rate-limited)
|
|
||||||
- Estimates → Job Cards → Invoices (services, parts, expense items, internal
|
|
||||||
notes, labels, document attachments)
|
|
||||||
- Credit Notes
|
|
||||||
- Payments Received
|
|
||||||
- Appointments (calendar)
|
|
||||||
|
|
||||||
**Purchases**
|
|
||||||
- Vendors (addresses, status, credits)
|
|
||||||
- Expenses & Expense Items
|
|
||||||
- Purchase Orders (with internal notes, labels)
|
|
||||||
- Bills
|
|
||||||
- Payments Made
|
|
||||||
- Vendor Credits
|
|
||||||
|
|
||||||
**Items / inventory**
|
|
||||||
- Services and Service Groups (with includes/pricing/parts)
|
|
||||||
- Parts (with categories, unit types)
|
|
||||||
- Inventory Adjustments
|
|
||||||
- Labor Rates, Taxes
|
|
||||||
|
|
||||||
**HR / productivity**
|
|
||||||
- Employees (with documents, certifications, avatar, performance, permissions)
|
|
||||||
- Departments, Roles (with `permission.check` middleware on every route)
|
|
||||||
- Leave Requests + Leave Balance
|
|
||||||
- Payroll Runs + Entries + Slips
|
|
||||||
- Tasks, Task Sections, Task Types, TimeSheet
|
|
||||||
- Shop Calendar, Shop Timing, Holidays
|
|
||||||
|
|
||||||
**Platform**
|
|
||||||
- PDF generation via `DocumentPrintController` + Blade templates
|
|
||||||
- Document share tokens
|
|
||||||
- Settings (company, including logo + Terms & Conditions in `privacy_policy`)
|
|
||||||
- i18n EN/AR with RTL
|
|
||||||
- OpenAPI client (`packages/api/`) regenerated from backend spec
|
|
||||||
|
|
||||||
**Sidebar shows planned-but-disabled groups** (commented out in
|
|
||||||
`navGroups.tsx`): CRM (leads/calls/tasks), Marketing (service reminders,
|
|
||||||
ratings/reviews, Google reviews), Accountants (manual journals, chart of
|
|
||||||
accounts), Reports, Payroll, Integrations, Templates.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Priority matrix
|
|
||||||
|
|
||||||
| Tier | Meaning |
|
|
||||||
|------|---------|
|
|
||||||
| **P0** | Table-stakes for a modern garage SaaS — competitors all ship it, customers ask first |
|
|
||||||
| **P1** | Significant value-add, expected by mid-market shops |
|
|
||||||
| **P2** | Differentiators / nice-to-haves |
|
|
||||||
| **P3** | Long-tail integrations and advanced workflows |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. P0 — Table-stakes gaps
|
|
||||||
|
|
||||||
### 3.1 Reporting & Analytics dashboard
|
|
||||||
**Status:** No `/reports` route exists; sidebar entry is commented out. A
|
|
||||||
`/` dashboard page exists but is not analytics-rich.
|
|
||||||
|
|
||||||
**What competitors ship:**
|
|
||||||
- Revenue by day/week/month, by service category, by technician
|
|
||||||
- Open jobs / WIP value, ARO (Average Repair Order), gross profit %
|
|
||||||
- Aging receivables (already implicit in invoices, no view)
|
|
||||||
- Parts margin, labor margin
|
|
||||||
- Technician productivity (billed hours vs. clocked hours)
|
|
||||||
- Inventory turnover, stock-outs
|
|
||||||
- Customer retention / first-visit vs. repeat
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- New backend controllers: `ReportController` exposing aggregations
|
|
||||||
(revenue, AR aging, technician utilization, inventory turnover).
|
|
||||||
- New dashboard area: `apps/dashboard/app/(authenticated)/reports/`
|
|
||||||
with sub-routes per report.
|
|
||||||
- Re-use TanStack Query + a chart lib already approved (or ask before adding
|
|
||||||
recharts / visx). KPIs on home page should pull from the same endpoints.
|
|
||||||
|
|
||||||
### 3.2 Service Reminders (mileage- and time-based)
|
|
||||||
**Status:** `Vehicle` has mileage logs (`VehicleMileAndKm`) and documents
|
|
||||||
have expiry dates, but no reminder engine. Sidebar Marketing group is
|
|
||||||
commented out.
|
|
||||||
|
|
||||||
**What competitors ship:**
|
|
||||||
- "Next service in 5,000 km" rules per vehicle/service
|
|
||||||
- Insurance / registration / inspection expiry reminders
|
|
||||||
- Auto-send via email/SMS X days before due
|
|
||||||
- Customer can click to book
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- New model: `ServiceReminderRule` (per vehicle or template per make/model:
|
|
||||||
due_at_date, due_at_mileage, service_group_id, channel).
|
|
||||||
- Scheduled job (Laravel scheduler) that scans daily and queues notifications.
|
|
||||||
- Channel adapters wired to the notification stack from §3.3.
|
|
||||||
- UI under `productivity` or new `marketing/` area.
|
|
||||||
|
|
||||||
### 3.3 Customer notifications (Email / SMS / WhatsApp)
|
|
||||||
**Status:** No notification channels found beyond document share links. No
|
|
||||||
`Notification` or messaging tables in models.
|
|
||||||
|
|
||||||
**What competitors ship:**
|
|
||||||
- Twilio/Vonage SMS, WhatsApp Business API
|
|
||||||
- Two-way SMS thread per customer/job (Tekmetric, Shopmonkey)
|
|
||||||
- Templated estimate-ready / job-ready / pickup-ready messages
|
|
||||||
- Inbox view of all customer conversations
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Add `notification_channels` config + adapter interface
|
|
||||||
(`App\Services\Notifications\Channel`).
|
|
||||||
- Provider drivers behind feature flags (SMS via Twilio/MessageBird, email
|
|
||||||
via existing Laravel mail, WhatsApp via Meta Cloud API).
|
|
||||||
- Tables: `customer_messages` (inbound + outbound), `notification_templates`
|
|
||||||
(subject/body, locale, type).
|
|
||||||
- Dashboard inbox under `/sales/customers/[id]/messages` + global `/inbox`.
|
|
||||||
|
|
||||||
### 3.4 Customer-facing portal (estimate approval, history)
|
|
||||||
**Status:** Only `PublicInspectionController` exists for public viewing.
|
|
||||||
Estimates and invoices have no customer-side approval flow.
|
|
||||||
|
|
||||||
**What competitors ship:**
|
|
||||||
- Customer logs in (or magic-link) and sees: vehicles, history, estimates,
|
|
||||||
invoices, upcoming appointments.
|
|
||||||
- One-click approve / decline / partial-approve on estimate line items
|
|
||||||
(digital authorization with audit trail).
|
|
||||||
- Pay invoice via portal.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Reuse `DocumentShare` token pattern, broaden into a `customer_portal_token`.
|
|
||||||
- New `PublicEstimateController` mirroring `PublicInspectionController`,
|
|
||||||
with POST endpoints for approve/decline per line item.
|
|
||||||
- Persist signature/IP/timestamp on `EstimateAuthorisationHistory` (model
|
|
||||||
already exists — confirm fields cover approvals from portal).
|
|
||||||
- Frontend: new public route group `app/portal/` (no auth, token-scoped).
|
|
||||||
|
|
||||||
### 3.5 Online payments
|
|
||||||
**Status:** `PaymentMode` table exists, payments are recorded manually. No
|
|
||||||
gateway integration.
|
|
||||||
|
|
||||||
**What competitors ship:**
|
|
||||||
- Stripe / Square / regional gateway integration
|
|
||||||
- "Pay invoice" link inside email/SMS
|
|
||||||
- Saved cards, partial payments, tips
|
|
||||||
- Reconciliation back to `PaymentRecieved`
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Pluggable gateway driver under `App\Services\Payments\`.
|
|
||||||
- New endpoint `POST /api/invoices/{id}/payment-link` returns hosted URL.
|
|
||||||
- Webhook handler that creates `PaymentRecieved` rows on capture.
|
|
||||||
- Frontend `pay/[token]` page bundled with the portal in §3.4.
|
|
||||||
|
|
||||||
### 3.6 Audit log
|
|
||||||
**Status:** No audit/activity table found.
|
|
||||||
|
|
||||||
**What competitors ship:** Who changed what, when, on every business
|
|
||||||
record. Required for shops with multiple staff.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Adopt `spatie/laravel-activitylog` (request before adding the dep) or
|
|
||||||
hand-roll a polymorphic `activity_log` table.
|
|
||||||
- Log on estimate/job-card/invoice state transitions, permission changes,
|
|
||||||
payment events.
|
|
||||||
- Read-only view at `/settings/activity-log`.
|
|
||||||
|
|
||||||
### 3.7 Workflow / Kanban board for Job Cards
|
|
||||||
**Status:** Job Cards live in a list view. No status pipeline UI.
|
|
||||||
|
|
||||||
**What competitors ship:** Drag-and-drop columns ("Checked-in", "Awaiting
|
|
||||||
Parts", "In Progress", "QC", "Ready for Pickup"). Drives the shop's day.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Add `job_card_status` (enum or FK to `job_card_statuses` table editable
|
|
||||||
in settings).
|
|
||||||
- Backend: status transition endpoint with allowed-transition guard.
|
|
||||||
- Frontend: new `/sales/job-cards/board` route using dnd-kit (already in
|
|
||||||
the React ecosystem; confirm dep). Cards link to existing detail page.
|
|
||||||
|
|
||||||
### 3.8 Vehicle service history (per VIN, cross-customer)
|
|
||||||
**Status:** History is currently scoped via the vehicle's job cards, but
|
|
||||||
there is no consolidated "vehicle history" tab summarizing services,
|
|
||||||
inspections, mileage, and recommendations together.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- New endpoint `GET /api/vehicles/{id}/timeline` merging job cards,
|
|
||||||
inspections, recommendations, document expiries, mileage events into a
|
|
||||||
single chronological feed.
|
|
||||||
- Tab on the vehicle detail page rendering the timeline.
|
|
||||||
|
|
||||||
### 3.9 Recommended / deferred work tracking
|
|
||||||
**Status:** `FastShopRecommendation` and `ShopRecommendation` models exist
|
|
||||||
but there is no "deferred services" view that follows the vehicle across
|
|
||||||
visits.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Extend recommendations with `status` (open/accepted/declined/expired) and
|
|
||||||
`next_followup_at`.
|
|
||||||
- Surface on vehicle detail, estimate creation ("pull deferred items"), and
|
|
||||||
in service-reminder logic (§3.2).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. P1 — Significant value-add
|
|
||||||
|
|
||||||
### 4.1 Technician time tracking on job cards (clock in/out per labor line)
|
|
||||||
**Status:** Generic `TimeSheet` exists but is not bound to job-card lines.
|
|
||||||
The sidebar already shows "Time Clocks" — confirm whether implemented or
|
|
||||||
stubbed.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- New table `job_card_labor_time` (job_card_service_id, employee_id,
|
|
||||||
started_at, stopped_at).
|
|
||||||
- Mobile-friendly start/stop UI on the job-card page (tap-and-go).
|
|
||||||
- Feed billed-vs-clocked into the productivity report (§3.1).
|
|
||||||
|
|
||||||
### 4.2 Estimate templates / service packages with menus
|
|
||||||
**Status:** Service Groups exist (`ServiceGroup`, `ServiceGroupService`,
|
|
||||||
`ServiceGroupPart`, `ServiceGroupPricing`). Gap: no canned "menus" UI
|
|
||||||
(e.g., "30k-mile service" preset that drops services + parts + labor onto
|
|
||||||
an estimate in one click).
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Repurpose Service Groups as menus; add a "Add menu" picker on the
|
|
||||||
estimate editor that expands the group into individual lines (so they
|
|
||||||
can still be edited).
|
|
||||||
|
|
||||||
### 4.3 Customer digital signature on documents
|
|
||||||
**Status:** Documents print to PDF; no signature capture.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Add a signature pad component (svg path → PNG) on the customer portal
|
|
||||||
approval screen (§3.4) and in-shop tablet flow.
|
|
||||||
- Persist as a `document_signatures` row (signer name, type, timestamp,
|
|
||||||
IP/UA, image blob in storage).
|
|
||||||
- Embed signature in printed PDF.
|
|
||||||
|
|
||||||
### 4.4 Parts barcode / QR scanning
|
|
||||||
**Status:** Parts have SKUs but no barcode field or scan UI.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Add `barcode` column to `parts`.
|
|
||||||
- Use the device camera (BarcodeDetector API) on the inventory adjustment
|
|
||||||
and job-card "Add part" dialogs.
|
|
||||||
|
|
||||||
### 4.5 Tablet / shop-floor UI
|
|
||||||
**Status:** UI is desktop-first.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Audit job-card detail, inspection editor, and time-clock screens for
|
|
||||||
touch targets and one-hand portrait use.
|
|
||||||
- Optional dedicated route `/floor/[job-card]` with a stripped-down layout.
|
|
||||||
|
|
||||||
### 4.6 Photos & videos on inspections (with public share)
|
|
||||||
**Status:** `InspectionCheckPointAttachment` and `InspectionAttachment`
|
|
||||||
models exist — confirm whether the share link renders attachments.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Verify the public inspection view (`PublicInspectionController@show`)
|
|
||||||
exposes media URLs with signed access.
|
|
||||||
- Add front-camera capture in the inspection editor for fast photo-taking.
|
|
||||||
|
|
||||||
### 4.7 Multi-location / branch support
|
|
||||||
**Status:** `Settings` is single-tenant; no `branch_id` scoping on
|
|
||||||
business records.
|
|
||||||
|
|
||||||
**Plan:** This is a bigger lift. Phased:
|
|
||||||
1. Add `branches` table and `branch_id` FK on the major aggregates
|
|
||||||
(job_cards, invoices, vehicles, parts, employees).
|
|
||||||
2. Default to a single seeded branch for existing deployments.
|
|
||||||
3. Add branch selector in header and scope queries via global scope.
|
|
||||||
|
|
||||||
### 4.8 Custom fields
|
|
||||||
**Status:** No custom-field infrastructure.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- New `custom_field_definitions` (entity_type, key, label, type, options)
|
|
||||||
and `custom_field_values` (polymorphic).
|
|
||||||
- Render dynamically on customer/vehicle/job-card forms.
|
|
||||||
|
|
||||||
### 4.9 Marketing campaigns
|
|
||||||
**Status:** Sidebar has the group commented out.
|
|
||||||
|
|
||||||
**Plan:**
|
|
||||||
- Reuse §3.3 channels.
|
|
||||||
- New `marketing_campaigns` (name, audience filter, template_id, schedule)
|
|
||||||
and `marketing_sends` (per-recipient log).
|
|
||||||
- Audience builder uses the customer/vehicle filters already in the table
|
|
||||||
views.
|
|
||||||
|
|
||||||
### 4.10 Ratings & reviews capture
|
|
||||||
**Plan:**
|
|
||||||
- Post-pickup auto-message asking for a rating (1–5) and free text.
|
|
||||||
- If 4–5, deep-link to Google review URL (configurable in settings).
|
|
||||||
- Internal review wall + ability to publish to a public testimonials
|
|
||||||
endpoint.
|
|
||||||
|
|
||||||
### 4.11 Accounting export (QuickBooks / Xero / Zoho)
|
|
||||||
**Status:** No GL / chart of accounts (sidebar group is disabled).
|
|
||||||
|
|
||||||
**Plan (lightweight first):**
|
|
||||||
- CSV export of invoices, payments, bills, payments-made tagged with
|
|
||||||
configurable account codes.
|
|
||||||
- Later: OAuth integration with QuickBooks Online / Xero APIs.
|
|
||||||
|
|
||||||
### 4.12 Tire & wheel module (heavy in GarageBox, Tekmetric)
|
|
||||||
**Plan:** Tire size lookup, DOT tracking, storage racks (off-season tire
|
|
||||||
storage is a common revenue line in cold-climate markets). Skip unless
|
|
||||||
target market needs it.
|
|
||||||
|
|
||||||
### 4.13 Warranty tracking on parts and services
|
|
||||||
**Plan:**
|
|
||||||
- Add `warranty_months` / `warranty_km` on parts and services.
|
|
||||||
- Show "under warranty" badge when re-invoicing the same VIN within the
|
|
||||||
window. Block billing or flag for review.
|
|
||||||
|
|
||||||
### 4.14 Fleet customer accounts
|
|
||||||
**Plan:**
|
|
||||||
- Allow a customer to own many vehicles already supported, but add a
|
|
||||||
"fleet" customer type with: bulk PO upload, monthly statement instead of
|
|
||||||
per-invoice billing, optional driver/vehicle list.
|
|
||||||
|
|
||||||
### 4.15 Online appointment booking widget
|
|
||||||
**Plan:**
|
|
||||||
- Public route `/book` that surfaces shop services + free calendar slots
|
|
||||||
(derived from `ShopTiming` and existing appointments).
|
|
||||||
- Creates a draft `Appointment` + customer/vehicle if new.
|
|
||||||
- Embed snippet for the shop's marketing site.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. P2 — Differentiators
|
|
||||||
|
|
||||||
### 5.1 VIN decoder integration (NHTSA free API + paid Carfax)
|
|
||||||
- NHTSA `vpic.nhtsa.dot.gov/api/` is free, no auth — wire it into the
|
|
||||||
vehicle create form to auto-fill make/model/year/engine from VIN.
|
|
||||||
- Carfax/AutoCheck for paid history reports (US/CA).
|
|
||||||
|
|
||||||
### 5.2 OEM repair info integration (Mitchell 1, AllData, Identifix, Haynes)
|
|
||||||
- Big lift, paid feeds. Out of scope for v1; design the parts/services
|
|
||||||
data model so labor times can be imported.
|
|
||||||
|
|
||||||
### 5.3 Parts catalog integrations (WorldPac, NAPA PROLink, PartsTech)
|
|
||||||
- Real-time pricing + availability + ordering from inside a job card.
|
|
||||||
- Phase 1: PartsTech (aggregator) since it covers the most vendors.
|
|
||||||
|
|
||||||
### 5.4 Two-way calendar sync (Google / Microsoft)
|
|
||||||
- iCal feed for read-only first.
|
|
||||||
- Full two-way sync via Google Calendar API later.
|
|
||||||
|
|
||||||
### 5.5 AI-assisted estimate writer
|
|
||||||
- "Customer says: knocking noise on left front when braking" → suggested
|
|
||||||
service lines + parts list from history of similar jobs. Useful and
|
|
||||||
novel; defer until enough invoice data exists.
|
|
||||||
|
|
||||||
### 5.6 Mobile apps (technician + customer)
|
|
||||||
- React Native (or PWA first) sharing `@garage/api`.
|
|
||||||
- Technician: today's jobs, start/stop labor, take photos, mark complete.
|
|
||||||
- Customer: portal features (§3.4) packaged as an app.
|
|
||||||
|
|
||||||
### 5.7 OBD-II / telematics integration
|
|
||||||
- Long tail. Plan only the data model now (`vehicle_telemetry_events`).
|
|
||||||
|
|
||||||
### 5.8 Loyalty / gift cards / membership plans
|
|
||||||
- "Service plan: 2 oil changes/year + 10% off for $X/mo".
|
|
||||||
- Recurring billing on top of §3.5.
|
|
||||||
|
|
||||||
### 5.9 Discounts and promo codes at line-item or document level
|
|
||||||
- Currently no promo entity. Add `discounts` (code, type, %/amount, scope,
|
|
||||||
expiry, usage cap) with hook in estimate/invoice totals.
|
|
||||||
|
|
||||||
### 5.10 Multi-currency
|
|
||||||
- `Settings` is implicitly single-currency. Add currency on documents and a
|
|
||||||
daily rates table if shops need cross-border invoicing.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. P3 — Long-tail / future
|
|
||||||
|
|
||||||
- Insurance claim workflow (estimator → adjuster handoff, photos packet,
|
|
||||||
EMS export).
|
|
||||||
- Inventory replenishment automation (min/max → auto PO draft).
|
|
||||||
- Bay / lift management (assign job card to a bay; show bay utilization).
|
|
||||||
- AI photo damage assessment for inspections.
|
|
||||||
- Recall lookup (NHTSA recall API by VIN).
|
|
||||||
- TPMS / tire pressure history per vehicle.
|
|
||||||
- Public price-list / "instant quote" widget.
|
|
||||||
- Webhook system for third-party integrators.
|
|
||||||
- Bring-your-own-domain customer portal branding.
|
|
||||||
- Backup export of entire tenant data (GDPR-friendly).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Cross-cutting platform work
|
|
||||||
|
|
||||||
These aren't a single feature, but unlock many of the above:
|
|
||||||
|
|
||||||
1. **Background job runner** — Laravel Horizon + Redis if not already set
|
|
||||||
up; required for §3.2, §3.3, §4.9.
|
|
||||||
2. **Storage policy** — confirm S3-compatible storage so signatures,
|
|
||||||
media, and PDFs scale.
|
|
||||||
3. **Feature flag system** — many of the above are tenant-gated; even a
|
|
||||||
simple `tenant_features` table beats hard-coded toggles.
|
|
||||||
4. **OpenAPI coverage** — every new backend endpoint must add an
|
|
||||||
annotation so `packages/api` stays in sync (already a project
|
|
||||||
convention).
|
|
||||||
5. **Permission seeds** — every new route requires a matching permission
|
|
||||||
(project rule: routes are gated by `permission.check`).
|
|
||||||
6. **Lang pairs** — every `lang/en/*.php` key must have a matching
|
|
||||||
`lang/ar/*.php` key (project rule).
|
|
||||||
7. **PDF template** — every new printable type needs an entry in
|
|
||||||
`DocumentPrintController::TYPES` plus a Blade template under
|
|
||||||
`resources/views/pdf/`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. Suggested phased roadmap
|
|
||||||
|
|
||||||
A pragmatic build order that maximizes early customer value and reuses
|
|
||||||
infrastructure:
|
|
||||||
|
|
||||||
**Phase 1 — "Looks competitive"** (P0 core)
|
|
||||||
- Reporting dashboard (§3.1)
|
|
||||||
- Workflow board for job cards (§3.7)
|
|
||||||
- Audit log (§3.6)
|
|
||||||
- Vehicle timeline (§3.8)
|
|
||||||
- Recommended / deferred work tracking (§3.9)
|
|
||||||
|
|
||||||
**Phase 2 — "Talks to the customer"**
|
|
||||||
- Notifications channel (§3.3) — SMS + email first
|
|
||||||
- Customer portal w/ estimate approval (§3.4)
|
|
||||||
- Online payments (§3.5)
|
|
||||||
- Service reminders (§3.2)
|
|
||||||
- Ratings & reviews capture (§4.10)
|
|
||||||
|
|
||||||
**Phase 3 — "Runs the shop floor"**
|
|
||||||
- Technician time tracking on labor (§4.1)
|
|
||||||
- Estimate menus / service packages UI (§4.2)
|
|
||||||
- Photos on inspections, end-to-end (§4.6)
|
|
||||||
- Customer digital signature (§4.3)
|
|
||||||
- Tablet / shop-floor UI polish (§4.5)
|
|
||||||
|
|
||||||
**Phase 4 — "Scales the business"**
|
|
||||||
- Multi-location (§4.7)
|
|
||||||
- Custom fields (§4.8)
|
|
||||||
- Marketing campaigns (§4.9)
|
|
||||||
- Online booking widget (§4.15)
|
|
||||||
- Accounting exports (§4.11)
|
|
||||||
|
|
||||||
**Phase 5 — "Differentiators"**
|
|
||||||
- VIN decoder (§5.1)
|
|
||||||
- Parts catalog integrations (§5.3)
|
|
||||||
- Calendar sync (§5.4)
|
|
||||||
- Loyalty / memberships (§5.8)
|
|
||||||
- Mobile apps (§5.6)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Open questions to confirm before starting
|
|
||||||
|
|
||||||
1. Target market geography — drives gateway choice (Stripe vs. local), SMS
|
|
||||||
provider, accounting integration (QuickBooks vs. Zoho vs. Tally), and
|
|
||||||
whether tire/snow modules matter.
|
|
||||||
2. Is multi-tenancy single-DB (current) or DB-per-tenant?
|
|
||||||
3. Are Horizon + Redis available in production today?
|
|
||||||
4. Is there an approved chart library, or does adding one need a green
|
|
||||||
light? (CLAUDE.md says no new deps without approval.)
|
|
||||||
5. Should the customer portal share auth with the dashboard (Sanctum) or
|
|
||||||
use a token-only public route like inspections do today?
|
|
||||||
@@ -1,551 +0,0 @@
|
|||||||
# Reparee → Garage Box Feature Parity — Implementation Roadmap
|
|
||||||
|
|
||||||
> **Purpose of this doc.** Single source of truth for closing the gap between Reparee's current dashboard and Garage Box. Captures the gap analysis, the canonical Reparee patterns to mimic, and a per-phase implementation spec detailed enough for a fresh agent to pick up any phase and ship it without re-discovering conventions.
|
|
||||||
|
|
||||||
> **Status (2026-05-21).** Phase 1 (Integrations placeholder) is the only phase ready to execute. Phases 2–8 are spec'd here but not started. Pick one, re-open it in a focused planning session, and implement.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 0. Reading order
|
|
||||||
|
|
||||||
1. **Part A — Gap analysis** (what's missing and why).
|
|
||||||
2. **Part B — Project conventions cheatsheet** (the patterns every phase MUST follow).
|
|
||||||
3. **Part C — Phase index** (the at-a-glance table).
|
|
||||||
4. **Part D — Per-phase implementation specs** (Phases 1–8, in recommended build order).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part A — Gap analysis (Garage Box vs Reparee)
|
|
||||||
|
|
||||||
Legend: ✅ exists ⚠️ partial / different location ❌ missing
|
|
||||||
|
|
||||||
### Already covered
|
|
||||||
- **Sales** (Customers, Vehicles, Inspections, Estimates, Job Cards, Invoices, Payments Received, Credit Notes) — ✅
|
|
||||||
- **Purchases** (Vendors, Expenses, POs, Bills, Payments Made, Vendor Credits) — ✅
|
|
||||||
- **Employees / Productivity** (Employees, Time Clocks, Time Sheets, Payroll, Shop Calendars, Shop Timing, Holidays, Tasks, Leave Requests) — ✅ (Reparee adds Leave Requests beyond Garage Box)
|
|
||||||
- **Items** (Services, Parts, Expense Item, Service Group, Inventory Adjustments) — ✅
|
|
||||||
- **Settings** Company / Shop Types / Tax & Rates / Configurations — ✅
|
|
||||||
|
|
||||||
### Gaps
|
|
||||||
| Garage Box | Status in Reparee | Phase |
|
|
||||||
|---|---|---|
|
|
||||||
| Settings → Integrations | ❌ → placeholder | **Phase 1** |
|
|
||||||
| Settings → Master (hub for body types + make & model + other lookups) | ❌ as a hub (data scattered) | **Phase 2** |
|
|
||||||
| Settings → Templates (notification template library, ~35 templates × 4 channels) | ⚠️ only inspection templates | **Phase 3** |
|
|
||||||
| Reports (top-level module) | ❌ | **Phase 4** |
|
|
||||||
| CRM (Leads pipeline, Calls log + calendar, Tasks pipeline) | ❌ (Reparee has only productivity tasks, not CRM tasks) | **Phase 5** |
|
|
||||||
| Marketing (Service Reminders, Rating & Reviews, Google Business Reviews) | ❌ | **Phase 6** |
|
|
||||||
| Settings → Integrations (real connectors: Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp) | ❌ | **Phase 7** |
|
|
||||||
| Accountants (Chart of Accounts + Manual Journals + default account wiring) | ❌ | **Phase 8** |
|
|
||||||
|
|
||||||
### Cross-cutting Garage Box conventions to mimic
|
|
||||||
- **Pipelines** (Leads, Tasks) have user-editable column **sections** (add / rename / reorder). Default sections seeded on first run.
|
|
||||||
- **`+ Label`** chip on every record (taxonomy / colored tags).
|
|
||||||
- **Configurable doc-number sequences** with a gear icon next to the `#` field (`LD-000001`, `CL-000001`, `TK-000001`, `JN-000001`, etc.).
|
|
||||||
- **Notification templates** are channel-aware (SMS / WhatsApp / Email / Push) with per-channel toggles.
|
|
||||||
- **Per-row Department filter** is universal — every list view has a Department dropdown in the toolbar.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part B — Project conventions cheatsheet (MUST follow in every phase)
|
|
||||||
|
|
||||||
> Every phase below assumes these patterns. Don't re-invent.
|
|
||||||
|
|
||||||
### B1. Frontend module structure
|
|
||||||
- **Modules live at** `garage-erp/apps/dashboard/modules/<area>/`.
|
|
||||||
- Each resource gets: `<resource>-form.tsx`, `<resource>.schema.ts` (Zod), optional `<resource>-actions.tsx`, optional inline section components (e.g. `<resource>-services-section.tsx`).
|
|
||||||
- **Reference**: `garage-erp/apps/dashboard/modules/estimates/` is the canonical example. Mirror its file layout for any new resource.
|
|
||||||
|
|
||||||
### B2. Routes (Next.js App Router)
|
|
||||||
- List page: `app/(authenticated)/<area>/<resource>/page.tsx` (`"use client"` + `ResourcePage<Client>`).
|
|
||||||
- Detail page: `app/(authenticated)/<area>/<resource>/[id]/page.tsx` (async server component, uses `getServerApi()` + `DashboardPage`).
|
|
||||||
- Sub-tabs of a detail (e.g. notes, documents): `[id]/<subroute>/page.tsx`.
|
|
||||||
- **Reference**: `app/(authenticated)/sales/estimates/page.tsx` (list) + `[id]/page.tsx` (detail).
|
|
||||||
|
|
||||||
### B3. Tables & row actions
|
|
||||||
- Use TanStack Table via `ResourcePage` wrapper.
|
|
||||||
- Row actions via `actionsColumn({ extraItems: (row) => [...] })`.
|
|
||||||
- Print buttons via `useDocumentPrint(type, id)` from `apps/dashboard/shared/hooks/use-document-print.ts`.
|
|
||||||
|
|
||||||
### B4. Forms
|
|
||||||
- React Hook Form 7 + Zod 4. Schema lives in `<resource>.schema.ts`.
|
|
||||||
- Use `useResourceForm<FormValues, ApiPayload>({ schema, resourceId, initialize, mapToFormValues })` from `apps/dashboard/shared/hooks/`.
|
|
||||||
- Mutations: `useFormMutation` for create/update; invalidate via `tableQuery.invalidateQuery()` or the resource's query key.
|
|
||||||
|
|
||||||
### B5. Sidebar navigation
|
|
||||||
- Single source: `garage-erp/apps/dashboard/config/navGroups.tsx` — hard-coded, **no i18n layer**.
|
|
||||||
- Add a new group entry or a sub-item; pick a `lucide-react` icon already imported (or add to the import block at top of file).
|
|
||||||
|
|
||||||
### B6. API client (`@garage/api`)
|
|
||||||
- All clients extend `CrudClient<INDEX_ROUTE, BY_ID_ROUTE>` (path: `packages/api/src/clients/<name>.ts`).
|
|
||||||
- After backend changes, **regenerate**: `pnpm --filter @garage/api generate` (runs `generate:openapi && generate:types`).
|
|
||||||
- The generated files in `packages/api/` are NOT hand-edited; only the thin client wrappers are.
|
|
||||||
|
|
||||||
### B7. Backend routes
|
|
||||||
- **Legacy string controller resolution** in `reparee_backend/routes/api.php`:
|
|
||||||
```php
|
|
||||||
Route::get('/leads', 'LeadController@index');
|
|
||||||
Route::post('/leads', 'LeadController@store');
|
|
||||||
// etc.
|
|
||||||
```
|
|
||||||
- **Every route is gated** by `permission.check` middleware (auto-applied group-wide).
|
|
||||||
|
|
||||||
### B8. Backend controllers
|
|
||||||
- Standard CRUD shape: `index`, `show`, `store`, `update`, `destroy` returning `JsonResponse`.
|
|
||||||
- Path: `reparee_backend/app/Http/Controllers/Api/<Name>Controller.php`.
|
|
||||||
- Use `vyuldashev/laravel-openapi` annotations so OpenAPI spec stays in sync (mirror `EstimateController`).
|
|
||||||
|
|
||||||
### B9. Models & migrations
|
|
||||||
- Models in `reparee_backend/app/Models/`. Use `$fillable`, `$casts`, relations.
|
|
||||||
- Migrations: `php artisan make:migration create_<table>_table` → standard `Schema::create` with `$table->id()` + `timestamps()`.
|
|
||||||
|
|
||||||
### B10. Permissions
|
|
||||||
- Permissions are **columns on the `roles` table**: `can_{view|create|update|delete}_{resource}`.
|
|
||||||
- To add a new resource:
|
|
||||||
1. Create a migration that adds the four boolean columns to `roles` (default `false`).
|
|
||||||
2. Update `database/seeders/RoleSeeder.php` so Super Admin gets `true` for all new columns (it auto-discovers `can_*` columns — verify).
|
|
||||||
3. The `permission.check` middleware reads the column name from the route name; ensure route is named `<resource>.<ability>` or matches its existing convention.
|
|
||||||
- **Reference migration**: `2026_04_06_120000_create_roles_table_and_refactor_employee_permissions.php`.
|
|
||||||
|
|
||||||
### B11. i18n (backend)
|
|
||||||
- Pairs required: every new key in `lang/en/<file>.php` MUST have the matching `lang/ar/<file>.php` key in the same change.
|
|
||||||
- Use `__('api.<area>.<key>')` in controllers and responses.
|
|
||||||
- Dashboard nav labels are NOT translated (hard-coded in `navGroups.tsx`).
|
|
||||||
|
|
||||||
### B12. Document-print (PDF)
|
|
||||||
- Single entry: `POST /api/document-print` → `DocumentPrintController@handle`.
|
|
||||||
- To add a printable type:
|
|
||||||
1. Add string to `DocumentPrintController::TYPES`.
|
|
||||||
2. Add `payload<Type>()` method on the controller.
|
|
||||||
3. Add `resources/views/pdf/document-print-<type>.blade.php`.
|
|
||||||
4. Add the type to the `DocumentPrintType` union in `packages/api/src/clients/document-print.ts`.
|
|
||||||
|
|
||||||
### B13. Pipeline-with-sections precedent
|
|
||||||
- `TaskSection` model + `task-section-form.tsx` already exist. Fields: `title`, `arrangement` (sort order), `is_default`.
|
|
||||||
- Reuse this pattern for `LeadSection`, `CallSection` (if needed), `JournalSection`, etc.
|
|
||||||
|
|
||||||
### B14. House rules (from `CLAUDE.md`)
|
|
||||||
- Never `git commit / push / tag / reset --hard / rebase` — stop at file edits.
|
|
||||||
- Don't add new dependencies without explicit approval.
|
|
||||||
- After edits, run `pnpm --filter dashboard typecheck`, `pnpm --filter dashboard lint`, and `php -l` on changed PHP files, then report results.
|
|
||||||
- Match existing conventions before introducing new patterns.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part C — Phase index
|
|
||||||
|
|
||||||
| # | Phase | Effort | Backend changes | Frontend changes | Depends on |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| 1 | Integrations placeholder | XS (1 hr) | none | 2 files | — |
|
|
||||||
| 2 | Settings → Master hub | S (1 day) | none (regroup) | 1 layout + tabs | — |
|
|
||||||
| 3 | Notification Templates library | M (3 days) | new table + CRUD + permission | full module | — |
|
|
||||||
| 4 | Reports (4 reports locked) | M (1 wk) | 4 aggregation endpoints | reports module + 4 reports w/ Recharts | reads existing data |
|
|
||||||
| 5 | CRM (Leads, Calls, Tasks-CRM) | XL (2–3 wks) | 3 resources + sections + permissions + i18n | 3 modules + pipelines | reuses TaskSection pattern |
|
|
||||||
| 6 | Marketing (Reminders email+SMS, Reviews) | L (1–2 wks) | reminder engine + Twilio integration + reviews | 3 sub-pages | needs Phase 3 (templates); Twilio composer dep |
|
|
||||||
| 7 | ~~Integrations (real)~~ | DEFERRED | — | — | — |
|
|
||||||
| 8A | Accountants — COA + Manual Journals | L (1.5 wks) | ledger UI only, no auto-post | 3 sub-pages | — |
|
|
||||||
| 8B | Accountants — auto-posting | L (1–2 wks) | observers on Invoice/Bill/Payment/Expense + reversal | linkage panels on source docs | requires 8A stable |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part D — Per-phase implementation specs
|
|
||||||
|
|
||||||
# Phase 1 — Settings → Integrations (Coming Soon)
|
|
||||||
|
|
||||||
**Goal.** Add an Integrations entry under Settings that renders a "Coming soon" placeholder.
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
None.
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
1. **Edit** `garage-erp/apps/dashboard/config/navGroups.tsx` (around line 183):
|
|
||||||
- There is already a commented-out entry:
|
|
||||||
```tsx
|
|
||||||
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> }
|
|
||||||
```
|
|
||||||
- Uncomment it but change `href` to `/settings/integrations` (single page, no sub-tabs yet).
|
|
||||||
- Insert between `Inspection Templates` and `Configurations`. Confirm `PlugZapIcon` is in the top-of-file imports; if not, add `PlugZapIcon` to the `lucide-react` import.
|
|
||||||
|
|
||||||
2. **Create** `garage-erp/apps/dashboard/app/(authenticated)/settings/integrations/page.tsx`:
|
|
||||||
- Use `DashboardPage` with `headerProps={{ title: "Integrations" }}` (match `settings/insurance-types/page.tsx`).
|
|
||||||
- Centered `Empty` block (from `@/shared/components/ui/empty`):
|
|
||||||
- `EmptyMedia`: `<PlugZapIcon className="size-12 text-muted-foreground" />`
|
|
||||||
- `EmptyTitle`: "Coming soon"
|
|
||||||
- `EmptyDescription`: "Connect WhatsApp, payments, accounting and email providers. Available in an upcoming release."
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. `pnpm --filter dashboard dev`.
|
|
||||||
2. Sidebar → Settings expands → new "Integrations" entry visible between Inspection Templates and Configurations.
|
|
||||||
3. Click → page renders with the Empty state.
|
|
||||||
4. `pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`.
|
|
||||||
|
|
||||||
### Out of scope
|
|
||||||
Sub-tabs (Providers / Integrations), any provider logic, backend.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 2 — Settings → Master hub
|
|
||||||
|
|
||||||
**Goal.** Group existing lookup data screens under one "Master" sidebar entry with tabs, matching Garage Box's UX.
|
|
||||||
|
|
||||||
### Tabs (in order)
|
|
||||||
1. Body Types (existing `/settings/...`)
|
|
||||||
2. Make & Model (existing `/settings/make-and-models`)
|
|
||||||
3. Insurance Types (existing `/settings/insurance-types`)
|
|
||||||
4. Departments (existing `/settings/departments`)
|
|
||||||
5. Shop Types (move from top-level OR alias)
|
|
||||||
6. Vehicle Transmissions, Fuel Types, Colors, Unit Types, Payment Terms, Payment Modes, Labor Rates, Reasons, Referral Sources, Document Types, Labels — surface those that currently lack a dedicated screen.
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
None new. Verify every tab's data source has a controller in `app/Http/Controllers/Api/` (most already do: `MakeAndModelController`, `InsuranceTypeController`, `DepartmentController`, `VehicleBodyTypeController`, `VehicleTransmissionController`, `VehicleFuelTypeController`, `VehicleColorController`, `UnitTypeController`, `PaymentTermController`, `PaymentModeController`, `LaborRateController`, `ReasonController`, `ReferralSourceController`, `DocumentTypeController`, `LabelController`).
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
1. **Create** `app/(authenticated)/settings/master/layout.tsx` with a `Tabs` header (use existing `Tabs` from `packages/ui`) and the 11+ tab labels above.
|
|
||||||
2. **Create** `app/(authenticated)/settings/master/page.tsx` that redirects to `./body-types`.
|
|
||||||
3. **Create** `app/(authenticated)/settings/master/<each-tab>/page.tsx`. Each is a thin wrapper that imports and renders the existing module list component from `modules/settings/<existing-folder>/`.
|
|
||||||
4. **Edit** `config/navGroups.tsx`: add `{ title: "Master", href: "/settings/master", icon: <DatabaseIcon /> }` after Integrations. **Keep** the existing top-level entries (Insurance Types, Departments, Make & Models) in the Settings list — they coexist as aliases for backwards-compat (per Part F decision).
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. Sidebar → Settings → Master → tabs render and each tab CRUDs correctly.
|
|
||||||
2. Direct URL `/settings/master/insurance-types` works.
|
|
||||||
3. Removed/aliased entries still resolve to the same screen.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 3 — Notification Templates library
|
|
||||||
|
|
||||||
**Goal.** Manage ~35 notification templates (per Garage Box screenshot 16) with per-channel toggles and bodies. Required for Phase 6 (Marketing) and any reminder/automation.
|
|
||||||
|
|
||||||
### Data model
|
|
||||||
| Table | Columns |
|
|
||||||
|---|---|
|
|
||||||
| `notification_templates` | `id`, `key` (unique e.g. `appointment_created`), `title`, `description` (nullable), `created_at`, `updated_at` |
|
|
||||||
| `notification_template_channels` | `id`, `notification_template_id` (FK), `channel` enum(`sms`,`whatsapp`,`email`,`push`), `enabled` bool, `subject` (nullable, for email), `body` text, `created_at`, `updated_at` |
|
|
||||||
|
|
||||||
Seed all template `key`s from this list (extracted from Garage Box image 16):
|
|
||||||
- `appointment_assigned`, `appointment_cancelled`, `appointment_confirmed`, `appointment_create`, `appointment_no_shows`, `appointment_reminder`, `appointment_requested`, `appointment_reschedule`, `appointment_unconfirmed`
|
|
||||||
- `attendance_details`, `attendance_reminder`
|
|
||||||
- `call_assigned`, `call_cancelled`, `call_completed`, `call_rescheduled`, `call_scheduled`
|
|
||||||
- `estimate_approved_by_admin`, `estimate_approved_by_customer`, `estimate_send`
|
|
||||||
- `job_card_customer`, `job_card_technician`
|
|
||||||
- `login_otp`
|
|
||||||
- `new_lead_notification`
|
|
||||||
- `part_requisition_create`
|
|
||||||
- `purchase_order_create`
|
|
||||||
- `ratings_reviews_link`
|
|
||||||
- `salary_change_notification`
|
|
||||||
- `send_customer_statement`, `send_inspection`, `send_invoice`, `send_vendor_statement`
|
|
||||||
- `service_reminder_cancelled`, `service_reminder_reschedule`, `service_reminder_scheduled`, `service_reminder_send`
|
|
||||||
- `work_request_form_send`, `workorder_create`
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
- `NotificationTemplateController` (`index`, `show`, `update` only — templates are seeded, not user-created).
|
|
||||||
- Routes (string-resolution style):
|
|
||||||
```php
|
|
||||||
Route::get('/notification-templates', 'NotificationTemplateController@index');
|
|
||||||
Route::get('/notification-templates/{key}', 'NotificationTemplateController@show');
|
|
||||||
Route::put('/notification-templates/{key}', 'NotificationTemplateController@update');
|
|
||||||
```
|
|
||||||
- Permissions: `can_view_notification_templates`, `can_update_notification_templates` (skip create/delete — seed-managed).
|
|
||||||
- Lang keys in `lang/en/api.php` + `lang/ar/api.php` under `notification_templates`.
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
1. **Module** `apps/dashboard/modules/notification-templates/` with `notification-template-row.tsx`, `notification-template-edit-dialog.tsx`, `notification-template.schema.ts`.
|
|
||||||
2. **Route** `app/(authenticated)/settings/templates/notifications/page.tsx` — TanStack Table with columns: Title, SMS (✓/—), WhatsApp, Email, Push, Actions.
|
|
||||||
3. **Sidebar entry**: `config/navGroups.tsx` add `{ title: "Templates", href: "/settings/templates/notifications", icon: <FileTextIcon /> }` between Inspection Templates and Integrations. (Or restructure existing `/settings/templates` if free.)
|
|
||||||
4. **Edit dialog**: tabs per channel, body editor with **variable picker** (e.g. `{{customer.name}}`, `{{vehicle.plate}}`, `{{appointment.date}}`). Variables list lives in a `notification-template-variables.ts` constants file co-located with the module.
|
|
||||||
5. **API client**: `packages/api/src/clients/notification-templates.ts` extends `CrudClient`.
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. Seeded list shows all 35+ rows.
|
|
||||||
2. Toggle a channel → persists.
|
|
||||||
3. Edit body → re-render shows updated body.
|
|
||||||
4. Backend `__('api.notification_templates.updated')` returns Arabic when locale is `ar`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 4 — Reports
|
|
||||||
|
|
||||||
**Goal.** Top-level Reports module with categorized reports across Sales, Purchases, Inventory, Employees, Accountants.
|
|
||||||
|
|
||||||
### Reports to ship (v1 — locked per Part F)
|
|
||||||
1. **Sales by Customer** — revenue grouped by customer with date range + department filter.
|
|
||||||
2. **Invoices Aging** — outstanding invoices bucketed 0–30 / 31–60 / 61–90 / 90+ days.
|
|
||||||
3. **Technician Productivity** — hours logged vs billable per technician, derived from `TimeSheet` + job-card service rows.
|
|
||||||
4. **Inventory Valuation + Low-Stock** — current stock value by part + list of parts under reorder threshold.
|
|
||||||
|
|
||||||
All other reports candidates (Sales by Service/Vehicle, Payments Summary, Estimates Conversion, Purchases by Vendor, Bills Aging, Stock Movement, Attendance, Payroll, Job Card Turnaround/Status) are deferred to a follow-up phase. Architect the reports module so adding the 5th report is trivial.
|
|
||||||
|
|
||||||
### Charting
|
|
||||||
Use **Recharts** via the already-installed wrapper `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency. Wrapper exports `ChartContainer`, `ChartTooltip`, `ChartTooltipContent`, etc. — mimic shadcn's chart usage docs.
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
- `app/Http/Controllers/Api/Reports/` directory — one controller per report category (`SalesReportController`, `PurchasesReportController`, etc.).
|
|
||||||
- Each report = single GET endpoint accepting `from`, `to`, optional `department_id`, `customer_id`, etc. Returns aggregated rows.
|
|
||||||
- Use Eloquent + `selectRaw` aggregations. Index any frequently-grouped columns via migration.
|
|
||||||
- Routes grouped under `/api/reports/...`. New permission per category: `can_view_reports_sales`, `can_view_reports_purchases`, ...
|
|
||||||
- **No new models or tables** — pure read aggregation over existing data.
|
|
||||||
- Lang keys for report titles in `lang/en/reports.php` + `lang/ar/reports.php`.
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
1. **Module** `apps/dashboard/modules/reports/` with:
|
|
||||||
- `report-card.tsx` (preview tile in the index).
|
|
||||||
- `report-filters.tsx` (date range, department, customer/vendor).
|
|
||||||
- One subdirectory per category: `sales/`, `purchases/`, `inventory/`, `employees/`, `job-cards/`. Each contains a `<report-name>-report.tsx` data view.
|
|
||||||
2. **Routes**:
|
|
||||||
- `app/(authenticated)/reports/page.tsx` — index grid of report cards grouped by category.
|
|
||||||
- `app/(authenticated)/reports/<category>/<slug>/page.tsx` — individual report view with filters + table + export buttons.
|
|
||||||
3. **Sidebar**: add a new top-level group `{ title: "Reports", href: "/reports", icon: <BarChart3Icon /> }` after Items/Employees in `navGroups.tsx`.
|
|
||||||
4. **Export**: reuse `useDocumentPrint` pattern for PDF; for Excel use existing `maatwebsite/excel` backend integration (add new export classes in `app/Exports/Reports/`).
|
|
||||||
5. **Charts**: prefer `recharts` if already in `packages/ui` dependencies; otherwise propose to user before adding.
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. Each report renders with sample data filtered by date range.
|
|
||||||
2. PDF export uses the same layout shell as other prints (`resources/views/pdf/layouts/document.blade.php`).
|
|
||||||
3. Excel export downloads a valid `.xlsx`.
|
|
||||||
4. Permissions block access when role lacks `can_view_reports_<category>`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 5 — CRM (Leads, Calls, Tasks-CRM)
|
|
||||||
|
|
||||||
**Goal.** Add the missing CRM module with three pipelines: Leads, Calls, Tasks (distinct from existing productivity tasks). Mirrors Garage Box screenshots 1–8.
|
|
||||||
|
|
||||||
### Sub-phase 5a — Leads
|
|
||||||
|
|
||||||
#### Data model
|
|
||||||
| Table | Key columns |
|
|
||||||
|---|---|
|
|
||||||
| `lead_sections` | `id`, `title`, `arrangement`, `is_default`, `kind` enum(`open`,`won`,`lost`) (kind drives default behavior). Reuse `TaskSection` pattern. |
|
|
||||||
| `leads` | `id`, `number` (unique, e.g. `LD-000001`), `title`, `date`, `lead_owner_id` (FK users), `referral_source_id` (FK), `lead_status_id` (FK), `department_id`, `description`, `lead_section_id` (FK), `customer_id` (nullable), `vehicle_id` (nullable), salutation, first/last/company name, phone, email, address fields, vehicle fields (make, model, plate, body_type_id). |
|
|
||||||
| `lead_services` | pivot to services |
|
|
||||||
| `lead_parts` | pivot to parts |
|
|
||||||
| `lead_labels` | pivot to `labels` table |
|
|
||||||
|
|
||||||
#### Backend
|
|
||||||
- `LeadController`, `LeadSectionController`, `LeadServiceController`, `LeadPartController` (mirror Estimate's split).
|
|
||||||
- Permissions: `can_view_leads`, `can_create_leads`, `can_update_leads`, `can_delete_leads`, plus `can_manage_lead_sections`.
|
|
||||||
- Number sequence: reuse `InvoiceSequenceController` pattern (add `LeadSequenceController`).
|
|
||||||
- Lang keys under `lang/en/api.php` `leads` section + `lang/ar/api.php`.
|
|
||||||
- OpenAPI annotations on each method.
|
|
||||||
|
|
||||||
#### Frontend
|
|
||||||
- **Module** `apps/dashboard/modules/leads/` with `lead-form.tsx`, `lead.schema.ts`, `lead-pipeline.tsx` (Kanban view), `lead-actions.tsx`, inline sections for services/parts.
|
|
||||||
- **Routes** `app/(authenticated)/crm/leads/page.tsx` (Kanban + table toggle), `[id]/page.tsx` (detail).
|
|
||||||
- **Sidebar** new group `{ title: "CRM", icon: <UsersIcon />, items: [Leads, Calls, Tasks] }` after Purchases in `navGroups.tsx`.
|
|
||||||
- **Pipeline UI**: Kanban with `@dnd-kit` (check if already in deps before adding). Each column = a `LeadSection`. "+ Section" button opens a section dialog (reuse `task-section-form.tsx` pattern).
|
|
||||||
- **API client** `packages/api/src/clients/leads.ts`.
|
|
||||||
|
|
||||||
### Sub-phase 5b — Calls
|
|
||||||
|
|
||||||
#### Data model
|
|
||||||
| Table | Key columns |
|
|
||||||
|---|---|
|
|
||||||
| `calls` | `id`, `number` (`CL-000001`), `call_for` (polymorphic morphs to Customer/Lead), `vehicle_id`, `status` enum(`requested`,`scheduled`,`completed`,`cancelled`), `type` enum(`inbound`,`outbound`), `subject`, `call_owner_id`, `call_date`, `from_time`, `to_time`, `department_id`, `purpose_id` (FK to lookup), `agenda` text, `outcome_id` (nullable FK), `description`, `duration_minutes`, `duration_seconds`, `voice_recording_path`, `send_notification` bool. |
|
|
||||||
| `call_reminders` | `id`, `call_id`, `unit` int, `unit_type` enum(`minute`,`hour`,`day`), `event` enum(`before`,`after`), `channel` enum(`sms`,`email`,`whatsapp`). |
|
|
||||||
| `call_purposes`, `call_outcomes` | lookups |
|
|
||||||
|
|
||||||
#### Backend
|
|
||||||
- `CallController` (CRUD + special endpoints: `complete`, `cancel`, `reschedule`).
|
|
||||||
- `CallReminderController` (nested).
|
|
||||||
- Reminder dispatcher: a Laravel scheduled job in `app/Console/Commands/SendDueCallReminders.php` runs every minute, sends pending reminders via the relevant notification template (Phase 3) through the provider configured in Phase 7. If Phase 7 not yet shipped, log-only.
|
|
||||||
- Permissions: standard four + `can_log_calls`, `can_complete_calls`.
|
|
||||||
|
|
||||||
#### Frontend
|
|
||||||
- **Module** `apps/dashboard/modules/calls/` with `call-form.tsx` (schedule), `call-log-form.tsx` (log), `call.schema.ts`, `call-calendar.tsx`.
|
|
||||||
- **Routes** `app/(authenticated)/crm/calls/page.tsx` (table + tabs Requested/Scheduled/Completed/Cancelled), `crm/calls/calendar/page.tsx` (month view), `[id]/page.tsx`.
|
|
||||||
|
|
||||||
### Sub-phase 5c — Tasks (CRM)
|
|
||||||
|
|
||||||
**Approach locked per Part F: Option A — extend existing `tasks` table.**
|
|
||||||
|
|
||||||
#### Migration
|
|
||||||
Add to the existing `tasks` table:
|
|
||||||
- `context` enum (`productivity`, `crm`), default `productivity`, NOT NULL.
|
|
||||||
- `customer_id` nullable FK to `customers`.
|
|
||||||
- `vehicle_id` nullable FK to `vehicles`.
|
|
||||||
- Index on `(context, status)` for the pipeline filter.
|
|
||||||
|
|
||||||
#### Backend
|
|
||||||
- Backfill existing rows to `context = 'productivity'`.
|
|
||||||
- All existing `TaskController` queries get a `->where('context', 'productivity')` filter so `/productivity/tasks` keeps showing only what it shows today.
|
|
||||||
- Add `CrmTaskController` (thin) that scopes to `context = 'crm'` and exposes the same CRUD + section endpoints. Reuse the `TaskSection` table for sections (add a `context` column there too, same enum).
|
|
||||||
- Permissions: introduce `can_view_crm_tasks`, `can_create_crm_tasks`, `can_update_crm_tasks`, `can_delete_crm_tasks` separate from the existing productivity-task permissions.
|
|
||||||
|
|
||||||
#### Frontend
|
|
||||||
- New module `apps/dashboard/modules/crm-tasks/` mirroring Leads pipeline pattern (Kanban with sections).
|
|
||||||
- Route `app/(authenticated)/crm/tasks/page.tsx` (Kanban + table toggle).
|
|
||||||
- Re-use schema fragments from `modules/tasks/` where possible — extract shared bits to a `modules/tasks/shared/` if duplication grows.
|
|
||||||
|
|
||||||
### Verification (Phase 5 overall)
|
|
||||||
1. Pipeline drag-and-drop persists section + arrangement.
|
|
||||||
2. New lead with vehicle info creates a corresponding draft Customer + Vehicle (or links existing) — confirm desired behavior.
|
|
||||||
3. Call scheduled with a 10-min reminder → cron job fires at expected time.
|
|
||||||
4. Number sequences advance correctly when a record is created.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 6 — Marketing (Service Reminders + Reviews)
|
|
||||||
|
|
||||||
**Goal.** Automate service reminders based on mileage / time, plus collect and surface customer reviews.
|
|
||||||
|
|
||||||
### Service Reminders
|
|
||||||
- New table `service_reminders`: `id`, `customer_id`, `vehicle_id`, `reminder_type` (`mileage` / `time`), `interval_value`, `interval_unit`, `last_triggered_at`, `next_due_at`, `status` enum(`scheduled`,`sent`,`cancelled`), `channels` JSON (subset of `['email','sms']`).
|
|
||||||
- Scheduled command `app/Console/Commands/SendDueServiceReminders.php` runs daily; sends via Phase 3 templates (`service_reminder_send`).
|
|
||||||
- **Channels (per Part F)**: **Email** via Laravel `Mail::to(...)->send(...)` using the configured mail sender; **SMS** via Twilio.
|
|
||||||
- Install `twilio/sdk` (Composer) — flag this dependency add for user approval per CLAUDE.md house rules.
|
|
||||||
- Add a `NotificationDispatcher` service in `app/Services/Notifications/` with `sendEmail()` and `sendSms()` methods. Reads Twilio credentials from `config/services.php` (`twilio.sid`, `twilio.token`, `twilio.from`) which read from `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`).
|
|
||||||
- WhatsApp/Push channel toggles render but are disabled with a "Requires integration" tooltip — wiring up to providers happens in deferred Phase 7.
|
|
||||||
- Frontend: `app/(authenticated)/marketing/service-reminders/page.tsx` — list with status tabs, "Create reminder" form with Email + SMS channel checkboxes.
|
|
||||||
|
|
||||||
### Rating & Reviews
|
|
||||||
- New table `customer_reviews`: `id`, `customer_id`, `job_card_id`, `rating` 1–5, `comment`, `submitted_at`, `source` enum(`internal`,`google`).
|
|
||||||
- Public-facing review form already partially served by `PublicInspectionController` pattern — extend with `PublicReviewController`.
|
|
||||||
- After job-card completion, fire `ratings_reviews_link` template (Phase 3).
|
|
||||||
- Frontend list at `app/(authenticated)/marketing/reviews/page.tsx`.
|
|
||||||
|
|
||||||
### Google Business Reviews
|
|
||||||
- Read-only sync via Google Business Profile API (requires Phase 7 Google integration).
|
|
||||||
- Background job polls every 6 h.
|
|
||||||
- Render in same Reviews list with `source = google` badge.
|
|
||||||
|
|
||||||
### Sidebar
|
|
||||||
- Add CRM-style group `{ title: "Marketing", icon: <MegaphoneIcon />, items: [Service Reminders, Reviews, Google Reviews] }` after CRM.
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. Create a mileage-based reminder → next_due_at calculated.
|
|
||||||
2. Cron tick at due time → template send is recorded (or logged if Phase 7 incomplete).
|
|
||||||
3. Submit a public review → appears in admin list.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 7 — Integrations (real connectors) — DEFERRED
|
|
||||||
|
|
||||||
**Status (per Part F decision): NOT IN ROADMAP.** The Phase 1 "Coming soon" placeholder is the long-term state for now. Twilio (SMS) and Laravel mail (email) used by Phase 6 are configured via `.env` only — no user-facing integrations UI.
|
|
||||||
|
|
||||||
Keep this spec as reference for when integrations become a priority later.
|
|
||||||
|
|
||||||
**Goal (when revived).** Replace the Phase 1 placeholder with a real Providers/Integrations page connecting Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp. Twilio also moves into the UI at that point.
|
|
||||||
|
|
||||||
### Data model
|
|
||||||
| Table | Key columns |
|
|
||||||
|---|---|
|
|
||||||
| `integration_providers` | seeded list: `id`, `key` (slug), `name`, `purpose`, `icon_path`, `auth_type` (`oauth2`/`api_key`/`webhook`), `is_active`. |
|
|
||||||
| `integration_connections` | per-tenant connection: `id`, `provider_id`, `credentials` (encrypted JSON), `status` (`connected`/`disconnected`/`error`), `last_synced_at`. |
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
- `IntegrationProviderController` (list), `IntegrationConnectionController` (CRUD + `connect`, `disconnect`, `test`).
|
|
||||||
- One service class per provider in `app/Services/Integrations/<Provider>/`. Each implements a common contract `IntegrationDriver` with `connect()`, `disconnect()`, `sendMessage()`, `pullData()`.
|
|
||||||
- OAuth callback routes: `/integrations/{provider}/callback`.
|
|
||||||
- Permissions: `can_manage_integrations`.
|
|
||||||
- Lang keys for connection status messages.
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
- **Replace** the Phase 1 placeholder page with `app/(authenticated)/settings/integrations/page.tsx` showing a `Tabs` of "Providers" (catalog) + "Integrations" (connected list).
|
|
||||||
- **Provider catalog tile** with "Connect" button → opens OAuth popup or credentials dialog.
|
|
||||||
- Update `navGroups.tsx`: `href: "/settings/integrations/providers"` (the original commented-out path).
|
|
||||||
|
|
||||||
### Verification
|
|
||||||
1. Connect Google → OAuth popup → callback persists tokens → "Connected" badge appears.
|
|
||||||
2. Test SMS via Vonage → message delivered (in sandbox).
|
|
||||||
3. Disconnect → credentials zeroed.
|
|
||||||
|
|
||||||
### Out of scope for first cut
|
|
||||||
Real-time webhook handlers for each provider (do them incrementally, one provider per follow-up PR).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# Phase 8 — Accountants
|
|
||||||
|
|
||||||
**Goal.** Introduce a real general ledger. Split into two sub-phases per Part F: ship the ledger UI first (8A), wire auto-posting into existing modules afterward (8B).
|
|
||||||
|
|
||||||
## Phase 8A — Chart of Accounts + Manual Journals + Default Configuration
|
|
||||||
|
|
||||||
Ship the standalone ledger. No existing controllers are touched. Users can manually post journal entries; nothing auto-posts.
|
|
||||||
|
|
||||||
### Data model
|
|
||||||
| Table | Key columns |
|
|
||||||
|---|---|
|
|
||||||
| `chart_of_accounts` | `id`, `name`, `code` (nullable), `account_type` enum(`asset`,`liability`,`equity`,`income`,`expense`,`cogs`), `parent_id` (nullable, for sub-accounts), `is_system` bool (lock icon in UI), `note`. |
|
|
||||||
| `journals` | `id`, `number` (`JN-000001`), `date`, `reference`, `notes`, `total_amount` (must balance), `posted_by`, `posted_at`. |
|
|
||||||
| `journal_lines` | `id`, `journal_id`, `account_id`, `debit`, `credit`, `description`. Constraint: sum(debit) == sum(credit) per journal. |
|
|
||||||
| `default_account_settings` | single-row config table for: `sales_account_id`, `purchase_account_id`, `inventory_account_id`, `adjustment_account_id`, `customer_advance_account_id`, `deposit_to_account_id`, `vendor_advance_account_id`, `paid_through_account_id`, `purchase_discount_account_id`, `expense_account_id`. |
|
|
||||||
|
|
||||||
### Seed
|
|
||||||
Seed ~80 standard accounts matching Garage Box screenshot 9 (Accounts Payable, Accounts Receivable, Advance Tax, … VAT Payable). Mark system accounts (`is_system = true`).
|
|
||||||
|
|
||||||
### Backend (8A only)
|
|
||||||
- `ChartOfAccountController`, `JournalController`, `DefaultAccountSettingsController`.
|
|
||||||
- Permissions: `can_view_accountants`, `can_manage_chart_of_accounts`, `can_post_journals`.
|
|
||||||
- OpenAPI annotations.
|
|
||||||
- **No changes to existing controllers** in this sub-phase — Invoices/Bills/Payments/Expenses are untouched.
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
- **Sidebar group** `{ title: "Accountants", icon: <BookOpenIcon />, items: [Manual Journals, Chart Of Accounts] }` after Purchases.
|
|
||||||
- **Module** `apps/dashboard/modules/accountants/` with `chart-of-account-list.tsx`, `chart-of-account-form.tsx`, `journal-form.tsx` (multi-line debit/credit with running balance check), `default-account-settings-form.tsx`.
|
|
||||||
- **Routes**: `app/(authenticated)/accountants/chart-of-accounts/page.tsx`, `accountants/manual-journals/page.tsx`, `[id]/page.tsx`.
|
|
||||||
|
|
||||||
### Verification (8A)
|
|
||||||
1. Seed list matches Garage Box exactly (account names + types).
|
|
||||||
2. Create a manual journal with unbalanced lines → backend rejects.
|
|
||||||
3. Default Configuration dialog persists.
|
|
||||||
4. Invoices/Bills/Payments/Expenses still work unchanged (no regression).
|
|
||||||
|
|
||||||
## Phase 8B — Auto-posting + cross-doc linking
|
|
||||||
|
|
||||||
Wire the ledger into operational modules. **Only start after 8A is stable in production.**
|
|
||||||
|
|
||||||
### Backend
|
|
||||||
- New service `app/Services/Accounting/JournalPoster.php` with methods like `postInvoice(Invoice $i)`, `postBill(Bill $b)`, `postPaymentReceived(...)`, `postPaymentMade(...)`, `postExpense(...)`.
|
|
||||||
- Hook into existing controllers via Eloquent `created` / `updated` model observers (cleaner than editing every controller). Observers live in `app/Observers/`, registered in `EventServiceProvider`.
|
|
||||||
- Each posted journal gets a `source_type` + `source_id` morphable pair so it links back to the originating document.
|
|
||||||
- Reversal logic: when a source doc is deleted or voided, post the reverse journal (don't soft-delete the original).
|
|
||||||
- New permission: `can_post_automatic_journals` (default true for finance roles).
|
|
||||||
|
|
||||||
### Frontend
|
|
||||||
- On Invoice / Bill / Payment / Expense detail pages: add a "Journal Entry" panel showing the posted journal lines (read-only) with a deep link to `/accountants/manual-journals/<id>`.
|
|
||||||
- On Journal detail: show "Source Document" link back to the originating doc.
|
|
||||||
|
|
||||||
### Verification (8B)
|
|
||||||
1. Create an Invoice → Journal auto-posts (debit AR, credit Sales, credit Tax).
|
|
||||||
2. Edit Invoice amount → existing journal reversed + new one posted.
|
|
||||||
3. Delete Invoice → reversal posted; original journal preserved for audit.
|
|
||||||
4. Default Configuration changes are respected on next post.
|
|
||||||
5. Audit trail: every Journal has a non-null `source_type`/`source_id` when auto-posted.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part E — Cross-cutting follow-ups (every phase finishes with)
|
|
||||||
|
|
||||||
1. Run **`pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`** — must pass.
|
|
||||||
2. Run **`php -l`** on every changed PHP file.
|
|
||||||
3. Regenerate API client if backend changed: **`pnpm --filter @garage/api generate`**.
|
|
||||||
4. Update lang pairs (`lang/en/*.php` + `lang/ar/*.php`).
|
|
||||||
5. Update permission migration + seeder for any new permission columns.
|
|
||||||
6. Use the `code-review-graph` MCP `detect_changes_tool` + `get_review_context_tool` before opening the PR to self-review.
|
|
||||||
7. Update `claude-timeline/YYYY-MM-DD.md` with a one-line note about the phase shipped (per global memory rule).
|
|
||||||
8. **Do not commit** — leave the diff for the user to review.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Part F — Resolved decisions (2026-05-21)
|
|
||||||
|
|
||||||
All open questions answered by the user. These are now binding for the phases referenced.
|
|
||||||
|
|
||||||
- **Phase 2 (Master)** → **Keep top-level entries as aliases.** Insurance Types, Departments, Make & Models remain in the Settings sidebar AND appear under Master tabs. Backwards-compat for bookmarks. No redirects, no removals.
|
|
||||||
- **Phase 4 (Reports) — charts** → **Use Recharts (already installed)** via the existing wrapper at `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency.
|
|
||||||
- **Phase 4 (Reports) — v1 scope** → ship exactly these four reports:
|
|
||||||
1. Sales by Customer
|
|
||||||
2. Invoices Aging (0–30 / 31–60 / 61–90 / 90+ days)
|
|
||||||
3. Technician Productivity (hours logged vs billable per technician)
|
|
||||||
4. Inventory Valuation + Low-Stock
|
|
||||||
All other reports listed in Phase 4 are deferred.
|
|
||||||
- **Phase 5c (CRM Tasks)** → **Extend the existing `tasks` table** (Option A). Add `context` enum (`productivity` | `crm`), nullable `customer_id`, nullable `vehicle_id`. All existing task queries get a `context = 'productivity'` filter.
|
|
||||||
- **Phase 6 (Marketing reminders) — channels** → **Email + SMS in v1; WhatsApp deferred.**
|
|
||||||
- Email sends via Laravel's configured mail sender (`config/mail.php`) — works out of the box, no Integrations UI required.
|
|
||||||
- SMS sends via **Twilio**. Configured server-side via `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`) — not surfaced in the Integrations page yet.
|
|
||||||
- WhatsApp channel toggles are visible but disabled with a "Requires integration" tooltip.
|
|
||||||
- **Phase 7 (Integrations real)** → **Stays "coming soon."** The Phase 1 placeholder is the long-term state for now. Twilio + Laravel mail are configured server-side only; no user-facing connector UI in this roadmap. Phase 7's detailed spec is preserved as a future reference but no work is planned.
|
|
||||||
- **Phase 8 (Accountants)** → **Split into two sub-phases:**
|
|
||||||
- **Phase 8A**: Chart of Accounts + Manual Journals + Default Configuration UI. No automatic posting from other modules.
|
|
||||||
- **Phase 8B**: Auto-post journals on Invoice / Bill / Payment / Expense create + link from each source doc to its posted journal entry. Big blast radius — ship only after 8A is stable.
|
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
-179
@@ -1,179 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState } from "react"
|
|
||||||
import { useParams } from "next/navigation"
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
|
||||||
import { type ColumnDef } from "@tanstack/react-table"
|
|
||||||
import { Plus, Trash2, ExternalLinkIcon, AwardIcon } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/shared/components/ui/dialog"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
import { EmployeeCertificationForm } from "@/modules/employees/employee-certification-form"
|
|
||||||
|
|
||||||
type CertRow = {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
issuer?: string | null
|
|
||||||
certificate_number?: string | null
|
|
||||||
issued_date?: string | null
|
|
||||||
expiry_date?: string | null
|
|
||||||
file_url?: string | null
|
|
||||||
is_expired?: boolean
|
|
||||||
notes?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EmployeeCertificationsPage() {
|
|
||||||
const { id: employeeId } = useParams<{ id: string }>()
|
|
||||||
const api = useAuthApi()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const [open, setOpen] = useState(false)
|
|
||||||
const queryKey = ["employee-certifications", employeeId]
|
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey,
|
|
||||||
queryFn: () => api.employees.listCertifications(employeeId) as Promise<{ data: CertRow[] | { data: CertRow[] } }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const rows: CertRow[] = Array.isArray((data as any)?.data)
|
|
||||||
? (data as any).data
|
|
||||||
: ((data as any)?.data?.data ?? [])
|
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
|
||||||
mutationFn: (id: number) => api.employees.destroyCertification(employeeId, String(id)),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Certification deleted")
|
|
||||||
queryClient.invalidateQueries({ queryKey })
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to delete"),
|
|
||||||
})
|
|
||||||
|
|
||||||
async function handleDelete(row: CertRow) {
|
|
||||||
const ok = await confirm({
|
|
||||||
title: "Delete certification?",
|
|
||||||
description: `Permanently delete "${row.name}"?`,
|
|
||||||
confirmLabel: "Delete",
|
|
||||||
variant: "destructive",
|
|
||||||
})
|
|
||||||
if (ok) deleteMutation.mutate(row.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
const columns: ColumnDef<CertRow>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: "name",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<AwardIcon className="size-4 text-muted-foreground" />
|
|
||||||
<span className="font-medium">{row.original.name}</span>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "issuer",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Issuer" />,
|
|
||||||
cell: ({ row }) => row.original.issuer ?? "—",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "certificate_number",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Cert #" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const v = row.original.certificate_number
|
|
||||||
return v ? <span className="font-mono text-xs">{v}</span> : "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "issued_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
|
||||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "expiry_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span>{formatDate(row.original.expiry_date)}</span>
|
|
||||||
{row.original.is_expired && <Badge variant="destructive">Expired</Badge>}
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "actions",
|
|
||||||
header: () => <span className="sr-only">Actions</span>,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex justify-end gap-1">
|
|
||||||
{row.original.file_url && (
|
|
||||||
<Button variant="ghost" size="icon" asChild>
|
|
||||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
|
||||||
<ExternalLinkIcon className="size-4" />
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
disabled={deleteMutation.isPending}
|
|
||||||
onClick={() => handleDelete(row.original)}
|
|
||||||
>
|
|
||||||
<Trash2 className="size-4 text-destructive" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: "Certifications",
|
|
||||||
actions: (
|
|
||||||
<Button size="sm" onClick={() => setOpen(true)}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Add Certification
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DataTable
|
|
||||||
columns={columns}
|
|
||||||
data={rows}
|
|
||||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
|
||||||
sorting={[]}
|
|
||||||
onChange={() => {}}
|
|
||||||
isLoading={isLoading}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Add Certification</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
<EmployeeCertificationForm
|
|
||||||
employeeId={employeeId}
|
|
||||||
onSuccess={() => {
|
|
||||||
setOpen(false)
|
|
||||||
queryClient.invalidateQueries({ queryKey })
|
|
||||||
}}
|
|
||||||
onCancel={() => setOpen(false)}
|
|
||||||
/>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState } from "react"
|
|
||||||
import { useParams } from "next/navigation"
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
|
||||||
import { type ColumnDef } from "@tanstack/react-table"
|
|
||||||
import { Plus, Trash2, ExternalLinkIcon, FileTextIcon } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/shared/components/ui/dialog"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
import { EmployeeDocumentForm } from "@/modules/employees/employee-document-form"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
type DocRow = {
|
|
||||||
id: number
|
|
||||||
name: string
|
|
||||||
type: string
|
|
||||||
file_url?: string
|
|
||||||
issued_date?: string | null
|
|
||||||
expiry_date?: string | null
|
|
||||||
notes?: string | null
|
|
||||||
created_at?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function isExpired(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return false
|
|
||||||
const d = new Date(value)
|
|
||||||
return !Number.isNaN(d.getTime()) && d.getTime() < Date.now()
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EmployeeDocumentsPage() {
|
|
||||||
const { id: employeeId } = useParams<{ id: string }>()
|
|
||||||
const api = useAuthApi()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const [open, setOpen] = useState(false)
|
|
||||||
|
|
||||||
const queryKey = ["employee-documents", employeeId]
|
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey,
|
|
||||||
queryFn: () => api.employees.listDocuments(employeeId) as Promise<{ data: DocRow[] | { data: DocRow[] } }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const rows: DocRow[] = Array.isArray((data as any)?.data)
|
|
||||||
? (data as any).data
|
|
||||||
: ((data as any)?.data?.data ?? [])
|
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
|
||||||
mutationFn: (id: number) => api.employees.destroyDocument(employeeId, String(id)),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Document deleted")
|
|
||||||
queryClient.invalidateQueries({ queryKey })
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to delete document"),
|
|
||||||
})
|
|
||||||
|
|
||||||
async function handleDelete(row: DocRow) {
|
|
||||||
const ok = await confirm({
|
|
||||||
title: "Delete document?",
|
|
||||||
description: `Permanently delete "${row.name}"?`,
|
|
||||||
confirmLabel: "Delete",
|
|
||||||
variant: "destructive",
|
|
||||||
})
|
|
||||||
if (ok) deleteMutation.mutate(row.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
const columns: ColumnDef<DocRow>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: "name",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<FileTextIcon className="size-4 text-muted-foreground" />
|
|
||||||
<span className="font-medium">{row.original.name}</span>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "type",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
|
||||||
cell: ({ row }) => <Badge variant="outline">{formatEnum(row.original.type)}</Badge>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "issued_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
|
||||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "expiry_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const v = row.original.expiry_date
|
|
||||||
if (!v) return "—"
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span>{formatDate(v)}</span>
|
|
||||||
{isExpired(v) && <Badge variant="destructive">Expired</Badge>}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "actions",
|
|
||||||
header: () => <span className="sr-only">Actions</span>,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex justify-end gap-1">
|
|
||||||
{row.original.file_url && (
|
|
||||||
<Button variant="ghost" size="icon" asChild>
|
|
||||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
|
||||||
<ExternalLinkIcon className="size-4" />
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
disabled={deleteMutation.isPending}
|
|
||||||
onClick={() => handleDelete(row.original)}
|
|
||||||
>
|
|
||||||
<Trash2 className="size-4 text-destructive" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: "Documents",
|
|
||||||
actions: (
|
|
||||||
<Button size="sm" onClick={() => setOpen(true)}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Upload Document
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DataTable
|
|
||||||
columns={columns}
|
|
||||||
data={rows}
|
|
||||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
|
||||||
sorting={[]}
|
|
||||||
onChange={() => {}}
|
|
||||||
isLoading={isLoading}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Upload Document</DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
<EmployeeDocumentForm
|
|
||||||
employeeId={employeeId}
|
|
||||||
onSuccess={() => {
|
|
||||||
setOpen(false)
|
|
||||||
queryClient.invalidateQueries({ queryKey })
|
|
||||||
}}
|
|
||||||
onCancel={() => setOpen(false)}
|
|
||||||
/>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -30,11 +30,6 @@ export default async function layout(props: {
|
|||||||
{ href: `/productivity/employees/${id}`, label: 'Details' },
|
{ href: `/productivity/employees/${id}`, label: 'Details' },
|
||||||
{ href: `/productivity/employees/${id}/attendance`, label: 'Attendance' },
|
{ href: `/productivity/employees/${id}/attendance`, label: 'Attendance' },
|
||||||
{ href: `/productivity/employees/${id}/work-history`, label: 'Work History' },
|
{ href: `/productivity/employees/${id}/work-history`, label: 'Work History' },
|
||||||
{ href: `/productivity/employees/${id}/documents`, label: 'Documents' },
|
|
||||||
{ href: `/productivity/employees/${id}/certifications`, label: 'Certifications' },
|
|
||||||
{ href: `/productivity/employees/${id}/leave`, label: 'Leave' },
|
|
||||||
{ href: `/productivity/employees/${id}/payroll`, label: 'Payroll' },
|
|
||||||
{ href: `/productivity/employees/${id}/performance`, label: 'Performance' },
|
|
||||||
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,164 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { use, useState } from "react"
|
|
||||||
import { useQuery } from "@tanstack/react-query"
|
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { useEmployee } from "@/modules/employees/employee-context"
|
|
||||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
|
||||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
|
||||||
import type { LeaveRequestsClient } from "@garage/api"
|
|
||||||
import { CalendarIcon, PlaneIcon, ActivityIcon } from "lucide-react"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
type Balance = {
|
|
||||||
annual_total: number
|
|
||||||
annual_used: number
|
|
||||||
annual_remaining: number
|
|
||||||
sick_total: number
|
|
||||||
sick_used: number
|
|
||||||
sick_remaining: number
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
|
||||||
if (status === "approved") return "default"
|
|
||||||
if (status === "rejected") return "destructive"
|
|
||||||
if (status === "cancelled") return "outline"
|
|
||||||
return "secondary"
|
|
||||||
}
|
|
||||||
|
|
||||||
function BalanceCard({ icon: Icon, label, used, total, remaining }: {
|
|
||||||
icon: React.ComponentType<{ className?: string }>
|
|
||||||
label: string
|
|
||||||
used: number
|
|
||||||
total: number
|
|
||||||
remaining: number
|
|
||||||
}) {
|
|
||||||
const pct = total > 0 ? Math.min(100, (used / total) * 100) : 0
|
|
||||||
return (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
|
||||||
<Icon className="size-4" />
|
|
||||||
{label}
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-semibold">{remaining}<span className="ml-1 text-sm font-normal text-muted-foreground">/ {total}</span></div>
|
|
||||||
<p className="mt-1 text-xs text-muted-foreground">{used} used</p>
|
|
||||||
<div className="mt-2 h-2 w-full overflow-hidden rounded bg-muted">
|
|
||||||
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EmployeeLeavePage({ params }: { params: Promise<{ id: string }> }) {
|
|
||||||
const { id: employeeId } = use(params)
|
|
||||||
const api = useAuthApi()
|
|
||||||
const employee = useEmployee()
|
|
||||||
|
|
||||||
const balanceQuery = useQuery({
|
|
||||||
queryKey: ["employee-leave-balance", employeeId],
|
|
||||||
queryFn: () => api.employees.getLeaveBalance(employeeId) as Promise<{ data: Balance }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const balance = (balanceQuery.data as any)?.data as Balance | undefined
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{balance && (
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-2 px-4 pt-4">
|
|
||||||
<BalanceCard
|
|
||||||
icon={PlaneIcon}
|
|
||||||
label="Annual Leave"
|
|
||||||
used={Number(balance.annual_used)}
|
|
||||||
total={Number(balance.annual_total)}
|
|
||||||
remaining={Number(balance.annual_remaining)}
|
|
||||||
/>
|
|
||||||
<BalanceCard
|
|
||||||
icon={ActivityIcon}
|
|
||||||
label="Sick Leave"
|
|
||||||
used={Number(balance.sick_used)}
|
|
||||||
total={Number(balance.sick_total)}
|
|
||||||
remaining={Number(balance.sick_remaining)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<ResourcePage<LeaveRequestsClient>
|
|
||||||
pageTitle="Leave History"
|
|
||||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
|
||||||
getClient={(api) => api.leaveRequests}
|
|
||||||
extraParams={{ employee_id: employeeId }}
|
|
||||||
header={null}
|
|
||||||
headerProps={({ invalidateQuery }) => ({
|
|
||||||
actions: (
|
|
||||||
<FormDialog title="New Leave Request">
|
|
||||||
{() => (
|
|
||||||
<LeaveRequestForm
|
|
||||||
presetEmployee={{ id: employeeId, label: employee?.label ?? "" }}
|
|
||||||
onSuccess={() => {
|
|
||||||
invalidateQuery()
|
|
||||||
balanceQuery.refetch()
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</FormDialog>
|
|
||||||
),
|
|
||||||
})}
|
|
||||||
columns={() => [
|
|
||||||
{
|
|
||||||
accessorKey: "leave_type",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<CalendarIcon className="size-4 text-muted-foreground" />
|
|
||||||
<Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "start_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "end_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "days",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
|
||||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "status",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const s = (row.original as any).status as string
|
|
||||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "reason",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Reason" />,
|
|
||||||
cell: ({ row }) => (row.original as any).reason ?? "—",
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { use } from "react"
|
|
||||||
import { useQuery } from "@tanstack/react-query"
|
|
||||||
import { type ColumnDef } from "@tanstack/react-table"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
type Slip = {
|
|
||||||
id: number
|
|
||||||
payroll_run?: { id?: number; reference?: string; period_start?: string; period_end?: string; status?: string }
|
|
||||||
hours_worked: number
|
|
||||||
base_salary: number
|
|
||||||
commission_amount: number
|
|
||||||
allowances: number
|
|
||||||
deductions: number
|
|
||||||
net_pay: number
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function fmt(v: unknown) {
|
|
||||||
const n = Number(v)
|
|
||||||
if (!Number.isFinite(n)) return "—"
|
|
||||||
return n.toFixed(2)
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" {
|
|
||||||
if (status === "paid") return "default"
|
|
||||||
if (status === "finalized") return "outline"
|
|
||||||
return "secondary"
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EmployeePayrollPage({ params }: { params: Promise<{ id: string }> }) {
|
|
||||||
const { id: employeeId } = use(params)
|
|
||||||
const api = useAuthApi()
|
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey: ["employee-payroll-slips", employeeId],
|
|
||||||
queryFn: () => api.employees.listPayrollSlips(employeeId) as Promise<{ data: Slip[] | { data: Slip[] } }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const rows: Slip[] = Array.isArray((data as any)?.data)
|
|
||||||
? (data as any).data
|
|
||||||
: ((data as any)?.data?.data ?? [])
|
|
||||||
|
|
||||||
const columns: ColumnDef<Slip>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: "payroll_run",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Run" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const r = row.original.payroll_run
|
|
||||||
return r?.reference ?? (r?.id ? `#${r.id}` : "—")
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "period",
|
|
||||||
header: () => <span>Period</span>,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const r = row.original.payroll_run
|
|
||||||
if (!r) return "—"
|
|
||||||
return `${formatDate(r.period_start)} → ${formatDate(r.period_end)}`
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "hours_worked",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
|
||||||
cell: ({ row }) => fmt(row.original.hours_worked),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "base_salary",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
|
||||||
cell: ({ row }) => fmt(row.original.base_salary),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "commission_amount",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
|
||||||
cell: ({ row }) => fmt(row.original.commission_amount),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "deductions",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
|
||||||
cell: ({ row }) => fmt(row.original.deductions),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "net_pay",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
|
||||||
cell: ({ row }) => <span className="font-semibold">{fmt(row.original.net_pay)}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "status",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const s = row.original.payroll_run?.status
|
|
||||||
if (!s) return "—"
|
|
||||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage headerProps={{ title: "Payroll Slips" }}>
|
|
||||||
<DataTable
|
|
||||||
columns={columns}
|
|
||||||
data={rows}
|
|
||||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
|
||||||
sorting={[]}
|
|
||||||
onChange={() => {}}
|
|
||||||
isLoading={isLoading}
|
|
||||||
/>
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useMemo, useState } from "react"
|
|
||||||
import { useParams } from "next/navigation"
|
|
||||||
import { useQuery } from "@tanstack/react-query"
|
|
||||||
import { ClockIcon, WrenchIcon, CheckCircle2Icon, TimerIcon, PercentIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
|
||||||
import { Input } from "@/shared/components/ui/input"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Field, FieldLabel } from "@/shared/components/ui/field"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
|
|
||||||
type PerfData = {
|
|
||||||
period: { from: string; to: string }
|
|
||||||
hours_worked: number
|
|
||||||
jobs_total: number
|
|
||||||
jobs_completed: number
|
|
||||||
avg_job_duration_hours: number
|
|
||||||
completion_rate: number
|
|
||||||
}
|
|
||||||
|
|
||||||
function StatCard({
|
|
||||||
icon: Icon,
|
|
||||||
label,
|
|
||||||
value,
|
|
||||||
suffix,
|
|
||||||
}: {
|
|
||||||
icon: React.ComponentType<{ className?: string }>
|
|
||||||
label: string
|
|
||||||
value: string | number
|
|
||||||
suffix?: string
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="pb-2">
|
|
||||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
|
||||||
<Icon className="size-4" />
|
|
||||||
{label}
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-semibold">
|
|
||||||
{value}
|
|
||||||
{suffix && <span className="ml-1 text-base font-normal text-muted-foreground">{suffix}</span>}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstOfMonth() {
|
|
||||||
const d = new Date()
|
|
||||||
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
function lastOfMonth() {
|
|
||||||
const d = new Date()
|
|
||||||
return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EmployeePerformancePage() {
|
|
||||||
const { id: employeeId } = useParams<{ id: string }>()
|
|
||||||
const api = useAuthApi()
|
|
||||||
const [fromInput, setFromInput] = useState(firstOfMonth())
|
|
||||||
const [toInput, setToInput] = useState(lastOfMonth())
|
|
||||||
const [from, setFrom] = useState(fromInput)
|
|
||||||
const [to, setTo] = useState(toInput)
|
|
||||||
|
|
||||||
const { data, isLoading, isFetching } = useQuery({
|
|
||||||
queryKey: ["employee-performance", employeeId, from, to],
|
|
||||||
queryFn: () => api.employees.performance(employeeId, { from, to }) as Promise<{ data: PerfData }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const perf = useMemo(() => (data as any)?.data as PerfData | undefined, [data])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: perf ? `Performance · ${perf.period.from} → ${perf.period.to}` : "Performance",
|
|
||||||
actions: (
|
|
||||||
<div className="flex items-end gap-2">
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>From</FieldLabel>
|
|
||||||
<Input type="date" value={fromInput} onChange={(e) => setFromInput(e.target.value)} />
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>To</FieldLabel>
|
|
||||||
<Input type="date" value={toInput} onChange={(e) => setToInput(e.target.value)} />
|
|
||||||
</Field>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
disabled={isFetching}
|
|
||||||
onClick={() => {
|
|
||||||
setFrom(fromInput)
|
|
||||||
setTo(toInput)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isFetching ? "Loading..." : "Apply"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isLoading && !perf ? (
|
|
||||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
|
||||||
) : !perf ? (
|
|
||||||
<p className="text-sm text-muted-foreground">No data.</p>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
|
||||||
<StatCard icon={ClockIcon} label="Hours Worked" value={perf.hours_worked.toFixed(2)} suffix="h" />
|
|
||||||
<StatCard icon={WrenchIcon} label="Jobs Assigned" value={perf.jobs_total} />
|
|
||||||
<StatCard icon={CheckCircle2Icon} label="Jobs Completed" value={perf.jobs_completed} />
|
|
||||||
<StatCard icon={TimerIcon} label="Avg Job Duration" value={perf.avg_job_duration_hours.toFixed(2)} suffix="h" />
|
|
||||||
<StatCard icon={PercentIcon} label="Completion Rate" value={perf.completion_rate} suffix="%" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -4,10 +4,7 @@ import { useMemo, useState } from "react"
|
|||||||
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 { ImportDataButton } from "@/shared/components/import-data-button"
|
|
||||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
|
||||||
import { EmployeeForm } from "@/modules/employees/employee-form"
|
import { EmployeeForm } from "@/modules/employees/employee-form"
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||||
import type { EmployeesClient } from "@garage/api"
|
import type { EmployeesClient } from "@garage/api"
|
||||||
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
||||||
@@ -36,7 +33,6 @@ function initialsOf(first?: string | null, last?: string | null) {
|
|||||||
|
|
||||||
export default function EmployeesPage() {
|
export default function EmployeesPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const api = useAuthApi()
|
|
||||||
const [typeFilter, setTypeFilter] = useState<string>("all")
|
const [typeFilter, setTypeFilter] = useState<string>("all")
|
||||||
|
|
||||||
const extraParams = useMemo(() => {
|
const extraParams = useMemo(() => {
|
||||||
@@ -72,18 +68,6 @@ export default function EmployeesPage() {
|
|||||||
)}
|
)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ImportDataButton
|
|
||||||
onImport={(file) => api.employees.importData(file)}
|
|
||||||
onSuccess={invalidateQuery}
|
|
||||||
entityLabel="Employees"
|
|
||||||
onDownloadSample={() => api.employees.downloadImportSample() as Promise<Blob>}
|
|
||||||
sampleFileName="employees-import-sample"
|
|
||||||
/>
|
|
||||||
<ExportDataButton
|
|
||||||
onExport={(filters) => api.employees.exportData(filters)}
|
|
||||||
fileName="employees"
|
|
||||||
/>
|
|
||||||
<FormDialog title="Employee">
|
<FormDialog title="Employee">
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<EmployeeForm
|
<EmployeeForm
|
||||||
@@ -93,7 +77,6 @@ export default function EmployeesPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</FormDialog>
|
</FormDialog>
|
||||||
</div>
|
|
||||||
),
|
),
|
||||||
})}
|
})}
|
||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
|
|||||||
@@ -1,152 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useState } from "react"
|
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
|
||||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
|
||||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
|
||||||
import type { LeaveRequestsClient } from "@garage/api"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { useQueryClient } from "@tanstack/react-query"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { CheckIcon, XIcon } from "lucide-react"
|
|
||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
import { usePermissions } from "@/shared/hooks/use-permissions"
|
|
||||||
|
|
||||||
type LeaveRow = {
|
|
||||||
id: number
|
|
||||||
leave_type: string
|
|
||||||
start_date?: string
|
|
||||||
end_date?: string
|
|
||||||
days?: number
|
|
||||||
status: string
|
|
||||||
reason?: string | null
|
|
||||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
|
||||||
if (status === "approved") return "default"
|
|
||||||
if (status === "rejected") return "destructive"
|
|
||||||
if (status === "cancelled") return "outline"
|
|
||||||
return "secondary"
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function LeaveRequestsPage() {
|
|
||||||
const api = useAuthApi()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const perms = usePermissions()
|
|
||||||
|
|
||||||
async function handleDecision(id: number, action: "approve" | "reject") {
|
|
||||||
const ok = await confirm({
|
|
||||||
title: action === "approve" ? "Approve request?" : "Reject request?",
|
|
||||||
description: `This will mark the leave request as ${action}d.`,
|
|
||||||
confirmLabel: action === "approve" ? "Approve" : "Reject",
|
|
||||||
variant: action === "approve" ? "default" : "destructive",
|
|
||||||
})
|
|
||||||
if (!ok) return
|
|
||||||
const promise = action === "approve"
|
|
||||||
? api.leaveRequests.approve(String(id))
|
|
||||||
: api.leaveRequests.reject(String(id))
|
|
||||||
toast.promise(promise, {
|
|
||||||
loading: action === "approve" ? "Approving..." : "Rejecting...",
|
|
||||||
success: action === "approve" ? "Approved" : "Rejected",
|
|
||||||
error: "Failed",
|
|
||||||
})
|
|
||||||
await promise
|
|
||||||
queryClient.invalidateQueries({ queryKey: [LEAVE_REQUEST_ROUTES.INDEX] })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ResourcePage<LeaveRequestsClient>
|
|
||||||
pageTitle="Leave Requests"
|
|
||||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
|
||||||
getClient={(api) => api.leaveRequests}
|
|
||||||
statusFilter={{
|
|
||||||
statuses: ["pending", "approved", "rejected", "cancelled"],
|
|
||||||
paramKey: "status",
|
|
||||||
allLabel: "All",
|
|
||||||
}}
|
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
|
||||||
actions: perms.canCreate("leave_requests") ? (
|
|
||||||
<FormDialog title="Leave Request">
|
|
||||||
{(resourceId) => (
|
|
||||||
<LeaveRequestForm
|
|
||||||
resourceId={resourceId}
|
|
||||||
initialData={selectedItem}
|
|
||||||
onSuccess={invalidateQuery}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</FormDialog>
|
|
||||||
) : null,
|
|
||||||
})}
|
|
||||||
columns={({ actionsColumn }) => [
|
|
||||||
{
|
|
||||||
accessorKey: "employee",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const e = (row.original as any).employee
|
|
||||||
if (!e) return "—"
|
|
||||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "leave_type",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
|
||||||
cell: ({ row }) => <Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "start_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "end_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "days",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
|
||||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "status",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const s = (row.original as any).status as string
|
|
||||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "decide",
|
|
||||||
header: () => <span className="sr-only">Decide</span>,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const r = row.original as LeaveRow
|
|
||||||
if (r.status !== "pending" || !perms.canUpdate("leave_requests")) return null
|
|
||||||
return (
|
|
||||||
<div className="flex justify-end gap-1">
|
|
||||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "approve")}>
|
|
||||||
<CheckIcon className="size-4 text-green-600" />
|
|
||||||
</Button>
|
|
||||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "reject")}>
|
|
||||||
<XIcon className="size-4 text-destructive" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
actionsColumn(),
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,259 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { use } from "react"
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
|
||||||
import { type ColumnDef } from "@tanstack/react-table"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { CheckCircle2Icon, RefreshCwIcon, BanknoteIcon, Trash2, DownloadIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
|
||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
type Entry = {
|
|
||||||
id: number
|
|
||||||
employee_id: number
|
|
||||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
|
||||||
hours_worked: number
|
|
||||||
overtime_hours: number
|
|
||||||
base_salary: number
|
|
||||||
commission_amount: number
|
|
||||||
allowances: number
|
|
||||||
deductions: number
|
|
||||||
net_pay: number
|
|
||||||
note?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
type Run = {
|
|
||||||
id: number
|
|
||||||
reference?: string
|
|
||||||
period_start: string
|
|
||||||
period_end: string
|
|
||||||
status: "draft" | "finalized" | "paid"
|
|
||||||
entries: Entry[]
|
|
||||||
note?: string | null
|
|
||||||
finalized_at?: string | null
|
|
||||||
paid_at?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function fmtCurrency(value: unknown) {
|
|
||||||
const n = Number(value)
|
|
||||||
if (!Number.isFinite(n)) return "—"
|
|
||||||
return n.toFixed(2)
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
|
||||||
if (status === "paid") return "default"
|
|
||||||
if (status === "finalized") return "outline"
|
|
||||||
return "secondary"
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PayrollRunPage({ params }: { params: Promise<{ id: string }> }) {
|
|
||||||
const { id: runId } = use(params)
|
|
||||||
const api = useAuthApi()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
const queryKey = ["payroll-run", runId]
|
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
|
||||||
queryKey,
|
|
||||||
queryFn: () => api.payroll.show(runId) as Promise<{ data: Run; totals: Record<string, number> }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const run = (data as any)?.data as Run | undefined
|
|
||||||
const totals = (data as any)?.totals as Record<string, number> | undefined
|
|
||||||
|
|
||||||
const refetch = () => queryClient.invalidateQueries({ queryKey })
|
|
||||||
|
|
||||||
const finalizeMutation = useMutation({
|
|
||||||
mutationFn: () => api.payroll.finalize(runId),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Run finalized")
|
|
||||||
refetch()
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to finalize"),
|
|
||||||
})
|
|
||||||
|
|
||||||
const regenerateMutation = useMutation({
|
|
||||||
mutationFn: () => api.payroll.regenerate(runId),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Entries regenerated")
|
|
||||||
refetch()
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to regenerate"),
|
|
||||||
})
|
|
||||||
|
|
||||||
const markPaidMutation = useMutation({
|
|
||||||
mutationFn: () => api.payroll.markPaid(runId),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Marked as paid")
|
|
||||||
refetch()
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to mark paid"),
|
|
||||||
})
|
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
|
||||||
mutationFn: () => api.payroll.destroy(runId),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Run deleted")
|
|
||||||
router.push("/productivity/payroll")
|
|
||||||
},
|
|
||||||
onError: () => toast.error("Failed to delete"),
|
|
||||||
})
|
|
||||||
|
|
||||||
async function handleDelete() {
|
|
||||||
const ok = await confirm({
|
|
||||||
title: "Delete payroll run?",
|
|
||||||
description: "This permanently removes the run and all its entries.",
|
|
||||||
confirmLabel: "Delete",
|
|
||||||
variant: "destructive",
|
|
||||||
})
|
|
||||||
if (ok) deleteMutation.mutate()
|
|
||||||
}
|
|
||||||
|
|
||||||
const columns: ColumnDef<Entry>[] = [
|
|
||||||
{
|
|
||||||
accessorKey: "employee",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const e = row.original.employee
|
|
||||||
if (!e) return `#${row.original.employee_id}`
|
|
||||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "hours_worked",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
|
||||||
cell: ({ row }) => fmtCurrency(row.original.hours_worked),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "base_salary",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
|
||||||
cell: ({ row }) => fmtCurrency(row.original.base_salary),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "commission_amount",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
|
||||||
cell: ({ row }) => fmtCurrency(row.original.commission_amount),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "allowances",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Allowances" />,
|
|
||||||
cell: ({ row }) => fmtCurrency(row.original.allowances),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "deductions",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
|
||||||
cell: ({ row }) => fmtCurrency(row.original.deductions),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "net_pay",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
|
||||||
cell: ({ row }) => <span className="font-semibold">{fmtCurrency(row.original.net_pay)}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "slip",
|
|
||||||
header: () => <span className="sr-only">Slip</span>,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<Button variant="ghost" size="icon" asChild>
|
|
||||||
<a
|
|
||||||
href={`/api/payroll/runs/${runId}/entries/${row.original.id}/slip`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
title="Download slip PDF"
|
|
||||||
>
|
|
||||||
<DownloadIcon className="size-4" />
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
if (isLoading && !run) {
|
|
||||||
return <DashboardPage>Loading...</DashboardPage>
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!run) {
|
|
||||||
return <DashboardPage>Run not found.</DashboardPage>
|
|
||||||
}
|
|
||||||
|
|
||||||
const entries = run.entries ?? []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: `${run.reference ?? `Payroll #${run.id}`} · ${formatDate(run.period_start)} → ${formatDate(run.period_end)}`,
|
|
||||||
actions: (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Badge variant={statusVariant(run.status)}>{formatEnum(run.status)}</Badge>
|
|
||||||
{run.status === "draft" && (
|
|
||||||
<>
|
|
||||||
<Button size="sm" variant="outline" disabled={regenerateMutation.isPending} onClick={() => regenerateMutation.mutate()}>
|
|
||||||
<RefreshCwIcon className="size-4" />
|
|
||||||
Regenerate
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" disabled={finalizeMutation.isPending} onClick={() => finalizeMutation.mutate()}>
|
|
||||||
<CheckCircle2Icon className="size-4" />
|
|
||||||
Finalize
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="destructive" disabled={deleteMutation.isPending} onClick={handleDelete}>
|
|
||||||
<Trash2 className="size-4" />
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{run.status === "finalized" && (
|
|
||||||
<Button size="sm" disabled={markPaidMutation.isPending} onClick={() => markPaidMutation.mutate()}>
|
|
||||||
<BanknoteIcon className="size-4" />
|
|
||||||
Mark Paid
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{totals && (
|
|
||||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 mb-4">
|
|
||||||
{[
|
|
||||||
{ label: "Gross Base", value: totals.gross_base },
|
|
||||||
{ label: "Commission", value: totals.commission },
|
|
||||||
{ label: "Allowances", value: totals.allowances },
|
|
||||||
{ label: "Deductions", value: totals.deductions },
|
|
||||||
{ label: "Net Total", value: totals.net_pay },
|
|
||||||
].map((t) => (
|
|
||||||
<Card key={t.label}>
|
|
||||||
<CardHeader className="pb-1">
|
|
||||||
<CardTitle className="text-xs font-medium text-muted-foreground">{t.label}</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-lg font-semibold">{fmtCurrency(t.value)}</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={columns}
|
|
||||||
data={entries}
|
|
||||||
pagination={{ page: 1, pageSize: entries.length || 10, pageCount: 1, total: entries.length }}
|
|
||||||
sorting={[]}
|
|
||||||
onChange={() => {}}
|
|
||||||
isLoading={false}
|
|
||||||
/>
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
|
||||||
import { PayrollRunForm } from "@/modules/payroll/payroll-run-form"
|
|
||||||
import { PAYROLL_ROUTES } from "@garage/api"
|
|
||||||
import type { PayrollClient } from "@garage/api"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { useRouter } from "next/navigation"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
type RunRow = {
|
|
||||||
id: number
|
|
||||||
reference?: string | null
|
|
||||||
period_start?: string
|
|
||||||
period_end?: string
|
|
||||||
status: string
|
|
||||||
entries_count?: number
|
|
||||||
generated_at?: string | null
|
|
||||||
finalized_at?: string | null
|
|
||||||
paid_at?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
|
||||||
if (status === "paid") return "default"
|
|
||||||
if (status === "finalized") return "outline"
|
|
||||||
return "secondary"
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PayrollPage() {
|
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ResourcePage<PayrollClient>
|
|
||||||
pageTitle="Payroll"
|
|
||||||
routeKey={PAYROLL_ROUTES.RUNS_INDEX}
|
|
||||||
getClient={(api) => api.payroll}
|
|
||||||
statusFilter={{
|
|
||||||
statuses: ["draft", "finalized", "paid"],
|
|
||||||
paramKey: "status",
|
|
||||||
}}
|
|
||||||
onRowClick={(row) => router.push(`/productivity/payroll/${(row as any).id}`)}
|
|
||||||
headerProps={({ invalidateQuery }) => ({
|
|
||||||
actions: (
|
|
||||||
<FormDialog title="Payroll Run">
|
|
||||||
{() => (
|
|
||||||
<PayrollRunForm
|
|
||||||
onSuccess={(runId) => {
|
|
||||||
invalidateQuery()
|
|
||||||
if (runId) router.push(`/productivity/payroll/${runId}`)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</FormDialog>
|
|
||||||
),
|
|
||||||
})}
|
|
||||||
columns={({ actionsColumn }) => [
|
|
||||||
{
|
|
||||||
accessorKey: "reference",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Reference" />,
|
|
||||||
cell: ({ row }) => <span className="font-mono text-xs">{(row.original as any).reference ?? `#${(row.original as any).id}`}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "period_start",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Period Start" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).period_start),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "period_end",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Period End" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).period_end),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "entries_count",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Entries" />,
|
|
||||||
cell: ({ row }) => (row.original as any).entries_count ?? "—",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "status",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const s = (row.original as any).status as string
|
|
||||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "finalized_at",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Finalized" />,
|
|
||||||
cell: ({ row }) => formatDate((row.original as any).finalized_at),
|
|
||||||
},
|
|
||||||
actionsColumn({ onEdit: undefined }),
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,163 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useMemo, useState } from "react"
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
|
||||||
import { LogInIcon, LogOutIcon, TimerIcon, SearchIcon } from "lucide-react"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
|
||||||
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Input } from "@/shared/components/ui/input"
|
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
|
||||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
|
||||||
|
|
||||||
type Employee = {
|
|
||||||
id: number
|
|
||||||
first_name?: string
|
|
||||||
last_name?: string
|
|
||||||
email?: string
|
|
||||||
designation?: string
|
|
||||||
department?: { id?: number; name?: string }
|
|
||||||
track_attendance?: boolean
|
|
||||||
has_active_time_sheet?: boolean
|
|
||||||
active_time_sheet?: { id?: number; clock_in?: string; date?: string } | null
|
|
||||||
status?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialsOf(first?: string | null, last?: string | null) {
|
|
||||||
const f = (first ?? "").trim()[0] ?? ""
|
|
||||||
const l = (last ?? "").trim()[0] ?? ""
|
|
||||||
return (f + l).toUpperCase() || "?"
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTime(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
return value.length >= 5 ? value.slice(0, 5) : value
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TimeClocksPage() {
|
|
||||||
const api = useAuthApi()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
const [search, setSearch] = useState("")
|
|
||||||
|
|
||||||
const employeesQuery = useQuery({
|
|
||||||
queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }],
|
|
||||||
queryFn: () => api.employees.list({ per_page: 100, status: "active" } as any) as Promise<{ data: Employee[] }>,
|
|
||||||
})
|
|
||||||
|
|
||||||
const employees: Employee[] = useMemo(() => {
|
|
||||||
const rows: Employee[] = (employeesQuery.data as any)?.data ?? []
|
|
||||||
if (!search) return rows
|
|
||||||
const q = search.toLowerCase()
|
|
||||||
return rows.filter((e) => {
|
|
||||||
const name = `${e.first_name ?? ""} ${e.last_name ?? ""}`.toLowerCase()
|
|
||||||
return name.includes(q) || (e.email ?? "").toLowerCase().includes(q)
|
|
||||||
})
|
|
||||||
}, [employeesQuery.data, search])
|
|
||||||
|
|
||||||
const refetch = () => queryClient.invalidateQueries({ queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }] })
|
|
||||||
|
|
||||||
const clockInMutation = useMutation({
|
|
||||||
mutationFn: (employeeId: number) => api.timeSheets.clockIn({ employee_id: employeeId } as any),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Clocked in")
|
|
||||||
refetch()
|
|
||||||
},
|
|
||||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock in"),
|
|
||||||
})
|
|
||||||
|
|
||||||
const clockOutMutation = useMutation({
|
|
||||||
mutationFn: (timeSheetId: number) => api.timeSheets.clockOut({ time_sheet_id: timeSheetId } as any),
|
|
||||||
onSuccess: () => {
|
|
||||||
toast.success("Clocked out")
|
|
||||||
refetch()
|
|
||||||
},
|
|
||||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock out"),
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: "Time Clocks",
|
|
||||||
actions: (
|
|
||||||
<div className="relative w-64">
|
|
||||||
<SearchIcon className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
|
|
||||||
<Input
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search employees..."
|
|
||||||
className="pl-8"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{employeesQuery.isLoading ? (
|
|
||||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
|
||||||
) : employees.length === 0 ? (
|
|
||||||
<p className="text-sm text-muted-foreground">No employees found.</p>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
|
||||||
{employees.map((emp) => {
|
|
||||||
const fullName = `${emp.first_name ?? ""} ${emp.last_name ?? ""}`.trim() || emp.email
|
|
||||||
const isClockedIn = !!emp.has_active_time_sheet
|
|
||||||
const activeId = emp.active_time_sheet?.id
|
|
||||||
const clockedInAt = emp.active_time_sheet?.clock_in
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card key={emp.id}>
|
|
||||||
<CardContent className="flex items-center justify-between gap-3 p-4">
|
|
||||||
<div className="flex items-center gap-3 min-w-0">
|
|
||||||
<Avatar size="lg">
|
|
||||||
<AvatarFallback>{initialsOf(emp.first_name, emp.last_name)}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="min-w-0">
|
|
||||||
<div className="font-medium truncate">{fullName}</div>
|
|
||||||
<div className="text-xs text-muted-foreground truncate">
|
|
||||||
{emp.designation ?? emp.department?.name ?? emp.email}
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 flex items-center gap-2">
|
|
||||||
{isClockedIn ? (
|
|
||||||
<Badge variant="default" className="gap-1">
|
|
||||||
<TimerIcon className="size-3" />
|
|
||||||
Since {formatTime(clockedInAt)}
|
|
||||||
</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge variant="secondary">Idle</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{isClockedIn && activeId ? (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="destructive"
|
|
||||||
disabled={clockOutMutation.isPending}
|
|
||||||
onClick={() => clockOutMutation.mutate(activeId)}
|
|
||||||
>
|
|
||||||
<LogOutIcon className="size-4" />
|
|
||||||
Clock Out
|
|
||||||
</Button>
|
|
||||||
) : (
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
disabled={clockInMutation.isPending}
|
|
||||||
onClick={() => clockInMutation.mutate(emp.id)}
|
|
||||||
>
|
|
||||||
<LogInIcon className="size-4" />
|
|
||||||
Clock In
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</DashboardPage>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
|
||||||
import { TIME_SHEET_ROUTES } from "@garage/api"
|
|
||||||
import type { TimeSheetsClient } from "@garage/api"
|
|
||||||
import { ClockIcon } from "lucide-react"
|
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
|
||||||
|
|
||||||
function formatDate(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
const d = new Date(value)
|
|
||||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatTime(value: unknown) {
|
|
||||||
if (!value || typeof value !== "string") return "—"
|
|
||||||
return value.length >= 5 ? value.slice(0, 5) : value
|
|
||||||
}
|
|
||||||
|
|
||||||
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
|
|
||||||
general: "secondary",
|
|
||||||
order: "default",
|
|
||||||
task: "outline",
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function TimeSheetsPage() {
|
|
||||||
return (
|
|
||||||
<ResourcePage<TimeSheetsClient>
|
|
||||||
pageTitle="Time Sheets"
|
|
||||||
routeKey={TIME_SHEET_ROUTES.INDEX}
|
|
||||||
getClient={(api) => api.timeSheets}
|
|
||||||
statusFilter={{
|
|
||||||
statuses: ["general", "order", "task"],
|
|
||||||
paramKey: "activity_type",
|
|
||||||
allLabel: "All",
|
|
||||||
}}
|
|
||||||
columns={({ actionsColumn }) => [
|
|
||||||
{
|
|
||||||
accessorKey: "date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
|
||||||
cell: ({ row }) => (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ClockIcon className="size-4 text-muted-foreground" />
|
|
||||||
<span>{formatDate((row.original as any).date)}</span>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "employee",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const e = (row.original as any).employee
|
|
||||||
if (!e) return "—"
|
|
||||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "clock_in",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
|
|
||||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "clock_out",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
|
|
||||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "duration",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
|
|
||||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "activity_type",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const t = (row.original as any).activity_type ?? "general"
|
|
||||||
return <Badge variant={ACTIVITY_VARIANT[t] ?? "secondary"}>{formatEnum(t)}</Badge>
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "calculated_total_cost",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const v = (row.original as any).calculated_total_cost
|
|
||||||
if (v == null) return "—"
|
|
||||||
const n = Number(v)
|
|
||||||
return Number.isFinite(n) ? n.toFixed(2) : "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
actionsColumn({ onEdit: undefined }),
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
@@ -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,
|
||||||
|
|||||||
@@ -142,10 +142,11 @@ 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: "Leave Requests", href: "/productivity/leave-requests", icon: <CalendarIcon /> },
|
// { title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
|
||||||
{ title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
// { title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
|
||||||
|
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||||
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
// { title: "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 /> },
|
||||||
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||||
|
|||||||
@@ -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't have an account? <a href="#">Sign up</a>
|
|
||||||
</FieldDescription> */}
|
|
||||||
</Field>
|
</Field>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useRef, useState } from "react"
|
|
||||||
import { useMutation } from "@tanstack/react-query"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { useForm } from "react-hook-form"
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod"
|
|
||||||
import { z } from "zod"
|
|
||||||
import { UploadIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Input } from "@/shared/components/ui/input"
|
|
||||||
import { Textarea } from "@/shared/components/ui/textarea"
|
|
||||||
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
|
|
||||||
const schema = z.object({
|
|
||||||
name: z.string().trim().min(1, "Name is required").max(150),
|
|
||||||
issuer: z.string().trim().max(150).optional(),
|
|
||||||
certificate_number: z.string().trim().max(100).optional(),
|
|
||||||
issued_date: z.string().optional(),
|
|
||||||
expiry_date: z.string().optional(),
|
|
||||||
notes: z.string().max(2000).optional(),
|
|
||||||
})
|
|
||||||
|
|
||||||
type FormValues = z.infer<typeof schema>
|
|
||||||
|
|
||||||
export type EmployeeCertificationFormProps = {
|
|
||||||
employeeId: string
|
|
||||||
onSuccess?: () => void
|
|
||||||
onCancel?: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EmployeeCertificationForm({ employeeId, onSuccess, onCancel }: EmployeeCertificationFormProps) {
|
|
||||||
const api = useAuthApi()
|
|
||||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
|
||||||
const [file, setFile] = useState<File | null>(null)
|
|
||||||
|
|
||||||
const {
|
|
||||||
register,
|
|
||||||
handleSubmit,
|
|
||||||
formState: { errors },
|
|
||||||
reset,
|
|
||||||
} = useForm<FormValues>({
|
|
||||||
resolver: zodResolver(schema),
|
|
||||||
defaultValues: {
|
|
||||||
name: "", issuer: "", certificate_number: "",
|
|
||||||
issued_date: "", expiry_date: "", notes: "",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const mutation = useMutation({
|
|
||||||
mutationFn: (values: FormValues) => {
|
|
||||||
const promise = api.employees.createCertification(employeeId, {
|
|
||||||
name: values.name,
|
|
||||||
issuer: values.issuer || undefined,
|
|
||||||
certificate_number: values.certificate_number || undefined,
|
|
||||||
issued_date: values.issued_date || undefined,
|
|
||||||
expiry_date: values.expiry_date || undefined,
|
|
||||||
notes: values.notes || undefined,
|
|
||||||
file: file ?? undefined,
|
|
||||||
})
|
|
||||||
toast.promise(promise, {
|
|
||||||
loading: "Saving certification...",
|
|
||||||
success: "Certification added",
|
|
||||||
error: (err: any) => err?.message ?? "Failed to save",
|
|
||||||
})
|
|
||||||
return promise
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
reset()
|
|
||||||
setFile(null)
|
|
||||||
onSuccess?.()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Name</FieldLabel>
|
|
||||||
<Input {...register("name")} placeholder="e.g. ASE A1 Engine Repair" />
|
|
||||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Issuer</FieldLabel>
|
|
||||||
<Input {...register("issuer")} placeholder="ASE / SAE / ..." />
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Certificate Number</FieldLabel>
|
|
||||||
<Input {...register("certificate_number")} placeholder="Optional" />
|
|
||||||
</Field>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Issued Date</FieldLabel>
|
|
||||||
<Input type="date" {...register("issued_date")} />
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Expiry Date</FieldLabel>
|
|
||||||
<Input type="date" {...register("expiry_date")} />
|
|
||||||
</Field>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Attachment (optional)</FieldLabel>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
|
|
||||||
<UploadIcon className="size-4" />
|
|
||||||
Choose file
|
|
||||||
</Button>
|
|
||||||
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
|
|
||||||
<input
|
|
||||||
ref={fileRef}
|
|
||||||
type="file"
|
|
||||||
className="hidden"
|
|
||||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx"
|
|
||||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Notes</FieldLabel>
|
|
||||||
<Textarea rows={3} {...register("notes")} />
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-2">
|
|
||||||
{onCancel && (
|
|
||||||
<Button type="button" variant="outline" onClick={onCancel}>Cancel</Button>
|
|
||||||
)}
|
|
||||||
<Button type="submit" disabled={mutation.isPending}>
|
|
||||||
{mutation.isPending ? "Saving..." : "Save Certification"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useRef, useState } from "react"
|
|
||||||
import { useMutation } from "@tanstack/react-query"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { useForm } from "react-hook-form"
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod"
|
|
||||||
import { z } from "zod"
|
|
||||||
import { UploadIcon } from "lucide-react"
|
|
||||||
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Input } from "@/shared/components/ui/input"
|
|
||||||
import { Textarea } from "@/shared/components/ui/textarea"
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/shared/components/ui/select"
|
|
||||||
import { Field, FieldLabel, FieldError } from "@/shared/components/ui/field"
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
|
|
||||||
const DOCUMENT_TYPES = [
|
|
||||||
{ value: "contract", label: "Contract" },
|
|
||||||
{ value: "id", label: "ID / Passport" },
|
|
||||||
{ value: "ase", label: "ASE" },
|
|
||||||
{ value: "certification", label: "Certification" },
|
|
||||||
{ value: "other", label: "Other" },
|
|
||||||
] as const
|
|
||||||
|
|
||||||
const schema = z.object({
|
|
||||||
name: z.string().trim().min(1, "Name is required").max(150),
|
|
||||||
type: z.enum(["contract", "id", "ase", "certification", "other"]),
|
|
||||||
issued_date: z.string().optional(),
|
|
||||||
expiry_date: z.string().optional(),
|
|
||||||
notes: z.string().max(2000).optional(),
|
|
||||||
})
|
|
||||||
|
|
||||||
type FormValues = z.infer<typeof schema>
|
|
||||||
|
|
||||||
export type EmployeeDocumentFormProps = {
|
|
||||||
employeeId: string
|
|
||||||
onSuccess?: () => void
|
|
||||||
onCancel?: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EmployeeDocumentForm({ employeeId, onSuccess, onCancel }: EmployeeDocumentFormProps) {
|
|
||||||
const api = useAuthApi()
|
|
||||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
|
||||||
const [file, setFile] = useState<File | null>(null)
|
|
||||||
|
|
||||||
const {
|
|
||||||
register,
|
|
||||||
handleSubmit,
|
|
||||||
setValue,
|
|
||||||
watch,
|
|
||||||
formState: { errors },
|
|
||||||
reset,
|
|
||||||
} = useForm<FormValues>({
|
|
||||||
resolver: zodResolver(schema),
|
|
||||||
defaultValues: { name: "", type: "other", issued_date: "", expiry_date: "", notes: "" },
|
|
||||||
})
|
|
||||||
|
|
||||||
const type = watch("type")
|
|
||||||
|
|
||||||
const mutation = useMutation({
|
|
||||||
mutationFn: (values: FormValues) => {
|
|
||||||
if (!file) throw new Error("Select a file to upload.")
|
|
||||||
const promise = api.employees.uploadDocument(employeeId, {
|
|
||||||
file,
|
|
||||||
name: values.name,
|
|
||||||
type: values.type,
|
|
||||||
issued_date: values.issued_date || undefined,
|
|
||||||
expiry_date: values.expiry_date || undefined,
|
|
||||||
notes: values.notes || undefined,
|
|
||||||
})
|
|
||||||
toast.promise(promise, {
|
|
||||||
loading: "Uploading document...",
|
|
||||||
success: "Document uploaded",
|
|
||||||
error: (err: any) => err?.message ?? "Failed to upload",
|
|
||||||
})
|
|
||||||
return promise
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
reset()
|
|
||||||
setFile(null)
|
|
||||||
onSuccess?.()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form className="grid gap-4" onSubmit={handleSubmit((v) => mutation.mutate(v))}>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>File</FieldLabel>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Button type="button" variant="outline" size="sm" onClick={() => fileRef.current?.click()}>
|
|
||||||
<UploadIcon className="size-4" />
|
|
||||||
Choose file
|
|
||||||
</Button>
|
|
||||||
<span className="text-sm text-muted-foreground">{file ? file.name : "No file selected"}</span>
|
|
||||||
<input
|
|
||||||
ref={fileRef}
|
|
||||||
type="file"
|
|
||||||
className="hidden"
|
|
||||||
accept=".pdf,.jpg,.jpeg,.png,.webp,.doc,.docx,.xls,.xlsx"
|
|
||||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{!file && mutation.isError && (
|
|
||||||
<FieldError>Select a file before uploading.</FieldError>
|
|
||||||
)}
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Name</FieldLabel>
|
|
||||||
<Input {...register("name")} placeholder="e.g. Employment contract 2026" />
|
|
||||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Type</FieldLabel>
|
|
||||||
<Select value={type} onValueChange={(v) => setValue("type", v as FormValues["type"], { shouldValidate: true })}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Select type" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{DOCUMENT_TYPES.map((o) => (
|
|
||||||
<SelectItem key={o.value} value={o.value}>
|
|
||||||
{o.label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Issued Date</FieldLabel>
|
|
||||||
<Input type="date" {...register("issued_date")} />
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Expiry Date</FieldLabel>
|
|
||||||
<Input type="date" {...register("expiry_date")} />
|
|
||||||
</Field>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Notes</FieldLabel>
|
|
||||||
<Textarea rows={3} {...register("notes")} placeholder="Optional" />
|
|
||||||
</Field>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-2">
|
|
||||||
{onCancel && (
|
|
||||||
<Button type="button" variant="outline" onClick={onCancel}>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button type="submit" disabled={mutation.isPending}>
|
|
||||||
{mutation.isPending ? "Uploading..." : "Upload"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,16 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { AlertTriangle, ImageIcon, Plus, Save, UploadIcon } from "lucide-react"
|
import { AlertTriangle, Plus, Save } from "lucide-react"
|
||||||
import { useRef, useState } from "react"
|
|
||||||
|
|
||||||
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"
|
||||||
import { FieldGroup } from "@/shared/components/ui/field"
|
import { FieldGroup } from "@/shared/components/ui/field"
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
|
|
||||||
import { Separator } from "@/shared/components/ui/separator"
|
|
||||||
import {
|
import {
|
||||||
Rhform,
|
Rhform,
|
||||||
RhfTextField,
|
RhfTextField,
|
||||||
RhfSelectField,
|
RhfSelectField,
|
||||||
RhfAsyncSelectField,
|
RhfAsyncSelectField,
|
||||||
RhfCheckboxField,
|
RhfCheckboxField,
|
||||||
RhfTextareaField,
|
|
||||||
} 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"
|
||||||
@@ -28,18 +24,27 @@ import {
|
|||||||
STATUS_OPTIONS,
|
STATUS_OPTIONS,
|
||||||
TYPE_OPTIONS,
|
TYPE_OPTIONS,
|
||||||
WAGE_TYPE_OPTIONS,
|
WAGE_TYPE_OPTIONS,
|
||||||
GENDER_OPTIONS,
|
|
||||||
MARITAL_OPTIONS,
|
|
||||||
} from "./employee.schema"
|
} from "./employee.schema"
|
||||||
import { EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, SHOP_TIMING_ROUTES, SHOP_CALENDAR_ROUTES, GEO_ROUTES } from "@garage/api"
|
import { EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, SHOP_TIMING_ROUTES, SHOP_CALENDAR_ROUTES, GEO_ROUTES } from "@garage/api"
|
||||||
|
|
||||||
const titleCase = (v: string) => v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
|
// ── Constants ──
|
||||||
|
|
||||||
const STATUS_SELECT_OPTIONS = STATUS_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
const STATUS_SELECT_OPTIONS = STATUS_OPTIONS.map((v) => ({
|
||||||
const TYPE_SELECT_OPTIONS = TYPE_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
value: v,
|
||||||
const WAGE_TYPE_SELECT_OPTIONS = WAGE_TYPE_OPTIONS.map((v) => ({ value: v, label: v }))
|
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||||
const GENDER_SELECT_OPTIONS = GENDER_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
}))
|
||||||
const MARITAL_SELECT_OPTIONS = MARITAL_OPTIONS.map((v) => ({ value: v, label: titleCase(v) }))
|
|
||||||
|
const TYPE_SELECT_OPTIONS = TYPE_OPTIONS.map((v) => ({
|
||||||
|
value: v,
|
||||||
|
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const WAGE_TYPE_SELECT_OPTIONS = WAGE_TYPE_OPTIONS.map((v) => ({
|
||||||
|
value: v,
|
||||||
|
label: v,
|
||||||
|
}))
|
||||||
|
|
||||||
|
// ── Props ──
|
||||||
|
|
||||||
export type EmployeeFormProps = {
|
export type EmployeeFormProps = {
|
||||||
resourceId?: string | null
|
resourceId?: string | null
|
||||||
@@ -47,6 +52,8 @@ export type EmployeeFormProps = {
|
|||||||
onSuccess?: () => void
|
onSuccess?: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Default values ──
|
||||||
|
|
||||||
const DEFAULT_VALUES: EmployeeFormValues = {
|
const DEFAULT_VALUES: EmployeeFormValues = {
|
||||||
department: null,
|
department: null,
|
||||||
country: null,
|
country: null,
|
||||||
@@ -66,28 +73,12 @@ const DEFAULT_VALUES: EmployeeFormValues = {
|
|||||||
track_attendance: true,
|
track_attendance: true,
|
||||||
notify_owner_when_punch_in_out: false,
|
notify_owner_when_punch_in_out: false,
|
||||||
geo_fence_radius: null,
|
geo_fence_radius: null,
|
||||||
address: "",
|
|
||||||
date_of_birth: "",
|
|
||||||
gender: null,
|
|
||||||
marital_status: null,
|
|
||||||
national_id: "",
|
|
||||||
hire_date: "",
|
|
||||||
emergency_contact_name: "",
|
|
||||||
emergency_contact_phone: "",
|
|
||||||
bank_name: "",
|
|
||||||
bank_account_number: "",
|
|
||||||
bank_iban: "",
|
|
||||||
hourly_rate: null,
|
|
||||||
commission_rate: null,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Mapping helpers ──
|
||||||
|
|
||||||
function mapToFormValues(data: unknown): EmployeeFormValues {
|
function mapToFormValues(data: unknown): EmployeeFormValues {
|
||||||
const d = (data as any)?.data ?? data ?? {}
|
const d = (data as any)?.data ?? data ?? {}
|
||||||
const formatDate = (v: unknown): string => {
|
|
||||||
if (!v) return ""
|
|
||||||
const s = String(v)
|
|
||||||
return s.length >= 10 ? s.slice(0, 10) : s
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
department: toRelation(d.department_id, d.department?.name),
|
department: toRelation(d.department_id, d.department?.name),
|
||||||
@@ -108,19 +99,6 @@ function mapToFormValues(data: unknown): EmployeeFormValues {
|
|||||||
track_attendance: d.track_attendance ?? true,
|
track_attendance: d.track_attendance ?? true,
|
||||||
notify_owner_when_punch_in_out: d.notify_owner_when_punch_in_out ?? false,
|
notify_owner_when_punch_in_out: d.notify_owner_when_punch_in_out ?? false,
|
||||||
geo_fence_radius: d.geo_fence_radius ?? null,
|
geo_fence_radius: d.geo_fence_radius ?? null,
|
||||||
address: d.address || "",
|
|
||||||
date_of_birth: formatDate(d.date_of_birth),
|
|
||||||
gender: d.gender ?? null,
|
|
||||||
marital_status: d.marital_status ?? null,
|
|
||||||
national_id: d.national_id || "",
|
|
||||||
hire_date: formatDate(d.hire_date),
|
|
||||||
emergency_contact_name: d.emergency_contact_name || "",
|
|
||||||
emergency_contact_phone: d.emergency_contact_phone || "",
|
|
||||||
bank_name: d.bank_name || "",
|
|
||||||
bank_account_number: d.bank_account_number || "",
|
|
||||||
bank_iban: d.bank_iban || "",
|
|
||||||
hourly_rate: d.hourly_rate ?? null,
|
|
||||||
commission_rate: d.commission_rate ?? null,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +112,7 @@ function mapFormToPayload(values: EmployeeFormValues) {
|
|||||||
first_name: values.first_name,
|
first_name: values.first_name,
|
||||||
last_name: values.last_name,
|
last_name: values.last_name,
|
||||||
email: values.email,
|
email: values.email,
|
||||||
password: values.password || undefined,
|
password: values.password,
|
||||||
phone: values.phone || undefined,
|
phone: values.phone || undefined,
|
||||||
designation: values.designation || undefined,
|
designation: values.designation || undefined,
|
||||||
salary: values.salary ?? undefined,
|
salary: values.salary ?? undefined,
|
||||||
@@ -144,22 +122,11 @@ function mapFormToPayload(values: EmployeeFormValues) {
|
|||||||
track_attendance: values.track_attendance,
|
track_attendance: values.track_attendance,
|
||||||
notify_owner_when_punch_in_out: values.notify_owner_when_punch_in_out,
|
notify_owner_when_punch_in_out: values.notify_owner_when_punch_in_out,
|
||||||
geo_fence_radius: values.geo_fence_radius ?? undefined,
|
geo_fence_radius: values.geo_fence_radius ?? undefined,
|
||||||
address: values.address || undefined,
|
|
||||||
date_of_birth: values.date_of_birth || undefined,
|
|
||||||
gender: values.gender ?? undefined,
|
|
||||||
marital_status: values.marital_status ?? undefined,
|
|
||||||
national_id: values.national_id || undefined,
|
|
||||||
hire_date: values.hire_date || undefined,
|
|
||||||
emergency_contact_name: values.emergency_contact_name || undefined,
|
|
||||||
emergency_contact_phone: values.emergency_contact_phone || undefined,
|
|
||||||
bank_name: values.bank_name || undefined,
|
|
||||||
bank_account_number: values.bank_account_number || undefined,
|
|
||||||
bank_iban: values.bank_iban || undefined,
|
|
||||||
hourly_rate: values.hourly_rate ?? undefined,
|
|
||||||
commission_rate: values.commission_rate ?? undefined,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Shared mapOption for async selects ──
|
||||||
|
|
||||||
const mapLookupOption = (item: any) => ({
|
const mapLookupOption = (item: any) => ({
|
||||||
value: String(item.id),
|
value: String(item.id),
|
||||||
label: item.name ?? item.title ?? String(item.id),
|
label: item.name ?? item.title ?? String(item.id),
|
||||||
@@ -167,71 +134,7 @@ 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 }
|
||||||
|
|
||||||
function SectionHeading({ title, description }: { title: string; description?: string }) {
|
// ── Component ──
|
||||||
return (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<h3 className="text-sm font-semibold">{title}</h3>
|
|
||||||
{description && <p className="text-xs text-muted-foreground">{description}</p>}
|
|
||||||
<Separator className="mt-2" />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function AvatarUpload({ employeeId, initialUrl }: { employeeId: string; initialUrl?: string | null }) {
|
|
||||||
const api = useAuthApi()
|
|
||||||
const inputRef = useRef<HTMLInputElement | null>(null)
|
|
||||||
const [previewUrl, setPreviewUrl] = useState<string | null>(initialUrl ?? null)
|
|
||||||
const [uploading, setUploading] = useState(false)
|
|
||||||
|
|
||||||
async function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
||||||
const file = e.target.files?.[0]
|
|
||||||
if (!file) return
|
|
||||||
|
|
||||||
setUploading(true)
|
|
||||||
try {
|
|
||||||
const res: any = await api.employees.uploadAvatar(employeeId, file)
|
|
||||||
const url = res?.data?.avatar_url ?? URL.createObjectURL(file)
|
|
||||||
setPreviewUrl(url)
|
|
||||||
toast.success("Avatar updated")
|
|
||||||
} catch (err: any) {
|
|
||||||
toast.error(err?.message ?? "Failed to upload avatar")
|
|
||||||
} finally {
|
|
||||||
setUploading(false)
|
|
||||||
e.target.value = ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<Avatar size="lg">
|
|
||||||
{previewUrl ? <AvatarImage src={previewUrl} alt="Avatar" /> : null}
|
|
||||||
<AvatarFallback>
|
|
||||||
<ImageIcon className="size-5 text-muted-foreground" />
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
disabled={uploading}
|
|
||||||
onClick={() => inputRef.current?.click()}
|
|
||||||
>
|
|
||||||
<UploadIcon className="size-4" />
|
|
||||||
{uploading ? "Uploading..." : "Upload photo"}
|
|
||||||
</Button>
|
|
||||||
<p className="mt-1 text-xs text-muted-foreground">JPG, PNG, WEBP. Max 5 MB.</p>
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
type="file"
|
|
||||||
accept="image/jpeg,image/png,image/webp"
|
|
||||||
className="hidden"
|
|
||||||
onChange={handleFileChange}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFormProps) {
|
export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFormProps) {
|
||||||
const api = useAuthApi()
|
const api = useAuthApi()
|
||||||
@@ -265,9 +168,6 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const initialAvatarUrl = (initialData as any)?.avatar_url
|
|
||||||
?? ((initialData as any)?.avatar_path ? `/storage/${(initialData as any).avatar_path}` : null)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
||||||
{error && (
|
{error && (
|
||||||
@@ -281,67 +181,19 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<FieldGroup>
|
<FieldGroup>
|
||||||
{/* Personal */}
|
|
||||||
<SectionHeading title="Personal" />
|
|
||||||
|
|
||||||
{isEditing && resourceId ? (
|
|
||||||
<AvatarUpload employeeId={resourceId} initialUrl={initialAvatarUrl} />
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
<RhfTextField name="first_name" label="First Name" placeholder="Jane" required />
|
<RhfTextField name="first_name" label="First Name" placeholder="Jane" required />
|
||||||
<RhfTextField name="last_name" label="Last Name" placeholder="Smith" required />
|
<RhfTextField name="last_name" label="Last Name" placeholder="Smith" required />
|
||||||
</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">
|
||||||
<RhfTextField name="date_of_birth" label="Date of Birth" type="date" />
|
<RhfTextField name="email" label="Email" placeholder="jane@example.com" type="email" />
|
||||||
<RhfTextField name="national_id" label="National ID" placeholder="A1234567" />
|
<RhfTextField name="password" label="Password" placeholder="At least 6 characters" type="password" required />
|
||||||
</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">
|
||||||
<RhfSelectField name="gender" label="Gender" placeholder="Select gender" options={GENDER_SELECT_OPTIONS} />
|
<RhfTextField name="phone" label="Phone" placeholder="0501234567" type="tel" />
|
||||||
<RhfSelectField name="marital_status" label="Marital Status" placeholder="Select status" options={MARITAL_SELECT_OPTIONS} />
|
<RhfTextField name="designation" label="Designation" placeholder="Technician" />
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Contact */}
|
|
||||||
<SectionHeading title="Contact" />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="email" label="Email" placeholder="jane@example.com" type="email" required />
|
|
||||||
<RhfTextField name="password" label="Password" placeholder={isEditing ? "Leave blank to keep" : "At least 6 characters"} type="password" required={!isEditing} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="phone" label="Phone" placeholder="+971501234567" type="tel" />
|
|
||||||
<RhfAsyncSelectField
|
|
||||||
name="country"
|
|
||||||
label="Country"
|
|
||||||
placeholder="Select country"
|
|
||||||
queryKey={[GEO_ROUTES.COUNTRIES]}
|
|
||||||
listFn={() => api.geo.countries()}
|
|
||||||
mapOption={mapLookupOption}
|
|
||||||
{...STORE_OBJECT}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<RhfTextareaField name="address" label="Address" placeholder="Street, city, region..." rows={2} />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="emergency_contact_name" label="Emergency Contact Name" placeholder="Full name" />
|
|
||||||
<RhfTextField name="emergency_contact_phone" label="Emergency Contact Phone" type="tel" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Employment */}
|
|
||||||
<SectionHeading title="Employment" />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="hire_date" label="Hire Date" type="date" />
|
|
||||||
<RhfTextField name="designation" label="Designation" placeholder="Senior Technician" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfSelectField name="type" label="Type" placeholder="Select type" options={TYPE_SELECT_OPTIONS} />
|
|
||||||
<RhfSelectField name="status" label="Status" placeholder="Select status" options={STATUS_SELECT_OPTIONS} />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
@@ -357,32 +209,41 @@ export function EmployeeForm({ resourceId, initialData, onSuccess }: EmployeeFor
|
|||||||
<RhfTextField name="role_id" label="Role ID" placeholder="1" type="number" />
|
<RhfTextField name="role_id" label="Role ID" placeholder="1" type="number" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Compensation */}
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
<SectionHeading title="Compensation" />
|
<RhfSelectField
|
||||||
|
name="status"
|
||||||
|
label="Status"
|
||||||
|
placeholder="Select status"
|
||||||
|
options={STATUS_SELECT_OPTIONS}
|
||||||
|
/>
|
||||||
|
<RhfSelectField
|
||||||
|
name="type"
|
||||||
|
label="Type"
|
||||||
|
placeholder="Select type"
|
||||||
|
options={TYPE_SELECT_OPTIONS}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
<RhfSelectField name="wage_type" label="Wage Type" placeholder="Select wage type" options={WAGE_TYPE_SELECT_OPTIONS} />
|
|
||||||
<RhfTextField name="salary" label="Salary" placeholder="0" type="number" />
|
<RhfTextField name="salary" label="Salary" placeholder="0" type="number" />
|
||||||
|
<RhfSelectField
|
||||||
|
name="wage_type"
|
||||||
|
label="Wage Type"
|
||||||
|
placeholder="Select wage type"
|
||||||
|
options={WAGE_TYPE_SELECT_OPTIONS}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<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="hourly_rate" label="Hourly Rate" placeholder="0.00" type="number" />
|
<RhfAsyncSelectField
|
||||||
<RhfTextField name="commission_rate" label="Commission (%)" placeholder="0" type="number" />
|
name="country"
|
||||||
</div>
|
label="Country"
|
||||||
|
placeholder="Select country"
|
||||||
{/* Bank */}
|
queryKey={[GEO_ROUTES.COUNTRIES]}
|
||||||
<SectionHeading title="Bank" description="Used for payroll payouts." />
|
listFn={() => api.geo.countries()}
|
||||||
|
mapOption={mapLookupOption}
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
{...STORE_OBJECT}
|
||||||
<RhfTextField name="bank_name" label="Bank Name" placeholder="Bank of ..." />
|
/>
|
||||||
<RhfTextField name="bank_account_number" label="Account Number" placeholder="000123456789" />
|
|
||||||
</div>
|
|
||||||
<RhfTextField name="bank_iban" label="IBAN" placeholder="AE00 0000 0000 0000 0000 000" />
|
|
||||||
|
|
||||||
{/* Tracking */}
|
|
||||||
<SectionHeading title="Attendance Tracking" />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfAsyncSelectField
|
<RhfAsyncSelectField
|
||||||
name="shop_calender"
|
name="shop_calender"
|
||||||
label="Shop Calendar"
|
label="Shop Calendar"
|
||||||
|
|||||||
@@ -9,15 +9,6 @@ import {
|
|||||||
Calendar,
|
Calendar,
|
||||||
BadgeCheck,
|
BadgeCheck,
|
||||||
CircleDot,
|
CircleDot,
|
||||||
Cake,
|
|
||||||
Heart,
|
|
||||||
IdCard,
|
|
||||||
Home,
|
|
||||||
PhoneCall,
|
|
||||||
Landmark,
|
|
||||||
Wallet,
|
|
||||||
PercentIcon,
|
|
||||||
DollarSign,
|
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -25,7 +16,6 @@ import {
|
|||||||
CardHeader,
|
CardHeader,
|
||||||
CardTitle,
|
CardTitle,
|
||||||
} from "@/shared/components/ui/card"
|
} from "@/shared/components/ui/card"
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/shared/components/ui/avatar"
|
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { Separator } from "@/shared/components/ui/separator"
|
import { Separator } from "@/shared/components/ui/separator"
|
||||||
import { formatEnum } from "@/shared/utils/formatters"
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
@@ -48,22 +38,6 @@ type EmployeeData = {
|
|||||||
department?: { id?: number; name?: string } | null
|
department?: { id?: number; name?: string } | null
|
||||||
shop_calender?: { id?: number; title?: string } | null
|
shop_calender?: { id?: number; title?: string } | null
|
||||||
shop_timing?: { id?: number; title?: string } | null
|
shop_timing?: { id?: number; title?: string } | null
|
||||||
role?: { id?: number; name?: string } | null
|
|
||||||
avatar_url?: string | null
|
|
||||||
avatar_path?: string | null
|
|
||||||
address?: string | null
|
|
||||||
date_of_birth?: string | null
|
|
||||||
gender?: string | null
|
|
||||||
marital_status?: string | null
|
|
||||||
national_id?: string | null
|
|
||||||
hire_date?: string | null
|
|
||||||
emergency_contact_name?: string | null
|
|
||||||
emergency_contact_phone?: string | null
|
|
||||||
bank_name?: string | null
|
|
||||||
bank_account_number?: string | null
|
|
||||||
bank_iban?: string | null
|
|
||||||
hourly_rate?: string | number | null
|
|
||||||
commission_rate?: string | number | null
|
|
||||||
created_at?: string
|
created_at?: string
|
||||||
updated_at?: string
|
updated_at?: string
|
||||||
}
|
}
|
||||||
@@ -72,19 +46,6 @@ type EmployeeGeneralInfoProps = {
|
|||||||
employee: EmployeeData
|
employee: EmployeeData
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDate(value?: string | null): string | null {
|
|
||||||
if (!value) return null
|
|
||||||
const d = new Date(value)
|
|
||||||
if (Number.isNaN(d.getTime())) return value
|
|
||||||
return d.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialsOf(first?: string | null, last?: string | null) {
|
|
||||||
const f = (first ?? "").trim()[0] ?? ""
|
|
||||||
const l = (last ?? "").trim()[0] ?? ""
|
|
||||||
return (f + l).toUpperCase() || "?"
|
|
||||||
}
|
|
||||||
|
|
||||||
function InfoItem({
|
function InfoItem({
|
||||||
icon: Icon,
|
icon: Icon,
|
||||||
label,
|
label,
|
||||||
@@ -92,7 +53,7 @@ function InfoItem({
|
|||||||
}: {
|
}: {
|
||||||
icon: React.ComponentType<{ className?: string }>
|
icon: React.ComponentType<{ className?: string }>
|
||||||
label: string
|
label: string
|
||||||
value?: string | number | null
|
value?: string | null
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
@@ -102,7 +63,7 @@ function InfoItem({
|
|||||||
<div className="flex flex-col gap-0.5">
|
<div className="flex flex-col gap-0.5">
|
||||||
<span className="text-xs text-muted-foreground">{label}</span>
|
<span className="text-xs text-muted-foreground">{label}</span>
|
||||||
<span className="text-sm font-medium">
|
<span className="text-sm font-medium">
|
||||||
{value != null && value !== "" ? value : <span className="text-muted-foreground">—</span>}
|
{value || <span className="text-muted-foreground">—</span>}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -111,7 +72,6 @@ function InfoItem({
|
|||||||
|
|
||||||
export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
||||||
const fullName = [employee.first_name, employee.last_name].filter(Boolean).join(" ")
|
const fullName = [employee.first_name, employee.last_name].filter(Boolean).join(" ")
|
||||||
const avatarSrc = employee.avatar_url ?? (employee.avatar_path ? `/storage/${employee.avatar_path}` : null)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="grid gap-6 md:grid-cols-2">
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
@@ -124,11 +84,6 @@ export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
|||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="grid gap-4">
|
<CardContent className="grid gap-4">
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Avatar size="lg">
|
|
||||||
{avatarSrc ? <AvatarImage src={avatarSrc} alt={fullName} /> : null}
|
|
||||||
<AvatarFallback>{initialsOf(employee.first_name, employee.last_name)}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
|
<Badge variant="secondary">{fullName || "Unknown"}</Badge>
|
||||||
{employee.type && (
|
{employee.type && (
|
||||||
@@ -144,57 +99,46 @@ export function EmployeeGeneralInfo({ employee }: EmployeeGeneralInfoProps) {
|
|||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
<Separator />
|
<Separator />
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<InfoItem icon={Mail} label="Email" value={employee.email} />
|
<InfoItem icon={Mail} label="Email" value={employee.email} />
|
||||||
<InfoItem icon={Phone} label="Phone" value={employee.phone} />
|
<InfoItem icon={Phone} label="Phone" value={employee.phone} />
|
||||||
<InfoItem icon={Cake} label="Date of Birth" value={formatDate(employee.date_of_birth)} />
|
<InfoItem icon={Briefcase} label="Position" value={employee.position} />
|
||||||
<InfoItem icon={Heart} label="Marital Status" value={employee.marital_status ? formatEnum(employee.marital_status) : null} />
|
<InfoItem icon={BadgeCheck} label="Designation" value={employee.designation} />
|
||||||
<InfoItem icon={User} label="Gender" value={employee.gender ? formatEnum(employee.gender) : null} />
|
|
||||||
<InfoItem icon={IdCard} label="National ID" value={employee.national_id} />
|
|
||||||
</div>
|
|
||||||
<Separator />
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<InfoItem icon={Home} label="Address" value={employee.address} />
|
|
||||||
<InfoItem icon={PhoneCall} label="Emergency Contact" value={[employee.emergency_contact_name, employee.emergency_contact_phone].filter(Boolean).join(" • ")} />
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Employment + Compensation */}
|
{/* Work Details */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center gap-2">
|
||||||
<Building2 className="size-4" />
|
<Building2 className="size-4" />
|
||||||
Employment
|
Work Details
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="grid gap-4">
|
<CardContent className="grid gap-4">
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<InfoItem icon={Briefcase} label="Designation" value={employee.designation} />
|
<InfoItem
|
||||||
<InfoItem icon={Calendar} label="Hire Date" value={formatDate(employee.hire_date)} />
|
icon={Building2}
|
||||||
<InfoItem icon={Building2} label="Department" value={employee.department?.name} />
|
label="Department"
|
||||||
<InfoItem icon={BadgeCheck} label="Role" value={employee.role?.name} />
|
value={employee.department?.name}
|
||||||
</div>
|
/>
|
||||||
<Separator />
|
<InfoItem
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
icon={Calendar}
|
||||||
<InfoItem icon={DollarSign} label="Salary" value={employee.salary ? Number(employee.salary).toFixed(2) : null} />
|
label="Shop Calendar"
|
||||||
<InfoItem icon={Wallet} label="Wage Type" value={employee.wage_type} />
|
value={employee.shop_calender?.title}
|
||||||
<InfoItem icon={Clock} label="Hourly Rate" value={employee.hourly_rate != null ? Number(employee.hourly_rate).toFixed(2) : null} />
|
/>
|
||||||
<InfoItem icon={PercentIcon} label="Commission %" value={employee.commission_rate != null ? Number(employee.commission_rate).toFixed(2) : null} />
|
<InfoItem
|
||||||
</div>
|
icon={Clock}
|
||||||
<Separator />
|
label="Shop Timing"
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
value={employee.shop_timing?.title}
|
||||||
<InfoItem icon={Landmark} label="Bank" value={employee.bank_name} />
|
/>
|
||||||
<InfoItem icon={Wallet} label="Account #" value={employee.bank_account_number} />
|
<InfoItem
|
||||||
<InfoItem icon={Landmark} label="IBAN" value={employee.bank_iban} />
|
icon={MapPin}
|
||||||
</div>
|
label="Geo Fence Radius"
|
||||||
<Separator />
|
value={employee.geo_fence_radius != null ? String(employee.geo_fence_radius) : null}
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
/>
|
||||||
<InfoItem icon={Calendar} label="Shop Calendar" value={employee.shop_calender?.title} />
|
|
||||||
<InfoItem icon={Clock} label="Shop Timing" value={employee.shop_timing?.title} />
|
|
||||||
<InfoItem icon={MapPin} label="Geo Fence Radius (m)" value={employee.geo_fence_radius != null ? String(employee.geo_fence_radius) : null} />
|
|
||||||
</div>
|
</div>
|
||||||
<Separator />
|
<Separator />
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
|
|||||||
@@ -25,22 +25,9 @@ const optionalIntegerIdField = z.preprocess(
|
|||||||
z.number().int().positive().nullable(),
|
z.number().int().positive().nullable(),
|
||||||
)
|
)
|
||||||
|
|
||||||
const optionalTrimmedString = (max: number, msg?: string) =>
|
|
||||||
z.preprocess(
|
|
||||||
(value) => (typeof value !== "string" ? value : value.trim() === "" ? undefined : value.trim()),
|
|
||||||
z.string().max(max, msg ?? `Must be at most ${max} characters`).optional(),
|
|
||||||
)
|
|
||||||
|
|
||||||
const STATUS_OPTIONS = ["active", "inactive"] as const
|
const STATUS_OPTIONS = ["active", "inactive"] as const
|
||||||
const TYPE_OPTIONS = EmployeeType
|
const TYPE_OPTIONS = EmployeeType
|
||||||
const WAGE_TYPE_OPTIONS = WageType
|
const WAGE_TYPE_OPTIONS = WageType
|
||||||
const GENDER_OPTIONS = ["male", "female"] as const
|
|
||||||
const MARITAL_OPTIONS = ["single", "married"] as const
|
|
||||||
|
|
||||||
const optionalDate = z.preprocess(
|
|
||||||
(value) => (typeof value !== "string" || value.trim() === "" ? undefined : value),
|
|
||||||
z.string().optional(),
|
|
||||||
)
|
|
||||||
|
|
||||||
const employeeFormSchema = z.object({
|
const employeeFormSchema = z.object({
|
||||||
department: relationFieldSchema,
|
department: relationFieldSchema,
|
||||||
@@ -52,8 +39,8 @@ const employeeFormSchema = z.object({
|
|||||||
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"),
|
||||||
email: z.string().trim().min(1, "Email is required").email("Enter a valid email address").max(100, "Email must be at most 100 characters"),
|
email: z.string().trim().min(1, "Email is required").email("Enter a valid email address").max(100, "Email must be at most 100 characters"),
|
||||||
password: z.string().min(6, "Password must be at least 6 characters"),
|
password: z.string().min(6, "Password must be at least 6 characters"),
|
||||||
phone: optionalTrimmedString(30),
|
phone: z.string().trim().max(30, "Phone must be at most 30 characters").optional().or(z.literal("")),
|
||||||
designation: optionalTrimmedString(50),
|
designation: z.string().trim().max(50, "Designation must be at most 50 characters").optional().or(z.literal("")),
|
||||||
salary: optionalNumericField,
|
salary: optionalNumericField,
|
||||||
wage_type: z.enum(WAGE_TYPE_OPTIONS).nullable(),
|
wage_type: z.enum(WAGE_TYPE_OPTIONS).nullable(),
|
||||||
status: z.enum(STATUS_OPTIONS),
|
status: z.enum(STATUS_OPTIONS),
|
||||||
@@ -61,32 +48,9 @@ const employeeFormSchema = z.object({
|
|||||||
track_attendance: z.boolean(),
|
track_attendance: z.boolean(),
|
||||||
notify_owner_when_punch_in_out: z.boolean(),
|
notify_owner_when_punch_in_out: z.boolean(),
|
||||||
geo_fence_radius: optionalNumericField,
|
geo_fence_radius: optionalNumericField,
|
||||||
|
|
||||||
// Extended profile fields
|
|
||||||
address: optionalTrimmedString(500),
|
|
||||||
date_of_birth: optionalDate,
|
|
||||||
gender: z.enum(GENDER_OPTIONS).nullable().optional(),
|
|
||||||
marital_status: z.enum(MARITAL_OPTIONS).nullable().optional(),
|
|
||||||
national_id: optionalTrimmedString(50),
|
|
||||||
hire_date: optionalDate,
|
|
||||||
emergency_contact_name: optionalTrimmedString(100),
|
|
||||||
emergency_contact_phone: optionalTrimmedString(30),
|
|
||||||
bank_name: optionalTrimmedString(100),
|
|
||||||
bank_account_number: optionalTrimmedString(50),
|
|
||||||
bank_iban: optionalTrimmedString(50),
|
|
||||||
hourly_rate: optionalNumericField,
|
|
||||||
commission_rate: optionalNumericField,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
type EmployeeFormValues = z.infer<typeof employeeFormSchema>
|
type EmployeeFormValues = z.infer<typeof employeeFormSchema>
|
||||||
|
|
||||||
export {
|
export { employeeFormSchema, relationFieldSchema, STATUS_OPTIONS, TYPE_OPTIONS, WAGE_TYPE_OPTIONS }
|
||||||
employeeFormSchema,
|
|
||||||
relationFieldSchema,
|
|
||||||
STATUS_OPTIONS,
|
|
||||||
TYPE_OPTIONS,
|
|
||||||
WAGE_TYPE_OPTIONS,
|
|
||||||
GENDER_OPTIONS,
|
|
||||||
MARITAL_OPTIONS,
|
|
||||||
}
|
|
||||||
export type { EmployeeFormValues }
|
export type { EmployeeFormValues }
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { AlertTriangle, Plus, Save } from "lucide-react"
|
|
||||||
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
|
|
||||||
import { FieldGroup } from "@/shared/components/ui/field"
|
|
||||||
import {
|
|
||||||
Rhform,
|
|
||||||
RhfTextField,
|
|
||||||
RhfSelectField,
|
|
||||||
RhfTextareaField,
|
|
||||||
} from "@/shared/components/form"
|
|
||||||
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"
|
|
||||||
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 { toRelation, toId } from "@/shared/lib/utils"
|
|
||||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
|
||||||
|
|
||||||
import { z } from "zod"
|
|
||||||
|
|
||||||
const LEAVE_TYPES = ["annual", "sick", "unpaid", "maternity", "paternity", "other"] as const
|
|
||||||
|
|
||||||
const relationFieldSchema = z.object({ value: z.string(), label: z.string() }).nullable()
|
|
||||||
|
|
||||||
const schema = z.object({
|
|
||||||
employee: relationFieldSchema.refine((v) => !!v?.value, "Employee is required"),
|
|
||||||
leave_type: z.enum(LEAVE_TYPES),
|
|
||||||
start_date: z.string().min(1, "Start date is required"),
|
|
||||||
end_date: z.string().min(1, "End date is required"),
|
|
||||||
reason: z.string().max(2000).optional(),
|
|
||||||
})
|
|
||||||
|
|
||||||
type LeaveFormValues = z.infer<typeof schema>
|
|
||||||
|
|
||||||
const DEFAULT_VALUES: LeaveFormValues = {
|
|
||||||
employee: null,
|
|
||||||
leave_type: "annual",
|
|
||||||
start_date: "",
|
|
||||||
end_date: "",
|
|
||||||
reason: "",
|
|
||||||
}
|
|
||||||
|
|
||||||
const TYPE_SELECT_OPTIONS = LEAVE_TYPES.map((v) => ({
|
|
||||||
value: v,
|
|
||||||
label: v.replace(/^./, (c) => c.toUpperCase()),
|
|
||||||
}))
|
|
||||||
|
|
||||||
export type LeaveRequestFormProps = {
|
|
||||||
resourceId?: string | null
|
|
||||||
initialData?: unknown
|
|
||||||
onSuccess?: () => void
|
|
||||||
/** Pre-fill the employee select when opened from an employee detail page. */
|
|
||||||
presetEmployee?: { id: number | string; label: string } | null
|
|
||||||
}
|
|
||||||
|
|
||||||
function mapToFormValues(data: unknown, preset?: { id: number | string; label: string } | null): LeaveFormValues {
|
|
||||||
const d = (data as any)?.data ?? data ?? {}
|
|
||||||
const empLabel = d.employee
|
|
||||||
? `${d.employee.first_name ?? ""} ${d.employee.last_name ?? ""}`.trim()
|
|
||||||
: ""
|
|
||||||
|
|
||||||
const formatDate = (v: unknown) => {
|
|
||||||
if (!v || typeof v !== "string") return ""
|
|
||||||
return v.length >= 10 ? v.slice(0, 10) : v
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
employee: d.employee_id
|
|
||||||
? toRelation(d.employee_id, empLabel || `Employee #${d.employee_id}`)
|
|
||||||
: (preset ? toRelation(preset.id, preset.label) : null),
|
|
||||||
leave_type: d.leave_type || "annual",
|
|
||||||
start_date: formatDate(d.start_date),
|
|
||||||
end_date: formatDate(d.end_date),
|
|
||||||
reason: d.reason || "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LeaveRequestForm({ resourceId, initialData, onSuccess, presetEmployee }: LeaveRequestFormProps) {
|
|
||||||
const api = useAuthApi()
|
|
||||||
|
|
||||||
const { form, isEditing } = useResourceForm<LeaveFormValues, any>({
|
|
||||||
schema,
|
|
||||||
defaultValues: presetEmployee
|
|
||||||
? { ...DEFAULT_VALUES, employee: toRelation(presetEmployee.id, presetEmployee.label) }
|
|
||||||
: DEFAULT_VALUES,
|
|
||||||
resourceId,
|
|
||||||
initialData,
|
|
||||||
initialize: (id) => api.leaveRequests.show(id),
|
|
||||||
queryKey: [LEAVE_REQUEST_ROUTES.BY_ID, resourceId],
|
|
||||||
mapToFormValues: (data) => mapToFormValues(data, presetEmployee),
|
|
||||||
})
|
|
||||||
|
|
||||||
const { mutate, error, isPending } = useFormMutation(form, {
|
|
||||||
mutationFn: (values: LeaveFormValues) => {
|
|
||||||
const payload = {
|
|
||||||
employee_id: toId(values.employee) ?? 0,
|
|
||||||
leave_type: values.leave_type,
|
|
||||||
start_date: values.start_date,
|
|
||||||
end_date: values.end_date,
|
|
||||||
reason: values.reason || undefined,
|
|
||||||
}
|
|
||||||
const promise = isEditing && resourceId
|
|
||||||
? api.leaveRequests.update(resourceId, payload)
|
|
||||||
: api.leaveRequests.create(payload as any)
|
|
||||||
toast.promise(promise, {
|
|
||||||
loading: isEditing ? "Updating..." : "Submitting...",
|
|
||||||
success: isEditing ? "Leave request updated" : "Leave request submitted",
|
|
||||||
error: isEditing ? "Failed to update" : "Failed to submit",
|
|
||||||
})
|
|
||||||
return promise
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
form.reset()
|
|
||||||
onSuccess?.()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
|
||||||
{error && (
|
|
||||||
<Alert variant="destructive" className="mb-4">
|
|
||||||
<AlertTriangle className="me-2 h-4 w-4" />
|
|
||||||
<AlertTitle>{isEditing ? "Failed to update" : "Failed to submit"}</AlertTitle>
|
|
||||||
{error.message}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<FieldGroup>
|
|
||||||
<RhfEmployeeSelectField name="employee" label="Employee" required />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfSelectField
|
|
||||||
name="leave_type"
|
|
||||||
label="Leave Type"
|
|
||||||
placeholder="Select type"
|
|
||||||
options={TYPE_SELECT_OPTIONS}
|
|
||||||
/>
|
|
||||||
<div />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="start_date" label="Start Date" type="date" required />
|
|
||||||
<RhfTextField name="end_date" label="End Date" type="date" required />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<RhfTextareaField name="reason" label="Reason" rows={3} />
|
|
||||||
|
|
||||||
<Button type="submit" variant="default" disabled={isPending}>
|
|
||||||
{isEditing ? <Save /> : <Plus />}
|
|
||||||
{isPending ? "Saving..." : (isEditing ? "Update" : "Submit Request")}
|
|
||||||
</Button>
|
|
||||||
</FieldGroup>
|
|
||||||
</Rhform>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -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,105 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { AlertTriangle, Plus } from "lucide-react"
|
|
||||||
|
|
||||||
import { Button } from "@/shared/components/ui/button"
|
|
||||||
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
|
|
||||||
import { FieldGroup } from "@/shared/components/ui/field"
|
|
||||||
import {
|
|
||||||
Rhform,
|
|
||||||
RhfTextField,
|
|
||||||
RhfTextareaField,
|
|
||||||
} from "@/shared/components/form"
|
|
||||||
import { toast } from "sonner"
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
|
||||||
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
|
|
||||||
import { useForm } from "react-hook-form"
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod"
|
|
||||||
import { z } from "zod"
|
|
||||||
|
|
||||||
const schema = z.object({
|
|
||||||
period_start: z.string().min(1, "Required"),
|
|
||||||
period_end: z.string().min(1, "Required"),
|
|
||||||
reference: z.string().max(50).optional(),
|
|
||||||
note: z.string().max(2000).optional(),
|
|
||||||
})
|
|
||||||
|
|
||||||
type PayrollRunFormValues = z.infer<typeof schema>
|
|
||||||
|
|
||||||
function firstOfMonth() {
|
|
||||||
const d = new Date()
|
|
||||||
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
|
|
||||||
}
|
|
||||||
function lastOfMonth() {
|
|
||||||
const d = new Date()
|
|
||||||
return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PayrollRunFormProps = {
|
|
||||||
onSuccess?: (runId?: string) => void
|
|
||||||
}
|
|
||||||
|
|
||||||
export function PayrollRunForm({ onSuccess }: PayrollRunFormProps) {
|
|
||||||
const api = useAuthApi()
|
|
||||||
|
|
||||||
const form = useForm<PayrollRunFormValues>({
|
|
||||||
resolver: zodResolver(schema),
|
|
||||||
defaultValues: {
|
|
||||||
period_start: firstOfMonth(),
|
|
||||||
period_end: lastOfMonth(),
|
|
||||||
reference: "",
|
|
||||||
note: "",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const { mutate, error, isPending } = useFormMutation(form, {
|
|
||||||
mutationFn: (values: PayrollRunFormValues) => {
|
|
||||||
const payload = {
|
|
||||||
period_start: values.period_start,
|
|
||||||
period_end: values.period_end,
|
|
||||||
reference: values.reference || undefined,
|
|
||||||
note: values.note || undefined,
|
|
||||||
}
|
|
||||||
const promise = api.payroll.create(payload)
|
|
||||||
toast.promise(promise, {
|
|
||||||
loading: "Creating run + generating entries...",
|
|
||||||
success: "Payroll run created",
|
|
||||||
error: "Failed to create run",
|
|
||||||
})
|
|
||||||
return promise
|
|
||||||
},
|
|
||||||
onSuccess: (res: any) => {
|
|
||||||
const runId = res?.data?.id ?? res?.id
|
|
||||||
form.reset()
|
|
||||||
onSuccess?.(runId ? String(runId) : undefined)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Rhform form={form} onSubmit={(values) => mutate(values)}>
|
|
||||||
{error && (
|
|
||||||
<Alert variant="destructive" className="mb-4">
|
|
||||||
<AlertTriangle className="me-2 h-4 w-4" />
|
|
||||||
<AlertTitle>Failed to create payroll run</AlertTitle>
|
|
||||||
{error.message}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<FieldGroup>
|
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
|
||||||
<RhfTextField name="period_start" label="Period Start" type="date" required />
|
|
||||||
<RhfTextField name="period_end" label="Period End" type="date" required />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<RhfTextField name="reference" label="Reference" placeholder="Auto if blank" />
|
|
||||||
|
|
||||||
<RhfTextareaField name="note" label="Note" rows={2} />
|
|
||||||
|
|
||||||
<Button type="submit" variant="default" disabled={isPending}>
|
|
||||||
<Plus />
|
|
||||||
{isPending ? "Creating..." : "Create & Generate"}
|
|
||||||
</Button>
|
|
||||||
</FieldGroup>
|
|
||||||
</Rhform>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -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
@@ -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
@@ -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>
|
||||||
|
|||||||
@@ -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: '/**',
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
"use client"
|
|
||||||
|
|
||||||
import { useMemo } from "react"
|
|
||||||
import { useAuthStore } from "@/shared/stores/auth-store"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* UI-side permission checks. The backend `permission.check` middleware is the
|
|
||||||
* authoritative guard (returns 403 on missing permission); this hook only hides
|
|
||||||
* controls so the UI doesn't dead-end users.
|
|
||||||
*
|
|
||||||
* Permission flags arrive on the authenticated user payload as boolean columns
|
|
||||||
* (e.g. `can_view_employees`, `can_create_payroll`). Unknown keys default to
|
|
||||||
* `true` so the UI doesn't accidentally hide everything when the payload shape
|
|
||||||
* changes — backend stays the source of truth.
|
|
||||||
*/
|
|
||||||
export function usePermissions() {
|
|
||||||
const user = useAuthStore((s) => s.user)
|
|
||||||
|
|
||||||
return useMemo(() => {
|
|
||||||
const flags = (user ?? {}) as Record<string, unknown>
|
|
||||||
|
|
||||||
function check(action: "view" | "create" | "update" | "delete", resource: string): boolean {
|
|
||||||
const key = `can_${action}_${resource}`
|
|
||||||
const value = flags[key]
|
|
||||||
// Default to true when the flag is absent — backend is the source of truth.
|
|
||||||
if (value === undefined || value === null) return true
|
|
||||||
return Boolean(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
can: check,
|
|
||||||
canView: (resource: string) => check("view", resource),
|
|
||||||
canCreate: (resource: string) => check("create", resource),
|
|
||||||
canUpdate: (resource: string) => check("update", resource),
|
|
||||||
canDelete: (resource: string) => check("delete", resource),
|
|
||||||
}
|
|
||||||
}, [user])
|
|
||||||
}
|
|
||||||
+79
-66
@@ -59,75 +59,88 @@ import { ExpenseItemsClient } from "./clients/expense-items"
|
|||||||
import { InventoryCategoriesClient } from "./clients/inventory-categories"
|
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"
|
||||||
import { LeaveRequestsClient } from "./clients/leave-requests"
|
|
||||||
import { PayrollClient } from "./clients/payroll"
|
|
||||||
|
|
||||||
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),
|
||||||
leaveRequests: new LeaveRequestsClient(undefined, options),
|
|
||||||
payroll: new PayrollClient(undefined, options),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Unauthenticated singleton — use for public calls (login, register) */
|
/** Unauthenticated singleton — use for public calls (login, register). */
|
||||||
export const api = createApi()
|
export const api = createApi()
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { CrudClient } from "../infra/crud-client"
|
import { CrudClient } from "../infra/crud-client"
|
||||||
import type { ApiClientOptions } from "../infra/client"
|
import type { ApiClientOptions } from "../infra/client"
|
||||||
import type { ApiPath, ApiRequestBody } from "../infra/types"
|
import type { ApiPath, ApiRequestBody } from "../infra/types"
|
||||||
import type { ApiListQueryParams } from "../contracts/types"
|
|
||||||
|
|
||||||
export const EMPLOYEE_ROUTES = {
|
export const EMPLOYEE_ROUTES = {
|
||||||
INDEX: "/api/employees",
|
INDEX: "/api/employees",
|
||||||
@@ -9,36 +8,12 @@ export const EMPLOYEE_ROUTES = {
|
|||||||
UPDATE_PERMISSIONS: "/api/employees/{id}/update-permissions",
|
UPDATE_PERMISSIONS: "/api/employees/{id}/update-permissions",
|
||||||
} as const satisfies Record<string, ApiPath>
|
} as const satisfies Record<string, ApiPath>
|
||||||
|
|
||||||
// Routes added after the last OpenAPI regen — not yet in the generated `paths`
|
|
||||||
// type, so callers go through `as never` casts.
|
|
||||||
export const EMPLOYEE_EXTRA_ROUTES = {
|
|
||||||
UPLOAD_AVATAR: "/api/employees/{id}/upload-avatar",
|
|
||||||
PERFORMANCE: "/api/employees/{id}/performance",
|
|
||||||
IMPORT: "/api/employees/import",
|
|
||||||
EXPORT: "/api/employees/export",
|
|
||||||
IMPORT_SAMPLE: "/api/employees/import/sample",
|
|
||||||
DOCUMENTS: "/api/employees/{employee}/documents",
|
|
||||||
DOCUMENT_BY_ID: "/api/employees/{employee}/documents/{id}",
|
|
||||||
CERTIFICATIONS: "/api/employees/{employee}/certifications",
|
|
||||||
CERTIFICATION_BY_ID: "/api/employees/{employee}/certifications/{id}",
|
|
||||||
LEAVE_BALANCE: "/api/employees/{employee}/leave-balance",
|
|
||||||
PAYROLL_SLIPS: "/api/employees/{employee}/payroll-slips",
|
|
||||||
} as const
|
|
||||||
|
|
||||||
export class EmployeesClient extends CrudClient<
|
export class EmployeesClient extends CrudClient<
|
||||||
typeof EMPLOYEE_ROUTES.INDEX,
|
typeof EMPLOYEE_ROUTES.INDEX,
|
||||||
typeof EMPLOYEE_ROUTES.BY_ID
|
typeof EMPLOYEE_ROUTES.BY_ID
|
||||||
> {
|
> {
|
||||||
constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
|
constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
|
||||||
super(
|
super(baseUrl, defaultOptions, EMPLOYEE_ROUTES.INDEX, EMPLOYEE_ROUTES.BY_ID)
|
||||||
baseUrl,
|
|
||||||
defaultOptions,
|
|
||||||
EMPLOYEE_ROUTES.INDEX,
|
|
||||||
EMPLOYEE_ROUTES.BY_ID,
|
|
||||||
EMPLOYEE_EXTRA_ROUTES.IMPORT as never,
|
|
||||||
EMPLOYEE_EXTRA_ROUTES.EXPORT as never,
|
|
||||||
"GET",
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getById(id: string) {
|
async getById(id: string) {
|
||||||
@@ -48,118 +23,4 @@ export class EmployeesClient extends CrudClient<
|
|||||||
async updatePermissions(id: string, payload: ApiRequestBody<typeof EMPLOYEE_ROUTES.UPDATE_PERMISSIONS, "post">) {
|
async updatePermissions(id: string, payload: ApiRequestBody<typeof EMPLOYEE_ROUTES.UPDATE_PERMISSIONS, "post">) {
|
||||||
return this.post(EMPLOYEE_ROUTES.UPDATE_PERMISSIONS, payload as never, { params: { id } } as never)
|
return this.post(EMPLOYEE_ROUTES.UPDATE_PERMISSIONS, payload as never, { params: { id } } as never)
|
||||||
}
|
}
|
||||||
|
|
||||||
async uploadAvatar(id: string, file: File) {
|
|
||||||
const fd = new FormData()
|
|
||||||
fd.append("avatar", file)
|
|
||||||
return this.postFormData(`/api/employees/${id}/upload-avatar`, fd)
|
|
||||||
}
|
|
||||||
|
|
||||||
async downloadImportSample() {
|
|
||||||
return this.fetchBlob(EMPLOYEE_EXTRA_ROUTES.IMPORT_SAMPLE as never, { method: "GET" })
|
|
||||||
}
|
|
||||||
|
|
||||||
async performance(id: string, query?: { from?: string; to?: string }) {
|
|
||||||
return this.get(EMPLOYEE_EXTRA_ROUTES.PERFORMANCE as never, { params: { id }, query } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Documents ────────────────────────────────────────────────────
|
|
||||||
async listDocuments(employeeId: string, query?: ApiListQueryParams) {
|
|
||||||
return this.get(EMPLOYEE_EXTRA_ROUTES.DOCUMENTS as never, { params: { employee: employeeId }, query } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async uploadDocument(employeeId: string, payload: {
|
|
||||||
file: File
|
|
||||||
name: string
|
|
||||||
type: string
|
|
||||||
issued_date?: string
|
|
||||||
expiry_date?: string
|
|
||||||
notes?: string
|
|
||||||
}) {
|
|
||||||
const fd = new FormData()
|
|
||||||
fd.append("file", payload.file)
|
|
||||||
fd.append("name", payload.name)
|
|
||||||
fd.append("type", payload.type)
|
|
||||||
if (payload.issued_date) fd.append("issued_date", payload.issued_date)
|
|
||||||
if (payload.expiry_date) fd.append("expiry_date", payload.expiry_date)
|
|
||||||
if (payload.notes) fd.append("notes", payload.notes)
|
|
||||||
return this.postFormData(`/api/employees/${employeeId}/documents`, fd)
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateDocument(employeeId: string, id: string, payload: Record<string, unknown>) {
|
|
||||||
return this.put(EMPLOYEE_EXTRA_ROUTES.DOCUMENT_BY_ID as never, payload as never, { params: { employee: employeeId, id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async destroyDocument(employeeId: string, id: string) {
|
|
||||||
return this.delete(EMPLOYEE_EXTRA_ROUTES.DOCUMENT_BY_ID as never, { params: { employee: employeeId, id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Certifications ───────────────────────────────────────────────
|
|
||||||
async listCertifications(employeeId: string, query?: ApiListQueryParams) {
|
|
||||||
return this.get(EMPLOYEE_EXTRA_ROUTES.CERTIFICATIONS as never, { params: { employee: employeeId }, query } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async createCertification(employeeId: string, payload: {
|
|
||||||
name: string
|
|
||||||
issuer?: string
|
|
||||||
certificate_number?: string
|
|
||||||
issued_date?: string
|
|
||||||
expiry_date?: string
|
|
||||||
notes?: string
|
|
||||||
file?: File
|
|
||||||
}) {
|
|
||||||
const fd = new FormData()
|
|
||||||
fd.append("name", payload.name)
|
|
||||||
if (payload.issuer) fd.append("issuer", payload.issuer)
|
|
||||||
if (payload.certificate_number) fd.append("certificate_number", payload.certificate_number)
|
|
||||||
if (payload.issued_date) fd.append("issued_date", payload.issued_date)
|
|
||||||
if (payload.expiry_date) fd.append("expiry_date", payload.expiry_date)
|
|
||||||
if (payload.notes) fd.append("notes", payload.notes)
|
|
||||||
if (payload.file) fd.append("file", payload.file)
|
|
||||||
return this.postFormData(`/api/employees/${employeeId}/certifications`, fd)
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateCertification(employeeId: string, id: string, payload: {
|
|
||||||
name?: string
|
|
||||||
issuer?: string
|
|
||||||
certificate_number?: string
|
|
||||||
issued_date?: string
|
|
||||||
expiry_date?: string
|
|
||||||
notes?: string
|
|
||||||
file?: File
|
|
||||||
}) {
|
|
||||||
const fd = new FormData()
|
|
||||||
if (payload.name) fd.append("name", payload.name)
|
|
||||||
if (payload.issuer) fd.append("issuer", payload.issuer)
|
|
||||||
if (payload.certificate_number) fd.append("certificate_number", payload.certificate_number)
|
|
||||||
if (payload.issued_date) fd.append("issued_date", payload.issued_date)
|
|
||||||
if (payload.expiry_date) fd.append("expiry_date", payload.expiry_date)
|
|
||||||
if (payload.notes) fd.append("notes", payload.notes)
|
|
||||||
if (payload.file) fd.append("file", payload.file)
|
|
||||||
return this.postFormData(`/api/employees/${employeeId}/certifications/${id}`, fd)
|
|
||||||
}
|
|
||||||
|
|
||||||
async destroyCertification(employeeId: string, id: string) {
|
|
||||||
return this.delete(EMPLOYEE_EXTRA_ROUTES.CERTIFICATION_BY_ID as never, { params: { employee: employeeId, id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Leave balance ────────────────────────────────────────────────
|
|
||||||
async getLeaveBalance(employeeId: string, year?: number) {
|
|
||||||
return this.get(EMPLOYEE_EXTRA_ROUTES.LEAVE_BALANCE as never, {
|
|
||||||
params: { employee: employeeId },
|
|
||||||
query: year ? { year } : undefined,
|
|
||||||
} as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateLeaveBalance(employeeId: string, payload: { year: number; annual_total?: number; sick_total?: number }) {
|
|
||||||
return this.put(EMPLOYEE_EXTRA_ROUTES.LEAVE_BALANCE as never, payload as never, { params: { employee: employeeId } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Payroll slips for an employee ────────────────────────────────
|
|
||||||
async listPayrollSlips(employeeId: string, query?: ApiListQueryParams & { year?: number }) {
|
|
||||||
return this.get(EMPLOYEE_EXTRA_ROUTES.PAYROLL_SLIPS as never, {
|
|
||||||
params: { employee: employeeId },
|
|
||||||
query,
|
|
||||||
} as never)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,5 +83,3 @@ export { ConfigurationsClient, CONFIGURATION_ROUTES } from "./configurations"
|
|||||||
export { AutoGenerateClient, AUTO_GENERATE_ROUTES } from "./auto-generate"
|
export { AutoGenerateClient, AUTO_GENERATE_ROUTES } from "./auto-generate"
|
||||||
export { ExpenseItemsClient, EXPENSE_ITEM_ROUTES } from "./expense-items"
|
export { ExpenseItemsClient, EXPENSE_ITEM_ROUTES } from "./expense-items"
|
||||||
export { InventoryCategoriesClient, INVENTORY_CATEGORY_ROUTES } from "./inventory-categories"
|
export { InventoryCategoriesClient, INVENTORY_CATEGORY_ROUTES } from "./inventory-categories"
|
||||||
export { LeaveRequestsClient, LEAVE_REQUEST_ROUTES } from "./leave-requests"
|
|
||||||
export { PayrollClient, PAYROLL_ROUTES } from "./payroll"
|
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
import { ApiClient, type ApiClientOptions } from "../infra/client"
|
|
||||||
import type { ApiListQueryParams } from "../contracts/types"
|
|
||||||
|
|
||||||
// New endpoints — not yet in the OpenAPI spec; routes are raw strings cast as needed.
|
|
||||||
export const LEAVE_REQUEST_ROUTES = {
|
|
||||||
INDEX: "/api/leave-requests",
|
|
||||||
BY_ID: "/api/leave-requests/{id}",
|
|
||||||
APPROVE: "/api/leave-requests/{id}/approve",
|
|
||||||
REJECT: "/api/leave-requests/{id}/reject",
|
|
||||||
} as const
|
|
||||||
|
|
||||||
export type LeaveStatus = "pending" | "approved" | "rejected" | "cancelled"
|
|
||||||
|
|
||||||
export class LeaveRequestsClient extends ApiClient {
|
|
||||||
constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
|
|
||||||
super(baseUrl, defaultOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
async list(query?: ApiListQueryParams & { employee_id?: string | number; status?: LeaveStatus; leave_type?: string; year?: number }) {
|
|
||||||
return this.get(LEAVE_REQUEST_ROUTES.INDEX as never, { query } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async show(id: string) {
|
|
||||||
return this.get(LEAVE_REQUEST_ROUTES.BY_ID as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async getById(id: string) {
|
|
||||||
return this.show(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(payload: { employee_id: number | string; leave_type: string; start_date: string; end_date: string; reason?: string }) {
|
|
||||||
return this.post(LEAVE_REQUEST_ROUTES.INDEX as never, payload as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async update(id: string, payload: { leave_type?: string; start_date?: string; end_date?: string; reason?: string }) {
|
|
||||||
return this.put(LEAVE_REQUEST_ROUTES.BY_ID as never, payload as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async destroy(id: string) {
|
|
||||||
return this.delete(LEAVE_REQUEST_ROUTES.BY_ID as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async approve(id: string, payload?: { decision_note?: string; approved_by?: number }) {
|
|
||||||
return this.post(LEAVE_REQUEST_ROUTES.APPROVE as never, (payload ?? {}) as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async reject(id: string, payload?: { decision_note?: string; approved_by?: number }) {
|
|
||||||
return this.post(LEAVE_REQUEST_ROUTES.REJECT as never, (payload ?? {}) as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
import { ApiClient, type ApiClientOptions } from "../infra/client"
|
|
||||||
import type { ApiListQueryParams } from "../contracts/types"
|
|
||||||
|
|
||||||
export const PAYROLL_ROUTES = {
|
|
||||||
RUNS_INDEX: "/api/payroll/runs",
|
|
||||||
RUN_BY_ID: "/api/payroll/runs/{id}",
|
|
||||||
REGENERATE: "/api/payroll/runs/{id}/regenerate",
|
|
||||||
FINALIZE: "/api/payroll/runs/{id}/finalize",
|
|
||||||
MARK_PAID: "/api/payroll/runs/{id}/mark-paid",
|
|
||||||
ENTRY_BY_ID: "/api/payroll/runs/{run}/entries/{entry}",
|
|
||||||
} as const
|
|
||||||
|
|
||||||
export type PayrollStatus = "draft" | "finalized" | "paid"
|
|
||||||
|
|
||||||
export class PayrollClient extends ApiClient {
|
|
||||||
constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
|
|
||||||
super(baseUrl, defaultOptions)
|
|
||||||
}
|
|
||||||
|
|
||||||
async list(query?: ApiListQueryParams & { status?: PayrollStatus; year?: number }) {
|
|
||||||
return this.get(PAYROLL_ROUTES.RUNS_INDEX as never, { query } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async show(id: string) {
|
|
||||||
return this.get(PAYROLL_ROUTES.RUN_BY_ID as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async getById(id: string) {
|
|
||||||
return this.show(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
async create(payload: { period_start: string; period_end: string; reference?: string; note?: string }) {
|
|
||||||
return this.post(PAYROLL_ROUTES.RUNS_INDEX as never, payload as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async destroy(id: string) {
|
|
||||||
return this.delete(PAYROLL_ROUTES.RUN_BY_ID as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async regenerate(id: string) {
|
|
||||||
return this.post(PAYROLL_ROUTES.REGENERATE as never, {} as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async finalize(id: string) {
|
|
||||||
return this.post(PAYROLL_ROUTES.FINALIZE as never, {} as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async markPaid(id: string) {
|
|
||||||
return this.post(PAYROLL_ROUTES.MARK_PAID as never, {} as never, { params: { id } } as never)
|
|
||||||
}
|
|
||||||
|
|
||||||
async updateEntry(runId: string, entryId: string, payload: {
|
|
||||||
hours_worked?: number
|
|
||||||
overtime_hours?: number
|
|
||||||
base_salary?: number
|
|
||||||
commission_amount?: number
|
|
||||||
allowances?: number
|
|
||||||
deductions?: number
|
|
||||||
note?: string
|
|
||||||
}) {
|
|
||||||
return this.put(PAYROLL_ROUTES.ENTRY_BY_ID as never, payload as never, { params: { run: runId, entry: entryId } } as never)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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> {
|
||||||
|
|||||||
Reference in New Issue
Block a user