Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bfd8c84a9 | ||
|
|
54d11f01b4 | ||
|
|
fcbba6247d | ||
|
|
05b55b5721 | ||
|
|
6b356d2855 | ||
|
|
cc7dc1bd17 | ||
|
|
349a458c3c | ||
|
|
25c3125894 | ||
|
|
4b51ffe457 | ||
|
|
b0361fcbfb | ||
|
|
38565298fc | ||
|
|
dd32658500 | ||
|
|
c7eb23dd3f | ||
|
|
4faafe6667 | ||
|
|
1fda8d8d7b | ||
|
|
cdd1cbc31a | ||
|
|
c5d406792f | ||
|
|
97364f4734 | ||
|
|
e1ef6fa2ea | ||
|
|
0c43c8edd2 | ||
|
|
615a0fda59 | ||
|
|
65964605e1 | ||
|
|
564e9e510f | ||
|
|
c0f78c6e18 | ||
|
|
f17dd1486c | ||
|
|
973149e974 | ||
|
|
020ffccfd6 | ||
|
|
3eb471a604 | ||
|
|
29cc9c6f4e | ||
|
|
c5f6d2f596 | ||
|
|
17d8e1c90d | ||
|
|
bb02b77be2 | ||
|
|
90c84a0bda | ||
|
|
38ef10da4d | ||
|
|
c47f7c1b6a | ||
|
|
9fd7b61c5a |
Binary file not shown.
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(pnpm --version)",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?|jsx?\\)$\")",
|
||||
"Bash(grep -E \"\\\\.\\(tsx?\\)$\")"
|
||||
]
|
||||
},
|
||||
"enabledMcpjsonServers": [
|
||||
"code-review-graph"
|
||||
],
|
||||
"enableAllProjectMcpServers": true
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
NIXPACKS_NODE_VERSION=22
|
||||
NEXT_PUBLIC_API_URL=http://reparee.test
|
||||
@@ -74,6 +74,7 @@ Create `apps/dashboard/modules/<feature>/<feature>-form.tsx`:
|
||||
5. Use `useFormMutation()` for submit with automatic validation error mapping
|
||||
6. Render with `Rhform` + `RhfTextField` / `RhfSelectField` / `RhfAsyncSelectField` etc.
|
||||
7. Include error alert, submit button with loading/edit states
|
||||
8. For every required schema/backend field, pass `required` to the rendered form field component so required UI indicators and consistency are preserved
|
||||
|
||||
### Step 5: Create Page Component
|
||||
|
||||
@@ -111,13 +112,44 @@ Create `apps/dashboard/app/(authenticated)/<section>/<feature>/page.tsx`:
|
||||
| Form component | `<PascalFeature>Form` | `JobCardForm` |
|
||||
| Page component | `<PascalFeature>Page` (default export) | `JobCardsPage` |
|
||||
|
||||
### Relation Fields (Foreign Keys)
|
||||
### Relation Fields — Choosing the Right Component
|
||||
|
||||
**Two patterns exist. Pick the right one before building any relational field.**
|
||||
|
||||
#### Simple FK → `RhfAsyncSelectField`
|
||||
|
||||
Use for single-record foreign keys within the same domain or to a simple lookup/reference entity.
|
||||
|
||||
Examples: invoice → customer, bill → vendor, part → category, service → unit type, job card → vehicle, PO → department, any `*_type` or `*_terms` relation.
|
||||
|
||||
- Stored in form as `{ value: string, label: string } | null`
|
||||
- Use `toRelation(id, name)` to convert API data → form value
|
||||
- Use `toId(relation)` to convert form value → API payload
|
||||
- Schema uses `relationFieldSchema = z.object({ value: z.string(), label: z.string() }).nullable()`
|
||||
- Rendered with `<RhfAsyncSelectField>` (fetches options via React Query)
|
||||
|
||||
#### Cross-Domain Line Items → `RhfResourceField` (resource-selector skill)
|
||||
|
||||
Use when the relationship involves a **join table with extra fields** (quantity, rate, description) or the related items are from a **fully separate domain with its own CRUD page** and multiple records can be linked.
|
||||
|
||||
Examples: adding parts to a bill, linking services to an invoice, attaching expense items to a PO.
|
||||
|
||||
**→ Read the `resource-selector` SKILL before implementing these fields.**
|
||||
|
||||
Ready-to-use selector fields (import directly — do not re-implement):
|
||||
|
||||
| Component | Import path | For |
|
||||
|---|---|---|
|
||||
| `PartsSelectorField` | `@/modules/parts/parts-selector-field` | Parts line items |
|
||||
| `ServicesSelectorField` | `@/modules/services/services-selector-field` | Service line items |
|
||||
| `ExpenseItemsSelectorField` | `@/modules/expense-items/expense-items-selector-field` | Expense line items |
|
||||
|
||||
```tsx
|
||||
// Schema: use an array sub-schema with part_id / service_id / expense_id
|
||||
part_items: z.array(z.object({ part_id: z.number(), title: z.string(), quantity: z.number(), rate: z.number(), description: z.string().optional() })).optional()
|
||||
|
||||
// Form: render inside <FieldGroup>
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
```
|
||||
|
||||
### Async Select Pattern
|
||||
|
||||
@@ -144,8 +176,24 @@ const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) =
|
||||
| `RhfTextareaField` | Multi-line text |
|
||||
| `RhfCheckboxField` | Boolean toggles |
|
||||
| `RhfSelectField` | Static option dropdowns |
|
||||
| `RhfAsyncSelectField` | Server-fetched single-select combobox |
|
||||
| `RhfAsyncSelectField` | Server-fetched single FK combobox (same-domain relation) |
|
||||
| `RhfAsyncMultiSelectField` | Server-fetched multi-select combobox |
|
||||
| `RhfResourceField` | Cross-domain multi-select with join table extra fields (parts, services, expenses) — see resource-selector skill |
|
||||
| `RhfDateField` | Date picker — see date-time-pickers skill |
|
||||
| `RhfTimeField` | Time picker — see date-time-pickers skill |
|
||||
|
||||
### Required Prop Rule (Important)
|
||||
|
||||
When a field is required by schema or backend validation, always pass the `required` prop on the matching form component.
|
||||
|
||||
- Applies to all controls that support it, including custom selectors (for example `RhfCustomerSelectField`, `RhfVehicleSelectField`) and standard fields (`RhfTextField`, `RhfSelectField`, etc.)
|
||||
- Do not rely on schema-only required validation; keep UI required indicator (`*`) in sync with validation requirements
|
||||
|
||||
```tsx
|
||||
<RhfTextField name="title" label="Title" required />
|
||||
<RhfCustomerSelectField name="customer" required />
|
||||
<RhfVehicleSelectField name="vehicle" required customer_id={customer?.value} />
|
||||
```
|
||||
|
||||
### Imports Cheat Sheet
|
||||
|
||||
|
||||
@@ -37,11 +37,18 @@ import { <RESOURCE>_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
// Static select options (if needed):
|
||||
// const STATUS_OPTIONS = [
|
||||
// { value: "active", label: "Active" },
|
||||
// { value: "inactive", label: "Inactive" },
|
||||
// ]
|
||||
// ALWAYS derive select options from API enums imported from "@garage/api".
|
||||
// NEVER hardcode enum values inline — they must stay in sync with the backend.
|
||||
//
|
||||
// Pattern: import the enum array, then .map() to produce { value, label } pairs.
|
||||
//
|
||||
// const STATUS_OPTIONS = SomeStatus.map((v) => ({
|
||||
// value: v,
|
||||
// label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
// }))
|
||||
//
|
||||
// If no matching enum exists in packages/api/src/contracts/enums.ts, add it there first,
|
||||
// then import and use it here.
|
||||
|
||||
// ── Props ──
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# Invoice Pattern Skill
|
||||
|
||||
This skill defines the standard for implementing invoice-like forms (Invoice, Estimate, Job Card, Purchase Order, Bill, etc.) in the carage-erp dashboard. All such forms must follow this pattern for layout, discount/tax handling, and summary calculation. The current Invoice form is the canonical reference.
|
||||
|
||||
---
|
||||
|
||||
## 1. Layout
|
||||
- **Two-column grid:**
|
||||
- **Main column (9/12):**
|
||||
- Subject, invoice number/title
|
||||
- Status select, Discount Type select
|
||||
- Conditional Transaction Discount field
|
||||
- Line item selectors: Parts, Services, Expense Items (with optional line-level discount)
|
||||
- Notes, Terms & Conditions
|
||||
- Submit button
|
||||
- **Sidebar column (3/12):**
|
||||
- Invoice date, Due date
|
||||
- Customer, Vehicle selectors
|
||||
- Tax select (see below)
|
||||
- Department, Payment Terms, Invoice Sequence, Insurance fields
|
||||
- Summary card (see below)
|
||||
|
||||
## 2. Discount Implementation
|
||||
- **Discount Type:**
|
||||
- Field: `discount` (enum: 'no', 'line_item_level', 'transaction_level')
|
||||
- Select field in main column
|
||||
- **Transaction-level Discount:**
|
||||
- Field: `discount_amount` (number)
|
||||
- Only shown when `discount === "transaction_level"`
|
||||
- **Line-level Discount:**
|
||||
- Each line item (parts, services, expenses) has `discount_amount` field
|
||||
- Only shown when `discount === "line_item_level"`
|
||||
- **Payload Mapping:**
|
||||
- Only include `discount_amount` at transaction level if `discount === "transaction_level"`
|
||||
- Only include per-line `discount_amount` if `discount === "line_item_level"`
|
||||
|
||||
## 3. Tax Type Implementation
|
||||
- **Tax Field:**
|
||||
- Field: `tax` (relationFieldSchema: `{ value: string, label: string } | null`)
|
||||
- Uses `RhfAsyncSelectField` in sidebar
|
||||
- `mapOption`: `{ value: String(item.id), label: `${item.title} (${item.rate}%)` }`
|
||||
- The selected tax's rate is parsed from the label string in the summary (regex: `/\((\d+(?:\.\d+)?)%\)/`)
|
||||
|
||||
## 4. Summary Implementation
|
||||
- **Summary Card:**
|
||||
- Always rendered in the sidebar below the Details card
|
||||
- Uses `InvoiceFormSummary` (form-aware adapter)
|
||||
- `InvoiceFormSummary` flattens all line items, reads discount/tax fields, and passes them to `useDocumentTotals` hook
|
||||
- `useDocumentTotals` (pure hook) computes subtotal, discounts, tax, and total
|
||||
- `DocumentTotalsSummary` (pure display component) renders the summary
|
||||
|
||||
---
|
||||
|
||||
## Reference: Invoice Form
|
||||
- See `apps/dashboard/modules/invoices/invoice-form.tsx` for the canonical implementation.
|
||||
- Schema: `apps/dashboard/modules/invoices/invoice.schema.ts`
|
||||
- Summary logic: `apps/dashboard/modules/invoices/invoice-form-summary.tsx`, `shared/hooks/use-document-totals.ts`, `shared/components/document-totals-summary.tsx`
|
||||
|
||||
---
|
||||
|
||||
## Required for All Invoice-like Forms
|
||||
- Follow the above layout and field conventions
|
||||
- Use the same discount/tax logic and summary calculation
|
||||
- Use the same field and payload mapping patterns
|
||||
- Use the same summary component structure
|
||||
|
||||
---
|
||||
|
||||
## Example: Tax Field (in sidebar)
|
||||
```tsx
|
||||
<RhfAsyncSelectField
|
||||
name="tax"
|
||||
label="Tax"
|
||||
placeholder="Select tax rate"
|
||||
queryKey={[TAX_ROUTES.INDEX]}
|
||||
listFn={() => api.taxes.list()}
|
||||
mapOption={(item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.title ? `${item.title} (${item.rate}%)` : `#${item.id}`,
|
||||
})}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
```
|
||||
|
||||
## Example: Discount Type Select (in main column)
|
||||
```tsx
|
||||
<RhfSelectField name="discount" label="Discount Type" options={DISCOUNT_OPTIONS} />
|
||||
```
|
||||
|
||||
## Example: Summary Card
|
||||
```tsx
|
||||
<div className="mt-4">
|
||||
<InvoiceFormSummary />
|
||||
</div>
|
||||
```
|
||||
@@ -0,0 +1,258 @@
|
||||
---
|
||||
name: resource-filters
|
||||
description: "Add advanced filtering to resource list pages using a drawer/sheet with RHF forms and nuqs query params. Use when: adding filters to a ResourcePage, creating a filter drawer for any list page, implementing advanced search with URL-persisted filter state, adding query-param-based filtering to a CRUD page."
|
||||
---
|
||||
|
||||
# Resource Filters
|
||||
|
||||
Add URL-persisted advanced filtering to any ResourcePage or data table list. Filters live in a right-side Sheet drawer, powered by React Hook Form (RHF) and synced to URL query params via nuqs.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to add filters or advanced filters to a list/index page
|
||||
- User wants URL-shareable filter state on a resource page
|
||||
- User asks to filter by relations, dates, or boolean flags on any data table
|
||||
- User wants a filter drawer/dialog for any CRUD listing
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ useFilterParams (generic hook) │ ← Manages RHF form + nuqs URL sync
|
||||
│ • schema + defaults │
|
||||
│ • paramsParsers (nuqs) │
|
||||
│ • mapParamsToFormValues │
|
||||
│ • mapFormValuesToParams │
|
||||
│ Returns: form, appliedParams, │
|
||||
│ open/close/submit/reset, │
|
||||
│ activeFilterCount │
|
||||
└──────────────┬──────────────────┘
|
||||
│
|
||||
┌──────────┴──────────┐
|
||||
│ │
|
||||
┌───▼───────┐ ┌────────▼──────────┐
|
||||
│FilterDrawer│ │ ResourcePage │
|
||||
│(Sheet UI) │ │ extraParams={ │
|
||||
│ │ │ ...appliedParams│
|
||||
│ <Fields /> │ │ ...quickFilters │
|
||||
│ Apply/Reset│ │ } │
|
||||
└────────────┘ └───────────────────┘
|
||||
```
|
||||
|
||||
## File Locations
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `shared/hooks/use-filter-params.ts` | Generic hook — form + nuqs state sync |
|
||||
| `shared/components/filter-drawer.tsx` | `FilterDrawer` sheet + `FilterTrigger` button |
|
||||
| `modules/<feature>/<feature>-filters.tsx` | Feature-specific schema, parsers, mappers, fields |
|
||||
|
||||
## Procedure
|
||||
|
||||
### Step 1: Create the filter config file
|
||||
|
||||
Create `modules/<feature>/<feature>-filters.tsx` with:
|
||||
|
||||
1. **Zod schema** — all filter fields. Use `relationField` for foreign-key selects, `z.string().optional()` for dates, `z.boolean().optional()` for flags.
|
||||
2. **Default values** — matching the schema (null for relations, `""` for strings, `false` for booleans).
|
||||
3. **nuqs parsers** — `parseAsInteger` for relation IDs, `parseAsString` for dates/text, `parseAsBoolean` for flags.
|
||||
4. **`mapParamsToFormValues`** — URL params → form values. Use `toRelation(id)` for relation fields.
|
||||
5. **`mapFormValuesToParams`** — form values → URL params. Use `toId(relation)` for relation fields.
|
||||
6. **Config export** — `UseFilterParamsOptions<T>` object with schema, defaults, parsers, mappers.
|
||||
7. **Fields component** — renders RHF fields inside the drawer.
|
||||
|
||||
#### Template
|
||||
|
||||
```tsx
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { parseAsInteger, parseAsString, parseAsBoolean } from "nuqs"
|
||||
import { toRelation, toId, type RelationFieldValue } from "@/shared/lib/utils"
|
||||
import {
|
||||
RhfAsyncSelectField,
|
||||
RhfDateField,
|
||||
RhfCheckboxField,
|
||||
RhfSelectField,
|
||||
} from "@/shared/components/form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { SOME_ROUTES } from "@garage/api"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import type { UseFilterParamsOptions } from "@/shared/hooks/use-filter-params"
|
||||
|
||||
// ── Schema ──
|
||||
|
||||
const relationField = z.object({ value: z.string(), label: z.string() }).nullable().optional()
|
||||
|
||||
const filterSchema = z.object({
|
||||
some_relation_id: relationField,
|
||||
some_date: z.string().optional(),
|
||||
some_flag: z.boolean().optional(),
|
||||
})
|
||||
|
||||
type FilterValues = z.infer<typeof filterSchema>
|
||||
|
||||
// ── Defaults ──
|
||||
|
||||
const defaultValues: FilterValues = {
|
||||
some_relation_id: null,
|
||||
some_date: "",
|
||||
some_flag: false,
|
||||
}
|
||||
|
||||
// ── nuqs Parsers ──
|
||||
|
||||
const paramsParsers = {
|
||||
some_relation_id: parseAsInteger,
|
||||
some_date: parseAsString,
|
||||
some_flag: parseAsBoolean,
|
||||
}
|
||||
|
||||
// ── Mappers ──
|
||||
|
||||
function mapParamsToFormValues(params: Record<string, any>): Partial<FilterValues> {
|
||||
return {
|
||||
some_relation_id: params.some_relation_id ? toRelation(params.some_relation_id) : null,
|
||||
some_date: params.some_date ?? "",
|
||||
some_flag: params.some_flag ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormValuesToParams(values: FilterValues): Record<string, any> {
|
||||
return {
|
||||
some_relation_id: toId(values.some_relation_id as RelationFieldValue) ?? null,
|
||||
some_date: values.some_date || null,
|
||||
some_flag: values.some_flag || null,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Filter Config ──
|
||||
|
||||
export const featureFilterConfig: UseFilterParamsOptions<FilterValues> = {
|
||||
schema: filterSchema,
|
||||
defaultValues,
|
||||
paramsParsers,
|
||||
mapParamsToFormValues,
|
||||
mapFormValuesToParams,
|
||||
}
|
||||
|
||||
// ── Filter Fields Component ──
|
||||
|
||||
export function FeatureFilterFields() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<>
|
||||
<RhfAsyncSelectField
|
||||
name="some_relation_id"
|
||||
label="Some Relation"
|
||||
queryKey={[SOME_ROUTES.INDEX]}
|
||||
listFn={() => api.someResource.list( )}
|
||||
mapOption={(item: any) => ({ value: String(item.id), label: item.name })}
|
||||
placeholder="All"
|
||||
/>
|
||||
|
||||
<RhfDateField name="some_date" label="Some Date" />
|
||||
|
||||
<RhfCheckboxField name="some_flag" label="Some Flag" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Integrate into the page
|
||||
|
||||
In the page component:
|
||||
|
||||
```tsx
|
||||
import { useFilterParams } from '@/shared/hooks/use-filter-params'
|
||||
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
|
||||
import { featureFilterConfig, FeatureFilterFields } from '@/modules/<feature>/<feature>-filters'
|
||||
|
||||
export default function FeaturePage() {
|
||||
const filter = useFilterParams(featureFilterConfig)
|
||||
|
||||
// Combine drawer filters with any quick filters (tabs, search, etc.)
|
||||
const extraParams = useMemo(() => {
|
||||
const params: Record<string, unknown> = { ...filter.appliedParams }
|
||||
// Add quick filters if present
|
||||
if (search) params.search = search
|
||||
if (statusFilter !== "all") params.status = statusFilter
|
||||
return params
|
||||
}, [filter.appliedParams, search, statusFilter])
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourcePage
|
||||
extraParams={extraParams}
|
||||
headerProps={({ ... }) => ({
|
||||
title: "Feature",
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<FilterTrigger
|
||||
onClick={filter.open}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
/>
|
||||
{/* other actions like FormDialog */}
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
{/* columns, tableHeader, etc. */}
|
||||
/>
|
||||
|
||||
<FilterDrawer
|
||||
form={filter.form}
|
||||
isOpen={filter.isOpen}
|
||||
onOpenChange={(open) => { if (!open) filter.close() }}
|
||||
onSubmit={filter.onSubmit}
|
||||
onReset={filter.reset}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
title="Filter Features"
|
||||
>
|
||||
<FeatureFilterFields />
|
||||
</FilterDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Key Conventions
|
||||
|
||||
### Field Types
|
||||
|
||||
| Filter Type | Schema | nuqs Parser | Form Component | Default |
|
||||
|---|---|---|---|---|
|
||||
| Foreign key (select) | `relationField` (nullable object) | `parseAsInteger` | `RhfAsyncSelectField` | `null` |
|
||||
| Date | `z.string().optional()` | `parseAsString` | `RhfDateField` | `""` |
|
||||
| Boolean flag | `z.boolean().optional()` | `parseAsBoolean` | `RhfCheckboxField` | `false` |
|
||||
| Enum select | `z.string().optional()` | `parseAsString` | `RhfSelectField` | `""` |
|
||||
| Text/search | `z.string().optional()` | `parseAsString` | `RhfTextField` | `""` |
|
||||
| Comma-separated IDs | `z.string().optional()` | `parseAsString` | custom / `RhfTextField` | `""` |
|
||||
|
||||
### Relation Field Mapping
|
||||
|
||||
- **URL → Form**: `toRelation(params.field_id)` produces `{ value: "5", label: "5" }`. The async select resolves the display label from loaded options.
|
||||
- **Form → URL**: `toId(values.field_id)` extracts the numeric ID.
|
||||
- Import `toRelation`, `toId`, and `RelationFieldValue` from `@/shared/lib/utils`.
|
||||
|
||||
### Section Grouping
|
||||
|
||||
Group related filters with `<Separator />` and section labels:
|
||||
```tsx
|
||||
<Separator />
|
||||
<p className="text-sm font-medium text-muted-foreground pt-2">Section Name</p>
|
||||
```
|
||||
|
||||
### Pagination Reset
|
||||
|
||||
The `useFilterParams` hook automatically resets the `page` query param to `1` when filters are applied or reset, preventing empty-page issues.
|
||||
|
||||
### Quick Filters vs Drawer Filters
|
||||
|
||||
- **Quick filters** (status tabs, search input) live directly in `tableHeader` and are managed via `useState` or separate nuqs params on the page.
|
||||
- **Drawer filters** (advanced) are managed by `useFilterParams` and rendered inside `FilterDrawer`.
|
||||
- Both are merged into `extraParams` with `useMemo`.
|
||||
|
||||
## Reference Implementation
|
||||
|
||||
See `modules/job-cards/job-card-filters.tsx` and `app/(authenticated)/sales/job-cards/page.tsx` for the complete working example.
|
||||
@@ -0,0 +1,315 @@
|
||||
---
|
||||
name: resource-selector
|
||||
description: "Use RhfResourceField and ResourceSelectorDialog for cross-domain relational line-item fields in forms. Use when: linking parts/services/expense-items to invoices, bills, purchase orders, or estimates; adding line-item tables with qty/rate/description; picking multiple records from a separate domain entity. Do NOT use for simple FK relations like 'customer type' or 'payment terms' — use RhfAsyncSelectField for those."
|
||||
---
|
||||
|
||||
# Resource Selector (Cross-Domain Relations)
|
||||
|
||||
Use `RhfResourceField` + `ResourceSelectorDialog` when a form needs to pick **one or more records from a different domain** and store them as an **editable line-item array with extra data** (quantity, rate, description, etc.).
|
||||
|
||||
## Decision: RhfResourceField vs RhfAsyncSelectField
|
||||
|
||||
| Situation | Use |
|
||||
|---|---|
|
||||
| Linking parts / services / expense items to a bill, invoice, PO, or estimate | **`RhfResourceField`** |
|
||||
| Picking multiple cross-domain items that need per-row extra fields (qty, rate) | **`RhfResourceField`** |
|
||||
| Simple FK: invoice → customer, PO → vendor, job card → vehicle | **`RhfAsyncSelectField`** |
|
||||
| Simple FK: insurance type, payment terms, category, department, unit type | **`RhfAsyncSelectField`** |
|
||||
| Single-record lookup within the same domain | **`RhfAsyncSelectField`** |
|
||||
|
||||
**Rule:** If the relationship involves a **join table with extra fields** (quantity, rate, description, chart_of_account) or the related items are from a **fully separate domain with its own CRUD page**, use `RhfResourceField`. Otherwise use `RhfAsyncSelectField`.
|
||||
|
||||
### Domain Boundary Examples
|
||||
|
||||
```
|
||||
Cross-domain (use RhfResourceField): Simple FK (use RhfAsyncSelectField):
|
||||
Invoice ←→ Parts Invoice → Customer
|
||||
Invoice ←→ Services Invoice → Payment Terms
|
||||
Bill ←→ Parts Bill → Vendor
|
||||
Bill ←→ Services Bill → Department
|
||||
Bill ←→ Expense Items Part → Category
|
||||
PO ←→ Parts Service → Unit Type
|
||||
Estimate ←→ Services Job Card → Vehicle
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `shared/components/resource-selector/resource-selector-dialog.tsx` | Generic dialog wrapping `CrudResource` with multi-row selection + Confirm/Cancel |
|
||||
| `shared/components/resource-selector/rhf-resource-field.tsx` | RHF field: Card with trigger → opens dialog → renders items via `renderItems` callback |
|
||||
| `modules/<domain>/<domain>-columns.tsx` | Shared column definitions reused by both the domain page and selector dialogs |
|
||||
| `modules/<domain>/<domain>-selector-field.tsx` | Self-contained wrapper for a specific domain (e.g. `PartsSelectorField`) |
|
||||
|
||||
## Procedure
|
||||
|
||||
### Step 1: Create / Reuse Domain Columns File
|
||||
|
||||
If the domain already has a page, extract shared columns to `modules/<domain>/<domain>-columns.tsx`. This avoids duplication between the list page and the selector dialog.
|
||||
|
||||
```tsx
|
||||
// modules/parts/parts-columns.tsx
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
|
||||
export const partColumns = {
|
||||
title: {
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => <span className="font-medium">{(row.original as any).title || "—"}</span>,
|
||||
},
|
||||
purchasePrice: {
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
// ... more columns
|
||||
} satisfies Record<string, ColumnDef<any, any>>
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// CRITICAL: use `satisfies Record<string, ColumnDef<any, any>>`
|
||||
// NOT `as ColumnDef<unknown>` — the latter causes type errors in ResourceSelectorDialog
|
||||
```
|
||||
|
||||
### Step 2: Define the Item Shape in the Schema
|
||||
|
||||
Add a sub-schema for the line items inside the form schema:
|
||||
|
||||
```tsx
|
||||
// In <resource>.schema.ts
|
||||
const billPartItemSchema = z.object({
|
||||
part_id: z.number(),
|
||||
title: z.string(), // display only, not sent to API
|
||||
quantity: z.number().min(1),
|
||||
rate: z.number().min(0),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
|
||||
const billFormSchema = z.object({
|
||||
// ... other fields
|
||||
part_items: z.array(billPartItemSchema).optional(),
|
||||
service_items: z.array(billServiceItemSchema).optional(),
|
||||
})
|
||||
```
|
||||
|
||||
### Step 3: Create the Selector Field Component
|
||||
|
||||
Create `modules/<domain>/<domain>-selector-field.tsx`:
|
||||
|
||||
```tsx
|
||||
"use client"
|
||||
|
||||
import type { FieldValues, FieldPath } from "react-hook-form"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import {
|
||||
Table, TableHeader, TableBody,
|
||||
TableHead, TableRow, TableCell,
|
||||
} from "@/shared/components/ui/table"
|
||||
import { RhfResourceField } from "@/shared/components/resource-selector"
|
||||
import { partColumns } from "./parts-columns"
|
||||
import { PARTS_ROUTES } from "@garage/api"
|
||||
import type { PartsClient } from "@garage/api"
|
||||
|
||||
type PartItem = {
|
||||
part_id: number
|
||||
title: string
|
||||
quantity: number
|
||||
rate: number
|
||||
description?: string
|
||||
}
|
||||
|
||||
type Constraint = PartItem[] | undefined
|
||||
|
||||
export type PartsSelectorFieldProps<
|
||||
TValues extends FieldValues,
|
||||
TName extends FieldPath<TValues>,
|
||||
> = {
|
||||
name: TName & (TValues[TName] extends Constraint ? TName : never)
|
||||
label?: string
|
||||
triggerLabel?: string
|
||||
}
|
||||
|
||||
export function PartsSelectorField<
|
||||
TValues extends FieldValues,
|
||||
TName extends FieldPath<TValues>,
|
||||
>({ name, label = "Parts", triggerLabel = "Add Parts" }: PartsSelectorFieldProps<TValues, TName>) {
|
||||
return (
|
||||
<RhfResourceField<TValues, TName, PartsClient>
|
||||
name={name}
|
||||
label={label}
|
||||
triggerLabel={triggerLabel}
|
||||
itemKey="part_id" // deduplicate by this key when re-selecting
|
||||
dialogProps={{
|
||||
title: "Select Parts",
|
||||
crudProps: {
|
||||
routeKey: PARTS_ROUTES.INDEX,
|
||||
getClient: (api) => api.parts,
|
||||
columns: [
|
||||
partColumns.title,
|
||||
partColumns.partNumber,
|
||||
partColumns.purchasePrice,
|
||||
partColumns.stock,
|
||||
],
|
||||
},
|
||||
}}
|
||||
mapSelected={(row) => {
|
||||
const r = row as any
|
||||
return {
|
||||
part_id: r.id,
|
||||
title: r.title || "",
|
||||
quantity: 1,
|
||||
rate: Number(r.purchase_price) || 0,
|
||||
description: "",
|
||||
} as any
|
||||
}}
|
||||
renderItems={(items, { remove, update }) => (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Part</TableHead>
|
||||
<TableHead className="w-24">Qty</TableHead>
|
||||
<TableHead className="w-28">Rate</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead className="w-12" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{((items as PartItem[] | undefined) ?? []).map((item, index) => (
|
||||
<TableRow key={item.part_id}>
|
||||
<TableCell className="font-medium">{item.title}</TableCell>
|
||||
<TableCell>
|
||||
<Input type="number" min={1} value={item.quantity}
|
||||
onChange={(e) => update(index, { ...item, quantity: Number(e.target.value) || 1 } as any)}
|
||||
className="h-8 w-20" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input type="number" min={0} step={0.01} value={item.rate}
|
||||
onChange={(e) => update(index, { ...item, rate: Number(e.target.value) || 0 } as any)}
|
||||
className="h-8 w-24" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input value={item.description ?? ""}
|
||||
onChange={(e) => update(index, { ...item, description: e.target.value } as any)}
|
||||
placeholder="Optional description" className="h-8" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={() => remove(index)}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Wire into the Form
|
||||
|
||||
```tsx
|
||||
// In <resource>-form.tsx
|
||||
|
||||
// 1. Import
|
||||
import { PartsSelectorField } from "@/modules/parts/parts-selector-field"
|
||||
import { ServicesSelectorField } from "@/modules/services/services-selector-field"
|
||||
|
||||
// 2. Add to DEFAULT_VALUES
|
||||
const DEFAULT_VALUES = {
|
||||
// ...
|
||||
part_items: [],
|
||||
service_items: [],
|
||||
}
|
||||
|
||||
// 3. Map from API → form (in mapToFormValues)
|
||||
part_items: (d.parts ?? []).map((p: any) => ({
|
||||
part_id: p.part_id ?? p.id,
|
||||
title: p.part?.title ?? p.title ?? "",
|
||||
quantity: Number(p.quantity) || 1,
|
||||
rate: Number(p.rate) || 0,
|
||||
description: p.description ?? "",
|
||||
})),
|
||||
|
||||
// 4. Map from form → API payload (in mapFormToPayload)
|
||||
part_items: (values.part_items ?? []).map((item) => ({
|
||||
part_id: item.part_id,
|
||||
quantity: item.quantity,
|
||||
rate: item.rate,
|
||||
description: item.description || undefined,
|
||||
})),
|
||||
|
||||
// 5. Render inside <FieldGroup>
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
<ServicesSelectorField<MyFormValues, "service_items"> name="service_items" />
|
||||
```
|
||||
|
||||
## Existing Selector Fields (Ready to Use)
|
||||
|
||||
These are already built. Import and use directly — do NOT re-implement from scratch:
|
||||
|
||||
| Component | File | `itemKey` | Notes |
|
||||
|---|---|---|---|
|
||||
| `PartsSelectorField` | `modules/parts/parts-selector-field.tsx` | `part_id` | qty + rate + description editable |
|
||||
| `ServicesSelectorField` | `modules/services/services-selector-field.tsx` | `service_id` | qty + rate + description editable |
|
||||
| `ExpenseItemsSelectorField` | `modules/expense-items/expense-items-selector-field.tsx` | `expense_id` | qty + rate + description editable |
|
||||
|
||||
**Usage:**
|
||||
```tsx
|
||||
import { PartsSelectorField } from "@/modules/parts/parts-selector-field"
|
||||
import { ServicesSelectorField } from "@/modules/services/services-selector-field"
|
||||
import { ExpenseItemsSelectorField } from "@/modules/expense-items/expense-items-selector-field"
|
||||
|
||||
// Inside <FieldGroup>:
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
<ServicesSelectorField<MyFormValues, "service_items"> name="service_items" />
|
||||
<ExpenseItemsSelectorField<MyFormValues, "expense_items"> name="expense_items" />
|
||||
```
|
||||
|
||||
## API Props Reference
|
||||
|
||||
### `RhfResourceField`
|
||||
|
||||
| Prop | Type | Required | Description |
|
||||
|---|---|---|---|
|
||||
| `name` | `FieldPath<TValues>` | ✅ | RHF field name; value is an array |
|
||||
| `label` | `string` | ✅ | Card heading |
|
||||
| `triggerLabel` | `string` | | Button label (defaults to `label`) |
|
||||
| `mapSelected` | `(row) => ItemShape` | ✅ | Maps a selected table row to the form item shape |
|
||||
| `renderItems` | `(items, helpers) => ReactNode` | ✅ | Renders the editable item table |
|
||||
| `dialogProps` | object | ✅ | Config for the selector dialog (see below) |
|
||||
| `itemKey` | `string` | | Field used for deduplication. Defaults to `"id"` |
|
||||
|
||||
### `dialogProps`
|
||||
|
||||
```ts
|
||||
{
|
||||
title: string // Dialog heading
|
||||
crudProps: {
|
||||
routeKey: ApiPath // e.g. PARTS_ROUTES.INDEX
|
||||
getClient: (api) => client // e.g. (api) => api.parts
|
||||
columns: ColumnDef[] // Subset of domain columns to show
|
||||
}
|
||||
rowKey?: keyof Item // Selection identity key (defaults to "id")
|
||||
}
|
||||
```
|
||||
|
||||
### `renderItems` helpers
|
||||
|
||||
| Helper | Signature | Description |
|
||||
|---|---|---|
|
||||
| `remove` | `(index: number) => void` | Remove item at index |
|
||||
| `update` | `(index: number, item) => void` | Replace item at index |
|
||||
| `replace` | `(items) => void` | Replace entire array |
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Column type error**: Always use `satisfies Record<string, ColumnDef<any, any>>` on the columns object. Using `as ColumnDef<unknown>` per-entry causes type errors in the selector dialog.
|
||||
- **itemKey mismatch**: The `itemKey` on `RhfResourceField` must match the field name in your item shape (e.g. `"part_id"`, not `"id"`).
|
||||
- **Pre-fill in create mode**: `useResourceForm` uses a shallow spread for initial data. Pre-fill the field with already-shaped items (not raw API shape) to avoid empty arrays. See the `mapToFormValues` pattern above.
|
||||
- **Selector field generic parameters**: Always pass both type params when using a selector field in a form: `<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />`.
|
||||
@@ -5,11 +5,11 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -26,6 +26,9 @@ export default function AppointmentsPage() {
|
||||
<ResourcePage<AppointmentsClient>
|
||||
pageTitle="Appointments"
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -86,22 +89,14 @@ export default function AppointmentsPage() {
|
||||
id: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const jobCardId = (row.original as any).job_card_id
|
||||
if (!jobCardId) return <span className="text-muted-foreground">—</span>
|
||||
const item = row.original as any
|
||||
const jobCardId = item.job_card_id ?? item.job_card?.id
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
router.push(`/sales/job-cards/${jobCardId}`)
|
||||
}}
|
||||
>
|
||||
<ClipboardListIcon className="size-3" />
|
||||
#{jobCardId}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Button>
|
||||
<RelationLink
|
||||
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
export default function CalendarsPage() {
|
||||
return redirect("/calendar/appointment/list")
|
||||
}
|
||||
|
||||
@@ -201,15 +201,20 @@ export default function InventoryAdjustmentsPage() {
|
||||
<ResourcePage<InventoryAdjustmentsClient>
|
||||
pageTitle="Inventory Adjustments"
|
||||
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search adjustments..."
|
||||
getClient={(api) => api.inventoryAdjustments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inventory Adjustment">
|
||||
{(resourceId) => (
|
||||
<FormDialog
|
||||
title="Inventory Adjustment"
|
||||
classNames={{ dialogContent: "lg:min-w-4xl" }}
|
||||
>
|
||||
{(resourceId, { close }) => (
|
||||
<InventoryAdjustmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => { invalidateQuery(); close() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"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 { ExpenseItemForm } from "@/modules/expense-items/expense-item-form"
|
||||
import { EXPENSE_ITEM_ROUTES } from "@garage/api"
|
||||
import type { ExpenseItemsClient } from "@garage/api"
|
||||
|
||||
export default function ExpenseItemPage() {
|
||||
return (
|
||||
<ResourcePage<ExpenseItemsClient>
|
||||
pageTitle="Expense Items"
|
||||
routeKey={EXPENSE_ITEM_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expense items..."
|
||||
getClient={(api) => api.expenseItems}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Expense Item">
|
||||
{(resourceId, { close }) => (
|
||||
<ExpenseItemForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "item_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Item Name" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_chart_of_account",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Chart of Account" />,
|
||||
cell: ({ row }) => (row.original as any).purchase_chart_of_account || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<span className={active ? "text-green-600" : "text-muted-foreground"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +1,37 @@
|
||||
"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 { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { PartForm } from "@/modules/parts/part-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { partColumns } from "@/modules/parts/parts-columns"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { PARTS_ROUTES } from "@garage/api"
|
||||
import type { PartsClient } from "@garage/api"
|
||||
|
||||
export default function PartsPage() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<ResourcePage<PartsClient>
|
||||
pageTitle="Parts"
|
||||
routeKey={PARTS_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search parts..."
|
||||
getClient={(api) => api.parts}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.parts.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Parts"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.parts.exportData(filters)}
|
||||
fileName="parts"
|
||||
/>
|
||||
<FormDialog title="Part">
|
||||
{(resourceId) => (
|
||||
<PartForm
|
||||
@@ -25,72 +41,21 @@ export default function PartsPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
return (
|
||||
<div>
|
||||
<span className="font-medium">{r.title || "—"}</span>
|
||||
{r.sku && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{r.sku}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "part_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Part #" />,
|
||||
cell: ({ row }) => (row.original as any).part_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "manufactured_by",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Manufacturer" />,
|
||||
cell: ({ row }) => (row.original as any).manufactured_by || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "selling_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Sell Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).selling_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<Badge variant={active ? "default" : "secondary"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
partColumns.title,
|
||||
partColumns.partNumber,
|
||||
partColumns.manufacturer,
|
||||
partColumns.sellingPrice,
|
||||
partColumns.purchasePrice,
|
||||
partColumns.stock,
|
||||
partColumns.status,
|
||||
partColumns.createdAt,
|
||||
actionsColumn(),
|
||||
]}
|
||||
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
|
||||
<ResourcePage<ServiceGroupsClient>
|
||||
pageTitle="Service Groups"
|
||||
routeKey={SERVICE_GROUP_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search service groups..."
|
||||
getClient={(api) => api.serviceGroups}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -3,18 +3,35 @@
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ServiceForm } from "@/modules/services/service-form"
|
||||
import { SERVICE_ROUTES } from "@garage/api"
|
||||
import type { ServicesClient } from "@garage/api"
|
||||
|
||||
export default function ServicesPage() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<ResourcePage<ServicesClient>
|
||||
pageTitle="Services"
|
||||
routeKey={SERVICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search services..."
|
||||
getClient={(api) => api.services}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.services.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Services"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.services.exportData(filters)}
|
||||
fileName="services"
|
||||
/>
|
||||
<FormDialog title="Service">
|
||||
{(resourceId) => (
|
||||
<ServiceForm
|
||||
@@ -24,6 +41,7 @@ export default function ServicesPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -48,7 +66,7 @@ export default function ServicesPage() {
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).description
|
||||
return val
|
||||
? <span className="max-w-[200px] truncate block">{val}</span>
|
||||
? <span className="max-w-50 truncate block">{val}</span>
|
||||
: "—"
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { DashboardHeader } from "@/base/components/layout/dashboard";
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page";
|
||||
import { DashboardContent } from "@/modules/home/dashboard-content";
|
||||
import { DashboardFiltersToolbar } from "@/modules/home/dashboard-filters-toolbar";
|
||||
|
||||
export default function page() {
|
||||
return (
|
||||
<DashboardPage headerProps={{title: "Dashboard"}} >
|
||||
<DashboardPage headerProps={{ title: "Dashboard", actions: <DashboardFiltersToolbar /> }} >
|
||||
<DashboardContent />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -23,7 +23,7 @@ export default async function layout(props: {
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={employee.data?.position || employee.data?.designation || undefined}
|
||||
description={(employee.data as any)?.position || employee.data?.designation || undefined}
|
||||
backHref="/productivity/employees"
|
||||
actions={<EmployeeActions employeeId={id} />}
|
||||
tabs={[
|
||||
|
||||
@@ -14,6 +14,9 @@ export default function EmployeesPage() {
|
||||
<ResourcePage<EmployeesClient>
|
||||
pageTitle="Employees"
|
||||
routeKey={EMPLOYEE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search employees..."
|
||||
statusFilter={{ statuses: ["active", "inactive"] }}
|
||||
getClient={(api) => api.employees}
|
||||
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
|
||||
@@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
|
||||
<ResourcePage<HolidayYearsClient>
|
||||
pageTitle="Holiday Years"
|
||||
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search holidays..."
|
||||
getClient={(api) => api.holidayYears}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
|
||||
<ResourcePage<ShopCalendarsClient>
|
||||
pageTitle="Shop Calendars"
|
||||
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop calendars..."
|
||||
getClient={(api) => api.shopCalendars}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
|
||||
<ResourcePage<ShopTimingsClient>
|
||||
pageTitle="Shop Timings"
|
||||
routeKey={SHOP_TIMING_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop timings..."
|
||||
getClient={(api) => api.shopTimings}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
|
||||
export default function TasksPage() {
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Tasks",
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
|
||||
export default function BillEditPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params)
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: [BILL_ROUTES.BY_ID, id],
|
||||
queryFn: () => api.bills.show(id),
|
||||
})
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="flex items-center justify-center p-8 text-muted-foreground">
|
||||
Loading...
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="p-6">
|
||||
<BillForm
|
||||
resourceId={id}
|
||||
initialData={data}
|
||||
onSuccess={() => router.push(`/purchase/bill/${id}`)}
|
||||
/>
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { BillActions } from '@/modules/bills/bill-actions'
|
||||
import { BillProvider, type BillResponse } from '@/modules/bills/bill-context'
|
||||
import BillStatusBadge from '@/modules/bills/bill-status-badge'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function BillDetailLayout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const bill = await api.bills.show(id)
|
||||
const data = bill.data as BillResponse
|
||||
const title = data?.title || data?.bill_number || 'Bill Details'
|
||||
return (
|
||||
<BillProvider bill={data}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={data?.bill_number ? `Bill #: ${data.bill_number}` : undefined}
|
||||
icon={<ReceiptIcon className="size-5" />}
|
||||
backHref="/purchase/bill"
|
||||
actions={
|
||||
<div className="flex space-x-2 items-center">
|
||||
<BillStatusBadge bill={{id, status:data?.status}} />
|
||||
<ShareDocumentButton type="bill" id={id} />
|
||||
<BillActions billId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/purchase/bill/${id}`,
|
||||
label: 'Details',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</BillProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { BillGeneralInfo } from '@/modules/bills/bill-general-info'
|
||||
import { BillPartsSection } from '@/modules/bills/bill-parts-section'
|
||||
import { BillServicesSection } from '@/modules/bills/bill-services-section'
|
||||
import { BillExpensesSection } from '@/modules/bills/bill-expenses-section'
|
||||
import { BillTotalsSummary } from '@/modules/bills/bill-totals-summary'
|
||||
import { BillPaymentsSection } from '@/modules/bills/bill-payments-section'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function BillDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const bill = await api.bills.show(id)
|
||||
const data = (bill as any)?.data ?? bill
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Bill not found.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-6">
|
||||
<BillGeneralInfo />
|
||||
<BillPartsSection parts={data.parts} />
|
||||
<BillServicesSection services={data.services} />
|
||||
<BillExpensesSection expenses={data.expenses} />
|
||||
<BillPaymentsSection />
|
||||
<BillTotalsSummary />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2 } from "lucide-react"
|
||||
|
||||
export default function BillsPage() {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
pageTitle="Bills"
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Bill">
|
||||
<FormDialog classNames={{ dialogContent: "lg:min-w-6xl" }} title="Bill">
|
||||
{(resourceId) => (
|
||||
<BillForm
|
||||
resourceId={resourceId}
|
||||
@@ -33,37 +45,60 @@ export default function BillsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Total" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).total
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Balance Due" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).balance_due
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
accessorKey: "vendor",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill Date" />,
|
||||
cell: ({ row }) => {
|
||||
const value = (row.original as any).bill_date
|
||||
return value ? new Date(value).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ row }) => formatDate((row.original as any).bill_date) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_due_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||
cell: ({ row }) => {
|
||||
const value = (row.original as any).bill_due_date
|
||||
return value ? new Date(value).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ row }) => formatDate((row.original as any).bill_due_date) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status?.replace(/_/g, " ") || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
@@ -71,3 +106,4 @@ export default function BillsPage() {
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { ExpenseActions } from '@/modules/expenses/expense-actions'
|
||||
import { ExpenseProvider, type ExpenseContextValue } from '@/modules/expenses/expense-context'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function ExpenseDetailLayout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const expense = await api.expenses.getById(id)
|
||||
const data = expense.data as ExpenseContextValue
|
||||
const title = data?.title || data?.invoice_number || 'Expense Details'
|
||||
|
||||
return (
|
||||
<ExpenseProvider expense={data}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
||||
icon={<ReceiptIcon className="size-5" />}
|
||||
backHref="/purchase/expense"
|
||||
actions={<ExpenseActions expenseId={id} />}
|
||||
tabs={[
|
||||
{
|
||||
href: `/purchase/expense/${id}`,
|
||||
label: 'Details',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</ExpenseProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import { ExpenseGeneralInfo } from '@/modules/expenses/expense-general-info'
|
||||
import { ExpenseItemsSection } from '@/modules/expenses/expense-items-section'
|
||||
import { ExpensePaymentsSection } from '@/modules/expenses/expense-payments-section'
|
||||
import { formatTaxLabel } from '@/shared/utils/formatters'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
|
||||
export default async function ExpenseDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const expense = await api.expenses.show(id)
|
||||
const data = (expense as any)?.data ?? expense
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Expense not found.</div>
|
||||
}
|
||||
|
||||
const taxLabel = formatTaxLabel(data.tax, '') || undefined
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-6">
|
||||
<ExpenseGeneralInfo />
|
||||
<ExpensePaymentsSection />
|
||||
<ExpenseItemsSection
|
||||
items={data.expense_items}
|
||||
discountType={data.discount}
|
||||
subTotal={data.sub_total}
|
||||
discountAmount={data.discount_amount_major}
|
||||
taxAmount={data.tax_amount}
|
||||
total={data.total}
|
||||
taxLabel={taxLabel}
|
||||
/>
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -5,18 +5,32 @@ import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { EXPENSE_ROUTES } from "@garage/api"
|
||||
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
|
||||
import type { ExpensesClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2 } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function ExpensesPage() {
|
||||
const router = useRouter()
|
||||
return (
|
||||
<ResourcePage<ExpensesClient>
|
||||
pageTitle="Expenses"
|
||||
routeKey={EXPENSE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expenses..."
|
||||
statusFilter={{ statuses: ExpenseStatus }}
|
||||
getClient={(api) => api.expenses}
|
||||
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Expense">
|
||||
<FormDialog
|
||||
title="Expense"
|
||||
classNames={{ dialogContent: "lg:min-w-6xl" }}
|
||||
>
|
||||
{(resourceId) => (
|
||||
<ExpenseForm
|
||||
resourceId={resourceId}
|
||||
@@ -38,38 +52,53 @@ export default function ExpensesPage() {
|
||||
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
accessorKey: "vendor",
|
||||
header: () => "Vendor",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor) || vendor?.name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "expense_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).expense_date
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
cell: ({ row }) => formatDate((row.original as any).expense_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: () => "Total",
|
||||
cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: () => "Balance Due",
|
||||
cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
const variantMap: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
draft: "secondary",
|
||||
open: "default",
|
||||
un_paid: "destructive",
|
||||
partially_paid: "secondary",
|
||||
paid: "default",
|
||||
}
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status || "—"}
|
||||
<Badge variant={variantMap[status] ?? "outline"}>
|
||||
{formatEnum(status) || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -32,8 +32,11 @@ import {
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { PAYMENT_MADE_ROUTES } from "@garage/api"
|
||||
import type { PaymentMadesClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2 } from "lucide-react"
|
||||
|
||||
// ── Attachment helpers ──
|
||||
|
||||
@@ -208,10 +211,13 @@ function AttachmentsDialog({
|
||||
type PaymentMadeItem = {
|
||||
id: number
|
||||
payment_number?: string
|
||||
vendor?: { id?: number | string; company_name?: string | null; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
vendor_name?: string
|
||||
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
employee_name?: string
|
||||
payment_for?: string
|
||||
payment_made?: string | number
|
||||
payment_mode?: { name?: string | null; title?: string | null } | null
|
||||
payment_mode_name?: string
|
||||
payment_date?: string
|
||||
paid_through?: string
|
||||
@@ -230,14 +236,20 @@ export default function PaymentsMadePage() {
|
||||
<ResourcePage<PaymentMadesClient>
|
||||
pageTitle="Payments Made"
|
||||
routeKey={PAYMENT_MADE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => api.paymentMades}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Record Payment">
|
||||
{(resourceId) => (
|
||||
{(resourceId, { close }) => (
|
||||
<PaymentMadeForm
|
||||
resourceId={resourceId}
|
||||
onSuccess={invalidateQuery}
|
||||
initialData={selectedItem}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -262,11 +274,27 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const isVendor =
|
||||
item.vendor?.company_name ||
|
||||
getFullName(item.vendor) ||
|
||||
item.vendor?.name ||
|
||||
item.vendor_name
|
||||
const label =
|
||||
isVendor ||
|
||||
getFullName(item.employee) ||
|
||||
item.employee?.name ||
|
||||
item.employee_name
|
||||
const href = isVendor && item.vendor?.id
|
||||
? `/purchase/vendor/${item.vendor.id}`
|
||||
: item.employee?.id
|
||||
? `/productivity/employees/${item.employee.id}`
|
||||
: null
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.vendor_name || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={href}
|
||||
icon={isVendor ? Building2 : UserIcon}
|
||||
label={label}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -309,10 +337,15 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const label =
|
||||
item.payment_mode?.name ||
|
||||
item.payment_mode?.title ||
|
||||
item.payment_mode_name ||
|
||||
"—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
||||
<span className="capitalize">{label}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { PurchaseOrderActions } from '@/modules/purchase-orders/purchase-order-actions'
|
||||
import { PurchaseOrderProvider } from '@/modules/purchase-orders/purchase-order-context'
|
||||
import { CreateBillFromPOButton } from '@/modules/purchase-orders/create-bill-from-po-button'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { ClipboardList } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const purchaseOrder = (await api.purchaseOrders.getById(id)) as any
|
||||
|
||||
const data = purchaseOrder?.data ?? purchaseOrder
|
||||
const title = data?.title || data?.order_number || 'Purchase Order'
|
||||
const orderNumber = data?.order_number
|
||||
const description = orderNumber ? `Order #: ${orderNumber}` : undefined
|
||||
|
||||
return (
|
||||
<PurchaseOrderProvider purchaseOrder={{ id, label: title, data }}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
icon={<ClipboardList className="size-5" />}
|
||||
title={title}
|
||||
description={description}
|
||||
backHref="/purchase/purchase-order"
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<CreateBillFromPOButton />
|
||||
<ShareDocumentButton type="purchase_order" id={id} />
|
||||
<PurchaseOrderActions purchaseOrderId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{ href: `/purchase/purchase-order/${id}`, label: 'Details' },
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</PurchaseOrderProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { PurchaseOrderGeneralInfo } from '@/modules/purchase-orders/purchase-order-general-info'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = await api.purchaseOrders.getById(id)
|
||||
|
||||
const purchaseOrder = (response as any)?.data ?? response
|
||||
|
||||
if (!purchaseOrder) {
|
||||
return <div className="text-muted-foreground">Purchase order not found.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<PurchaseOrderGeneralInfo purchaseOrder={purchaseOrder} />
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -1,26 +1,35 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2 } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function PurchaseOrdersPage() {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
pageTitle="Purchase Orders"
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Purchase Order">
|
||||
{(resourceId) => (
|
||||
<FormDialog classNames={{ dialogContent: "min-w-6xl" }} title="Purchase Order">
|
||||
{(resourceId, { close }) => (
|
||||
<PurchaseOrderForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => { invalidateQuery(); close()}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -39,7 +48,16 @@ export default function PurchaseOrdersPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
|
||||
@@ -5,14 +5,20 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
|
||||
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
|
||||
import { VENDOR_CREDIT_ROUTES, VendorCreditStatus } from "@garage/api"
|
||||
import type { VendorCreditsClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function VendorCreditsPage() {
|
||||
return (
|
||||
<ResourcePage<VendorCreditsClient>
|
||||
pageTitle="Vendor Credits"
|
||||
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendor credits..."
|
||||
statusFilter={{ statuses: VendorCreditStatus }}
|
||||
getClient={(api) => api.vendorCredits}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
@@ -35,12 +41,30 @@ export default function VendorCreditsPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.bill?.id ? `/purchase/bill/${item.bill.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill?.bill_number || item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_credit_date",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DashboardDetailsPage } from "@/base/components/layout/dashboard"
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorActions } from "@/modules/vendors/vendor-actions"
|
||||
import { VendorProvider } from "@/modules/vendors/vendor-context"
|
||||
import React from "react"
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
const company = vendor?.company_name as string | undefined
|
||||
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
|
||||
const title = company || fullName || "Vendor Details"
|
||||
const isActive = vendor?.is_active ?? vendor?.status === "active"
|
||||
|
||||
return (
|
||||
<VendorProvider vendor={{ id, label: title }}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={vendor?.email ?? vendor?.phone ?? undefined}
|
||||
backHref="/purchase/vendor"
|
||||
actions={<VendorActions vendorId={id} isActive={Boolean(isActive)} />}
|
||||
tabs={[
|
||||
{ href: `/purchase/vendor/${id}`, label: "Details" },
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</VendorProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorGeneralInfo } from "@/modules/vendors/vendor-general-info"
|
||||
|
||||
export default async function VendorDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
|
||||
// so cast through `any` here until the schema is regenerated.
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
if (!vendor) {
|
||||
return <div className="text-muted-foreground p-6">Vendor not found.</div>
|
||||
}
|
||||
|
||||
return <VendorGeneralInfo vendor={vendor} />
|
||||
}
|
||||
+42
-1
@@ -1,18 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { Power } from "lucide-react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { VendorForm } from "@/modules/vendors/vendor-form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { VENDOR_ROUTES } from "@garage/api"
|
||||
import type { VendorsClient } from "@garage/api"
|
||||
|
||||
export default function VendorsPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<VendorsClient>
|
||||
pageTitle="Vendors"
|
||||
routeKey={VENDOR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendors..."
|
||||
getClient={(api) => api.vendors}
|
||||
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Vendor">
|
||||
@@ -46,6 +56,18 @@ export default function VendorsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
|
||||
cell: ({ row }) => (row.original as any).email || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const isActive = Boolean((row.original as any).is_active)
|
||||
return (
|
||||
<Badge variant={isActive ? "default" : "outline"}>
|
||||
{isActive ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
@@ -54,7 +76,26 @@ export default function VendorsPage() {
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => {
|
||||
const isActive = Boolean((row as any).is_active)
|
||||
return [
|
||||
{
|
||||
label: isActive ? "Deactivate" : "Activate",
|
||||
icon: Power,
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
|
||||
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast.error("Failed to update vendor status.")
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } 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 { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { CreditNoteDocumentForm } from "@/modules/credit-notes/credit-note-document-form"
|
||||
|
||||
type CreditNoteAttachment = {
|
||||
id: number
|
||||
name?: string
|
||||
url?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export default function CreditNoteDocumentsPage() {
|
||||
const { id: creditNoteId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
const queryKey = ["credit-note-attachments", creditNoteId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const response = await api.creditNotes.show(creditNoteId)
|
||||
return (response as any)?.data ?? response
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (attachmentId: number) =>
|
||||
api.creditNotes.deleteAttachment(creditNoteId, { attachment_id: attachmentId }),
|
||||
onSuccess: () => {
|
||||
toast.success("Attachment deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete attachment.")
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = async (attachment: CreditNoteAttachment) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Attachment",
|
||||
description: `Are you sure you want to delete "${attachment.name || "this attachment"}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (confirmed) {
|
||||
deleteMutation.mutate(attachment.id)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CreditNoteAttachment>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ getValue, row }) => {
|
||||
const name = getValue<string>()
|
||||
const url = row.original.url
|
||||
if (url) {
|
||||
return (
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" className="text-primary underline">
|
||||
{name || "Attachment"}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return name || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
title="Delete attachment"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
]
|
||||
|
||||
const attachments: CreditNoteAttachment[] = (data as any)?.attachments ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 lg:p-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Attachment
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={attachments}
|
||||
pagination={{ page: 1, pageSize: 15, pageCount: 1, total: attachments.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Attachment</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreditNoteDocumentForm
|
||||
creditNoteId={creditNoteId}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { CreditNoteActions } from '@/modules/credit-notes/credit-note-actions'
|
||||
import { CreditNoteProvider } from '@/modules/credit-notes/credit-note-context'
|
||||
import { ReceiptTextIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function CreditNoteDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const creditNote = await api.creditNotes.show(id)
|
||||
const data = (creditNote as any)?.data ?? creditNote
|
||||
const title = data?.subject || data?.credit_invoice || 'Credit Note Details'
|
||||
|
||||
return (
|
||||
<CreditNoteProvider creditNote={{ id, label: title }}>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
title={title}
|
||||
description={data?.credit_invoice ? `Credit Note #: ${data.credit_invoice}` : undefined}
|
||||
icon={<ReceiptTextIcon className="size-5" />}
|
||||
backHref="/sales/credit-notes"
|
||||
actions={<CreditNoteActions creditNoteId={id} />}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/credit-notes/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
{
|
||||
href: `/sales/credit-notes/${id}/documents`,
|
||||
label: 'Documents'
|
||||
},
|
||||
{
|
||||
href: `/sales/credit-notes/${id}/notes`,
|
||||
label: 'Notes'
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</CreditNoteProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } 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 { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { CreditNoteNoteForm } from "@/modules/credit-notes/credit-note-note-form"
|
||||
|
||||
type CreditNoteNote = {
|
||||
id: number
|
||||
note?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export default function CreditNoteNotesPage() {
|
||||
const { id: creditNoteId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
const queryKey = ["credit-note-notes", creditNoteId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const response = await api.creditNotes.show(creditNoteId)
|
||||
return (response as any)?.data ?? response
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (noteId: number) =>
|
||||
api.creditNotes.deleteInternalNote(creditNoteId, { note_id: noteId } as never),
|
||||
onSuccess: () => {
|
||||
toast.success("Note deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete note.")
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = async (note: CreditNoteNote) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Note",
|
||||
description: "Are you sure you want to delete this note?",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (confirmed) {
|
||||
deleteMutation.mutate(note.id)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CreditNoteNote>[] = [
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
title="Delete note"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
]
|
||||
|
||||
const notes: CreditNoteNote[] = (data as any)?.internal_notes ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 lg:p-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Note
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={notes}
|
||||
pagination={{ page: 1, pageSize: 15, pageCount: 1, total: notes.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Note</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreditNoteNoteForm
|
||||
creditNoteId={creditNoteId}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { CreditNoteGeneralInfo } from '@/modules/credit-notes/credit-note-general-info'
|
||||
|
||||
export default async function CreditNoteDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = await api.creditNotes.show(id)
|
||||
const creditNote = (response as any)?.data ?? response
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-6">
|
||||
<CreditNoteGeneralInfo creditNote={creditNote} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { CreditNoteForm } from "@/modules/credit-notes/credit-note-form"
|
||||
import { CREDIT_NOTE_ROUTES, CreditNoteStatus } from "@garage/api"
|
||||
import type { CreditNotesClient } from "@garage/api"
|
||||
|
||||
type CreditNoteItem = {
|
||||
id: number
|
||||
subject?: string
|
||||
credit_invoice?: string
|
||||
customer_id?: number
|
||||
status?: string
|
||||
date?: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export default function CreditNotesPage() {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<ResourcePage<CreditNotesClient>
|
||||
pageTitle="Credit Notes"
|
||||
routeKey={CREDIT_NOTE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search credit notes..."
|
||||
statusFilter={{ statuses: CreditNoteStatus }}
|
||||
getClient={(api) => api.creditNotes}
|
||||
onRowClick={(row) => router.push(`/sales/credit-notes/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Credit Note">
|
||||
{(resourceId) => (
|
||||
<CreditNoteForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "subject",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Subject" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "credit_invoice",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Credit Note #" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as CreditNoteItem
|
||||
const status = item.status
|
||||
const colorMap: Record<string, string> = {
|
||||
draft: "text-muted-foreground",
|
||||
open: "text-blue-600",
|
||||
applied: "text-green-600",
|
||||
void: "text-gray-400",
|
||||
}
|
||||
return (
|
||||
<span className={colorMap[status ?? ""] ?? ""}>
|
||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -146,14 +146,15 @@ export default function CustomerNotesPage() {
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
header={null}
|
||||
title="Notes"
|
||||
toolbar={
|
||||
headerProps={{
|
||||
title: "Notes",
|
||||
actions: (
|
||||
<Button size="sm" onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Note
|
||||
</Button>
|
||||
}
|
||||
),
|
||||
}}
|
||||
>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
|
||||
|
||||
return (
|
||||
<ResourcePage<VehiclesClient>
|
||||
toolbar={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
<FormDialog title="Vehicle">
|
||||
{(resourceId) => (
|
||||
<VehicleForm
|
||||
@@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
|
||||
)}
|
||||
pageTitle="Customer Vehicles"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
extraParams={{ customer_id: customerId }}
|
||||
header={null}
|
||||
|
||||
@@ -4,6 +4,9 @@ import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import { CustomerForm } from '@/modules/customers/customer-form'
|
||||
import { CUSTOMER_ROUTES } from '@garage/api'
|
||||
import type { CustomersClient } from '@garage/api'
|
||||
@@ -11,14 +14,29 @@ import { Building2Icon, UserIcon } from 'lucide-react'
|
||||
|
||||
export default function CustomersPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<CustomersClient>
|
||||
pageTitle='Customers'
|
||||
routeKey={CUSTOMER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search customers..."
|
||||
getClient={(api) => api.customers}
|
||||
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className='flex items-center gap-2'>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.customers.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Customers"
|
||||
onDownloadSample={() => api.customers.downloadImportSample()}
|
||||
sampleFileName='customers-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.customers.exportData(filters)}
|
||||
fileName='customers'
|
||||
/>
|
||||
<FormDialog title="Customer">
|
||||
{(resourceId) => (
|
||||
<CustomerForm
|
||||
@@ -28,6 +46,7 @@ export default function CustomersPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -37,7 +56,7 @@ export default function CustomersPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const customerName = row.original.first_name
|
||||
const isCompany = row.original.customer_type?.name?.toLocaleLowerCase() === "company";
|
||||
const isCompany = (row.original as any).customer_type?.name?.toLocaleLowerCase() === "company";
|
||||
const companyName = row.original.company_name
|
||||
const name = isCompany && companyName ? `${customerName} (${row.original.last_name})` : customerName
|
||||
|
||||
|
||||
@@ -2,8 +2,12 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { EstimateActions } from '@/modules/estimates/estimate-actions'
|
||||
import { EstimateProvider } from '@/modules/estimates/estimate-context'
|
||||
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
|
||||
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
@@ -11,25 +15,36 @@ export default async function layout(props: {
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const estimate = await api.estimates.getById(id)
|
||||
const estimate = await api.estimates.show(id)
|
||||
|
||||
const estimateData = (estimate as any)?.data
|
||||
const estimateData = estimate?.data
|
||||
const title = estimateData?.title || estimateData?.estimate_number || `Estimate #${id}`
|
||||
const estimateLabel = estimateData?.estimate_number
|
||||
? `${estimateData.estimate_number}${estimateData.title ? ` — ${estimateData.title}` : ''}`
|
||||
: title
|
||||
|
||||
if (!estimateData) {
|
||||
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<EstimateProvider estimate={{ id, label: estimateLabel }}>
|
||||
<EstimateProvider estimate={estimateData}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
icon={<FileTextIcon className="size-5" />}
|
||||
title={title}
|
||||
description={
|
||||
estimateData?.date ? `Date: ${estimateData.date}` : undefined
|
||||
estimateData?.date ? `Date: ${formatDate(estimateData.date)}` : undefined
|
||||
}
|
||||
backHref="/sales/estimates"
|
||||
actions={<EstimateActions estimateId={id} />}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<CreateInvoiceFromEstimateButton />
|
||||
<CreateJobCardFromEstimateButton />
|
||||
<ShareDocumentButton type="estimate" id={id} />
|
||||
<EstimateActions estimateId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{ href: `/sales/estimates/${id}`, label: 'Details' },
|
||||
]}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { EstimateGeneralInfo } from '@/modules/estimates/estimate-general-info'
|
||||
import { EstimateServicesSection } from '@/modules/estimates/estimate-services-section'
|
||||
import { EstimatePartsSection } from '@/modules/estimates/estimate-parts-section'
|
||||
import { EstimateExpenseItemsSection } from '@/modules/estimates/estimate-expense-items-section'
|
||||
import { EstimateTotalsSummary } from '@/modules/estimates/estimate-totals-summary'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const estimate = await api.estimates.getById(id)
|
||||
const estimate = await api.estimates.show(id)
|
||||
|
||||
const estimateData = (estimate as any)?.data
|
||||
const estimateData = estimate?.data
|
||||
|
||||
if (!estimateData) {
|
||||
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
||||
@@ -15,7 +19,14 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-6">
|
||||
<EstimateGeneralInfo estimate={estimateData} />
|
||||
<EstimateServicesSection estimateId={id} />
|
||||
<EstimatePartsSection estimateId={id} />
|
||||
<EstimateExpenseItemsSection estimateId={id} />
|
||||
<EstimateTotalsSummary />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,29 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { Car, FileTextIcon } from 'lucide-react'
|
||||
import { Button } from '@/shared/components/ui/button'
|
||||
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function EstimatesPage() {
|
||||
const router = useRouter()
|
||||
return (
|
||||
<ResourcePage<EstimatesClient>
|
||||
pageTitle="Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Estimate">
|
||||
@@ -36,7 +44,7 @@ export default function EstimatesPage() {
|
||||
const item = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
|
||||
<FileTextIcon className="text-muted-foreground h-4 w-4" />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
@@ -51,22 +59,39 @@ export default function EstimatesPage() {
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item: any = row.original
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle_id",
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original
|
||||
return <Button variant="outline" asChild size="sm">
|
||||
<Link href={`/sales/vehicles/${item.vehicle_id}`}>
|
||||
<Car/> Go to vehicle
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
const item: any = row.original
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item.vehicle as any)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original
|
||||
return formatDate(item.date)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "has_insurance",
|
||||
|
||||
@@ -1,589 +1,458 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState, useRef, useCallback } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Plus,
|
||||
Ellipsis,
|
||||
Pencil,
|
||||
Trash2,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
XCircle,
|
||||
MinusCircle,
|
||||
CircleDot,
|
||||
Paperclip,
|
||||
FileUp,
|
||||
FileText,
|
||||
FileImage,
|
||||
File,
|
||||
X,
|
||||
Car,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleCheck,
|
||||
FileSignature,
|
||||
Gauge,
|
||||
Image as ImageIcon,
|
||||
Loader2,
|
||||
Share2,
|
||||
StickyNote,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Types ──
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Progress } from "@/shared/components/ui/progress"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import {
|
||||
CheckpointFillDialog,
|
||||
isCheckpointComplete,
|
||||
type Checkpoint,
|
||||
type Severity,
|
||||
} from "@/modules/inspections/checkpoint-fill-dialog"
|
||||
import { SignaturePad } from "@/modules/inspections/signature-pad"
|
||||
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
|
||||
|
||||
type CheckpointItem = {
|
||||
type Inspection = {
|
||||
id: number
|
||||
inspection_id?: number
|
||||
name?: string
|
||||
description?: string
|
||||
record_type?: string
|
||||
condition_rate?: number
|
||||
file?: string
|
||||
status?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
title: string
|
||||
order_number?: string | null
|
||||
status?: string | null
|
||||
odometer?: number | null
|
||||
template?: { id: number; name: string } | null
|
||||
customer?: { first_name?: string; last_name?: string } | null
|
||||
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string } | null
|
||||
check_points: Checkpoint[]
|
||||
technician_signature_url?: string | null
|
||||
customer_signature_url?: string | null
|
||||
}
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const CHECKPOINT_STATUSES = [
|
||||
{ value: "passed", label: "Passed", icon: CheckCircle2, color: "bg-green-100 text-green-800" },
|
||||
{ value: "need_attention", label: "Need Attention", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800" },
|
||||
{ value: "failed", label: "Failed", icon: XCircle, color: "bg-red-100 text-red-800" },
|
||||
{ value: "not_applicable", label: "Not Applicable", icon: MinusCircle, color: "bg-gray-100 text-gray-800" },
|
||||
{ value: "not_inspected", label: "Not Inspected", icon: CircleDot, color: "bg-blue-100 text-blue-800" },
|
||||
] as const
|
||||
|
||||
const RECORD_TYPES = [
|
||||
{ value: "record_conditions", label: "Record Conditions" },
|
||||
{ value: "record_audio", label: "Record Audio" },
|
||||
{ value: "record_video", label: "Record Video" },
|
||||
{ value: "capture_photo", label: "Capture Photo" },
|
||||
] as const
|
||||
|
||||
function formatStatus(status?: string) {
|
||||
if (!status) return "Not Inspected"
|
||||
return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
const SEVERITY_DOT: Record<Severity, string> = {
|
||||
good: "bg-emerald-500 shadow-emerald-500/30",
|
||||
attention: "bg-amber-500 shadow-amber-500/30",
|
||||
critical: "bg-rose-500 shadow-rose-500/30",
|
||||
na: "bg-slate-400 shadow-slate-400/30",
|
||||
not_inspected: "bg-muted shadow-none",
|
||||
}
|
||||
const SEVERITY_LABEL: Record<Severity, string> = {
|
||||
good: "Good",
|
||||
attention: "Attention",
|
||||
critical: "Critical",
|
||||
na: "N/A",
|
||||
not_inspected: "Not inspected",
|
||||
}
|
||||
const SEVERITY_BADGE: Record<Severity, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
good: "default",
|
||||
attention: "secondary",
|
||||
critical: "destructive",
|
||||
na: "outline",
|
||||
not_inspected: "outline",
|
||||
}
|
||||
|
||||
function getStatusConfig(status?: string) {
|
||||
return CHECKPOINT_STATUSES.find((s) => s.value === status) || CHECKPOINT_STATUSES[4]
|
||||
function groupBySection(cps: Checkpoint[]) {
|
||||
const map = new Map<string, Checkpoint[]>()
|
||||
for (const cp of cps) {
|
||||
const key = cp.section_name || "Other"
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key)!.push(cp)
|
||||
}
|
||||
return Array.from(map.entries()).map(([name, items]) => ({ name, items }))
|
||||
}
|
||||
|
||||
// ── Checkpoint Form Dialog ──
|
||||
|
||||
function CheckpointFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
inspectionId,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
inspectionId: string
|
||||
checkpoint?: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
export default function InspectionCheckpointsPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [name, setName] = useState(checkpoint?.name ?? "")
|
||||
const [description, setDescription] = useState(checkpoint?.description ?? "")
|
||||
const [recordType, setRecordType] = useState(checkpoint?.record_type ?? "record_conditions")
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
|
||||
const isEditing = !!checkpoint
|
||||
const [data, setData] = useState<Inspection | null>(null)
|
||||
const [initialLoad, setInitialLoad] = useState(true)
|
||||
const [refetching, setRefetching] = useState(false)
|
||||
const [activeIndex, setActiveIndex] = useState<number | null>(null)
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
const [mode, setMode] = useState<"all" | "wizard">("all")
|
||||
const [wizardSectionIdx, setWizardSectionIdx] = useState(0)
|
||||
const [signing, setSigning] = useState<{ who: "technician" | "customer" } | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!name.trim()) {
|
||||
toast.error("Name is required")
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
const load = useCallback(async () => {
|
||||
const isFirst = !data
|
||||
if (isFirst) setInitialLoad(true)
|
||||
else setRefetching(true)
|
||||
try {
|
||||
const payload = {
|
||||
inspection_id: Number(inspectionId),
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
record_type: recordType,
|
||||
const res = await api.inspections.showOne(id)
|
||||
setData(res.data as Inspection)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to load inspection")
|
||||
} finally {
|
||||
setInitialLoad(false)
|
||||
setRefetching(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id])
|
||||
|
||||
const patchCheckpoint = useCallback((checkpointId: number, patch: Partial<Checkpoint>) => {
|
||||
setData((prev) => {
|
||||
if (!prev) return prev
|
||||
return {
|
||||
...prev,
|
||||
check_points: prev.check_points.map((c) =>
|
||||
c.id === checkpointId ? { ...c, ...patch } : c
|
||||
),
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const sections = useMemo(() => data ? groupBySection(data.check_points ?? []) : [], [data])
|
||||
const flatCheckpoints = useMemo(() => sections.flatMap((s) => s.items), [sections])
|
||||
|
||||
const totals = useMemo(() => {
|
||||
const t = { good: 0, attention: 0, critical: 0, na: 0, not_inspected: 0 }
|
||||
for (const cp of data?.check_points ?? []) {
|
||||
const s = (cp.severity as Severity) ?? "not_inspected"
|
||||
t[s]++
|
||||
}
|
||||
return t
|
||||
}, [data])
|
||||
|
||||
const setSeverity = async (cp: Checkpoint, severity: Severity) => {
|
||||
patchCheckpoint(cp.id, { severity })
|
||||
try {
|
||||
await api.inspections.updateCheckpoint(String(cp.id), { severity } as any)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save")
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
const promise = api.inspections.updateCheckpoint(String(checkpoint.id), payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Updating checkpoint...",
|
||||
success: "Checkpoint updated",
|
||||
error: "Failed to update checkpoint",
|
||||
})
|
||||
await promise
|
||||
} else {
|
||||
const promise = api.inspections.createCheckpoint(payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Creating checkpoint...",
|
||||
success: "Checkpoint created",
|
||||
error: "Failed to create checkpoint",
|
||||
})
|
||||
await promise
|
||||
}
|
||||
onSuccess()
|
||||
onOpenChange(false)
|
||||
const handleSign = async (who: "technician" | "customer", dataUrl: string) => {
|
||||
setSigning({ who })
|
||||
try {
|
||||
await api.inspections.sign(id, who, dataUrl)
|
||||
toast.success(who === "technician" ? "Technician signature saved" : "Customer signature saved")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save signature")
|
||||
} finally {
|
||||
setIsPending(false)
|
||||
setSigning(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (initialLoad) {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex items-center justify-center">
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-sm">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading inspection…
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!data) return <div className="p-6 text-muted-foreground">Inspection not found</div>
|
||||
|
||||
const vehicleLine = data.vehicle
|
||||
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
|
||||
: "—"
|
||||
const customerName = data.customer ? `${data.customer.first_name ?? ""} ${data.customer.last_name ?? ""}`.trim() : "—"
|
||||
const totalCount = data.check_points.length
|
||||
const inspectedCount = totalCount - totals.not_inspected
|
||||
const progress = totalCount > 0 ? Math.round((inspectedCount / totalCount) * 100) : 0
|
||||
|
||||
const wizardSection = sections[wizardSectionIdx]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Checkpoint" : "Add Checkpoint"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="grid gap-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-name">Name *</Label>
|
||||
<Input
|
||||
id="cp-name"
|
||||
placeholder="e.g. Engine Oil Level"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4">
|
||||
{/* Header */}
|
||||
<Card>
|
||||
<CardHeader className="gap-3">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<Link href={`/sales/inspections/${id}`}>
|
||||
<Button variant="ghost" size="sm" className="-ms-2">
|
||||
<ChevronLeft className="size-4" /> Back to inspection
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
{refetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
|
||||
<Button variant="outline" size="sm" onClick={() => setShareOpen(true)}>
|
||||
<Share2 className="size-4" /> Share with customer
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-description">Description</Label>
|
||||
<Textarea
|
||||
id="cp-description"
|
||||
placeholder="Check oil level and condition"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-record-type">Record Type</Label>
|
||||
<Select value={recordType} onValueChange={setRecordType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{RECORD_TYPES.map((rt) => (
|
||||
<SelectItem key={rt.value} value={rt.value}>
|
||||
{rt.label}
|
||||
</SelectItem>
|
||||
<Separator />
|
||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||
<div className="min-w-0">
|
||||
<CardDescription className="uppercase tracking-wide text-[11px]">Inspection</CardDescription>
|
||||
<CardTitle className="text-2xl">{data.title}</CardTitle>
|
||||
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground flex-wrap">
|
||||
<span className="inline-flex items-center gap-1.5"><User className="size-3.5" /> {customerName}</span>
|
||||
<span className="inline-flex items-center gap-1.5"><Car className="size-3.5" /> {vehicleLine}</span>
|
||||
{data.vehicle?.license_plate && (
|
||||
<Badge variant="outline" className="font-mono">{data.vehicle.license_plate}</Badge>
|
||||
)}
|
||||
{data.odometer != null && (
|
||||
<span className="inline-flex items-center gap-1.5"><Gauge className="size-3.5" /> {Number(data.odometer).toLocaleString()} km</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3">
|
||||
{/* Progress */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Progress</span>
|
||||
<span className="tabular-nums">{inspectedCount} / {totalCount} ({progress}%)</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
</div>
|
||||
|
||||
{/* Severity tally */}
|
||||
<div className="flex items-center gap-2 flex-wrap mt-3">
|
||||
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
|
||||
<Badge key={s} variant={SEVERITY_BADGE[s]} className="gap-1.5">
|
||||
<span className={`size-1.5 rounded-full ${SEVERITY_DOT[s].split(" ")[0]}`} />
|
||||
{totals[s]} {SEVERITY_LABEL[s]}
|
||||
</Badge>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isEditing ? <Pencil className="size-4" /> : <Plus className="size-4" />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Checkpoint" : "Create Checkpoint")}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Attachments Dialog ──
|
||||
|
||||
function getFileIcon(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")) return FileImage
|
||||
if (ext === "pdf") return FileText
|
||||
return File
|
||||
}
|
||||
|
||||
function getFileName(url: string) {
|
||||
try {
|
||||
return decodeURIComponent(url.split("/").pop() ?? "Attachment")
|
||||
} catch {
|
||||
return url.split("/").pop() ?? "Attachment"
|
||||
}
|
||||
}
|
||||
|
||||
function isImageUrl(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
return ["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")
|
||||
}
|
||||
|
||||
function CheckpointAttachmentsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
checkpoint: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
const api = useAuthApi()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
const handleUpload = useCallback(async (file: globalThis.File) => {
|
||||
if (!checkpoint) return
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const promise = api.inspections.uploadCheckpointMedia(
|
||||
String(checkpoint.id),
|
||||
{ file },
|
||||
)
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment...",
|
||||
success: "Attachment uploaded",
|
||||
error: "Failed to upload attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||
}
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!checkpoint) return
|
||||
const promise = api.inspections.deleteCheckpointMedia(String(checkpoint.id))
|
||||
toast.promise(promise, {
|
||||
loading: "Removing attachment...",
|
||||
success: "Attachment removed",
|
||||
error: "Failed to remove attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const hasFile = !!checkpoint?.file
|
||||
const FileIcon = checkpoint?.file ? getFileIcon(checkpoint.file) : File
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Attachments — {checkpoint?.name}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Current attachment */}
|
||||
{hasFile ? (
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0 ">
|
||||
{isImageUrl(checkpoint.file!) ? (
|
||||
<img
|
||||
src={checkpoint.file!}
|
||||
alt="Checkpoint attachment"
|
||||
className="size-12 rounded-md object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-md bg-muted">
|
||||
<FileIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex flex-col gap-0.5 max-w-48">
|
||||
<a
|
||||
href={checkpoint.file!}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="truncate text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
{getFileName(checkpoint.file!)}
|
||||
</a>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Current attachment
|
||||
{/* Legend */}
|
||||
<div className="mt-3 rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
|
||||
<span className="font-medium text-foreground">Tap a dot to mark:</span>
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => (
|
||||
<span key={s} className="inline-flex items-center gap-1.5">
|
||||
<span className={`size-3 rounded-full ${SEVERITY_DOT[s].split(" ")[0]} shadow-md`} />
|
||||
{SEVERITY_LABEL[s]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={handleDelete}
|
||||
title="Remove attachment"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-muted-foreground">
|
||||
<Paperclip className="size-8" />
|
||||
<span className="text-sm">No attachments yet</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mode tabs */}
|
||||
{totalCount > 0 && (
|
||||
<Tabs value={mode} onValueChange={(v) => setMode(v as any)} className="w-full">
|
||||
<TabsList className="w-full sm:w-auto">
|
||||
<TabsTrigger value="all">All sections</TabsTrigger>
|
||||
<TabsTrigger value="wizard">Wizard</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{/* Upload area */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,audio/*,video/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
}}
|
||||
/>
|
||||
{/* Sections */}
|
||||
{totalCount === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-10 text-center">
|
||||
<CircleCheck className="size-8 mx-auto text-muted-foreground/60 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This inspection has no checkpoints yet. It was probably created from an empty template.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : mode === "all" ? (
|
||||
sections.map((section) => (
|
||||
<Card key={section.name}>
|
||||
<CardHeader className="py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">{section.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{section.items.filter(isCheckpointComplete).length} / {section.items.length} done
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{section.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
wizardSection && (() => {
|
||||
const pendingItems = wizardSection.items.filter((cp) => !isCheckpointComplete(cp))
|
||||
const sectionDone = pendingItems.length === 0
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="py-3 gap-1">
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<CardTitle className="text-base">{wizardSection.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
Section {wizardSectionIdx + 1} / {sections.length}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{wizardSection.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
<div className="px-4 py-3 border-t bg-muted/30 space-y-2">
|
||||
{!sectionDone && (
|
||||
<div className="flex items-start gap-2 text-xs text-amber-900">
|
||||
<AlertTriangle className="size-3.5 mt-0.5 shrink-0 text-amber-600" />
|
||||
<div>
|
||||
<span className="font-medium">{pendingItems.length} pending.</span>{' '}
|
||||
Each checkpoint needs a finding and its required recording before you can move on.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={isUploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<FileUp className="size-4" />
|
||||
{isUploading
|
||||
? "Uploading..."
|
||||
: hasFile
|
||||
? "Replace Attachment"
|
||||
: "Add Attachment"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main Page ──
|
||||
|
||||
export default function InspectionCheckpointsPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: inspectionId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [editingCheckpoint, setEditingCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
const [attachmentsCheckpoint, setAttachmentsCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
|
||||
const queryKey = [INSPECTION_ROUTES.CHECKPOINTS, inspectionId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.inspections.listCheckpoints({ inspection_id: inspectionId } as never),
|
||||
})
|
||||
|
||||
const invalidate = () => {
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
|
||||
// ── Status change mutation ──
|
||||
const changeStatusMutation = useMutation({
|
||||
mutationFn: ({ checkpointId, status }: { checkpointId: number; status: string }) =>
|
||||
api.inspections.changeCheckpointStatus({
|
||||
inspection_id: Number(inspectionId),
|
||||
inspection_check_point_id: String(checkpointId),
|
||||
name: "", // required by API type but server uses checkpoint id from context
|
||||
record_type: "record_conditions",
|
||||
status,
|
||||
} as never),
|
||||
onSuccess: () => invalidate(),
|
||||
})
|
||||
|
||||
// ── Delete checkpoint mutation ──
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (checkpointId: string) => api.inspections.destroyCheckpoint(checkpointId),
|
||||
onSuccess: () => {
|
||||
toast.success("Checkpoint deleted")
|
||||
invalidate()
|
||||
},
|
||||
onError: () => toast.error("Failed to delete checkpoint"),
|
||||
})
|
||||
|
||||
const handleEdit = (checkpoint: CheckpointItem) => {
|
||||
setEditingCheckpoint(checkpoint)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditingCheckpoint(null)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleStatusChange = (checkpointId: number, status: string) => {
|
||||
const promise = changeStatusMutation.mutateAsync({ checkpointId, status, })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating status...",
|
||||
success: `Status changed to ${formatStatus(status)}`,
|
||||
error: "Failed to update status",
|
||||
})
|
||||
}
|
||||
|
||||
const checkpoints = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
const pagination = {
|
||||
page: meta?.current_page ?? 1,
|
||||
pageSize: meta?.per_page ?? 15,
|
||||
pageCount: meta?.last_page ?? 1,
|
||||
total: meta?.total ?? 0,
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{item.name}</span>
|
||||
{item.description && (
|
||||
<span className="text-xs text-muted-foreground">{item.description}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "record_type",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Record Type" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const rt = RECORD_TYPES.find((r) => r.value === item.record_type)
|
||||
return rt?.label ?? item.record_type ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const config = getStatusConfig(item.status)
|
||||
return (
|
||||
<Badge className={config.color}>
|
||||
<config.icon className="mr-1 size-3" />
|
||||
{formatStatus(item.status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "condition_rate",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Condition" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return item.condition_rate != null ? `${item.condition_rate}/10` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: () => <span className="text-xs">Attachments</span>,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() => setAttachmentsCheckpoint(item)}
|
||||
disabled={wizardSectionIdx === 0}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.max(0, i - 1))}
|
||||
>
|
||||
<Paperclip className="size-3.5" />
|
||||
{item.file ? (
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-xs">1</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">0</span>
|
||||
)}
|
||||
<ChevronLeft className="size-4" /> Previous
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{CHECKPOINT_STATUSES.map((s) => (
|
||||
<DropdownMenuItem
|
||||
key={s.value}
|
||||
onClick={() => handleStatusChange(item.id, s.value)}
|
||||
disabled={item.status === s.value}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={wizardSectionIdx >= sections.length - 1 || !sectionDone}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.min(sections.length - 1, i + 1))}
|
||||
>
|
||||
<s.icon className="size-4" />
|
||||
{s.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => handleEdit(item)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => deleteMutation.mutate(String(item.id))}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<h3 className="text-lg font-semibold">Checkpoints</h3>
|
||||
<Button onClick={handleAdd} size="sm">
|
||||
<Plus className="size-4" />
|
||||
Add Checkpoint
|
||||
Next <ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={checkpoints}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
})()
|
||||
)}
|
||||
|
||||
{/* Signatures */}
|
||||
{totalCount > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3 flex-row items-center gap-2">
|
||||
<FileSignature className="size-4 text-muted-foreground" />
|
||||
<CardTitle className="text-base">Sign-off</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3 grid grid-cols-1 md:grid-cols-2">
|
||||
<SignaturePad
|
||||
label="Technician signature"
|
||||
existingUrl={data.technician_signature_url}
|
||||
saving={signing?.who === "technician"}
|
||||
onSave={(d) => handleSign("technician", d)}
|
||||
/>
|
||||
<CheckpointFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={(open) => {
|
||||
setFormOpen(open)
|
||||
if (!open) setEditingCheckpoint(null)
|
||||
}}
|
||||
inspectionId={inspectionId}
|
||||
checkpoint={editingCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
<SignaturePad
|
||||
label="Customer signature"
|
||||
existingUrl={data.customer_signature_url}
|
||||
saving={signing?.who === "customer"}
|
||||
onSave={(d) => handleSign("customer", d)}
|
||||
/>
|
||||
<CheckpointAttachmentsDialog
|
||||
open={!!attachmentsCheckpoint}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setAttachmentsCheckpoint(null)
|
||||
}}
|
||||
checkpoint={attachmentsCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<CheckpointFillDialog
|
||||
open={activeIndex !== null}
|
||||
onOpenChange={(o) => { if (!o) setActiveIndex(null) }}
|
||||
checkpoints={flatCheckpoints}
|
||||
activeIndex={activeIndex}
|
||||
onIndexChange={setActiveIndex}
|
||||
onSaved={load}
|
||||
onPatch={patchCheckpoint}
|
||||
/>
|
||||
</DashboardPage>
|
||||
|
||||
<InspectionShareDialog
|
||||
open={shareOpen}
|
||||
onOpenChange={setShareOpen}
|
||||
inspectionId={id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CheckpointRow({
|
||||
cp,
|
||||
onSeverity,
|
||||
onOpen,
|
||||
}: {
|
||||
cp: Checkpoint
|
||||
onSeverity: (cp: Checkpoint, s: Severity) => void
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const current = (cp.severity as Severity) ?? "not_inspected"
|
||||
const attachments = cp.attachments ?? cp.media ?? []
|
||||
const photoCount = attachments.filter((m) => m.media_type === "photo").length
|
||||
const complete = isCheckpointComplete(cp)
|
||||
return (
|
||||
<li
|
||||
className={`px-3 sm:px-4 py-3 transition-colors hover:bg-muted/30 ${!complete ? "bg-amber-50/40" : ""}`}
|
||||
>
|
||||
<div className="flex items-start gap-3 flex-wrap sm:flex-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex-1 min-w-0 text-left group"
|
||||
>
|
||||
<div className="font-medium text-sm flex items-center gap-2">
|
||||
<span className="group-hover:text-primary transition">{cp.name}</span>
|
||||
{!complete && (
|
||||
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{cp.technician_notes && (
|
||||
<div className="flex items-start gap-1 text-xs text-muted-foreground mt-1">
|
||||
<StickyNote className="size-3 mt-0.5 shrink-0" />
|
||||
<span className="italic line-clamp-1">{cp.technician_notes}</span>
|
||||
</div>
|
||||
)}
|
||||
{photoCount > 0 && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
|
||||
<ImageIcon className="size-3" /> {photoCount} photo{photoCount === 1 ? "" : "s"}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<div className="flex gap-2 justify-end shrink-0 w-full sm:w-auto">
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => {
|
||||
const active = current === s
|
||||
return (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onSeverity(cp, s) }}
|
||||
aria-label={SEVERITY_LABEL[s]}
|
||||
title={SEVERITY_LABEL[s]}
|
||||
className={`size-10 sm:size-9 rounded-full transition shadow-md ${SEVERITY_DOT[s]} ${active ? "ring-2 ring-offset-2 ring-foreground/40 scale-105" : "opacity-60 hover:opacity-100"}`}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionActions } from '@/modules/inspections/inspection-actions'
|
||||
import { InspectionProvider } from '@/modules/inspections/inspection-context'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import React from 'react'
|
||||
|
||||
export default async function layout(props: {
|
||||
@@ -23,7 +24,12 @@ export default async function layout(props: {
|
||||
title={title}
|
||||
description={orderNumber ? `Order: ${orderNumber}` : undefined}
|
||||
backHref="/sales/inspections"
|
||||
actions={<InspectionActions inspectionId={id} status={status} />}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<ShareDocumentButton type="inspection" id={id} />
|
||||
<InspectionActions inspectionId={id} status={status} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/inspections/${id}`,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
|
||||
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
@@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
return <div className="text-muted-foreground">Inspection not found.</div>
|
||||
}
|
||||
|
||||
const data = inspection.data as { title?: string }
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<InspectionDetailHeader inspectionId={id} title={data.title} />
|
||||
<InspectionGeneralInfo inspection={inspection.data} />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -1,25 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
|
||||
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import Link from "next/link"
|
||||
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
const STATUS_BADGE_CLASS: Record<string, string> = {
|
||||
in_progress: "bg-amber-100 text-amber-800",
|
||||
completed: "bg-emerald-100 text-emerald-800",
|
||||
cancelled: "bg-rose-100 text-rose-800",
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
in_progress: "In Progress",
|
||||
completed: "Completed",
|
||||
cancelled: "Cancelled",
|
||||
}
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<ResourcePage<InspectionsClient>
|
||||
pageTitle="Inspections"
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inspection">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/settings/inspection-templates">
|
||||
<ListChecks className="size-4" />
|
||||
Manage templates
|
||||
</Link>
|
||||
</Button>
|
||||
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
|
||||
<ClipboardList className="size-4" />
|
||||
New from template
|
||||
</Button>
|
||||
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
@@ -28,19 +71,55 @@ export default function InspectionsPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
|
||||
<DialogContent className="min-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">
|
||||
New inspection from template
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<InspectionFromTemplateForm
|
||||
onSuccess={(id) => {
|
||||
setFromTemplateOpen(false)
|
||||
invalidateQuery()
|
||||
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
columns={({ openEdit, deleteItem }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{r.title ?? "—"}</span>
|
||||
{r.order_number && (
|
||||
<span className="text-xs text-muted-foreground">{r.order_number}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -48,27 +127,51 @@ export default function InspectionsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inspection_category",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
|
||||
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
|
||||
cell: ({ row }) => {
|
||||
const ic = (row.original as any).inspection_category
|
||||
return ic?.inspection_name ?? ic?.name ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
const status = (row.original as any).status as string | undefined
|
||||
if (!status) return "—"
|
||||
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
|
||||
return (
|
||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
||||
{status ?? "—"}
|
||||
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
|
||||
{STATUS_LABEL[status] ?? status}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<InspectionRowActions
|
||||
inspection={row.original as any}
|
||||
onEdit={() => openEdit(row.original as any)}
|
||||
onDelete={() => deleteItem(String((row.original as any).id))}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -4,6 +4,8 @@ import { InvoiceActions } from '@/modules/invoices/invoice-actions'
|
||||
import { InvoiceProvider } from '@/modules/invoices/invoice-context'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
|
||||
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||
const { id } = await props.params
|
||||
@@ -13,19 +15,26 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
|
||||
const title = data?.subject || data?.invoice_number || 'Invoice Details'
|
||||
|
||||
return (
|
||||
<InvoiceProvider invoice={{ id, label: title }}>
|
||||
<InvoiceProvider invoice={data}>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
title={title}
|
||||
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
||||
icon={<ReceiptIcon className="size-5" />}
|
||||
backHref="/sales/invoice"
|
||||
actions={<InvoiceActions invoiceId={id} />}
|
||||
actions={
|
||||
<div className="flex space-x-2 items-center">
|
||||
|
||||
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
|
||||
<ShareDocumentButton type="invoice" id={id} />
|
||||
<InvoiceActions invoiceId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/invoice/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
|
||||
{
|
||||
href: `/sales/invoice/${id}/documents`,
|
||||
label: 'Documents'
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InvoiceGeneralInfo } from '@/modules/invoices/invoice-general-info'
|
||||
import { InvoicePartsSection } from '@/modules/invoices/invoice-parts-section'
|
||||
import { InvoiceServicesSection } from '@/modules/invoices/invoice-services-section'
|
||||
import { InvoiceExpensesSection } from '@/modules/invoices/invoice-expenses-section'
|
||||
import { InvoiceTotalsSummary } from '@/modules/invoices/invoice-totals-summary'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import InvoicePaymentsSection from '@/modules/invoices/invoice-payments-section'
|
||||
|
||||
|
||||
export default async function InvoiceDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
@@ -14,7 +20,14 @@ export default async function InvoiceDetailPage(props: { params: Promise<{ id: s
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<InvoiceGeneralInfo invoice={data} />
|
||||
<div className="grid gap-6">
|
||||
<InvoiceGeneralInfo />
|
||||
<InvoicePartsSection parts={data.invoice_parts} />
|
||||
<InvoiceServicesSection services={data.invoice_services} />
|
||||
<InvoiceExpensesSection expenses={data.invoice_expenses} />
|
||||
<InvoicePaymentsSection></InvoicePaymentsSection>
|
||||
<InvoiceTotalsSummary />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,22 +1,82 @@
|
||||
"use client"
|
||||
|
||||
import { Car, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InvoiceForm } from "@/modules/invoices/invoice-form"
|
||||
import { INVOICE_ROUTES } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
|
||||
import type { InvoicesClient } from "@garage/api"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
type InvoiceItem = {
|
||||
id: number
|
||||
subject?: string
|
||||
invoice_title?: string
|
||||
invoice_number?: string
|
||||
customer_name?: string
|
||||
status?: string
|
||||
invoice_date?: string
|
||||
due_date?: string
|
||||
created_at?: string
|
||||
total?: number | string
|
||||
balance_due?: number | string
|
||||
customer?: {
|
||||
id?: number | string
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
company_name?: string
|
||||
phone?: string
|
||||
} | null
|
||||
vehicle?: {
|
||||
make?: string
|
||||
model?: string
|
||||
sub_model?: string
|
||||
year?: number | string
|
||||
license_plate?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
function getCustomerLabel(item: InvoiceItem): string {
|
||||
const firstName = item.customer?.first_name?.trim()
|
||||
const lastName = item.customer?.last_name?.trim()
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(" ").trim()
|
||||
|
||||
return fullName || item.customer_name || item.customer?.company_name || "—"
|
||||
}
|
||||
|
||||
function getVehicleLabel(item: InvoiceItem): string {
|
||||
const vehicle = item.vehicle
|
||||
if (!vehicle) return "—"
|
||||
|
||||
const core = [vehicle.make, vehicle.model, vehicle.sub_model].filter(Boolean).join(" ")
|
||||
const suffix = [vehicle.year, vehicle.license_plate].filter(Boolean).join(" • ")
|
||||
|
||||
if (core && suffix) return `${core} (${suffix})`
|
||||
return core || suffix || "—"
|
||||
}
|
||||
|
||||
function getDueMeta(dueDate?: string) {
|
||||
if (!dueDate) return { text: "No due date", tone: "muted" as const }
|
||||
|
||||
const due = new Date(dueDate)
|
||||
if (isNaN(due.getTime())) return { text: "Invalid due date", tone: "muted" as const }
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
due.setHours(0, 0, 0, 0)
|
||||
|
||||
const days = Math.ceil((due.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
if (days < 0) return { text: `${Math.abs(days)} day(s) overdue`, tone: "danger" as const }
|
||||
if (days === 0) return { text: "Due today", tone: "warning" as const }
|
||||
if (days <= 3) return { text: `Due in ${days} day(s)`, tone: "warning" as const }
|
||||
|
||||
return { text: `Due in ${days} day(s)`, tone: "ok" as const }
|
||||
}
|
||||
|
||||
export default function InvoicesPage() {
|
||||
@@ -26,11 +86,14 @@ export default function InvoicesPage() {
|
||||
<ResourcePage<InvoicesClient>
|
||||
pageTitle="Invoices"
|
||||
routeKey={INVOICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search invoices..."
|
||||
statusFilter={{ statuses: InvoiceStatus }}
|
||||
getClient={(api) => api.invoices}
|
||||
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Invoice">
|
||||
<FormDialog classNames={{dialogContent:'lg:min-w-6xl'}} title="Invoice">
|
||||
{(resourceId) => (
|
||||
<InvoiceForm
|
||||
resourceId={resourceId}
|
||||
@@ -44,15 +107,64 @@ export default function InvoicesPage() {
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "subject",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Subject" />,
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const title = item.subject || item.invoice_title || "Untitled invoice"
|
||||
|
||||
return (
|
||||
<div className="min-w-[220px]">
|
||||
<p className="font-medium leading-none">{title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{item.invoice_number || "No invoice number"}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
return (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{item.invoice_number || "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getCustomerLabel(item)}
|
||||
meta={item.customer?.phone}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const vehicleId = (item.vehicle as any)?.id
|
||||
return (
|
||||
<RelationLink
|
||||
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
@@ -60,27 +172,71 @@ export default function InvoicesPage() {
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const status = item.status
|
||||
const colorMap: Record<string, string> = {
|
||||
draft: "text-muted-foreground",
|
||||
open: "text-blue-600",
|
||||
paid: "text-green-600",
|
||||
overdue: "text-red-600",
|
||||
void: "text-gray-400",
|
||||
const classMap: Record<string, string> = {
|
||||
draft: "bg-slate-100 text-slate-700",
|
||||
open: "bg-blue-100 text-blue-700",
|
||||
paid: "bg-emerald-100 text-emerald-700",
|
||||
over_due: "bg-red-100 text-red-700",
|
||||
un_paid: "bg-orange-100 text-orange-700",
|
||||
partially_paid: "bg-amber-100 text-amber-700",
|
||||
void: "bg-zinc-100 text-zinc-700",
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={colorMap[status ?? ""] ?? ""}>
|
||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
||||
</span>
|
||||
<Badge variant="outline" className={classMap[status ?? ""] ?? ""}>
|
||||
{formatEnum(status) || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return formatDate(item.invoice_date)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "due_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const dueMeta = getDueMeta(item.due_date)
|
||||
const toneClassMap = {
|
||||
danger: "text-red-600",
|
||||
warning: "text-amber-600",
|
||||
ok: "text-emerald-600",
|
||||
muted: "text-muted-foreground",
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p className="font-medium leading-none">{formatDate(item.due_date)}</p>
|
||||
<p className={`mt-1 text-xs ${toneClassMap[dueMeta.tone]}`}>
|
||||
{dueMeta.text}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "amounts",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Amounts" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
return (
|
||||
<div className="min-w-[150px]">
|
||||
<p className="font-medium leading-none">
|
||||
Total: {<Money value={item.total ?? 0} />}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Due: {<Money value={item.balance_due ?? 0} />}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
import { use } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -27,15 +30,48 @@ export default function JobCardAppointmentsPage({
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const jobCard = useJobCard()
|
||||
|
||||
const defaultJobCard = jobCard
|
||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
||||
useEffect(() => {
|
||||
if (searchParams.get("create") !== "1") return
|
||||
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
params.delete("create")
|
||||
params.set("dialog", "true")
|
||||
|
||||
router.replace(`${pathname}?${params.toString()}`)
|
||||
}, [pathname, router, searchParams])
|
||||
|
||||
const jc = jobCard as any
|
||||
const defaultJobCard = jc
|
||||
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
|
||||
: null
|
||||
|
||||
const appointmentDefaults = jc
|
||||
? {
|
||||
job_card_id: jc.id,
|
||||
job_card_title: jc.title || `Job Card #${jc.id}`,
|
||||
customer_id: jc.customer?.id,
|
||||
customer_name: getFullName(jc.customer),
|
||||
vehicle_id: jc.vehicle?.id,
|
||||
vehicle_name: getVehicleLabel(jc.vehicle),
|
||||
service_writer_id: jc.service_writer?.id,
|
||||
service_writer_name: getFullName(jc.service_writer),
|
||||
technician_id: jc.primary_technician?.id,
|
||||
technician_name: getFullName(jc.primary_technician),
|
||||
department_id: jc.department?.id,
|
||||
department_name: jc.department?.name,
|
||||
}
|
||||
: { job_card: defaultJobCard }
|
||||
|
||||
return (
|
||||
<ResourcePage<AppointmentsClient>
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,8 +82,8 @@ export default function JobCardAppointmentsPage({
|
||||
{(resourceId) => (
|
||||
<AppointmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
||||
initialData={selectedItem ?? appointmentDefaults}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { useState, useRef } from "react"
|
||||
import { useState, useRef, useTransition } from "react"
|
||||
import { Plus, Trash2, FileIcon, ImageIcon, FileTextIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { JOB_CARD_ROUTES, JobCardResponseData } from "@garage/api"
|
||||
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { CONSTANTS } from "@/config/constants"
|
||||
@@ -22,10 +22,68 @@ function getFileIcon(mimeType?: string) {
|
||||
return FileIcon
|
||||
}
|
||||
|
||||
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
|
||||
|
||||
function describeAttachmentError(rawMessage: string, filename: string): string {
|
||||
const msg = rawMessage.toLowerCase()
|
||||
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
|
||||
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
|
||||
}
|
||||
if (msg.includes("may not be greater") || msg.includes("max")) {
|
||||
return `${filename}: exceeds 5 MB limit.`
|
||||
}
|
||||
if (msg.includes("must be a file")) {
|
||||
return `${filename}: invalid file.`
|
||||
}
|
||||
return `${filename}: ${rawMessage}`
|
||||
}
|
||||
|
||||
function showUploadError(err: unknown, files: File[]) {
|
||||
if (!(err instanceof ApiError)) {
|
||||
toast.error("Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const validation = err.validationErrors
|
||||
if (!validation || Object.keys(validation).length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const messages: string[] = []
|
||||
for (const [key, msgs] of Object.entries(validation)) {
|
||||
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
|
||||
if (!firstMsg) continue
|
||||
|
||||
const match = key.match(/^attachments\.(\d+)$/)
|
||||
if (match) {
|
||||
const idx = Number(match[1])
|
||||
const filename = files[idx]?.name ?? `File #${idx + 1}`
|
||||
messages.push(describeAttachmentError(firstMsg, filename))
|
||||
} else if (key === "attachments") {
|
||||
messages.push(firstMsg)
|
||||
} else {
|
||||
messages.push(firstMsg)
|
||||
}
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const shown = messages.slice(0, 3)
|
||||
const extra = messages.length - shown.length
|
||||
shown.forEach((m) => toast.error(m))
|
||||
if (extra > 0) toast.error(`...and ${extra} more`)
|
||||
}
|
||||
|
||||
export default function JobCardAttachmentsPage() {
|
||||
const { id: jobCardId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const [isRefreshing, startRefreshTransition] = useTransition()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
@@ -41,13 +99,14 @@ export default function JobCardAttachmentsPage() {
|
||||
onSuccess: () => {
|
||||
toast.success("Attachment deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
startRefreshTransition(() => router.refresh())
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete attachment.")
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = async (attachment: JobCardResponseData['attachment_files'][number]) => {
|
||||
const handleDelete = async (attachment: any) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Attachment",
|
||||
description: `Are you sure you want to delete "${attachment.original_name}"?`,
|
||||
@@ -63,17 +122,19 @@ export default function JobCardAttachmentsPage() {
|
||||
const files = e.target.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const fileList = Array.from(files)
|
||||
setIsUploading(true)
|
||||
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment(s)...",
|
||||
success: "Attachment(s) uploaded successfully",
|
||||
error: "Failed to upload attachment(s)",
|
||||
})
|
||||
const loadingToast = toast.loading("Uploading attachment(s)...")
|
||||
|
||||
try {
|
||||
await promise
|
||||
await api.jobCards.addAttachment(jobCardId, fileList)
|
||||
toast.dismiss(loadingToast)
|
||||
toast.success("Attachment(s) uploaded successfully")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
startRefreshTransition(() => router.refresh())
|
||||
} catch (err) {
|
||||
toast.dismiss(loadingToast)
|
||||
showUploadError(err, fileList)
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) {
|
||||
@@ -112,7 +173,7 @@ export default function JobCardAttachmentsPage() {
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
|
||||
{attachments?.map((attachment) => {
|
||||
{(attachments as any[])?.map((attachment) => {
|
||||
const Icon = getFileIcon(attachment.attachment_path)
|
||||
return (
|
||||
<Card key={attachment.id}>
|
||||
|
||||
@@ -6,9 +6,12 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function JobCardBillsPage({
|
||||
params,
|
||||
@@ -25,6 +28,9 @@ export default function JobCardBillsPage({
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +52,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/bill/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +70,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardExpenseItemForm } from "@/modules/job-cards/job-card-expense-item-form"
|
||||
import { 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.
|
||||
|
||||
export default function JobCardExpenseItemsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const queryKey = ["job-card-expense-items", jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey , refetchType:'all'}).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete this expense item?",
|
||||
description: `Remove "${row.expense_item?.item_name ?? "this expense item"}" from the job card?`,
|
||||
})
|
||||
if (!confirmed) return
|
||||
const promise = api.jobCards.deleteExpenseItem(jobCardId, row.id)
|
||||
toast.promise(promise, {
|
||||
loading: "Deleting...",
|
||||
success: "Expense item deleted",
|
||||
error: "Failed to delete expense item",
|
||||
})
|
||||
await promise
|
||||
invalidate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: "expense_item.item_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expense Item" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original.expense_item
|
||||
return item ? (
|
||||
<div>
|
||||
<span className="font-medium">{item.item_name}</span>
|
||||
{item.sku && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{item.sku}</span>
|
||||
)}
|
||||
</div>
|
||||
) : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Qty" />,
|
||||
cell: ({ row }) => row.original.quantity ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "rate",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||
cell: ({ row }) => row.original.department?.name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Description" />,
|
||||
cell: ({ row }) => row.original.description || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Added" />,
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditItem(row.original)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
<div className="flex justify-end">
|
||||
<Dialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setDialogOpen(open)
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => setEditItem(null)}>
|
||||
<Plus className="me-2 h-4 w-4" />
|
||||
Add Expense Item
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editItem ? "Edit Expense Item" : "Add Expense Item"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<JobCardExpenseItemForm
|
||||
jobCardId={jobCardId}
|
||||
jobCardExpenseItemId={editItem?.id ?? null}
|
||||
initialData={editItem}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
invalidate()
|
||||
}}
|
||||
onCancel={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{
|
||||
page: 1,
|
||||
pageSize: rows.length || 15,
|
||||
pageCount: 1,
|
||||
total: rows.length,
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { use } 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 { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { EXPENSE_ROUTES } from "@garage/api"
|
||||
import type { ExpensesClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
|
||||
export default function JobCardExpensesPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const jobCard = useJobCard()
|
||||
|
||||
const defaultJobCard = jobCard
|
||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
||||
: null
|
||||
|
||||
return (
|
||||
<ResourcePage<ExpensesClient>
|
||||
routeKey={EXPENSE_ROUTES.INDEX}
|
||||
getClient={(api) => api.expenses}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
<div className="flex justify-end">
|
||||
|
||||
<FormDialog title="Expense">
|
||||
{(resourceId) => (
|
||||
<ExpenseForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
)}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
||||
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "expense_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).expense_date
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"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 { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Car, UserIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
const jobCard = useJobCard()
|
||||
return (
|
||||
<ResourcePage<InspectionsClient>
|
||||
pageTitle="Inspections"
|
||||
extraParams={{job_card_id: jobCard?.id}}
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inspection">
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? {job_card: {value: jobCard?.id, label: jobCard?.title || `Job Card #${jobCard?.id}`}}}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inspection_category",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
|
||||
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return (
|
||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
||||
{status ?? "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -12,11 +12,11 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
|
||||
const jobCard = await api.jobCards.show(id).then(res => res.data)
|
||||
const jobCard:any = await api.jobCards.show(id).then(res => res.data)
|
||||
|
||||
const title = jobCard?.title || 'Job Card Details'
|
||||
const status = jobCard?.status || 'draft'
|
||||
const docs = jobCard?.documents
|
||||
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
|
||||
|
||||
return (
|
||||
<JobCardProvider jobCard={{ ...jobCard }}>
|
||||
@@ -35,34 +35,53 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
href: `/sales/job-cards/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/parts`,
|
||||
label: `Parts (${jobCard?.parts_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/services`,
|
||||
label: `Services (${jobCard?.services_count })`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/expense-items`,
|
||||
label: `Expense Items (${jobCard?.expense_items_count || 0})`
|
||||
},
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// TODO: Needs refactor from API side then refactor in frontend
|
||||
{
|
||||
href: `/sales/job-cards/${id}/attachments`,
|
||||
label: `Attachments (${docs?.length || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/purchase-orders`,
|
||||
label: `Purchase Orders (${jobCard?.purchase_orders_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/bills`,
|
||||
label: `Bills (${jobCard?.bills_count || 0})`
|
||||
label: `Attachments (${attachmentsCount})`
|
||||
},
|
||||
|
||||
{
|
||||
href: `/sales/job-cards/${id}/appointments`,
|
||||
label: `Appointments (${jobCard?.appointments_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/expenses`,
|
||||
label: `Expenses (${jobCard?.expenses_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/tasks`,
|
||||
label: `Tasks (${jobCard?.tasks_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/parts`,
|
||||
label: `Parts (${jobCard?.parts_count || 0})`
|
||||
},
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/inspections`,
|
||||
// label: `Inspections (${(jobCard as any)?.inspections_count || 0})`
|
||||
// },
|
||||
|
||||
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/tasks`,
|
||||
// label: `Tasks (${jobCard?.tasks_count || 0})`
|
||||
// },
|
||||
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/purchase-orders`,
|
||||
// label: `Purchase Orders (${jobCard?.purchase_orders_count || 0})`
|
||||
// },
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/bills`,
|
||||
// label: `Bills (${jobCard?.bills_count || 0})`
|
||||
// },
|
||||
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const jobCard = await api.jobCards.show(id)
|
||||
const data = (jobCard as any)?.data ?? jobCard
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Job card not found.</div>
|
||||
}
|
||||
|
||||
export default async function JobCardDetailPage() {
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<JobCardGeneralInfo jobCard={data} />
|
||||
<JobCardGeneralInfo />
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
@@ -24,6 +25,7 @@ import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||
|
||||
export default function JobCardPartsPage({
|
||||
params,
|
||||
@@ -33,7 +35,8 @@ export default function JobCardPartsPage({
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const queryKey = ["job-card-parts", jobCardId]
|
||||
const router = useRouter()
|
||||
const queryKey = [JOB_CARD_ROUTES.GET_PARTS, jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
@@ -41,11 +44,12 @@ export default function JobCardPartsPage({
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getParts(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey })
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey, type: 'all', refetchType: 'all' },).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
@@ -93,9 +97,17 @@ export default function JobCardPartsPage({
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax",
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax || "—",
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
|
||||
@@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function JobCardPurchaseOrdersPage({
|
||||
params,
|
||||
@@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
|
||||
cell: ({ row }) => (row.original as any).order_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/purchase-order/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.order_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardServiceForm } from "@/modules/job-cards/job-card-service-form"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
|
||||
// TODO: services invalidation is not working properly when create new service line. Need to investigate why and fix it.
|
||||
|
||||
export default function JobCardServicesPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const queryKey = ["job-card-services", jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getServices(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey , refetchType:'all'}).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete this service?",
|
||||
description: `Remove service "${row.service?.labor_name ?? "this service"}" from the job card?`,
|
||||
})
|
||||
if (!confirmed) return
|
||||
const promise = api.jobCards.deleteService(jobCardId, row.id)
|
||||
toast.promise(promise, {
|
||||
loading: "Deleting...",
|
||||
success: "Service deleted",
|
||||
error: "Failed to delete service",
|
||||
})
|
||||
await promise
|
||||
invalidate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: "service.labor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Service" />,
|
||||
cell: ({ row }) => {
|
||||
const service = row.original.service
|
||||
return service ? (
|
||||
<div>
|
||||
<span className="font-medium">{service.labor_name}</span>
|
||||
{service.service_code && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{service.service_code}</span>
|
||||
)}
|
||||
</div>
|
||||
) : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "rate_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate Type" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate_type
|
||||
if (!val) return "—"
|
||||
return (
|
||||
<Badge variant="outline">
|
||||
{val === "flat_rate" ? "Flat Rate" : val === "hourly" ? "Hourly" : val}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Qty" />,
|
||||
cell: ({ row }) => row.original.quantity ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "rate",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "labor_rate.title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const lr = row.original.labor_rate
|
||||
return lr ? `${lr.title} ($${Number(lr.rate).toFixed(2)})` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "working_hours",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Working Hrs" />,
|
||||
cell: ({ row }) => row.original.working_hours ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "labor_hours",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Labor Hrs" />,
|
||||
cell: ({ row }) => row.original.labor_hours ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||
cell: ({ row }) => row.original.department?.name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Description" />,
|
||||
cell: ({ row }) => row.original.description || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Added" />,
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditItem(row.original)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
<div className="flex justify-end">
|
||||
<Dialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setDialogOpen(open)
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => setEditItem(null)}>
|
||||
<Plus className="me-2 h-4 w-4" />
|
||||
Add Service
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editItem ? "Edit Service" : "Add Service"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<JobCardServiceForm
|
||||
jobCardId={jobCardId}
|
||||
jobCardServiceId={editItem?.id ?? null}
|
||||
initialData={editItem}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
invalidate()
|
||||
}}
|
||||
onCancel={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{
|
||||
page: 1,
|
||||
pageSize: rows.length || 15,
|
||||
pageCount: 1,
|
||||
total: rows.length,
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
|
||||
@@ -6,13 +6,13 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { JobCardForm } from '@/modules/job-cards/job-card-form'
|
||||
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
|
||||
import type { JobCardsClient } from '@garage/api'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
|
||||
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
|
||||
import { ClipboardListIcon } from 'lucide-react'
|
||||
import { Badge } from '@/shared/components/ui/badge'
|
||||
import { Input } from '@/shared/components/ui/input'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
|
||||
import { useFilterParams } from '@/shared/hooks/use-filter-params'
|
||||
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
|
||||
import { jobCardFilterConfig, JobCardFilterFields } from '@/modules/job-cards/job-card-filters'
|
||||
|
||||
type JobCardItem = {
|
||||
id: number
|
||||
@@ -34,38 +34,33 @@ const statusColorMap: Record<string, string> = {
|
||||
|
||||
export default function JobCardsPage() {
|
||||
const router = useRouter()
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<string>("check_in")
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearch(searchInput), 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
const extraParams: Record<string, unknown> = {}
|
||||
if (search) extraParams.search = search
|
||||
if (statusFilter !== "all") extraParams.status = statusFilter
|
||||
const filter = useFilterParams(jobCardFilterConfig)
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourcePage<JobCardsClient>
|
||||
|
||||
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||
getClient={(api) => api.jobCards}
|
||||
extraParams={extraParams}
|
||||
searchable
|
||||
searchPlaceholder="Search job cards..."
|
||||
statusFilter={{ statuses: JobCardStatus }}
|
||||
extraParams={filter.appliedParams}
|
||||
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Job Cards",
|
||||
actions: (
|
||||
<FormDialog classNames={{ dialogContent: 'min-w-6xl' }} title="Job Card" >
|
||||
{(resourceId) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<FilterTrigger onClick={filter.open} activeFilterCount={filter.activeFilterCount} />
|
||||
<FormDialog classNames={{ dialogContent: 'xl:min-w-6xl' }} title="Job Card" >
|
||||
{(resourceId, {close}) => (
|
||||
<JobCardForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={()=>{ invalidateQuery(); close();}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -82,11 +77,9 @@ export default function JobCardsPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Order Number" />,
|
||||
|
||||
},
|
||||
{
|
||||
accessorKey: "check_in_date",
|
||||
@@ -126,30 +119,19 @@ export default function JobCardsPage() {
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
|
||||
tableHeader={
|
||||
<div className="flex justify-between">
|
||||
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="all" >All</TabsTrigger>
|
||||
{JobCardStatus.map((status) => (
|
||||
<TabsTrigger key={status} value={status}>
|
||||
{formatEnum(status)}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search job cards..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<FilterDrawer
|
||||
form={filter.form}
|
||||
isOpen={filter.isOpen}
|
||||
onOpenChange={(open) => { if (!open) filter.close() }}
|
||||
onSubmit={filter.onSubmit}
|
||||
onReset={filter.reset}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
title="Filter Job Cards"
|
||||
>
|
||||
<JobCardFilterFields />
|
||||
</FilterDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
UserIcon,
|
||||
ClipboardListIcon,
|
||||
} from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
type PaymentReceivedItem = {
|
||||
id: number
|
||||
@@ -32,6 +34,8 @@ export default function PaymentReceivedPage() {
|
||||
return (
|
||||
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
|
||||
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => ({
|
||||
list: (query?: any) => api.paymentReceived.list(query),
|
||||
destroy: (id: string) => api.paymentReceived.destroy(id),
|
||||
@@ -63,29 +67,32 @@ export default function PaymentReceivedPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const customer = item.customer
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.customer_name || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "job_card_name",
|
||||
accessorKey: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const label = item.job_card_number || item.job_card_name
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const jobCard = item.job_card
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{label || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={jobCard?.title || item.job_card_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -111,14 +118,14 @@ export default function PaymentReceivedPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "payment_mode_name",
|
||||
accessorKey: "payment_mode",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const item:any = row.original as unknown as PaymentReceivedItem
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
||||
<span className="capitalize">{item.payment_mode?.title || "—"}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Download, ExternalLink, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -19,10 +19,27 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
type VehicleDocument = {
|
||||
id: number
|
||||
name: string
|
||||
document_number?: string
|
||||
document_type_id?: number
|
||||
document_type?: {
|
||||
id?: number
|
||||
name?: string
|
||||
} | null
|
||||
customer_id?: number
|
||||
customer?: {
|
||||
id?: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
name?: string
|
||||
} | null
|
||||
document_expire?: string
|
||||
document_file?: string
|
||||
document_file_url?: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -54,7 +71,7 @@ export default function VehicleDocumentsPage() {
|
||||
const handleDelete = async (doc: VehicleDocument) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Document",
|
||||
description: `Are you sure you want to delete "${doc.name}"?`,
|
||||
description: `Are you sure you want to delete "${doc.document_number || `Document #${doc.id}`}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -65,16 +82,74 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
const columns: ColumnDef<VehicleDocument>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
accessorKey: "document_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Number" />,
|
||||
cell: ({ getValue, row }) => {
|
||||
const number = getValue<string>()
|
||||
const fallbackName = row.original.document_file?.split("/").pop()
|
||||
return number || fallbackName || `Document #${row.original.id}`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_type_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Type" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const typeName = row.original.document_type?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return typeName || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const name = getFullName(row.original.customer as any) || row.original.customer?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return name || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_expire",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "file",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="File" />,
|
||||
cell: ({ row }) => {
|
||||
const url = row.original.document_file_url
|
||||
if (!url) return "No file"
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Open document"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
Open
|
||||
</a>
|
||||
<a
|
||||
href={url}
|
||||
download
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Download document"
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
Download
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -83,7 +158,10 @@ export default function VehicleDocumentsPage() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDelete(row.original)
|
||||
}}
|
||||
title="Delete document"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
@@ -93,6 +171,15 @@ export default function VehicleDocumentsPage() {
|
||||
},
|
||||
]
|
||||
|
||||
const handleRowClick = (doc: VehicleDocument) => {
|
||||
if (doc.document_file_url) {
|
||||
window.open(doc.document_file_url, "_blank", "noopener,noreferrer")
|
||||
return
|
||||
}
|
||||
|
||||
toast.info("This document has no file to open.")
|
||||
}
|
||||
|
||||
const documents = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
@@ -105,21 +192,25 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-end">
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Upload Document
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
}}
|
||||
columns={columns}
|
||||
data={documents}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
onChange={() => { }}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import { FileTextIcon, UserIcon } from 'lucide-react'
|
||||
import { useVehicle } from '@/modules/vehicles/vehicle-context'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
|
||||
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: vehicleId } = use(params)
|
||||
@@ -18,7 +20,7 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
return (
|
||||
<>
|
||||
<ResourcePage<EstimatesClient>
|
||||
toolbar={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
<FormDialog title="Estimate">
|
||||
{(resourceId) => (
|
||||
<EstimateForm
|
||||
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
}
|
||||
pageTitle="Vehicle Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
extraParams={{ vehicle_id: vehicleId }}
|
||||
header={
|
||||
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
|
||||
@@ -13,7 +13,6 @@ export default async function layout(props: { params: Promise<{ id: string }>, c
|
||||
return (
|
||||
<>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
avatarSrc={vehicle.data?.image_url || ""}
|
||||
// avatarSrc={vehicle.data?.image_url || ""}
|
||||
title={title}
|
||||
|
||||
@@ -25,11 +25,23 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { MileageForm } from "@/modules/vehicles/mileage-form"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
|
||||
type MileageRecord = {
|
||||
id: number
|
||||
name: string
|
||||
vehicle_id?: number
|
||||
miles?: number | null
|
||||
fuel_level?: number | null
|
||||
date?: string | null
|
||||
time?: string | null
|
||||
note?: string | null
|
||||
vehicle?: {
|
||||
id?: number
|
||||
make?: string | null
|
||||
model?: string | null
|
||||
year?: number | null
|
||||
license_plate?: string | null
|
||||
} | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -64,9 +76,10 @@ export default function VehicleMileagePage() {
|
||||
})
|
||||
|
||||
const handleDelete = async (record: MileageRecord) => {
|
||||
const label = record.miles != null ? `${record.miles} mi` : `Record #${record.id}`
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Mileage Record",
|
||||
description: `Are you sure you want to delete this mileage record?`,
|
||||
description: `Are you sure you want to delete ${label}?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -87,16 +100,59 @@ export default function VehicleMileagePage() {
|
||||
|
||||
const columns: ColumnDef<MileageRecord>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Mileage" />,
|
||||
accessorKey: "miles",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Miles" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : value.toLocaleString()
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "fuel_level",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Fuel Level" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : `${value}%`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | null | undefined>()),
|
||||
},
|
||||
{
|
||||
accessorKey: "time",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Time" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<string | null | undefined>()
|
||||
if (!value) return "—"
|
||||
if (value.includes("T")) {
|
||||
const timePart = value.split("T")[1]
|
||||
return timePart ? timePart.slice(0, 5) : "—"
|
||||
}
|
||||
return value.slice(0, 5)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ getValue }) => getValue<string | null | undefined>() || "—",
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const vehicle = row.original.vehicle
|
||||
if (!vehicle) return "—"
|
||||
const details = [vehicle.make, vehicle.model, vehicle.year].filter(Boolean).join(" ")
|
||||
return details || vehicle.license_plate || "—"
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -142,30 +198,25 @@ export default function VehicleMileagePage() {
|
||||
<div className="flex flex-col gap-4">
|
||||
|
||||
|
||||
<DashboardPage
|
||||
header={null}
|
||||
toolbar={
|
||||
<Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
}
|
||||
title='Milage'
|
||||
>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
}}
|
||||
columns={columns}
|
||||
data={records}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
onChange={() => { }}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="min-w-md">
|
||||
|
||||
@@ -129,17 +129,28 @@ export default function VehicleOwnersPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage title="Owners" header={null} toolbar={
|
||||
<Button className="w-full" size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
}>
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
|
||||
|
||||
<DataTable
|
||||
slots={{
|
||||
actions:
|
||||
<div className="flex justify-end">
|
||||
|
||||
<Button size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
</div>,
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
columns={columns}
|
||||
data={owners}
|
||||
pagination={pagination}
|
||||
@@ -160,7 +171,6 @@ export default function VehicleOwnersPage() {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage >
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,23 +3,45 @@
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
|
||||
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
|
||||
import { VEHICLE_ROUTES } from '@garage/api'
|
||||
import type { VehiclesClient } from '@garage/api'
|
||||
import { CarIcon } from 'lucide-react'
|
||||
import { CarIcon, UserIcon } from 'lucide-react'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function VehiclesPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<VehiclesClient>
|
||||
pageTitle="Vehicles"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Vehicle">
|
||||
<div className='flex items-center gap-2'>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.vehicles.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Vehicles"
|
||||
onDownloadSample={() => api.vehicles.downloadImportSample()}
|
||||
sampleFileName='vehicles-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.vehicles.exportData(filters)}
|
||||
fileName='vehicles'
|
||||
/>
|
||||
<FormDialog title="Vehicle" classNames={{ dialogContent: 'lg:min-w-4xl' }}>
|
||||
{(resourceId) => (
|
||||
<VehicleForm
|
||||
resourceId={resourceId}
|
||||
@@ -28,11 +50,14 @@ export default function VehiclesPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
id: "name",
|
||||
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
@@ -52,6 +77,20 @@ export default function VehiclesPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customers",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }: any) => {
|
||||
const customer = (row.original as any).customers?.[0]
|
||||
return (
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
} as any,
|
||||
{
|
||||
accessorKey: "year",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||
@@ -90,14 +129,7 @@ export default function VehiclesPage() {
|
||||
return val != null ? `${Number(val).toLocaleString()} mi` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
"use client"
|
||||
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { SettingsForm } from "@/modules/settings/company/settings-form"
|
||||
|
||||
export default function CompanySettingsPage() {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6 p-6">
|
||||
<DashboardPage headerProps={{title:'Company Settings'}}>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Company Settings</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Manage your workshop profile, contact details, and preferences.
|
||||
</p>
|
||||
</div>
|
||||
<SettingsForm />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
|
||||
<ResourcePage<DepartmentsClient>
|
||||
pageTitle="Departments"
|
||||
routeKey={DEPARTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search departments..."
|
||||
getClient={(api) => api.departments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Switch } from "@/shared/components/ui/switch"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { prompt } from "@/shared/components/prompt-dialog"
|
||||
import { TemplateCheckpointEditDialog } from "@/modules/inspections/template-checkpoint-edit-dialog"
|
||||
import type {
|
||||
InspectionTemplate,
|
||||
InspectionTemplateSection,
|
||||
InspectionTemplateCheckPoint,
|
||||
InspectionSeverity,
|
||||
} from "@garage/api"
|
||||
|
||||
const SEVERITY_BADGE: Record<InspectionSeverity, { label: string; cls: string }> = {
|
||||
good: { label: "Good", cls: "bg-emerald-100 text-emerald-800" },
|
||||
attention: { label: "Attention", cls: "bg-amber-100 text-amber-800" },
|
||||
critical: { label: "Critical", cls: "bg-rose-100 text-rose-800" },
|
||||
na: { label: "N/A", cls: "bg-slate-100 text-slate-700" },
|
||||
not_inspected: { label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
|
||||
}
|
||||
|
||||
const RECORD_TYPE_LABEL: Record<string, string> = {
|
||||
capture_photo: "Photo",
|
||||
record_video: "Video",
|
||||
record_audio: "Audio",
|
||||
record_conditions: "0–100",
|
||||
wire_frame: "Wireframe",
|
||||
none: "No media",
|
||||
}
|
||||
|
||||
export default function InspectionTemplateEditorPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const [editing, setEditing] = useState<{
|
||||
section: InspectionTemplateSection
|
||||
checkpoint: InspectionTemplateCheckPoint | null
|
||||
} | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.show(id)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load template")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const updateMeta = async (partial: Partial<InspectionTemplate>) => {
|
||||
if (!template) return
|
||||
try {
|
||||
const res = await api.inspectionTemplates.update(template.id, partial)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to save")
|
||||
}
|
||||
}
|
||||
|
||||
const addSection = async () => {
|
||||
if (!template) return
|
||||
const name = await prompt({
|
||||
title: "New section",
|
||||
label: "Section name",
|
||||
placeholder: "e.g. Brakes",
|
||||
confirmLabel: "Add section",
|
||||
})
|
||||
if (!name) return
|
||||
const nextOrder = (template.sections?.length ?? 0) + 1
|
||||
try {
|
||||
await api.inspectionTemplates.createSection(template.id, { name, sort_order: nextOrder })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to add section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteSection = async (section: InspectionTemplateSection) => {
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete section "${section.name}"?`,
|
||||
description: "This will remove the section and all its checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroySection(template.id, section.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete section")
|
||||
}
|
||||
}
|
||||
|
||||
const renameSection = async (section: InspectionTemplateSection, name: string) => {
|
||||
if (!template || name === section.name) return
|
||||
try {
|
||||
await api.inspectionTemplates.updateSection(template.id, section.id, { name })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to rename section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCheckpoint = async (section: InspectionTemplateSection, cp: InspectionTemplateCheckPoint, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${cp.name}"?`,
|
||||
description: "This checkpoint will be removed from the template.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroyCheckpoint(template.id, section.id, cp.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete checkpoint")
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="p-6 text-muted-foreground">Loading…</div>
|
||||
if (!template) return <div className="p-6 text-muted-foreground">Template not found</div>
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-4xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="/settings/inspection-templates">
|
||||
<Button variant="ghost" size="sm"><ChevronLeft className="size-4 mr-1" /> Back</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="rounded border p-4 space-y-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Name</label>
|
||||
<Input
|
||||
defaultValue={template.name}
|
||||
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<Switch
|
||||
checked={template.is_active}
|
||||
onCheckedChange={(checked) => updateMeta({ is_active: checked })}
|
||||
/>
|
||||
<span className="text-sm">{template.is_active ? "Active" : "Inactive"}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Description</label>
|
||||
<Textarea
|
||||
defaultValue={template.description ?? ""}
|
||||
rows={2}
|
||||
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">Sections & Checkpoints</h2>
|
||||
<Button onClick={addSection} size="sm"><Plus className="size-4 mr-1" /> Add section</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{(template.sections ?? []).length === 0 && (
|
||||
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
|
||||
No sections yet. Add one to start building the checklist.
|
||||
</div>
|
||||
)}
|
||||
{(template.sections ?? []).map((section) => (
|
||||
<div key={section.id} className="rounded border">
|
||||
<div className="flex items-center gap-2 px-3 py-2 bg-muted/40">
|
||||
<Input
|
||||
defaultValue={section.name}
|
||||
onBlur={(e) => renameSection(section, e.currentTarget.value)}
|
||||
className="max-w-md h-8"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(section.check_points ?? []).length} checkpoint{(section.check_points ?? []).length === 1 ? "" : "s"}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button size="sm" variant="ghost" onClick={() => setEditing({ section, checkpoint: null })}>
|
||||
<Plus className="size-4 mr-1" /> Checkpoint
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => deleteSection(section)}>
|
||||
<Trash2 className="size-4 text-red-600" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{(section.check_points ?? []).length === 0 && (
|
||||
<div className="p-3 text-sm text-muted-foreground">No checkpoints in this section.</div>
|
||||
)}
|
||||
{(section.check_points ?? []).map((cp) => {
|
||||
const sev = SEVERITY_BADGE[cp.severity_default] ?? SEVERITY_BADGE.not_inspected
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={cp.id}
|
||||
onClick={() => setEditing({ section, checkpoint: cp })}
|
||||
className="w-full text-left flex items-center gap-3 px-3 py-2 hover:bg-muted/30 transition"
|
||||
>
|
||||
<span className="text-xs text-muted-foreground w-6 text-right">
|
||||
{cp.sort_order}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0 truncate text-sm font-medium">
|
||||
{cp.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground hidden sm:inline-block">
|
||||
{RECORD_TYPE_LABEL[cp.record_type] ?? cp.record_type}
|
||||
</span>
|
||||
<span className={`text-xs rounded-full px-2 py-0.5 ${sev.cls}`}>
|
||||
{sev.label}
|
||||
</span>
|
||||
<Pencil className="size-3.5 text-muted-foreground" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => deleteCheckpoint(section, cp, e)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
aria-label="Delete checkpoint"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<TemplateCheckpointEditDialog
|
||||
open={!!editing}
|
||||
onOpenChange={(o) => { if (!o) setEditing(null) }}
|
||||
templateId={template.id}
|
||||
sectionId={editing.section.id}
|
||||
checkpoint={editing.checkpoint}
|
||||
nextSortOrder={(editing.section.check_points?.length ?? 0) + 1}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { Copy, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import type { InspectionTemplate } from "@garage/api"
|
||||
|
||||
export default function InspectionTemplatesPage() {
|
||||
const api = useAuthApi()
|
||||
const [items, setItems] = useState<InspectionTemplate[]>([])
|
||||
const [search, setSearch] = useState("")
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState("")
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.list(search ? { search } : undefined)
|
||||
setItems(res.data ?? [])
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load templates")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim()) return
|
||||
try {
|
||||
await api.inspectionTemplates.create({ name: newName.trim(), is_active: true })
|
||||
setNewName("")
|
||||
setCreating(false)
|
||||
toast.success("Template created")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to create template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDuplicate = async (id: number) => {
|
||||
try {
|
||||
await api.inspectionTemplates.duplicate(id)
|
||||
toast.success("Template duplicated")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to duplicate template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, name: string) => {
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${name}"?`,
|
||||
description: "This will remove the template and all its sections / checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroy(id)
|
||||
toast.success("Template deleted")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete template")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h1 className="text-2xl font-semibold">Inspection Templates</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && load()}
|
||||
className="w-56"
|
||||
/>
|
||||
<Button onClick={() => setCreating((c) => !c)}>
|
||||
<Plus className="size-4 mr-1" /> New template
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{creating && (
|
||||
<div className="flex items-center gap-2 rounded border p-3">
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder="Template name (e.g. Annual Safety)"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
|
||||
className="max-w-md"
|
||||
/>
|
||||
<Button onClick={handleCreate}>Create</Button>
|
||||
<Button variant="ghost" onClick={() => { setCreating(false); setNewName("") }}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted">
|
||||
<tr>
|
||||
<th className="text-left p-3">Name</th>
|
||||
<th className="text-left p-3">Sections</th>
|
||||
<th className="text-left p-3">Checkpoints</th>
|
||||
<th className="text-left p-3">Status</th>
|
||||
<th className="text-right p-3">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading…</td></tr>
|
||||
)}
|
||||
{!loading && items.length === 0 && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No templates yet</td></tr>
|
||||
)}
|
||||
{!loading && items.map((t) => {
|
||||
const sectionCount = t.sections?.length ?? 0
|
||||
const cpCount = (t.sections ?? []).reduce((sum, s) => sum + (s.check_points?.length ?? 0), 0)
|
||||
return (
|
||||
<tr key={t.id} className="border-t hover:bg-muted/40">
|
||||
<td className="p-3 font-medium">{t.name}</td>
|
||||
<td className="p-3">{sectionCount}</td>
|
||||
<td className="p-3">{cpCount}</td>
|
||||
<td className="p-3">
|
||||
<span className={`inline-block rounded-full px-2 py-0.5 text-xs ${t.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}>
|
||||
{t.is_active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="p-3 text-right space-x-1">
|
||||
<Link href={`/settings/inspection-templates/${t.id}`}>
|
||||
<Button size="sm" variant="ghost"><Pencil className="size-4" /></Button>
|
||||
</Link>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDuplicate(t.id)}><Copy className="size-4" /></Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDelete(t.id, t.name)}><Trash2 className="size-4 text-red-600" /></Button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export default function InsuranceTypesPage() {
|
||||
<ResourcePage<InsuranceTypesClient>
|
||||
pageTitle="Insurance Types"
|
||||
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search insurance types..."
|
||||
getClient={(api) => api.insuranceTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client"
|
||||
|
||||
import { MakeAndModelForm } from "@/modules/settings/make-and-models/make-and-model-form"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { MAKE_AND_MODEL_ROUTES } from "@garage/api"
|
||||
import type { MakeAndModelsClient } from "@garage/api"
|
||||
|
||||
export default function MakeAndModelsPage() {
|
||||
return (
|
||||
<ResourcePage<MakeAndModelsClient>
|
||||
pageTitle="Make & Models"
|
||||
routeKey={MAKE_AND_MODEL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search makes & models..."
|
||||
getClient={(api) => api.makeAndModels}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Make & Model">
|
||||
{(resourceId) => (
|
||||
<MakeAndModelForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "make",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Make" />,
|
||||
cell: ({ row }) => (row.original as any).make ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "model",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Model" />,
|
||||
cell: ({ row }) => (row.original as any).model ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "year",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||
cell: ({ row }) => (row.original as any).year ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "sub_model",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Sub Model" />,
|
||||
cell: ({ row }) => (row.original as any).sub_model ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "engine_size",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Engine Size" />,
|
||||
cell: ({ row }) => (row.original as any).engine_size ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "drivetrain",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Drivetrain" />,
|
||||
cell: ({ row }) => (row.original as any).drivetrain ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<span className={active ? "text-green-600" : "text-muted-foreground"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export default function ShopTypesPage() {
|
||||
<ResourcePage<ShopTypesClient>
|
||||
pageTitle="Shop Types"
|
||||
routeKey={SHOP_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop types..."
|
||||
getClient={(api) => api.shopTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function TaxesPage() {
|
||||
<ResourcePage<TaxesClient>
|
||||
pageTitle="Tax & Rates"
|
||||
routeKey={TAX_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tax rates..."
|
||||
getClient={(api) => api.taxes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,444 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import {
|
||||
AlertCircle,
|
||||
Calendar,
|
||||
Car,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Gauge,
|
||||
Loader2,
|
||||
Printer,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
|
||||
type Severity = "good" | "attention" | "critical" | "na" | "not_inspected"
|
||||
|
||||
type Photo = { id: number; url: string | null; caption?: string | null }
|
||||
|
||||
type CheckPoint = {
|
||||
name: string
|
||||
description?: string | null
|
||||
severity: Severity
|
||||
technician_notes?: string | null
|
||||
condition_rate?: number | null
|
||||
photos?: Photo[]
|
||||
}
|
||||
|
||||
type Section = { name: string; items: CheckPoint[] }
|
||||
|
||||
type PublicInspection = {
|
||||
title?: string
|
||||
order_number?: string
|
||||
date?: string
|
||||
time?: string
|
||||
status?: string
|
||||
odometer?: number | null
|
||||
note?: string | null
|
||||
description?: string | null
|
||||
customer?: { name?: string } | null
|
||||
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string; vin?: string } | null
|
||||
technician?: { name?: string } | null
|
||||
department?: string | null
|
||||
template?: string | null
|
||||
totals: { good: number; attention: number; critical: number; na: number; not_inspected: number; considered: number; all: number }
|
||||
score: number | null
|
||||
sections: Section[]
|
||||
share_expires_at?: string | null
|
||||
}
|
||||
|
||||
const SEVERITY_LABEL: Record<Severity, string> = {
|
||||
good: "Good",
|
||||
attention: "Attention",
|
||||
critical: "Critical",
|
||||
na: "N/A",
|
||||
not_inspected: "Not Inspected",
|
||||
}
|
||||
|
||||
const SEVERITY_DOT_BG: Record<Severity, string> = {
|
||||
good: "bg-emerald-500",
|
||||
attention: "bg-amber-500",
|
||||
critical: "bg-rose-500",
|
||||
na: "bg-slate-400",
|
||||
not_inspected: "bg-gray-300",
|
||||
}
|
||||
|
||||
const SEVERITY_PILL: Record<Severity, string> = {
|
||||
good: "bg-emerald-50 text-emerald-700 border-emerald-200",
|
||||
attention: "bg-amber-50 text-amber-800 border-amber-200",
|
||||
critical: "bg-rose-50 text-rose-700 border-rose-200",
|
||||
na: "bg-slate-50 text-slate-700 border-slate-200",
|
||||
not_inspected: "bg-gray-50 text-gray-600 border-gray-200",
|
||||
}
|
||||
|
||||
const SEVERITY_BORDER: Record<Severity, string> = {
|
||||
good: "border-l-emerald-500",
|
||||
attention: "border-l-amber-500",
|
||||
critical: "border-l-rose-500",
|
||||
na: "border-l-slate-400",
|
||||
not_inspected: "border-l-gray-300",
|
||||
}
|
||||
|
||||
function ScoreRing({ score }: { score: number | null }) {
|
||||
if (score === null) {
|
||||
return (
|
||||
<div className="size-32 rounded-full border-4 border-dashed border-muted-foreground/30 flex items-center justify-center text-xs text-muted-foreground">
|
||||
Not scored
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const color =
|
||||
score >= 80 ? "text-emerald-600" : score >= 50 ? "text-amber-600" : "text-rose-600"
|
||||
const stroke =
|
||||
score >= 80 ? "stroke-emerald-500" : score >= 50 ? "stroke-amber-500" : "stroke-rose-500"
|
||||
const r = 56
|
||||
const c = 2 * Math.PI * r
|
||||
const offset = c - (score / 100) * c
|
||||
|
||||
return (
|
||||
<div className="relative size-32 shrink-0">
|
||||
<svg viewBox="0 0 128 128" className="size-32 -rotate-90">
|
||||
<circle cx="64" cy="64" r={r} className="fill-none stroke-muted" strokeWidth="10" />
|
||||
<circle
|
||||
cx="64"
|
||||
cy="64"
|
||||
r={r}
|
||||
className={`fill-none ${stroke} transition-[stroke-dashoffset]`}
|
||||
strokeWidth="10"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={c}
|
||||
strokeDashoffset={offset}
|
||||
/>
|
||||
</svg>
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center">
|
||||
<div className={`text-3xl font-bold leading-none ${color}`}>{score}</div>
|
||||
<div className="text-[10px] uppercase tracking-wider text-muted-foreground mt-1">
|
||||
Health
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function PublicInspectionPage() {
|
||||
const params = useParams<{ token: string }>()
|
||||
const token = params.token
|
||||
const [data, setData] = useState<PublicInspection | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [lightbox, setLightbox] = useState<Photo | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const base = process.env.NEXT_PUBLIC_API_URL ?? ""
|
||||
fetch(`${base.replace(/\/$/, "")}/api/public/inspections/${token}`, {
|
||||
headers: { Accept: "application/json", "X-Lang": "en" },
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({} as any))
|
||||
throw new Error(body.message ?? `Failed (HTTP ${res.status})`)
|
||||
}
|
||||
return res.json()
|
||||
})
|
||||
.then((json: { data: PublicInspection }) => setData(json.data))
|
||||
.catch((e: Error) => setError(e.message))
|
||||
.finally(() => setLoading(false))
|
||||
}, [token])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading inspection…
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
|
||||
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
|
||||
<AlertCircle className="size-12 mx-auto text-rose-500" />
|
||||
<h1 className="text-lg font-semibold">Can't open this inspection</h1>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!data) return null
|
||||
|
||||
const vehicleLine = data.vehicle
|
||||
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
|
||||
: "—"
|
||||
|
||||
const criticalCount = data.totals.critical
|
||||
const attentionCount = data.totals.attention
|
||||
const headlineStatus =
|
||||
criticalCount > 0
|
||||
? { Icon: ShieldAlert, color: "text-rose-600", bg: "bg-rose-50", label: `${criticalCount} critical issue${criticalCount === 1 ? "" : "s"} found` }
|
||||
: attentionCount > 0
|
||||
? { Icon: AlertCircle, color: "text-amber-600", bg: "bg-amber-50", label: `${attentionCount} item${attentionCount === 1 ? "" : "s"} need attention` }
|
||||
: { Icon: ShieldCheck, color: "text-emerald-600", bg: "bg-emerald-50", label: "No issues found" }
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
|
||||
{/* Print is handled by downloading the backend-generated PDF
|
||||
(see the Print button), so this page no longer needs print CSS. */}
|
||||
|
||||
{/* Print bar */}
|
||||
<div className="no-print bg-white/80 backdrop-blur border-b sticky top-0 z-10">
|
||||
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<ClipboardList className="size-4" />
|
||||
<span className="font-medium text-foreground">Inspection report</span>
|
||||
</div>
|
||||
<a
|
||||
href={`${(process.env.NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, "")}/api/public/inspections/${token}/print`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm border bg-white hover:bg-muted/40 transition"
|
||||
>
|
||||
<Printer className="size-3.5" /> Print PDF
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-5">
|
||||
{/* Hero card */}
|
||||
<div className="rounded-2xl bg-white shadow-sm border overflow-hidden">
|
||||
<div className="p-6 sm:p-8">
|
||||
<div className="flex items-start justify-between gap-6 flex-wrap">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-xs uppercase tracking-wider text-muted-foreground">
|
||||
Vehicle inspection report
|
||||
</div>
|
||||
<h1 className="mt-1 text-2xl sm:text-3xl font-bold tracking-tight">{data.title ?? "Inspection"}</h1>
|
||||
{data.order_number && (
|
||||
<div className="text-sm text-muted-foreground font-mono mt-1">#{data.order_number}</div>
|
||||
)}
|
||||
|
||||
<div className={`mt-4 inline-flex items-center gap-2 rounded-full ${headlineStatus.bg} px-4 py-1.5`}>
|
||||
<headlineStatus.Icon className={`size-4 ${headlineStatus.color}`} />
|
||||
<span className={`text-sm font-medium ${headlineStatus.color}`}>
|
||||
{headlineStatus.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<ScoreRing score={data.score} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t bg-gray-50/60 px-6 sm:px-8 py-4">
|
||||
<div className="info-grid grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
|
||||
<InfoCell icon={User} label="Customer" value={data.customer?.name ?? "—"} />
|
||||
<InfoCell icon={Car} label="Vehicle" value={vehicleLine} subtitle={data.vehicle?.license_plate ?? undefined} />
|
||||
<InfoCell icon={Calendar} label="Inspected" value={data.date ?? "—"} subtitle={data.time ?? undefined} />
|
||||
<InfoCell icon={Gauge} label="Odometer" value={data.odometer != null ? `${Number(data.odometer).toLocaleString()} km` : "—"} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Severity summary */}
|
||||
<div className="totals-grid grid grid-cols-2 sm:grid-cols-5 gap-2 pb-avoid">
|
||||
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
|
||||
<div
|
||||
key={s}
|
||||
className={`rounded-xl border px-3 py-3 text-center ${SEVERITY_PILL[s]}`}
|
||||
>
|
||||
<div className="text-xl font-bold leading-none tabular-nums">{data.totals[s]}</div>
|
||||
<div className="text-[11px] font-medium mt-1.5">{SEVERITY_LABEL[s]}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sections */}
|
||||
{data.sections.length === 0 ? (
|
||||
<div className="rounded-2xl bg-white border p-8 text-center text-sm text-muted-foreground">
|
||||
This inspection has no recorded checkpoints yet.
|
||||
</div>
|
||||
) : (
|
||||
data.sections.map((section) => (
|
||||
<section key={section.name} className="rounded-2xl bg-white shadow-sm border overflow-hidden">
|
||||
<header className="px-5 sm:px-6 py-3 border-b flex items-center justify-between bg-gray-50/60">
|
||||
<h2 className="font-semibold text-sm sm:text-base">{section.name}</h2>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{section.items.length} {section.items.length === 1 ? "item" : "items"}
|
||||
</span>
|
||||
</header>
|
||||
<ul className="divide-y">
|
||||
{section.items.map((cp, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className={`cp-row pb-avoid px-5 sm:px-6 py-4 border-l-4 ${SEVERITY_BORDER[cp.severity]}`}
|
||||
>
|
||||
{/* Head: dot + name + severity pill (pill stays inline next to name) */}
|
||||
<div className="cp-head flex items-center gap-2">
|
||||
<span className={`size-2 rounded-full ${SEVERITY_DOT_BG[cp.severity]} shrink-0`} />
|
||||
<span className="font-medium text-sm flex-1 min-w-0 truncate">{cp.name}</span>
|
||||
<span className={`cp-pill inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium shrink-0 ${SEVERITY_PILL[cp.severity]}`}>
|
||||
{SEVERITY_LABEL[cp.severity]}
|
||||
</span>
|
||||
</div>
|
||||
<div className="cp-body ms-4">
|
||||
{cp.description && (
|
||||
<p className="text-xs text-muted-foreground mt-1">{cp.description}</p>
|
||||
)}
|
||||
{cp.technician_notes && (
|
||||
<p className="mt-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-foreground/80 italic border-l-2 border-muted-foreground/30">
|
||||
"{cp.technician_notes}"
|
||||
</p>
|
||||
)}
|
||||
{cp.condition_rate != null && (
|
||||
<div className="mt-2">
|
||||
<div className="h-1.5 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className={`h-full transition-all ${cp.severity === "critical" ? "bg-rose-500" : cp.severity === "attention" ? "bg-amber-500" : "bg-emerald-500"}`}
|
||||
style={{ width: `${cp.condition_rate}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-[11px] text-muted-foreground mt-0.5 tabular-nums">{cp.condition_rate}%</div>
|
||||
</div>
|
||||
)}
|
||||
{cp.photos && cp.photos.length > 0 && (
|
||||
<div className="photo-grid mt-3 grid grid-cols-3 sm:grid-cols-4 gap-2">
|
||||
{cp.photos.map((p) => (
|
||||
p.url ? (
|
||||
<button
|
||||
type="button"
|
||||
key={p.id}
|
||||
onClick={() => setLightbox(p)}
|
||||
className="group relative rounded-lg overflow-hidden border bg-muted aspect-square focus:outline-none focus:ring-2 focus:ring-primary/40"
|
||||
aria-label="View photo"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={p.url}
|
||||
alt={p.caption ?? ""}
|
||||
className="block w-full h-full object-cover transition group-hover:scale-105"
|
||||
/>
|
||||
</button>
|
||||
) : null
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
|
||||
{(data.note || data.description) && (
|
||||
<section className="rounded-2xl bg-white shadow-sm border p-5 sm:p-6">
|
||||
<h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
|
||||
<ChevronRight className="size-4 text-muted-foreground" />
|
||||
Additional notes from your technician
|
||||
</h2>
|
||||
{data.note && <p className="text-sm leading-relaxed">{data.note}</p>}
|
||||
{data.description && (
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">{data.description}</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Technician footer */}
|
||||
{data.technician?.name && (
|
||||
<div className="rounded-2xl bg-white shadow-sm border px-5 sm:px-6 py-4 flex items-center justify-between gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 rounded-full bg-gradient-to-br from-blue-500 to-blue-600 text-white flex items-center justify-center font-semibold text-sm">
|
||||
{data.technician.name
|
||||
.split(" ")
|
||||
.map((p) => p[0])
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.join("")}
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs text-muted-foreground">Inspected by</div>
|
||||
<div className="font-medium text-sm">{data.technician.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
{data.department && (
|
||||
<span className="text-xs text-muted-foreground">{data.department}</span>
|
||||
)}
|
||||
{data.template && (
|
||||
<span className="text-xs rounded-full border px-3 py-1 bg-muted/30">
|
||||
{data.template}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<footer className="text-center text-xs text-muted-foreground py-6 no-print">
|
||||
{data.share_expires_at && (
|
||||
<div>Link valid until {new Date(data.share_expires_at).toLocaleDateString()}</div>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
{/* Lightbox */}
|
||||
{lightbox && lightbox.url && (
|
||||
<div
|
||||
className="no-print fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
|
||||
onClick={() => setLightbox(null)}
|
||||
role="dialog"
|
||||
aria-modal
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={lightbox.url}
|
||||
alt={lightbox.caption ?? ""}
|
||||
className="max-w-full max-h-[88vh] object-contain shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLightbox(null)}
|
||||
className="absolute top-4 right-4 rounded-full bg-white/10 hover:bg-white/20 text-white size-9 inline-flex items-center justify-center"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
{lightbox.caption && (
|
||||
<div className="absolute bottom-4 inset-x-0 text-center text-white/90 text-sm px-4">
|
||||
{lightbox.caption}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InfoCell({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
subtitle,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string
|
||||
subtitle?: string
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-2 min-w-0">
|
||||
<Icon className="size-4 mt-0.5 text-muted-foreground shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</div>
|
||||
<div className="font-medium truncate">{value}</div>
|
||||
{subtitle && (
|
||||
<div className="text-xs text-muted-foreground font-mono truncate">{subtitle}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,15 +1,23 @@
|
||||
import { Geist_Mono, Inter } from "next/font/google"
|
||||
import NextTopLoader from "nextjs-toploader"
|
||||
|
||||
|
||||
import "./globals.css"
|
||||
import { QueryProvider } from "@/shared/components/query-provider"
|
||||
import { ThemeProvider } from "@/shared/components/theme-provider"
|
||||
import { Toaster } from "@/shared/components/ui/sonner"
|
||||
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
|
||||
import { PromptDialog } from "@/shared/components/prompt-dialog"
|
||||
import { NuqsAdapter } from "nuqs/adapters/next/app"
|
||||
import { cn } from "@/shared/lib/utils"
|
||||
import './globals.css'
|
||||
|
||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
||||
|
||||
export const metadata = {
|
||||
title: "Garage ERP Dashboard",
|
||||
description: "Manage your garage with ease using Garage ERP Dashboard.",
|
||||
}
|
||||
|
||||
const fontMono = Geist_Mono({
|
||||
subsets: ["latin"],
|
||||
variable: "--font-mono",
|
||||
@@ -27,11 +35,13 @@ export default function RootLayout({
|
||||
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
|
||||
>
|
||||
<body>
|
||||
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
|
||||
<NuqsAdapter>
|
||||
<ThemeProvider>
|
||||
<QueryProvider>{children}</QueryProvider>
|
||||
<Toaster />
|
||||
<ConfirmDialog />
|
||||
<PromptDialog />
|
||||
</ThemeProvider>
|
||||
</NuqsAdapter>
|
||||
</body>
|
||||
|
||||
@@ -141,9 +141,20 @@ export function AppSidebar({ navGroups, logo, user, ...props }: AppSidebarProps)
|
||||
)
|
||||
}
|
||||
|
||||
function isPathActive(pathname: string, href: string): boolean {
|
||||
if (href === '/') return pathname === '/'
|
||||
return pathname === href || pathname.startsWith(href + '/')
|
||||
}
|
||||
|
||||
function isItemActive(pathname: string, item: { href: string; matchPath?: string; isActive?: boolean }): boolean {
|
||||
if (item.isActive !== undefined) return item.isActive
|
||||
if (item.matchPath) return isPathActive(pathname, item.matchPath)
|
||||
return isPathActive(pathname, item.href)
|
||||
}
|
||||
|
||||
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||
const pathname = usePathname()
|
||||
const isActive = item.isActive ?? pathname === item.href
|
||||
const isActive = isItemActive(pathname, item)
|
||||
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
@@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
|
||||
|
||||
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||
const pathname = usePathname()
|
||||
const isChildActive = item.items?.some((sub) => pathname === sub.href)
|
||||
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
|
||||
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
|
||||
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
|
||||
|
||||
// Collapsed sidebar → flyout dropdown with sub-items
|
||||
if (isCollapsed) {
|
||||
@@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{item.items?.map((sub) => {
|
||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
||||
const isSubActive = isItemActive(pathname, sub)
|
||||
return (
|
||||
<DropdownMenuItem key={sub.href} asChild>
|
||||
<Link
|
||||
@@ -272,7 +283,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
|
||||
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
|
||||
<SidebarMenuSub>
|
||||
{item.items?.map((sub) => {
|
||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
||||
const isSubActive = isItemActive(pathname, sub)
|
||||
return (
|
||||
<SidebarMenuSubItem key={sub.href}>
|
||||
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
|
||||
|
||||
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
|
||||
</Button>
|
||||
)}
|
||||
{(avatarSrc || avatarFallback) && (
|
||||
<a rel="preload" target="_blank" href={avatarSrc} >
|
||||
avatarSrc ? (
|
||||
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
|
||||
<Avatar className="size-14">
|
||||
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
|
||||
<AvatarImage src={avatarSrc} alt={title} />
|
||||
<AvatarFallback>
|
||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</a>
|
||||
) : (
|
||||
<Avatar className="size-14">
|
||||
<AvatarFallback>
|
||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)
|
||||
)}
|
||||
{!avatarSrc && !avatarFallback && icon && (
|
||||
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
|
||||
@@ -109,6 +117,7 @@ export default function DashboardDetailsPageLayout({
|
||||
<Link
|
||||
key={tab.href}
|
||||
href={tab.href}
|
||||
prefetch
|
||||
className={cn(
|
||||
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
|
||||
"text-muted-foreground hover:text-foreground",
|
||||
|
||||
@@ -6,6 +6,12 @@ export type NavItem = {
|
||||
href: string
|
||||
icon?: ReactNode
|
||||
isActive?: boolean
|
||||
/**
|
||||
* Optional prefix used to decide active state when the link target
|
||||
* differs from the page's URL pattern (e.g. `/calendar/appointment/list`
|
||||
* is the link, but the item should stay active on `/calendar/appointment/{id}`).
|
||||
*/
|
||||
matchPath?: string
|
||||
badge?: string | number
|
||||
items?: NavSubItem[]
|
||||
}
|
||||
@@ -15,6 +21,7 @@ export type NavSubItem = {
|
||||
href: string
|
||||
icon?: ReactNode
|
||||
isActive?: boolean
|
||||
matchPath?: string
|
||||
}
|
||||
|
||||
export type NavGroup = {
|
||||
|
||||
@@ -57,14 +57,14 @@ export const navGroups: NavGroup[] = [
|
||||
},
|
||||
{
|
||||
title: "Customer & Vehicles",
|
||||
href: "/customer-vehicles",
|
||||
href: "/sales/vehicles",
|
||||
icon: <UsersIcon />,
|
||||
},
|
||||
{
|
||||
title: "Reports",
|
||||
href: "/reports",
|
||||
icon: <BarChart3Icon />,
|
||||
},
|
||||
// {
|
||||
// title: "Reports",
|
||||
// href: "/reports",
|
||||
// icon: <BarChart3Icon />,
|
||||
// },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -75,8 +75,8 @@ export const navGroups: NavGroup[] = [
|
||||
href: "/calendars",
|
||||
icon: <CalendarIcon />,
|
||||
items: [
|
||||
{ title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
|
||||
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
|
||||
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
|
||||
{ title: "Appointments", href: "/calendar/appointment/list", matchPath: "/calendar/appointment", icon: <CalendarCheck2Icon /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -107,35 +107,35 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Vendor Credits", href: "/purchase/vendor-credit", icon: <ReceiptTextIcon /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "CRM",
|
||||
href: "/crm",
|
||||
icon: <BriefcaseBusinessIcon />,
|
||||
items: [
|
||||
{ title: "Leads", href: "/crm/leads/list", icon: <GemIcon /> },
|
||||
{ title: "Calls", href: "/crm/calls-follow-up/list", icon: <PhoneCallIcon /> },
|
||||
{ title: "Tasks", href: "/crm/tasks/list", icon: <ListTodoIcon /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Marketing",
|
||||
href: "/marketing",
|
||||
icon: <MegaphoneIcon />,
|
||||
items: [
|
||||
{ title: "Service Reminders", href: "/marketing/service-reminder/list", icon: <AlarmClockIcon /> },
|
||||
{ title: "Rating & Reviews", href: "/marketing/rating-review", icon: <StarIcon /> },
|
||||
{ title: "Google Business Reviews", href: "/marketing/google-rating-review", icon: <AwardIcon /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Accountants",
|
||||
href: "/accountants",
|
||||
icon: <BookIcon />,
|
||||
items: [
|
||||
{ title: "Manual Journals", href: "/accountants/manual-journal", icon: <BookIcon /> },
|
||||
{ title: "Chart of Accounts", href: "/accountants/chart-of-account", icon: <GitBranchIcon /> },
|
||||
],
|
||||
},
|
||||
// {
|
||||
// title: "CRM",
|
||||
// href: "/crm",
|
||||
// icon: <BriefcaseBusinessIcon />,
|
||||
// items: [
|
||||
// { title: "Leads", href: "/crm/leads/list", icon: <GemIcon /> },
|
||||
// { title: "Calls", href: "/crm/calls-follow-up/list", icon: <PhoneCallIcon /> },
|
||||
// { title: "Tasks", href: "/crm/tasks/list", icon: <ListTodoIcon /> },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Marketing",
|
||||
// href: "/marketing",
|
||||
// icon: <MegaphoneIcon />,
|
||||
// items: [
|
||||
// { title: "Service Reminders", href: "/marketing/service-reminder/list", icon: <AlarmClockIcon /> },
|
||||
// { title: "Rating & Reviews", href: "/marketing/rating-review", icon: <StarIcon /> },
|
||||
// { title: "Google Business Reviews", href: "/marketing/google-rating-review", icon: <AwardIcon /> },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Accountants",
|
||||
// href: "/accountants",
|
||||
// icon: <BookIcon />,
|
||||
// items: [
|
||||
// { title: "Manual Journals", href: "/accountants/manual-journal", icon: <BookIcon /> },
|
||||
// { title: "Chart of Accounts", href: "/accountants/chart-of-account", icon: <GitBranchIcon /> },
|
||||
// ],
|
||||
// },
|
||||
{
|
||||
title: "Employees",
|
||||
href: "/productivity",
|
||||
@@ -144,10 +144,10 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
|
||||
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
|
||||
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
|
||||
{ title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||
{ title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
||||
{ title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
||||
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
||||
// { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
||||
// { title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||
{ title: "Holidays", href: "/productivity/holidays", icon: <CalendarIcon /> },
|
||||
{ title: "Tasks", href: "/productivity/tasks", icon: <ListTodoIcon /> },
|
||||
],
|
||||
@@ -161,7 +161,7 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Parts", href: "/items/parts", icon: <WrenchIcon /> },
|
||||
{ title: "Expense Item", href: "/items/expense-item", icon: <WalletIcon /> },
|
||||
{ title: "Service Group", href: "/items/service-group", icon: <PackageIcon /> },
|
||||
{ title: "Inspections", href: "/items/inspection", icon: <ClipboardCheckIcon /> },
|
||||
// { title: "Inspections", href: "/items/inspection", icon: <ClipboardCheckIcon /> },
|
||||
{ title: "Inventory Adjustments", href: "/items/adjustment", icon: <ListIcon /> },
|
||||
],
|
||||
},
|
||||
@@ -175,10 +175,12 @@ export const navGroups: NavGroup[] = [
|
||||
{ title: "Departments", href: "/settings/departments", icon: <Building2Icon /> },
|
||||
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
|
||||
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
|
||||
{ title: "Configurations", href: "/settings/configurations/preferences/sales", icon: <SettingsIcon /> },
|
||||
{ title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
|
||||
{ title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
|
||||
{ title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },
|
||||
{ title: "Make & Models", href: "/settings/make-and-models", icon: <CarIcon /> },
|
||||
{ title: "Inspection Templates", href: "/settings/inspection-templates", icon: <ClipboardListIcon /> },
|
||||
{ title: "Configurations", href: "/settings/configurations/preferences/sales", matchPath: "/settings/configurations", icon: <SettingsIcon /> },
|
||||
// { title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
|
||||
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
|
||||
// { title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
@@ -4,6 +4,8 @@ import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -15,6 +17,8 @@ import { Ellipsis, Pencil, Trash2, CheckCircle, Unlink } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "./appointment-form"
|
||||
|
||||
type AppointmentActionsProps = {
|
||||
appointmentId: string
|
||||
@@ -27,10 +31,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
const router = useRouter()
|
||||
const queryClient = useQueryClient()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleEdit = () => {
|
||||
router.push(`/calendar/appointment/${appointmentId}/edit`)
|
||||
}
|
||||
const editDialog = useFormDialog("appointment-details-edit")
|
||||
|
||||
const handleDelete = async () => {
|
||||
setIsLoading(true)
|
||||
@@ -75,6 +76,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" disabled={isLoading}>
|
||||
@@ -82,7 +84,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={handleEdit}>
|
||||
<DropdownMenuItem onClick={() => editDialog.open(appointmentId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
@@ -120,5 +122,22 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Appointment</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<AppointmentForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
RhfTextareaField,
|
||||
RhfSelectField,
|
||||
RhfAsyncSelectField,
|
||||
RhfTimeField,
|
||||
} from "@/shared/components/form"
|
||||
import { toast } from "sonner"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -40,8 +41,8 @@ export type AppointmentFormProps = {
|
||||
const DEFAULT_VALUES: AppointmentFormValues = {
|
||||
title: "",
|
||||
date: "",
|
||||
from_time: "",
|
||||
to_time: "",
|
||||
from_time: "00:00:00",
|
||||
to_time: "00:00:00",
|
||||
customer: null,
|
||||
vehicle: null,
|
||||
service_writer: null,
|
||||
@@ -157,8 +158,8 @@ export function AppointmentForm({ resourceId, initialData, onSuccess }: Appointm
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<RhfTextField name="from_time" label="From Time" placeholder="HH:MM" type="time" />
|
||||
<RhfTextField name="to_time" label="To Time" placeholder="HH:MM" type="time" />
|
||||
<RhfTimeField name="from_time" label="From Time" placeholder="HH:MM" />
|
||||
<RhfTimeField name="to_time" label="To Time" placeholder="HH:MM" />
|
||||
</div>
|
||||
</FieldGroup>
|
||||
|
||||
|
||||
@@ -1,31 +1,39 @@
|
||||
import { z } from "zod"
|
||||
import { AppointmentStatus } from "@garage/api"
|
||||
|
||||
const relationFieldSchema = z
|
||||
.object({ value: z.string(), label: z.string() })
|
||||
.nullable()
|
||||
|
||||
const APPOINTMENT_STATUS_OPTIONS = [
|
||||
{ value: "requested", label: "Requested" },
|
||||
{ value: "confirmed", label: "Confirmed" },
|
||||
{ value: "in_progress", label: "In Progress" },
|
||||
{ value: "completed", label: "Completed" },
|
||||
{ value: "cancelled", label: "Cancelled" },
|
||||
]
|
||||
const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
|
||||
value: v,
|
||||
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
}))
|
||||
|
||||
const appointmentFormSchema = z.object({
|
||||
title: z.string().min(1, "Title is required"),
|
||||
const appointmentFormSchema = z
|
||||
.object({
|
||||
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
|
||||
date: z.string().min(1, "Date is required"),
|
||||
from_time: z.string().min(1, "Start time is required"),
|
||||
to_time: z.string().min(1, "End time is required"),
|
||||
customer: relationFieldSchema,
|
||||
vehicle: relationFieldSchema,
|
||||
service_writer: relationFieldSchema,
|
||||
service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
|
||||
technician: relationFieldSchema,
|
||||
department: relationFieldSchema,
|
||||
job_card: relationFieldSchema,
|
||||
notes: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
})
|
||||
})
|
||||
.superRefine((val, ctx) => {
|
||||
if (val.from_time && val.to_time && val.to_time <= val.from_time) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["to_time"],
|
||||
message: "End time must be after start time",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { z } from "zod"
|
||||
|
||||
const loginFormSchema = z.object({
|
||||
email: z.string().trim().email("Enter a valid email address"),
|
||||
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||
password: z.string().min(6, "Password must be at least 6 characters"),
|
||||
})
|
||||
|
||||
type LoginFormValues = z.infer<typeof loginFormSchema>
|
||||
|
||||
@@ -55,7 +55,7 @@ export function LoginForm({
|
||||
|
||||
const { mutate, error, isPending: isSubmitting } = useMutation({
|
||||
mutationFn: (values: LoginFormValues) => api.auth.login(values),
|
||||
onSuccess: async (data) => {
|
||||
onSuccess: async (data:any) => {
|
||||
if (data.token && data.user) {
|
||||
await login(data.token, data.user as Parameters<typeof login>[1])
|
||||
router.push("/")
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { Ellipsis, Pencil, Trash2, Share2 } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||
import { BillForm } from "./bill-form"
|
||||
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"
|
||||
|
||||
type BillActionsProps = {
|
||||
billId: string
|
||||
}
|
||||
|
||||
export function BillActions({ billId }: BillActionsProps) {
|
||||
const api = useAuthApi()
|
||||
const router = useRouter()
|
||||
const editDialog = useFormDialog("bill-details-edit")
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
|
||||
const handleDelete = async () => {
|
||||
await api.bills.destroy(billId)
|
||||
router.push("/purchase/bill")
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => editDialog.open(billId)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShareOpen(true)}>
|
||||
<Share2 className="size-4" />
|
||||
Share
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<ShareDocumentDialog type="bill" id={billId} open={shareOpen} onOpenChange={setShareOpen} />
|
||||
|
||||
<Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
|
||||
<DialogContent className="min-w-xl lg:min-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">Edit Bill</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<BillForm
|
||||
resourceId={editDialog.resourceId}
|
||||
onSuccess={() => {
|
||||
editDialog.close()
|
||||
router.refresh()
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext } from "react"
|
||||
|
||||
export type BillVendor = {
|
||||
id?: number | null
|
||||
first_name?: string | null
|
||||
last_name?: string | null
|
||||
company_name?: string | null
|
||||
name?: string | null
|
||||
}
|
||||
|
||||
export type BillResponse = {
|
||||
id?: number | null
|
||||
title?: string | null
|
||||
job_card_id?: number | null
|
||||
vendor_id?: number | null
|
||||
vendor_address_id?: number | null
|
||||
purchase_order_id?: number | null
|
||||
bill_number?: string | null
|
||||
bill_date?: string | null
|
||||
bill_due_date?: string | null
|
||||
payment_terms_id?: number | null
|
||||
department_id?: number | null
|
||||
notes?: string | null
|
||||
status?: string | null
|
||||
discount_type?: string | null
|
||||
tax_id?: number | null
|
||||
sub_total?: number | null
|
||||
tax_amount?: number | null
|
||||
total?: number | null
|
||||
payments_made?: number | null
|
||||
balance_due?: number | null
|
||||
discount_amount_major?: number | null
|
||||
created_at?: string | null
|
||||
updated_at?: string | null
|
||||
vendor?: BillVendor | null
|
||||
vendor_address?: {
|
||||
id?: number | null
|
||||
address?: string | null
|
||||
country?: { id?: number; name?: string } | null
|
||||
state?: { id?: number; name?: string } | null
|
||||
} | null
|
||||
department?: { id?: number | null; name?: string | null } | null
|
||||
job_card?: { id?: number | null; order_number?: string | null; estimate_number?: string | null } | null
|
||||
purchase_order?: { id?: number | null; order_number?: string | null } | null
|
||||
tax?: { id?: number | null; name?: string | null; rate?: string | null } | null
|
||||
payment_terms?: { id?: number | null; name?: string | null } | null
|
||||
labels?: { id?: number; title?: string; color_code?: string }[]
|
||||
parts?: any[]
|
||||
services?: any[]
|
||||
expenses?: any[]
|
||||
}
|
||||
|
||||
type BillContextValue = BillResponse
|
||||
|
||||
const BillContext = createContext<BillContextValue | null>(null)
|
||||
|
||||
export function BillProvider({
|
||||
bill,
|
||||
children,
|
||||
}: {
|
||||
bill: BillContextValue
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<BillContext.Provider value={bill}>
|
||||
{children}
|
||||
</BillContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useBill() {
|
||||
return useContext(BillContext)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client"
|
||||
|
||||
import { Receipt } from "lucide-react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
|
||||
import { formatNumber } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
|
||||
type BillExpense = {
|
||||
id: number
|
||||
bill_id: number
|
||||
expense_id: number
|
||||
quantity: string | number
|
||||
rate: string | number
|
||||
description?: string
|
||||
expense?: { id?: number; title?: string; invoice_number?: string }
|
||||
}
|
||||
|
||||
type BillExpensesSectionProps = {
|
||||
expenses?: BillExpense[]
|
||||
}
|
||||
|
||||
export function BillExpensesSection({ expenses = [] }: BillExpensesSectionProps) {
|
||||
if (!expenses || expenses.length === 0) return null
|
||||
|
||||
const subtotal = expenses.reduce((sum, expense) => {
|
||||
const qty = parseFloat(String(expense.quantity))
|
||||
const rate = parseFloat(String(expense.rate))
|
||||
return sum + (qty * rate)
|
||||
}, 0)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Receipt className="size-4" />
|
||||
Expenses
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Expense</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead className="text-right">Quantity</TableHead>
|
||||
<TableHead className="text-right">Rate</TableHead>
|
||||
<TableHead className="text-right">Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{expenses.map((expense) => {
|
||||
const qty = parseFloat(String(expense.quantity))
|
||||
const rate = parseFloat(String(expense.rate))
|
||||
const amount = qty * rate
|
||||
return (
|
||||
<TableRow key={expense.id}>
|
||||
<TableCell className="font-medium">
|
||||
{expense.expense?.title || `Expense #${expense.expense_id}`}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-xs truncate text-muted-foreground">
|
||||
{expense.description || "—"}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{formatNumber(qty)}</TableCell>
|
||||
<TableCell className="text-right">{<Money value={rate} />}</TableCell>
|
||||
<TableCell className="text-right font-medium">{<Money value={amount} />}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<TableRow className="bg-muted/50 font-medium">
|
||||
<TableCell colSpan={4} className="text-right">Subtotal</TableCell>
|
||||
<TableCell className="text-right">{<Money value={subtotal} />}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client"
|
||||
|
||||
import { useFormContext } from "react-hook-form"
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import {
|
||||
useDocumentTotals,
|
||||
type DocumentLineItem,
|
||||
} from "@/shared/hooks/use-document-totals"
|
||||
import { DocumentTotalsSummary } from "@/shared/components/document-totals-summary"
|
||||
|
||||
import type { BillFormValues } from "./bill.schema"
|
||||
|
||||
function parseTaxRateFromLabel(label: string | undefined | null): number | undefined {
|
||||
if (!label) return undefined
|
||||
const match = label.match(/\((\d+(?:\.\d+)?)%\)/)
|
||||
return match ? Number(match[1]) : undefined
|
||||
}
|
||||
|
||||
export function BillFormSummary() {
|
||||
const { watch } = useFormContext<BillFormValues>()
|
||||
|
||||
const partItems = watch("part_items") ?? []
|
||||
const serviceItems = watch("service_items") ?? []
|
||||
const expenseItems = watch("expense_items") ?? []
|
||||
const discountType = watch("discount")
|
||||
const discountAmount = watch("discount_amount")
|
||||
const taxRelation = watch("tax")
|
||||
|
||||
const taxRate = parseTaxRateFromLabel(taxRelation?.label)
|
||||
const taxLabel = taxRelation?.label ?? "Tax"
|
||||
|
||||
const lineItems: DocumentLineItem[] = [
|
||||
...partItems.map((p) => ({
|
||||
quantity: p.quantity,
|
||||
rate: p.rate,
|
||||
discount_amount: p.discount_amount,
|
||||
})),
|
||||
...serviceItems.map((s) => ({
|
||||
quantity: s.quantity,
|
||||
rate: s.rate,
|
||||
discount_amount: s.discount_amount,
|
||||
})),
|
||||
...expenseItems.map((e) => ({
|
||||
quantity: e.quantity,
|
||||
rate: e.rate,
|
||||
discount_amount: e.discount_amount,
|
||||
})),
|
||||
]
|
||||
|
||||
const groupLabels: Record<string, number> = {}
|
||||
if (partItems.length > 0) {
|
||||
groupLabels[`Parts (${partItems.length})`] = partItems.reduce(
|
||||
(s, p) => s + (Number(p.quantity) || 0) * (Number(p.rate) || 0),
|
||||
0,
|
||||
)
|
||||
}
|
||||
if (serviceItems.length > 0) {
|
||||
groupLabels[`Services (${serviceItems.length})`] = serviceItems.reduce(
|
||||
(s, sv) => s + (Number(sv.quantity) || 0) * (Number(sv.rate) || 0),
|
||||
0,
|
||||
)
|
||||
}
|
||||
if (expenseItems.length > 0) {
|
||||
groupLabels[`Expenses (${expenseItems.length})`] = expenseItems.reduce(
|
||||
(s, e) => s + (Number(e.quantity) || 0) * (Number(e.rate) || 0),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
const totals = useDocumentTotals({
|
||||
lineItems,
|
||||
discountType,
|
||||
discountAmount,
|
||||
taxRate,
|
||||
})
|
||||
|
||||
if (!totals.hasLineItems) return null
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Summary
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DocumentTotalsSummary
|
||||
totals={totals}
|
||||
discountType={discountType}
|
||||
taxLabel={taxLabel}
|
||||
groupLabels={Object.keys(groupLabels).length > 1 ? groupLabels : undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user