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
|
5. Use `useFormMutation()` for submit with automatic validation error mapping
|
||||||
6. Render with `Rhform` + `RhfTextField` / `RhfSelectField` / `RhfAsyncSelectField` etc.
|
6. Render with `Rhform` + `RhfTextField` / `RhfSelectField` / `RhfAsyncSelectField` etc.
|
||||||
7. Include error alert, submit button with loading/edit states
|
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
|
### Step 5: Create Page Component
|
||||||
|
|
||||||
@@ -111,13 +112,44 @@ Create `apps/dashboard/app/(authenticated)/<section>/<feature>/page.tsx`:
|
|||||||
| Form component | `<PascalFeature>Form` | `JobCardForm` |
|
| Form component | `<PascalFeature>Form` | `JobCardForm` |
|
||||||
| Page component | `<PascalFeature>Page` (default export) | `JobCardsPage` |
|
| 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`
|
- Stored in form as `{ value: string, label: string } | null`
|
||||||
- Use `toRelation(id, name)` to convert API data → form value
|
- Use `toRelation(id, name)` to convert API data → form value
|
||||||
- Use `toId(relation)` to convert form value → API payload
|
- Use `toId(relation)` to convert form value → API payload
|
||||||
- Schema uses `relationFieldSchema = z.object({ value: z.string(), label: z.string() }).nullable()`
|
- 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
|
### Async Select Pattern
|
||||||
|
|
||||||
@@ -144,8 +176,24 @@ const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) =
|
|||||||
| `RhfTextareaField` | Multi-line text |
|
| `RhfTextareaField` | Multi-line text |
|
||||||
| `RhfCheckboxField` | Boolean toggles |
|
| `RhfCheckboxField` | Boolean toggles |
|
||||||
| `RhfSelectField` | Static option dropdowns |
|
| `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 |
|
| `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
|
### Imports Cheat Sheet
|
||||||
|
|
||||||
|
|||||||
@@ -37,11 +37,18 @@ import { <RESOURCE>_ROUTES } from "@garage/api"
|
|||||||
|
|
||||||
// ── Constants ──
|
// ── Constants ──
|
||||||
|
|
||||||
// Static select options (if needed):
|
// ALWAYS derive select options from API enums imported from "@garage/api".
|
||||||
// const STATUS_OPTIONS = [
|
// NEVER hardcode enum values inline — they must stay in sync with the backend.
|
||||||
// { value: "active", label: "Active" },
|
//
|
||||||
// { value: "inactive", label: "Inactive" },
|
// 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 ──
|
// ── 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 { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||||
import type { AppointmentsClient } from "@garage/api"
|
import type { AppointmentsClient } from "@garage/api"
|
||||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
|
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { Button } from "@/shared/components/ui/button"
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
|
||||||
const STATUS_COLORS: Record<string, string> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
requested: "bg-yellow-100 text-yellow-800",
|
requested: "bg-yellow-100 text-yellow-800",
|
||||||
@@ -26,6 +26,9 @@ export default function AppointmentsPage() {
|
|||||||
<ResourcePage<AppointmentsClient>
|
<ResourcePage<AppointmentsClient>
|
||||||
pageTitle="Appointments"
|
pageTitle="Appointments"
|
||||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search appointments..."
|
||||||
|
statusFilter={{ statuses: AppointmentStatus }}
|
||||||
getClient={(api) => api.appointments}
|
getClient={(api) => api.appointments}
|
||||||
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
@@ -86,22 +89,14 @@ export default function AppointmentsPage() {
|
|||||||
id: "job_card",
|
id: "job_card",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const jobCardId = (row.original as any).job_card_id
|
const item = row.original as any
|
||||||
if (!jobCardId) return <span className="text-muted-foreground">—</span>
|
const jobCardId = item.job_card_id ?? item.job_card?.id
|
||||||
return (
|
return (
|
||||||
<Button
|
<RelationLink
|
||||||
variant="outline"
|
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
|
||||||
size="sm"
|
icon={ClipboardListIcon}
|
||||||
className="h-7 gap-1.5"
|
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
|
||||||
onClick={(e) => {
|
/>
|
||||||
e.stopPropagation()
|
|
||||||
router.push(`/sales/job-cards/${jobCardId}`)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ClipboardListIcon className="size-3" />
|
|
||||||
#{jobCardId}
|
|
||||||
<ExternalLinkIcon className="size-3" />
|
|
||||||
</Button>
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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>
|
<ResourcePage<InventoryAdjustmentsClient>
|
||||||
pageTitle="Inventory Adjustments"
|
pageTitle="Inventory Adjustments"
|
||||||
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
|
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search adjustments..."
|
||||||
getClient={(api) => api.inventoryAdjustments}
|
getClient={(api) => api.inventoryAdjustments}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Inventory Adjustment">
|
<FormDialog
|
||||||
{(resourceId) => (
|
title="Inventory Adjustment"
|
||||||
|
classNames={{ dialogContent: "lg:min-w-4xl" }}
|
||||||
|
>
|
||||||
|
{(resourceId, { close }) => (
|
||||||
<InventoryAdjustmentForm
|
<InventoryAdjustmentForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
initialData={selectedItem}
|
initialData={selectedItem}
|
||||||
onSuccess={invalidateQuery}
|
onSuccess={() => { invalidateQuery(); close() }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</FormDialog>
|
</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,96 +1,61 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
|
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||||
|
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||||
import { PartForm } from "@/modules/parts/part-form"
|
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 { PARTS_ROUTES } from "@garage/api"
|
||||||
import type { PartsClient } from "@garage/api"
|
import type { PartsClient } from "@garage/api"
|
||||||
|
|
||||||
export default function PartsPage() {
|
export default function PartsPage() {
|
||||||
|
const api = useAuthApi()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<PartsClient>
|
<ResourcePage<PartsClient>
|
||||||
pageTitle="Parts"
|
pageTitle="Parts"
|
||||||
routeKey={PARTS_ROUTES.INDEX}
|
routeKey={PARTS_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search parts..."
|
||||||
getClient={(api) => api.parts}
|
getClient={(api) => api.parts}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Part">
|
<div className="flex items-center gap-2">
|
||||||
{(resourceId) => (
|
<ImportDataButton
|
||||||
<PartForm
|
onImport={(file) => api.parts.importData(file)}
|
||||||
resourceId={resourceId}
|
onSuccess={invalidateQuery}
|
||||||
initialData={selectedItem}
|
entityLabel="Parts"
|
||||||
onSuccess={invalidateQuery}
|
/>
|
||||||
/>
|
<ExportDataButton
|
||||||
)}
|
onExport={(filters) => api.parts.exportData(filters)}
|
||||||
</FormDialog>
|
fileName="parts"
|
||||||
|
/>
|
||||||
|
<FormDialog title="Part">
|
||||||
|
{(resourceId) => (
|
||||||
|
<PartForm
|
||||||
|
resourceId={resourceId}
|
||||||
|
initialData={selectedItem}
|
||||||
|
onSuccess={invalidateQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FormDialog>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
})}
|
})}
|
||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
{
|
partColumns.title,
|
||||||
accessorKey: "title",
|
partColumns.partNumber,
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
partColumns.manufacturer,
|
||||||
cell: ({ row }) => {
|
partColumns.sellingPrice,
|
||||||
const r = row.original as any
|
partColumns.purchasePrice,
|
||||||
return (
|
partColumns.stock,
|
||||||
<div>
|
partColumns.status,
|
||||||
<span className="font-medium">{r.title || "—"}</span>
|
partColumns.createdAt,
|
||||||
{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() : "—"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
actionsColumn(),
|
actionsColumn(),
|
||||||
]}
|
]}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
|
|||||||
<ResourcePage<ServiceGroupsClient>
|
<ResourcePage<ServiceGroupsClient>
|
||||||
pageTitle="Service Groups"
|
pageTitle="Service Groups"
|
||||||
routeKey={SERVICE_GROUP_ROUTES.INDEX}
|
routeKey={SERVICE_GROUP_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search service groups..."
|
||||||
getClient={(api) => api.serviceGroups}
|
getClient={(api) => api.serviceGroups}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
|
|||||||
@@ -3,27 +3,45 @@
|
|||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
|
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||||
|
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||||
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
import { ServiceForm } from "@/modules/services/service-form"
|
import { ServiceForm } from "@/modules/services/service-form"
|
||||||
import { SERVICE_ROUTES } from "@garage/api"
|
import { SERVICE_ROUTES } from "@garage/api"
|
||||||
import type { ServicesClient } from "@garage/api"
|
import type { ServicesClient } from "@garage/api"
|
||||||
|
|
||||||
export default function ServicesPage() {
|
export default function ServicesPage() {
|
||||||
|
const api = useAuthApi()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<ServicesClient>
|
<ResourcePage<ServicesClient>
|
||||||
pageTitle="Services"
|
pageTitle="Services"
|
||||||
routeKey={SERVICE_ROUTES.INDEX}
|
routeKey={SERVICE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search services..."
|
||||||
getClient={(api) => api.services}
|
getClient={(api) => api.services}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Service">
|
<div className="flex items-center gap-2">
|
||||||
{(resourceId) => (
|
<ImportDataButton
|
||||||
<ServiceForm
|
onImport={(file) => api.services.importData(file)}
|
||||||
resourceId={resourceId}
|
onSuccess={invalidateQuery}
|
||||||
initialData={selectedItem}
|
entityLabel="Services"
|
||||||
onSuccess={invalidateQuery}
|
/>
|
||||||
/>
|
<ExportDataButton
|
||||||
)}
|
onExport={(filters) => api.services.exportData(filters)}
|
||||||
</FormDialog>
|
fileName="services"
|
||||||
|
/>
|
||||||
|
<FormDialog title="Service">
|
||||||
|
{(resourceId) => (
|
||||||
|
<ServiceForm
|
||||||
|
resourceId={resourceId}
|
||||||
|
initialData={selectedItem}
|
||||||
|
onSuccess={invalidateQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FormDialog>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
})}
|
})}
|
||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
@@ -48,7 +66,7 @@ export default function ServicesPage() {
|
|||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const val = (row.original as any).description
|
const val = (row.original as any).description
|
||||||
return val
|
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 { DashboardHeader } from "@/base/components/layout/dashboard";
|
||||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page";
|
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page";
|
||||||
import { DashboardContent } from "@/modules/home/dashboard-content";
|
import { DashboardContent } from "@/modules/home/dashboard-content";
|
||||||
|
import { DashboardFiltersToolbar } from "@/modules/home/dashboard-filters-toolbar";
|
||||||
|
|
||||||
export default function page() {
|
export default function page() {
|
||||||
return (
|
return (
|
||||||
<DashboardPage headerProps={{title: "Dashboard"}} >
|
<DashboardPage headerProps={{ title: "Dashboard", actions: <DashboardFiltersToolbar /> }} >
|
||||||
<DashboardContent />
|
<DashboardContent />
|
||||||
</DashboardPage>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export default async function layout(props: {
|
|||||||
<DashboardDetailsPage
|
<DashboardDetailsPage
|
||||||
className="p-0 lg:p-0"
|
className="p-0 lg:p-0"
|
||||||
title={title}
|
title={title}
|
||||||
description={employee.data?.position || employee.data?.designation || undefined}
|
description={(employee.data as any)?.position || employee.data?.designation || undefined}
|
||||||
backHref="/productivity/employees"
|
backHref="/productivity/employees"
|
||||||
actions={<EmployeeActions employeeId={id} />}
|
actions={<EmployeeActions employeeId={id} />}
|
||||||
tabs={[
|
tabs={[
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ export default function EmployeesPage() {
|
|||||||
<ResourcePage<EmployeesClient>
|
<ResourcePage<EmployeesClient>
|
||||||
pageTitle="Employees"
|
pageTitle="Employees"
|
||||||
routeKey={EMPLOYEE_ROUTES.INDEX}
|
routeKey={EMPLOYEE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search employees..."
|
||||||
|
statusFilter={{ statuses: ["active", "inactive"] }}
|
||||||
getClient={(api) => api.employees}
|
getClient={(api) => api.employees}
|
||||||
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/productivity/employees/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
|
|||||||
<ResourcePage<HolidayYearsClient>
|
<ResourcePage<HolidayYearsClient>
|
||||||
pageTitle="Holiday Years"
|
pageTitle="Holiday Years"
|
||||||
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
|
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search holidays..."
|
||||||
getClient={(api) => api.holidayYears}
|
getClient={(api) => api.holidayYears}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
|
|||||||
<ResourcePage<ShopCalendarsClient>
|
<ResourcePage<ShopCalendarsClient>
|
||||||
pageTitle="Shop Calendars"
|
pageTitle="Shop Calendars"
|
||||||
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
|
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search shop calendars..."
|
||||||
getClient={(api) => api.shopCalendars}
|
getClient={(api) => api.shopCalendars}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
|
|||||||
<ResourcePage<ShopTimingsClient>
|
<ResourcePage<ShopTimingsClient>
|
||||||
pageTitle="Shop Timings"
|
pageTitle="Shop Timings"
|
||||||
routeKey={SHOP_TIMING_ROUTES.INDEX}
|
routeKey={SHOP_TIMING_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search shop timings..."
|
||||||
getClient={(api) => api.shopTimings}
|
getClient={(api) => api.shopTimings}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
|
|||||||
@@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
|||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { TaskForm } from "@/modules/tasks/task-form"
|
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 type { TasksClient } from "@garage/api"
|
||||||
|
|
||||||
export default function TasksPage() {
|
export default function TasksPage() {
|
||||||
return (
|
return (
|
||||||
<ResourcePage<TasksClient>
|
<ResourcePage<TasksClient>
|
||||||
routeKey={TASK_ROUTES.INDEX}
|
routeKey={TASK_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search tasks..."
|
||||||
|
statusFilter={{ statuses: TaskStatus }}
|
||||||
getClient={(api) => api.tasks}
|
getClient={(api) => api.tasks}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
title: "Tasks",
|
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"
|
"use client"
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import { BillForm } from "@/modules/bills/bill-form"
|
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 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() {
|
export default function BillsPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<BillsClient>
|
<ResourcePage<BillsClient>
|
||||||
pageTitle="Bills"
|
pageTitle="Bills"
|
||||||
routeKey={BILL_ROUTES.INDEX}
|
routeKey={BILL_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search bills..."
|
||||||
|
statusFilter={{ statuses: BillStatus }}
|
||||||
getClient={(api) => api.bills}
|
getClient={(api) => api.bills}
|
||||||
|
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Bill">
|
<FormDialog classNames={{ dialogContent: "lg:min-w-6xl" }} title="Bill">
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<BillForm
|
<BillForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
@@ -33,37 +45,60 @@ export default function BillsPage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
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",
|
accessorKey: "title",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="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",
|
accessorKey: "bill_date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Bill Date" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Bill Date" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => formatDate((row.original as any).bill_date) || "—",
|
||||||
const value = (row.original as any).bill_date
|
|
||||||
return value ? new Date(value).toLocaleDateString() : "—"
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "bill_due_date",
|
accessorKey: "bill_due_date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => formatDate((row.original as any).bill_due_date) || "—",
|
||||||
const value = (row.original as any).bill_due_date
|
|
||||||
return value ? new Date(value).toLocaleDateString() : "—"
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "status",
|
accessorKey: "status",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const status = (row.original as any).status
|
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(),
|
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 FormDialog from "@/shared/components/form-dialog"
|
||||||
import { ExpenseForm } from "@/modules/expenses/expense-form"
|
import { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
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 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() {
|
export default function ExpensesPage() {
|
||||||
|
const router = useRouter()
|
||||||
return (
|
return (
|
||||||
<ResourcePage<ExpensesClient>
|
<ResourcePage<ExpensesClient>
|
||||||
pageTitle="Expenses"
|
pageTitle="Expenses"
|
||||||
routeKey={EXPENSE_ROUTES.INDEX}
|
routeKey={EXPENSE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search expenses..."
|
||||||
|
statusFilter={{ statuses: ExpenseStatus }}
|
||||||
getClient={(api) => api.expenses}
|
getClient={(api) => api.expenses}
|
||||||
|
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Expense">
|
<FormDialog
|
||||||
|
title="Expense"
|
||||||
|
classNames={{ dialogContent: "lg:min-w-6xl" }}
|
||||||
|
>
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<ExpenseForm
|
<ExpenseForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
@@ -38,38 +52,53 @@ export default function ExpensesPage() {
|
|||||||
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
header: () => "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) || vendor?.name}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "expense_date",
|
accessorKey: "expense_date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => formatDate((row.original as any).expense_date),
|
||||||
const val = (row.original as any).expense_date
|
},
|
||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
{
|
||||||
},
|
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",
|
accessorKey: "status",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const status = (row.original as any).status
|
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 (
|
return (
|
||||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
<Badge variant={variantMap[status] ?? "outline"}>
|
||||||
{status || "—"}
|
{formatEnum(status) || "—"}
|
||||||
</Badge>
|
</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(),
|
actionsColumn(),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -32,8 +32,11 @@ import {
|
|||||||
} from "@/shared/components/ui/dialog"
|
} from "@/shared/components/ui/dialog"
|
||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
import { confirm } from "@/shared/components/confirm-dialog"
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
import { PAYMENT_MADE_ROUTES } from "@garage/api"
|
import { PAYMENT_MADE_ROUTES } from "@garage/api"
|
||||||
import type { PaymentMadesClient } from "@garage/api"
|
import type { PaymentMadesClient } from "@garage/api"
|
||||||
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
import { Building2 } from "lucide-react"
|
||||||
|
|
||||||
// ── Attachment helpers ──
|
// ── Attachment helpers ──
|
||||||
|
|
||||||
@@ -208,10 +211,13 @@ function AttachmentsDialog({
|
|||||||
type PaymentMadeItem = {
|
type PaymentMadeItem = {
|
||||||
id: number
|
id: number
|
||||||
payment_number?: string
|
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
|
vendor_name?: string
|
||||||
|
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||||
employee_name?: string
|
employee_name?: string
|
||||||
payment_for?: string
|
payment_for?: string
|
||||||
payment_made?: string | number
|
payment_made?: string | number
|
||||||
|
payment_mode?: { name?: string | null; title?: string | null } | null
|
||||||
payment_mode_name?: string
|
payment_mode_name?: string
|
||||||
payment_date?: string
|
payment_date?: string
|
||||||
paid_through?: string
|
paid_through?: string
|
||||||
@@ -230,14 +236,20 @@ export default function PaymentsMadePage() {
|
|||||||
<ResourcePage<PaymentMadesClient>
|
<ResourcePage<PaymentMadesClient>
|
||||||
pageTitle="Payments Made"
|
pageTitle="Payments Made"
|
||||||
routeKey={PAYMENT_MADE_ROUTES.INDEX}
|
routeKey={PAYMENT_MADE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search payments..."
|
||||||
getClient={(api) => api.paymentMades}
|
getClient={(api) => api.paymentMades}
|
||||||
headerProps={({ invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Record Payment">
|
<FormDialog title="Record Payment">
|
||||||
{(resourceId) => (
|
{(resourceId, { close }) => (
|
||||||
<PaymentMadeForm
|
<PaymentMadeForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
onSuccess={invalidateQuery}
|
initialData={selectedItem}
|
||||||
|
onSuccess={() => {
|
||||||
|
invalidateQuery()
|
||||||
|
close()
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</FormDialog>
|
</FormDialog>
|
||||||
@@ -262,11 +274,27 @@ export default function PaymentsMadePage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as PaymentMadeItem
|
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 (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<RelationLink
|
||||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
href={href}
|
||||||
<span>{item.vendor_name || "—"}</span>
|
icon={isVendor ? Building2 : UserIcon}
|
||||||
</div>
|
label={label}
|
||||||
|
/>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -309,10 +337,15 @@ export default function PaymentsMadePage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as PaymentMadeItem
|
const item = row.original as unknown as PaymentMadeItem
|
||||||
|
const label =
|
||||||
|
item.payment_mode?.name ||
|
||||||
|
item.payment_mode?.title ||
|
||||||
|
item.payment_mode_name ||
|
||||||
|
"—"
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
<span className="capitalize">{label}</span>
|
||||||
</div>
|
</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"
|
"use client"
|
||||||
|
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
|
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
|
||||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||||
import type { PurchaseOrdersClient } 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() {
|
export default function PurchaseOrdersPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<PurchaseOrdersClient>
|
<ResourcePage<PurchaseOrdersClient>
|
||||||
pageTitle="Purchase Orders"
|
pageTitle="Purchase Orders"
|
||||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search purchase orders..."
|
||||||
getClient={(api) => api.purchaseOrders}
|
getClient={(api) => api.purchaseOrders}
|
||||||
|
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Purchase Order">
|
<FormDialog classNames={{ dialogContent: "min-w-6xl" }} title="Purchase Order">
|
||||||
{(resourceId) => (
|
{(resourceId, { close }) => (
|
||||||
<PurchaseOrderForm
|
<PurchaseOrderForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
initialData={selectedItem}
|
initialData={selectedItem}
|
||||||
onSuccess={invalidateQuery}
|
onSuccess={() => { invalidateQuery(); close()}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</FormDialog>
|
</FormDialog>
|
||||||
@@ -39,7 +48,16 @@ export default function PurchaseOrdersPage() {
|
|||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
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",
|
accessorKey: "order_date",
|
||||||
|
|||||||
@@ -5,14 +5,20 @@ import { Badge } from "@/shared/components/ui/badge"
|
|||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
|
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 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() {
|
export default function VendorCreditsPage() {
|
||||||
return (
|
return (
|
||||||
<ResourcePage<VendorCreditsClient>
|
<ResourcePage<VendorCreditsClient>
|
||||||
pageTitle="Vendor Credits"
|
pageTitle="Vendor Credits"
|
||||||
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
|
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search vendor credits..."
|
||||||
|
statusFilter={{ statuses: VendorCreditStatus }}
|
||||||
getClient={(api) => api.vendorCredits}
|
getClient={(api) => api.vendorCredits}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
@@ -35,12 +41,30 @@ export default function VendorCreditsPage() {
|
|||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
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",
|
accessorKey: "bill_number",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
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",
|
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"
|
"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 { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { VendorForm } from "@/modules/vendors/vendor-form"
|
import { VendorForm } from "@/modules/vendors/vendor-form"
|
||||||
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
import { VENDOR_ROUTES } from "@garage/api"
|
import { VENDOR_ROUTES } from "@garage/api"
|
||||||
import type { VendorsClient } from "@garage/api"
|
import type { VendorsClient } from "@garage/api"
|
||||||
|
|
||||||
export default function VendorsPage() {
|
export default function VendorsPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const api = useAuthApi()
|
||||||
return (
|
return (
|
||||||
<ResourcePage<VendorsClient>
|
<ResourcePage<VendorsClient>
|
||||||
pageTitle="Vendors"
|
pageTitle="Vendors"
|
||||||
routeKey={VENDOR_ROUTES.INDEX}
|
routeKey={VENDOR_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search vendors..."
|
||||||
getClient={(api) => api.vendors}
|
getClient={(api) => api.vendors}
|
||||||
|
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Vendor">
|
<FormDialog title="Vendor">
|
||||||
@@ -46,6 +56,18 @@ export default function VendorsPage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
|
||||||
cell: ({ row }) => (row.original as any).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",
|
accessorKey: "created_at",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||||
@@ -54,7 +76,26 @@ export default function VendorsPage() {
|
|||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
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 (
|
return (
|
||||||
<DashboardPage
|
<DashboardPage
|
||||||
header={null}
|
headerProps={{
|
||||||
title="Notes"
|
title: "Notes",
|
||||||
toolbar={
|
actions: (
|
||||||
<Button size="sm" onClick={() => setDialogOpen(true)}>
|
<Button size="sm" onClick={() => setDialogOpen(true)}>
|
||||||
<Plus className="size-4" />
|
<Plus className="size-4" />
|
||||||
Add Note
|
Add Note
|
||||||
</Button>
|
</Button>
|
||||||
}
|
),
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<DataTable
|
<DataTable
|
||||||
columns={columns}
|
columns={columns}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<VehiclesClient>
|
<ResourcePage<VehiclesClient>
|
||||||
toolbar={({ invalidateQuery, selectedItem, closeDialog }) => (
|
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||||
<FormDialog title="Vehicle">
|
<FormDialog title="Vehicle">
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<VehicleForm
|
<VehicleForm
|
||||||
@@ -32,6 +32,8 @@ export default function CustomerVehiclesPage({ params }: { params: Promise<{ id:
|
|||||||
)}
|
)}
|
||||||
pageTitle="Customer Vehicles"
|
pageTitle="Customer Vehicles"
|
||||||
routeKey={VEHICLE_ROUTES.INDEX}
|
routeKey={VEHICLE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search vehicles..."
|
||||||
getClient={(api) => api.vehicles}
|
getClient={(api) => api.vehicles}
|
||||||
extraParams={{ customer_id: customerId }}
|
extraParams={{ customer_id: customerId }}
|
||||||
header={null}
|
header={null}
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import { useRouter } from 'next/navigation'
|
|||||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||||
import FormDialog from '@/shared/components/form-dialog'
|
import FormDialog from '@/shared/components/form-dialog'
|
||||||
|
import { 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 { CustomerForm } from '@/modules/customers/customer-form'
|
||||||
import { CUSTOMER_ROUTES } from '@garage/api'
|
import { CUSTOMER_ROUTES } from '@garage/api'
|
||||||
import type { CustomersClient } from '@garage/api'
|
import type { CustomersClient } from '@garage/api'
|
||||||
@@ -11,23 +14,39 @@ import { Building2Icon, UserIcon } from 'lucide-react'
|
|||||||
|
|
||||||
export default function CustomersPage() {
|
export default function CustomersPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const api = useAuthApi()
|
||||||
return (
|
return (
|
||||||
<ResourcePage<CustomersClient>
|
<ResourcePage<CustomersClient>
|
||||||
pageTitle='Customers'
|
pageTitle='Customers'
|
||||||
routeKey={CUSTOMER_ROUTES.INDEX}
|
routeKey={CUSTOMER_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search customers..."
|
||||||
getClient={(api) => api.customers}
|
getClient={(api) => api.customers}
|
||||||
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Customer">
|
<div className='flex items-center gap-2'>
|
||||||
{(resourceId) => (
|
<ImportDataButton
|
||||||
<CustomerForm
|
onImport={(file) => api.customers.importData(file)}
|
||||||
resourceId={resourceId}
|
onSuccess={invalidateQuery}
|
||||||
initialData={selectedItem}
|
entityLabel="Customers"
|
||||||
onSuccess={invalidateQuery}
|
onDownloadSample={() => api.customers.downloadImportSample()}
|
||||||
/>
|
sampleFileName='customers-import-sample'
|
||||||
)}
|
/>
|
||||||
</FormDialog>
|
<ExportDataButton
|
||||||
|
onExport={(filters) => api.customers.exportData(filters)}
|
||||||
|
fileName='customers'
|
||||||
|
/>
|
||||||
|
<FormDialog title="Customer">
|
||||||
|
{(resourceId) => (
|
||||||
|
<CustomerForm
|
||||||
|
resourceId={resourceId}
|
||||||
|
initialData={selectedItem}
|
||||||
|
onSuccess={invalidateQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FormDialog>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
})}
|
})}
|
||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
@@ -37,7 +56,7 @@ export default function CustomersPage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const customerName = row.original.first_name
|
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 companyName = row.original.company_name
|
||||||
const name = isCompany && companyName ? `${customerName} (${row.original.last_name})` : customerName
|
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 { getServerApi } from '@garage/api/server'
|
||||||
import { EstimateActions } from '@/modules/estimates/estimate-actions'
|
import { EstimateActions } from '@/modules/estimates/estimate-actions'
|
||||||
import { EstimateProvider } from '@/modules/estimates/estimate-context'
|
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 { FileTextIcon } from 'lucide-react'
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
import { formatDate } from '@/shared/utils/formatters'
|
||||||
|
|
||||||
export default async function layout(props: {
|
export default async function layout(props: {
|
||||||
params: Promise<{ id: string }>
|
params: Promise<{ id: string }>
|
||||||
@@ -11,25 +15,36 @@ export default async function layout(props: {
|
|||||||
}) {
|
}) {
|
||||||
const { id } = await props.params
|
const { id } = await props.params
|
||||||
const api = await getServerApi()
|
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 title = estimateData?.title || estimateData?.estimate_number || `Estimate #${id}`
|
||||||
const estimateLabel = estimateData?.estimate_number
|
const estimateLabel = estimateData?.estimate_number
|
||||||
? `${estimateData.estimate_number}${estimateData.title ? ` — ${estimateData.title}` : ''}`
|
? `${estimateData.estimate_number}${estimateData.title ? ` — ${estimateData.title}` : ''}`
|
||||||
: title
|
: title
|
||||||
|
|
||||||
|
if (!estimateData) {
|
||||||
|
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<EstimateProvider estimate={{ id, label: estimateLabel }}>
|
<EstimateProvider estimate={estimateData}>
|
||||||
<DashboardDetailsPage
|
<DashboardDetailsPage
|
||||||
className="p-0 lg:p-0"
|
className="p-0 lg:p-0"
|
||||||
icon={<FileTextIcon className="size-5" />}
|
icon={<FileTextIcon className="size-5" />}
|
||||||
title={title}
|
title={title}
|
||||||
description={
|
description={
|
||||||
estimateData?.date ? `Date: ${estimateData.date}` : undefined
|
estimateData?.date ? `Date: ${formatDate(estimateData.date)}` : undefined
|
||||||
}
|
}
|
||||||
backHref="/sales/estimates"
|
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={[
|
tabs={[
|
||||||
{ href: `/sales/estimates/${id}`, label: 'Details' },
|
{ href: `/sales/estimates/${id}`, label: 'Details' },
|
||||||
]}
|
]}
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import { getServerApi } from '@garage/api/server'
|
import { getServerApi } from '@garage/api/server'
|
||||||
import { EstimateGeneralInfo } from '@/modules/estimates/estimate-general-info'
|
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'
|
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||||
|
|
||||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||||
const { id } = await props.params
|
const { id } = await props.params
|
||||||
const api = await getServerApi()
|
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) {
|
if (!estimateData) {
|
||||||
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
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 (
|
return (
|
||||||
<DashboardPage header={null}>
|
<DashboardPage header={null}>
|
||||||
<EstimateGeneralInfo estimate={estimateData} />
|
<div className="grid gap-6">
|
||||||
|
<EstimateGeneralInfo estimate={estimateData} />
|
||||||
|
<EstimateServicesSection estimateId={id} />
|
||||||
|
<EstimatePartsSection estimateId={id} />
|
||||||
|
<EstimateExpenseItemsSection estimateId={id} />
|
||||||
|
<EstimateTotalsSummary />
|
||||||
|
</div>
|
||||||
</DashboardPage>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,29 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||||
import FormDialog from '@/shared/components/form-dialog'
|
import FormDialog from '@/shared/components/form-dialog'
|
||||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||||
import type { EstimatesClient } from '@garage/api'
|
import type { EstimatesClient } from '@garage/api'
|
||||||
import { Car, FileTextIcon } from 'lucide-react'
|
import { Car, FileTextIcon, UserIcon } from 'lucide-react'
|
||||||
import { Button } from '@/shared/components/ui/button'
|
|
||||||
import Link from 'next/link'
|
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() {
|
export default function EstimatesPage() {
|
||||||
|
const router = useRouter()
|
||||||
return (
|
return (
|
||||||
<ResourcePage<EstimatesClient>
|
<ResourcePage<EstimatesClient>
|
||||||
pageTitle="Estimates"
|
pageTitle="Estimates"
|
||||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search estimates..."
|
||||||
getClient={(api) => api.estimates}
|
getClient={(api) => api.estimates}
|
||||||
|
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Estimate">
|
<FormDialog title="Estimate">
|
||||||
@@ -36,7 +44,7 @@ export default function EstimatesPage() {
|
|||||||
const item = row.original
|
const item = row.original
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<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" />
|
<FileTextIcon className="text-muted-foreground h-4 w-4" />
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
</Link>
|
</Link>
|
||||||
@@ -51,22 +59,39 @@ export default function EstimatesPage() {
|
|||||||
{
|
{
|
||||||
accessorKey: "customer_name",
|
accessorKey: "customer_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
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" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original
|
const item: any = row.original
|
||||||
return <Button variant="outline" asChild size="sm">
|
return (
|
||||||
<Link href={`/sales/vehicles/${item.vehicle_id}`}>
|
<RelationLink
|
||||||
<Car/> Go to vehicle
|
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
|
||||||
</Link>
|
icon={Car}
|
||||||
</Button>
|
label={getVehicleLabel(item.vehicle as any)}
|
||||||
}
|
meta={item.vehicle?.license_plate}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "date",
|
accessorKey: "date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const item = row.original
|
||||||
|
return formatDate(item.date)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "has_insurance",
|
accessorKey: "has_insurance",
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
|||||||
import { getServerApi } from '@garage/api/server'
|
import { getServerApi } from '@garage/api/server'
|
||||||
import { InspectionActions } from '@/modules/inspections/inspection-actions'
|
import { InspectionActions } from '@/modules/inspections/inspection-actions'
|
||||||
import { InspectionProvider } from '@/modules/inspections/inspection-context'
|
import { InspectionProvider } from '@/modules/inspections/inspection-context'
|
||||||
|
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
export default async function layout(props: {
|
export default async function layout(props: {
|
||||||
@@ -23,7 +24,12 @@ export default async function layout(props: {
|
|||||||
title={title}
|
title={title}
|
||||||
description={orderNumber ? `Order: ${orderNumber}` : undefined}
|
description={orderNumber ? `Order: ${orderNumber}` : undefined}
|
||||||
backHref="/sales/inspections"
|
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={[
|
tabs={[
|
||||||
{
|
{
|
||||||
href: `/sales/inspections/${id}`,
|
href: `/sales/inspections/${id}`,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { getServerApi } from '@garage/api/server'
|
import { getServerApi } from '@garage/api/server'
|
||||||
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
|
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'
|
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||||
|
|
||||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
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>
|
return <div className="text-muted-foreground">Inspection not found.</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const data = inspection.data as { title?: string }
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardPage header={null}>
|
<DashboardPage header={null}>
|
||||||
|
<InspectionDetailHeader inspectionId={id} title={data.title} />
|
||||||
<InspectionGeneralInfo inspection={inspection.data} />
|
<InspectionGeneralInfo inspection={inspection.data} />
|
||||||
</DashboardPage>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,46 +1,125 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
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 type { InspectionsClient } from "@garage/api"
|
||||||
|
import Link from "next/link"
|
||||||
|
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
|
||||||
import { useRouter } from "next/navigation"
|
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() {
|
export default function InspectionsPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<InspectionsClient>
|
<ResourcePage<InspectionsClient>
|
||||||
pageTitle="Inspections"
|
pageTitle="Inspections"
|
||||||
routeKey={INSPECTION_ROUTES.INDEX}
|
routeKey={INSPECTION_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search inspections..."
|
||||||
|
statusFilter={{ statuses: InspectionStatus }}
|
||||||
getClient={(api) => api.inspections}
|
getClient={(api) => api.inspections}
|
||||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Inspection">
|
<div className="flex items-center gap-2">
|
||||||
{(resourceId) => (
|
<Button variant="outline" size="sm" asChild>
|
||||||
<InspectionForm
|
<Link href="/settings/inspection-templates">
|
||||||
resourceId={resourceId}
|
<ListChecks className="size-4" />
|
||||||
initialData={selectedItem}
|
Manage templates
|
||||||
onSuccess={invalidateQuery}
|
</Link>
|
||||||
/>
|
</Button>
|
||||||
)}
|
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
|
||||||
</FormDialog>
|
<ClipboardList className="size-4" />
|
||||||
|
New from template
|
||||||
|
</Button>
|
||||||
|
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
|
||||||
|
{(resourceId) => (
|
||||||
|
<InspectionForm
|
||||||
|
resourceId={resourceId}
|
||||||
|
initialData={selectedItem}
|
||||||
|
onSuccess={invalidateQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</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",
|
accessorKey: "title",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="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",
|
accessorKey: "customer",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const c = (row.original as any).customer
|
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" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const v = (row.original as any).vehicle
|
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",
|
accessorKey: "inspection_category",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="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",
|
accessorKey: "status",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||||
cell: ({ row }) => {
|
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 (
|
return (
|
||||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
|
||||||
{status ?? "—"}
|
{STATUS_LABEL[status] ?? status}
|
||||||
</span>
|
</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 { InvoiceProvider } from '@/modules/invoices/invoice-context'
|
||||||
import { ReceiptIcon } from 'lucide-react'
|
import { ReceiptIcon } from 'lucide-react'
|
||||||
import React from '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 }) {
|
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||||
const { id } = await props.params
|
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'
|
const title = data?.subject || data?.invoice_number || 'Invoice Details'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<InvoiceProvider invoice={{ id, label: title }}>
|
<InvoiceProvider invoice={data}>
|
||||||
<DashboardDetailsPage
|
<DashboardDetailsPage
|
||||||
className='p-0 lg:p-0'
|
|
||||||
title={title}
|
title={title}
|
||||||
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
||||||
icon={<ReceiptIcon className="size-5" />}
|
icon={<ReceiptIcon className="size-5" />}
|
||||||
backHref="/sales/invoice"
|
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={[
|
tabs={[
|
||||||
{
|
{
|
||||||
href: `/sales/invoice/${id}`,
|
href: `/sales/invoice/${id}`,
|
||||||
label: 'Details'
|
label: 'Details'
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
href: `/sales/invoice/${id}/documents`,
|
href: `/sales/invoice/${id}/documents`,
|
||||||
label: 'Documents'
|
label: 'Documents'
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import { getServerApi } from '@garage/api/server'
|
import { getServerApi } from '@garage/api/server'
|
||||||
import { InvoiceGeneralInfo } from '@/modules/invoices/invoice-general-info'
|
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 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 }> }) {
|
export default async function InvoiceDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||||
const { id } = await props.params
|
const { id } = await props.params
|
||||||
@@ -14,7 +20,14 @@ export default async function InvoiceDetailPage(props: { params: Promise<{ id: s
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardPage header={null}>
|
<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>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,82 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { Car, UserIcon } from "lucide-react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { InvoiceForm } from "@/modules/invoices/invoice-form"
|
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 type { InvoicesClient } from "@garage/api"
|
||||||
|
import { Money } from "@/shared/components/money"
|
||||||
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
|
||||||
type InvoiceItem = {
|
type InvoiceItem = {
|
||||||
id: number
|
id: number
|
||||||
subject?: string
|
subject?: string
|
||||||
|
invoice_title?: string
|
||||||
invoice_number?: string
|
invoice_number?: string
|
||||||
customer_name?: string
|
customer_name?: string
|
||||||
status?: string
|
status?: string
|
||||||
invoice_date?: string
|
invoice_date?: string
|
||||||
due_date?: string
|
due_date?: string
|
||||||
created_at?: 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() {
|
export default function InvoicesPage() {
|
||||||
@@ -26,11 +86,14 @@ export default function InvoicesPage() {
|
|||||||
<ResourcePage<InvoicesClient>
|
<ResourcePage<InvoicesClient>
|
||||||
pageTitle="Invoices"
|
pageTitle="Invoices"
|
||||||
routeKey={INVOICE_ROUTES.INDEX}
|
routeKey={INVOICE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search invoices..."
|
||||||
|
statusFilter={{ statuses: InvoiceStatus }}
|
||||||
getClient={(api) => api.invoices}
|
getClient={(api) => api.invoices}
|
||||||
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Invoice">
|
<FormDialog classNames={{dialogContent:'lg:min-w-6xl'}} title="Invoice">
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<InvoiceForm
|
<InvoiceForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
@@ -44,15 +107,64 @@ export default function InvoicesPage() {
|
|||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
{
|
{
|
||||||
accessorKey: "subject",
|
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",
|
accessorKey: "invoice_number",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
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",
|
accessorKey: "customer_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
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",
|
accessorKey: "status",
|
||||||
@@ -60,27 +172,71 @@ export default function InvoicesPage() {
|
|||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as InvoiceItem
|
const item = row.original as unknown as InvoiceItem
|
||||||
const status = item.status
|
const status = item.status
|
||||||
const colorMap: Record<string, string> = {
|
const classMap: Record<string, string> = {
|
||||||
draft: "text-muted-foreground",
|
draft: "bg-slate-100 text-slate-700",
|
||||||
open: "text-blue-600",
|
open: "bg-blue-100 text-blue-700",
|
||||||
paid: "text-green-600",
|
paid: "bg-emerald-100 text-emerald-700",
|
||||||
overdue: "text-red-600",
|
over_due: "bg-red-100 text-red-700",
|
||||||
void: "text-gray-400",
|
un_paid: "bg-orange-100 text-orange-700",
|
||||||
|
partially_paid: "bg-amber-100 text-amber-700",
|
||||||
|
void: "bg-zinc-100 text-zinc-700",
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className={colorMap[status ?? ""] ?? ""}>
|
<Badge variant="outline" className={classMap[status ?? ""] ?? ""}>
|
||||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
{formatEnum(status) || "—"}
|
||||||
</span>
|
</Badge>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "invoice_date",
|
accessorKey: "invoice_date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="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",
|
accessorKey: "due_date",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="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(),
|
actionsColumn(),
|
||||||
]}
|
]}
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useEffect } from "react"
|
||||||
import { use } 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 { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||||
import type { AppointmentsClient } from "@garage/api"
|
import type { AppointmentsClient } from "@garage/api"
|
||||||
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
|
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
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> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
requested: "bg-yellow-100 text-yellow-800",
|
requested: "bg-yellow-100 text-yellow-800",
|
||||||
@@ -27,15 +30,48 @@ export default function JobCardAppointmentsPage({
|
|||||||
}) {
|
}) {
|
||||||
const { id: jobCardId } = use(params)
|
const { id: jobCardId } = use(params)
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const pathname = usePathname()
|
||||||
|
const searchParams = useSearchParams()
|
||||||
const jobCard = useJobCard()
|
const jobCard = useJobCard()
|
||||||
|
|
||||||
const defaultJobCard = jobCard
|
useEffect(() => {
|
||||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
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
|
: 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 (
|
return (
|
||||||
<ResourcePage<AppointmentsClient>
|
<ResourcePage<AppointmentsClient>
|
||||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search appointments..."
|
||||||
|
statusFilter={{ statuses: AppointmentStatus }}
|
||||||
getClient={(api) => api.appointments}
|
getClient={(api) => api.appointments}
|
||||||
extraParams={{ job_card_id: jobCardId }}
|
extraParams={{ job_card_id: jobCardId }}
|
||||||
header={null}
|
header={null}
|
||||||
@@ -46,8 +82,8 @@ export default function JobCardAppointmentsPage({
|
|||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<AppointmentForm
|
<AppointmentForm
|
||||||
resourceId={resourceId}
|
resourceId={resourceId}
|
||||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
initialData={selectedItem ?? appointmentDefaults}
|
||||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</FormDialog>
|
</FormDialog>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useParams } from "next/navigation"
|
import { useParams, useRouter } from "next/navigation"
|
||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
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 { Plus, Trash2, FileIcon, ImageIcon, FileTextIcon } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
|
|||||||
import { confirm } from "@/shared/components/confirm-dialog"
|
import { confirm } from "@/shared/components/confirm-dialog"
|
||||||
import { Button } from "@/shared/components/ui/button"
|
import { Button } from "@/shared/components/ui/button"
|
||||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
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 DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||||
import { CONSTANTS } from "@/config/constants"
|
import { CONSTANTS } from "@/config/constants"
|
||||||
@@ -22,10 +22,68 @@ function getFileIcon(mimeType?: string) {
|
|||||||
return FileIcon
|
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() {
|
export default function JobCardAttachmentsPage() {
|
||||||
const { id: jobCardId } = useParams<{ id: string }>()
|
const { id: jobCardId } = useParams<{ id: string }>()
|
||||||
const api = useAuthApi()
|
const api = useAuthApi()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const router = useRouter()
|
||||||
|
const [isRefreshing, startRefreshTransition] = useTransition()
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
const [isUploading, setIsUploading] = useState(false)
|
const [isUploading, setIsUploading] = useState(false)
|
||||||
|
|
||||||
@@ -41,13 +99,14 @@ export default function JobCardAttachmentsPage() {
|
|||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success("Attachment deleted successfully.")
|
toast.success("Attachment deleted successfully.")
|
||||||
queryClient.invalidateQueries({ queryKey })
|
queryClient.invalidateQueries({ queryKey })
|
||||||
|
startRefreshTransition(() => router.refresh())
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error("Failed to delete attachment.")
|
toast.error("Failed to delete attachment.")
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const handleDelete = async (attachment: JobCardResponseData['attachment_files'][number]) => {
|
const handleDelete = async (attachment: any) => {
|
||||||
const confirmed = await confirm({
|
const confirmed = await confirm({
|
||||||
title: "Delete Attachment",
|
title: "Delete Attachment",
|
||||||
description: `Are you sure you want to delete "${attachment.original_name}"?`,
|
description: `Are you sure you want to delete "${attachment.original_name}"?`,
|
||||||
@@ -63,17 +122,19 @@ export default function JobCardAttachmentsPage() {
|
|||||||
const files = e.target.files
|
const files = e.target.files
|
||||||
if (!files || files.length === 0) return
|
if (!files || files.length === 0) return
|
||||||
|
|
||||||
|
const fileList = Array.from(files)
|
||||||
setIsUploading(true)
|
setIsUploading(true)
|
||||||
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
|
const loadingToast = toast.loading("Uploading attachment(s)...")
|
||||||
toast.promise(promise, {
|
|
||||||
loading: "Uploading attachment(s)...",
|
|
||||||
success: "Attachment(s) uploaded successfully",
|
|
||||||
error: "Failed to upload attachment(s)",
|
|
||||||
})
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await promise
|
await api.jobCards.addAttachment(jobCardId, fileList)
|
||||||
|
toast.dismiss(loadingToast)
|
||||||
|
toast.success("Attachment(s) uploaded successfully")
|
||||||
queryClient.invalidateQueries({ queryKey })
|
queryClient.invalidateQueries({ queryKey })
|
||||||
|
startRefreshTransition(() => router.refresh())
|
||||||
|
} catch (err) {
|
||||||
|
toast.dismiss(loadingToast)
|
||||||
|
showUploadError(err, fileList)
|
||||||
} finally {
|
} finally {
|
||||||
setIsUploading(false)
|
setIsUploading(false)
|
||||||
if (fileInputRef.current) {
|
if (fileInputRef.current) {
|
||||||
@@ -112,7 +173,7 @@ export default function JobCardAttachmentsPage() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
<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)
|
const Icon = getFileIcon(attachment.attachment_path)
|
||||||
return (
|
return (
|
||||||
<Card key={attachment.id}>
|
<Card key={attachment.id}>
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import { Badge } from "@/shared/components/ui/badge"
|
|||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import { BillForm } from "@/modules/bills/bill-form"
|
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 type { BillsClient } from "@garage/api"
|
||||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
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({
|
export default function JobCardBillsPage({
|
||||||
params,
|
params,
|
||||||
@@ -25,6 +28,9 @@ export default function JobCardBillsPage({
|
|||||||
return (
|
return (
|
||||||
<ResourcePage<BillsClient>
|
<ResourcePage<BillsClient>
|
||||||
routeKey={BILL_ROUTES.INDEX}
|
routeKey={BILL_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search bills..."
|
||||||
|
statusFilter={{ statuses: BillStatus }}
|
||||||
getClient={(api) => api.bills}
|
getClient={(api) => api.bills}
|
||||||
extraParams={{ job_card_id: jobCardId }}
|
extraParams={{ job_card_id: jobCardId }}
|
||||||
header={null}
|
header={null}
|
||||||
@@ -46,7 +52,16 @@ export default function JobCardBillsPage({
|
|||||||
{
|
{
|
||||||
accessorKey: "bill_number",
|
accessorKey: "bill_number",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
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",
|
accessorKey: "title",
|
||||||
@@ -55,7 +70,16 @@ export default function JobCardBillsPage({
|
|||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
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",
|
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,14 +12,14 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
|||||||
const { id } = await props.params
|
const { id } = await props.params
|
||||||
const api = await getServerApi()
|
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 title = jobCard?.title || 'Job Card Details'
|
||||||
const status = jobCard?.status || 'draft'
|
const status = jobCard?.status || 'draft'
|
||||||
const docs = jobCard?.documents
|
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<JobCardProvider jobCard={{ ...jobCard }}>
|
<JobCardProvider jobCard={{ ...jobCard }}>
|
||||||
<DashboardDetailsPage
|
<DashboardDetailsPage
|
||||||
className='p-0 lg:p-0'
|
className='p-0 lg:p-0'
|
||||||
title={title}
|
title={title}
|
||||||
@@ -35,34 +35,53 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
|||||||
href: `/sales/job-cards/${id}`,
|
href: `/sales/job-cards/${id}`,
|
||||||
label: 'Details'
|
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`,
|
href: `/sales/job-cards/${id}/attachments`,
|
||||||
label: `Attachments (${docs?.length || 0})`
|
label: `Attachments (${attachmentsCount})`
|
||||||
},
|
|
||||||
{
|
|
||||||
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})`
|
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
href: `/sales/job-cards/${id}/appointments`,
|
href: `/sales/job-cards/${id}/appointments`,
|
||||||
label: `Appointments (${jobCard?.appointments_count || 0})`
|
label: `Appointments (${jobCard?.appointments_count || 0})`
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
href: `/sales/job-cards/${id}/expenses`,
|
// href: `/sales/job-cards/${id}/inspections`,
|
||||||
label: `Expenses (${jobCard?.expenses_count || 0})`
|
// 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}/tasks`,
|
||||||
{
|
// label: `Tasks (${jobCard?.tasks_count || 0})`
|
||||||
href: `/sales/job-cards/${id}/parts`,
|
// },
|
||||||
label: `Parts (${jobCard?.parts_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}
|
{props.children}
|
||||||
|
|||||||
@@ -1,20 +1,10 @@
|
|||||||
import { getServerApi } from '@garage/api/server'
|
|
||||||
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
|
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
|
||||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||||
|
|
||||||
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
|
export default async function JobCardDetailPage() {
|
||||||
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>
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardPage header={null}>
|
<DashboardPage header={null}>
|
||||||
<JobCardGeneralInfo jobCard={data} />
|
<JobCardGeneralInfo />
|
||||||
</DashboardPage>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { use, useState } from "react"
|
import { use, useState } from "react"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
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 type { ColumnDef } from "@tanstack/react-table"
|
||||||
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
||||||
import { formatDate } from "@/shared/utils/formatters"
|
import { formatDate } from "@/shared/utils/formatters"
|
||||||
|
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||||
|
|
||||||
export default function JobCardPartsPage({
|
export default function JobCardPartsPage({
|
||||||
params,
|
params,
|
||||||
@@ -33,7 +35,8 @@ export default function JobCardPartsPage({
|
|||||||
const { id: jobCardId } = use(params)
|
const { id: jobCardId } = use(params)
|
||||||
const api = useAuthApi()
|
const api = useAuthApi()
|
||||||
const queryClient = useQueryClient()
|
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 [dialogOpen, setDialogOpen] = useState(false)
|
||||||
const [editItem, setEditItem] = useState<any | null>(null)
|
const [editItem, setEditItem] = useState<any | null>(null)
|
||||||
@@ -41,11 +44,12 @@ export default function JobCardPartsPage({
|
|||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
queryKey,
|
queryKey,
|
||||||
queryFn: () => api.jobCards.getParts(jobCardId),
|
queryFn: () => api.jobCards.getParts(jobCardId),
|
||||||
|
staleTime: 30_000,
|
||||||
})
|
})
|
||||||
|
|
||||||
const rows = (data as any)?.data ?? []
|
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) {
|
async function handleDelete(row: any) {
|
||||||
const confirmed = await confirm({
|
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" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||||
cell: ({ row }) => row.original.tax || "—",
|
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "department.name",
|
accessorKey: "department.name",
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
|
|||||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||||
import type { PurchaseOrdersClient } from "@garage/api"
|
import type { PurchaseOrdersClient } from "@garage/api"
|
||||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
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({
|
export default function JobCardPurchaseOrdersPage({
|
||||||
params,
|
params,
|
||||||
@@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
|
|||||||
return (
|
return (
|
||||||
<ResourcePage<PurchaseOrdersClient>
|
<ResourcePage<PurchaseOrdersClient>
|
||||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search purchase orders..."
|
||||||
getClient={(api) => api.purchaseOrders}
|
getClient={(api) => api.purchaseOrders}
|
||||||
extraParams={{ job_card_id: jobCardId }}
|
extraParams={{ job_card_id: jobCardId }}
|
||||||
header={null}
|
header={null}
|
||||||
@@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
|
|||||||
{
|
{
|
||||||
accessorKey: "order_number",
|
accessorKey: "order_number",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
|
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",
|
accessorKey: "title",
|
||||||
@@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
|
|||||||
{
|
{
|
||||||
accessorKey: "vendor_name",
|
accessorKey: "vendor_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
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",
|
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 { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { TaskForm } from "@/modules/tasks/task-form"
|
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 type { TasksClient } from "@garage/api"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||||
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
|
|||||||
return (
|
return (
|
||||||
<ResourcePage<TasksClient>
|
<ResourcePage<TasksClient>
|
||||||
routeKey={TASK_ROUTES.INDEX}
|
routeKey={TASK_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search tasks..."
|
||||||
|
statusFilter={{ statuses: TaskStatus }}
|
||||||
getClient={(api) => api.tasks}
|
getClient={(api) => api.tasks}
|
||||||
extraParams={{ job_card_id: jobCardId }}
|
extraParams={{ job_card_id: jobCardId }}
|
||||||
header={null}
|
header={null}
|
||||||
|
|||||||
@@ -6,13 +6,13 @@ import FormDialog from '@/shared/components/form-dialog'
|
|||||||
import { JobCardForm } from '@/modules/job-cards/job-card-form'
|
import { JobCardForm } from '@/modules/job-cards/job-card-form'
|
||||||
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
|
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
|
||||||
import type { JobCardsClient } from '@garage/api'
|
import type { JobCardsClient } from '@garage/api'
|
||||||
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
|
import { ClipboardListIcon } from 'lucide-react'
|
||||||
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
|
|
||||||
import { Badge } from '@/shared/components/ui/badge'
|
import { Badge } from '@/shared/components/ui/badge'
|
||||||
import { Input } from '@/shared/components/ui/input'
|
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { useState, useEffect } from 'react'
|
|
||||||
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
|
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 = {
|
type JobCardItem = {
|
||||||
id: number
|
id: number
|
||||||
@@ -34,122 +34,104 @@ const statusColorMap: Record<string, string> = {
|
|||||||
|
|
||||||
export default function JobCardsPage() {
|
export default function JobCardsPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const [searchInput, setSearchInput] = useState("")
|
const filter = useFilterParams(jobCardFilterConfig)
|
||||||
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
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<JobCardsClient>
|
<>
|
||||||
|
<ResourcePage<JobCardsClient>
|
||||||
routeKey={JOB_CARD_ROUTES.INDEX}
|
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||||
getClient={(api) => api.jobCards}
|
getClient={(api) => api.jobCards}
|
||||||
extraParams={extraParams}
|
searchable
|
||||||
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
|
searchPlaceholder="Search job cards..."
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
statusFilter={{ statuses: JobCardStatus }}
|
||||||
title: "Job Cards",
|
extraParams={filter.appliedParams}
|
||||||
actions: (
|
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
|
||||||
<FormDialog classNames={{ dialogContent: 'min-w-6xl' }} title="Job Card" >
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
{(resourceId) => (
|
title: "Job Cards",
|
||||||
<JobCardForm
|
actions: (
|
||||||
resourceId={resourceId}
|
<div className="flex items-center gap-2">
|
||||||
initialData={selectedItem}
|
<FilterTrigger onClick={filter.open} activeFilterCount={filter.activeFilterCount} />
|
||||||
onSuccess={invalidateQuery}
|
<FormDialog classNames={{ dialogContent: 'xl:min-w-6xl' }} title="Job Card" >
|
||||||
/>
|
{(resourceId, {close}) => (
|
||||||
)}
|
<JobCardForm
|
||||||
</FormDialog>
|
resourceId={resourceId}
|
||||||
),
|
initialData={selectedItem}
|
||||||
})}
|
onSuccess={()=>{ invalidateQuery(); close();}}
|
||||||
columns={({ actionsColumn }) => [
|
/>
|
||||||
{
|
)}
|
||||||
accessorKey: "title",
|
</FormDialog>
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
</div>
|
||||||
cell: ({ row }) => {
|
),
|
||||||
const item = row.original as unknown as JobCardItem
|
})}
|
||||||
return (
|
columns={({ actionsColumn }) => [
|
||||||
<div className="flex items-center gap-2">
|
{
|
||||||
<ClipboardListIcon className="text-muted-foreground h-4 w-4" />
|
accessorKey: "title",
|
||||||
<span>{item.title}</span>
|
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||||
</div>
|
cell: ({ row }) => {
|
||||||
)
|
const item = row.original as unknown as JobCardItem
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ClipboardListIcon className="text-muted-foreground h-4 w-4" />
|
||||||
|
<span>{item.title}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
|
accessorKey: "order_number",
|
||||||
{
|
header: ({ column }) => <ColumnHeader column={column} title="Order Number" />,
|
||||||
accessorKey: "order_number",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Order Number" />,
|
|
||||||
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "check_in_date",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Check-in Date" />,
|
|
||||||
cell: ({ getValue }) => {
|
|
||||||
const val = getValue<string>()
|
|
||||||
return formatDate(val)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
accessorKey: "vehicle_id",
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="KM In" />,
|
|
||||||
cell: ({ row }) => {
|
|
||||||
const item = row.original as unknown as JobCardItem
|
|
||||||
return item.km_in ? formatNumber(item.km_in) : "—"
|
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
accessorKey: "check_in_date",
|
||||||
accessorKey: "created_at",
|
header: ({ column }) => <ColumnHeader column={column} title="Check-in Date" />,
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
cell: ({ getValue }) => {
|
||||||
cell: ({ row }) => {
|
const val = getValue<string>()
|
||||||
const item = row.original as unknown as JobCardItem
|
return formatDate(val)
|
||||||
return formatDate(item.created_at)
|
}
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
accessorKey: "vehicle_id",
|
||||||
accessorKey: "status",
|
header: ({ column }) => <ColumnHeader column={column} title="KM In" />,
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
cell: ({ row }) => {
|
||||||
cell: ({ row }) => {
|
const item = row.original as unknown as JobCardItem
|
||||||
const item = row.original as unknown as JobCardItem
|
return item.km_in ? formatNumber(item.km_in) : "—"
|
||||||
return (
|
},
|
||||||
<Badge variant={statusColorMap[item.status ?? ""] as any ?? "outline"}>
|
|
||||||
{formatEnum(item.status)}
|
|
||||||
</Badge>
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
actionsColumn(),
|
accessorKey: "created_at",
|
||||||
]}
|
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const item = row.original as unknown as JobCardItem
|
||||||
|
return formatDate(item.created_at)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "status",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const item = row.original as unknown as JobCardItem
|
||||||
|
return (
|
||||||
|
<Badge variant={statusColorMap[item.status ?? ""] as any ?? "outline"}>
|
||||||
|
{formatEnum(item.status)}
|
||||||
|
</Badge>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
actionsColumn(),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
tableHeader={
|
<FilterDrawer
|
||||||
<div className="flex justify-between">
|
form={filter.form}
|
||||||
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
|
isOpen={filter.isOpen}
|
||||||
<TabsList variant="line">
|
onOpenChange={(open) => { if (!open) filter.close() }}
|
||||||
<TabsTrigger value="all" >All</TabsTrigger>
|
onSubmit={filter.onSubmit}
|
||||||
{JobCardStatus.map((status) => (
|
onReset={filter.reset}
|
||||||
<TabsTrigger key={status} value={status}>
|
activeFilterCount={filter.activeFilterCount}
|
||||||
{formatEnum(status)}
|
title="Filter Job Cards"
|
||||||
</TabsTrigger>
|
>
|
||||||
))}
|
<JobCardFilterFields />
|
||||||
</TabsList>
|
</FilterDrawer>
|
||||||
</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>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import {
|
|||||||
UserIcon,
|
UserIcon,
|
||||||
ClipboardListIcon,
|
ClipboardListIcon,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
|
||||||
type PaymentReceivedItem = {
|
type PaymentReceivedItem = {
|
||||||
id: number
|
id: number
|
||||||
@@ -32,6 +34,8 @@ export default function PaymentReceivedPage() {
|
|||||||
return (
|
return (
|
||||||
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
|
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
|
||||||
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
|
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search payments..."
|
||||||
getClient={(api) => ({
|
getClient={(api) => ({
|
||||||
list: (query?: any) => api.paymentReceived.list(query),
|
list: (query?: any) => api.paymentReceived.list(query),
|
||||||
destroy: (id: string) => api.paymentReceived.destroy(id),
|
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" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as PaymentReceivedItem
|
const item: any = row.original as unknown as PaymentReceivedItem
|
||||||
|
const customer = item.customer
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<RelationLink
|
||||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||||
<span>{item.customer_name || "—"}</span>
|
icon={UserIcon}
|
||||||
</div>
|
label={getFullName(customer) || item.customer_name}
|
||||||
|
/>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "job_card_name",
|
accessorKey: "job_card",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as PaymentReceivedItem
|
const item: any = row.original as unknown as PaymentReceivedItem
|
||||||
const label = item.job_card_number || item.job_card_name
|
const jobCard = item.job_card
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<RelationLink
|
||||||
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
|
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
|
||||||
<span>{label || "—"}</span>
|
icon={ClipboardListIcon}
|
||||||
</div>
|
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" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const item = row.original as unknown as PaymentReceivedItem
|
const item:any = row.original as unknown as PaymentReceivedItem
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useParams } from "next/navigation"
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||||
import { type ColumnDef } from "@tanstack/react-table"
|
import { type ColumnDef } from "@tanstack/react-table"
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { Plus, Trash2 } from "lucide-react"
|
import { Download, ExternalLink, Plus, Trash2 } from "lucide-react"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
@@ -19,10 +19,27 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/shared/components/ui/dialog"
|
} from "@/shared/components/ui/dialog"
|
||||||
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
|
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
|
||||||
|
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
|
|
||||||
type VehicleDocument = {
|
type VehicleDocument = {
|
||||||
id: number
|
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
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
@@ -54,7 +71,7 @@ export default function VehicleDocumentsPage() {
|
|||||||
const handleDelete = async (doc: VehicleDocument) => {
|
const handleDelete = async (doc: VehicleDocument) => {
|
||||||
const confirmed = await confirm({
|
const confirmed = await confirm({
|
||||||
title: "Delete Document",
|
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",
|
confirmLabel: "Delete",
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
})
|
})
|
||||||
@@ -65,16 +82,74 @@ export default function VehicleDocumentsPage() {
|
|||||||
|
|
||||||
const columns: ColumnDef<VehicleDocument>[] = [
|
const columns: ColumnDef<VehicleDocument>[] = [
|
||||||
{
|
{
|
||||||
accessorKey: "name",
|
accessorKey: "document_number",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
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",
|
accessorKey: "created_at",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
|
||||||
cell: ({ getValue }) => {
|
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||||
const val = getValue<string>()
|
|
||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "actions",
|
id: "actions",
|
||||||
@@ -83,7 +158,10 @@ export default function VehicleDocumentsPage() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
onClick={() => handleDelete(row.original)}
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
handleDelete(row.original)
|
||||||
|
}}
|
||||||
title="Delete document"
|
title="Delete document"
|
||||||
>
|
>
|
||||||
<Trash2 className="size-4 text-destructive" />
|
<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 documents = (data as any)?.data ?? []
|
||||||
const meta = (data as any)?.meta
|
const meta = (data as any)?.meta
|
||||||
|
|
||||||
@@ -105,21 +192,25 @@ export default function VehicleDocumentsPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<div className="flex items-center justify-end">
|
|
||||||
<Button onClick={() => setDialogOpen(true)}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Upload Document
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<DataTable
|
<DataTable
|
||||||
|
slots={{
|
||||||
|
actions: <div className="flex items-center justify-end">
|
||||||
|
<Button onClick={() => setDialogOpen(true)}>
|
||||||
|
<Plus className="size-4" />
|
||||||
|
Upload Document
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
}}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
data={documents}
|
data={documents}
|
||||||
pagination={pagination}
|
pagination={pagination}
|
||||||
sorting={[]}
|
sorting={[]}
|
||||||
onChange={() => {}}
|
onChange={() => { }}
|
||||||
|
onRowClick={handleRowClick}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
|
|||||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||||
import type { EstimatesClient } 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 { 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 }> }) {
|
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
const { id: vehicleId } = use(params)
|
const { id: vehicleId } = use(params)
|
||||||
@@ -18,7 +20,7 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ResourcePage<EstimatesClient>
|
<ResourcePage<EstimatesClient>
|
||||||
toolbar={({ invalidateQuery, selectedItem, closeDialog }) => (
|
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||||
<FormDialog title="Estimate">
|
<FormDialog title="Estimate">
|
||||||
{(resourceId) => (
|
{(resourceId) => (
|
||||||
<EstimateForm
|
<EstimateForm
|
||||||
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
|||||||
}
|
}
|
||||||
pageTitle="Vehicle Estimates"
|
pageTitle="Vehicle Estimates"
|
||||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search estimates..."
|
||||||
getClient={(api) => api.estimates}
|
getClient={(api) => api.estimates}
|
||||||
extraParams={{ vehicle_id: vehicleId }}
|
extraParams={{ vehicle_id: vehicleId }}
|
||||||
header={
|
header={
|
||||||
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
|||||||
{
|
{
|
||||||
accessorKey: "customer_name",
|
accessorKey: "customer_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
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",
|
accessorKey: "date",
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ export default async function layout(props: { params: Promise<{ id: string }>, c
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<DashboardDetailsPage
|
<DashboardDetailsPage
|
||||||
className='p-0 lg:p-0'
|
|
||||||
avatarSrc={vehicle.data?.image_url || ""}
|
avatarSrc={vehicle.data?.image_url || ""}
|
||||||
// avatarSrc={vehicle.data?.image_url || ""}
|
// avatarSrc={vehicle.data?.image_url || ""}
|
||||||
title={title}
|
title={title}
|
||||||
|
|||||||
@@ -25,11 +25,23 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/shared/components/ui/dropdown-menu"
|
} from "@/shared/components/ui/dropdown-menu"
|
||||||
import { MileageForm } from "@/modules/vehicles/mileage-form"
|
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 = {
|
type MileageRecord = {
|
||||||
id: number
|
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
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
@@ -64,9 +76,10 @@ export default function VehicleMileagePage() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const handleDelete = async (record: MileageRecord) => {
|
const handleDelete = async (record: MileageRecord) => {
|
||||||
|
const label = record.miles != null ? `${record.miles} mi` : `Record #${record.id}`
|
||||||
const confirmed = await confirm({
|
const confirmed = await confirm({
|
||||||
title: "Delete Mileage Record",
|
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",
|
confirmLabel: "Delete",
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
})
|
})
|
||||||
@@ -87,16 +100,59 @@ export default function VehicleMileagePage() {
|
|||||||
|
|
||||||
const columns: ColumnDef<MileageRecord>[] = [
|
const columns: ColumnDef<MileageRecord>[] = [
|
||||||
{
|
{
|
||||||
accessorKey: "name",
|
accessorKey: "miles",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Mileage" />,
|
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",
|
accessorKey: "created_at",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
|
||||||
cell: ({ getValue }) => {
|
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||||
const val = getValue<string>()
|
|
||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "actions",
|
id: "actions",
|
||||||
@@ -140,32 +196,27 @@ export default function VehicleMileagePage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
|
|
||||||
|
|
||||||
<DashboardPage
|
|
||||||
header={null}
|
|
||||||
toolbar={
|
|
||||||
<Button onClick={handleCreate}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Add Mileage
|
|
||||||
</Button>
|
|
||||||
}
|
|
||||||
title='Milage'
|
|
||||||
>
|
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<DataTable
|
<DataTable
|
||||||
|
slots={{
|
||||||
|
actions: <Button onClick={handleCreate}>
|
||||||
|
<Plus className="size-4" />
|
||||||
|
Add Mileage
|
||||||
|
</Button>
|
||||||
|
}}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
data={records}
|
data={records}
|
||||||
pagination={pagination}
|
pagination={pagination}
|
||||||
sorting={[]}
|
sorting={[]}
|
||||||
onChange={() => {}}
|
onChange={() => { }}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</DashboardPage>
|
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||||
<DialogContent className="min-w-md">
|
<DialogContent className="min-w-md">
|
||||||
|
|||||||
@@ -129,38 +129,48 @@ export default function VehicleOwnersPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardPage title="Owners" header={null} toolbar={
|
|
||||||
<Button className="w-full" size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
|
||||||
<Plus />
|
|
||||||
Add Owner
|
|
||||||
</Button>
|
|
||||||
}>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardContent>
|
|
||||||
|
|
||||||
<DataTable
|
<Card>
|
||||||
columns={columns}
|
<CardContent>
|
||||||
data={owners}
|
|
||||||
pagination={pagination}
|
|
||||||
sorting={[]}
|
|
||||||
|
|
||||||
onChange={() => { }}
|
|
||||||
isLoading={isLoading}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<LinkOwnerDialog
|
<DataTable
|
||||||
vehicleId={vehicleId}
|
slots={{
|
||||||
open={linkDialogOpen}
|
actions:
|
||||||
onOpenChange={setLinkDialogOpen}
|
<div className="flex justify-end">
|
||||||
onSuccess={() => {
|
|
||||||
queryClient.invalidateQueries({ queryKey })
|
<Button size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||||
setLinkDialogOpen(false)
|
<Plus />
|
||||||
}}
|
Add Owner
|
||||||
/>
|
</Button>
|
||||||
</CardContent>
|
</div>,
|
||||||
</Card>
|
|
||||||
</DashboardPage >
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
columns={columns}
|
||||||
|
data={owners}
|
||||||
|
pagination={pagination}
|
||||||
|
sorting={[]}
|
||||||
|
|
||||||
|
onChange={() => { }}
|
||||||
|
isLoading={isLoading}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<LinkOwnerDialog
|
||||||
|
vehicleId={vehicleId}
|
||||||
|
open={linkDialogOpen}
|
||||||
|
onOpenChange={setLinkDialogOpen}
|
||||||
|
onSuccess={() => {
|
||||||
|
queryClient.invalidateQueries({ queryKey })
|
||||||
|
setLinkDialogOpen(false)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,36 +3,61 @@
|
|||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table'
|
||||||
import FormDialog from '@/shared/components/form-dialog'
|
import FormDialog from '@/shared/components/form-dialog'
|
||||||
|
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||||
|
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||||
|
import { useAuthApi } from '@/shared/useApi'
|
||||||
|
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
|
||||||
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
|
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
|
||||||
import { VEHICLE_ROUTES } from '@garage/api'
|
import { VEHICLE_ROUTES } from '@garage/api'
|
||||||
import type { VehiclesClient } 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() {
|
export default function VehiclesPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const api = useAuthApi()
|
||||||
return (
|
return (
|
||||||
<ResourcePage<VehiclesClient>
|
<ResourcePage<VehiclesClient>
|
||||||
pageTitle="Vehicles"
|
pageTitle="Vehicles"
|
||||||
routeKey={VEHICLE_ROUTES.INDEX}
|
routeKey={VEHICLE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search vehicles..."
|
||||||
getClient={(api) => api.vehicles}
|
getClient={(api) => api.vehicles}
|
||||||
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
|
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Vehicle">
|
<div className='flex items-center gap-2'>
|
||||||
{(resourceId) => (
|
<ImportDataButton
|
||||||
<VehicleForm
|
onImport={(file) => api.vehicles.importData(file)}
|
||||||
resourceId={resourceId}
|
onSuccess={invalidateQuery}
|
||||||
initialData={selectedItem}
|
entityLabel="Vehicles"
|
||||||
onSuccess={invalidateQuery}
|
onDownloadSample={() => api.vehicles.downloadImportSample()}
|
||||||
/>
|
sampleFileName='vehicles-import-sample'
|
||||||
)}
|
/>
|
||||||
</FormDialog>
|
<ExportDataButton
|
||||||
|
onExport={(filters) => api.vehicles.exportData(filters)}
|
||||||
|
fileName='vehicles'
|
||||||
|
/>
|
||||||
|
<FormDialog title="Vehicle" classNames={{ dialogContent: 'lg:min-w-4xl' }}>
|
||||||
|
{(resourceId) => (
|
||||||
|
<VehicleForm
|
||||||
|
resourceId={resourceId}
|
||||||
|
initialData={selectedItem}
|
||||||
|
onSuccess={invalidateQuery}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</FormDialog>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
})}
|
})}
|
||||||
|
|
||||||
columns={({ actionsColumn }) => [
|
columns={({ actionsColumn }) => [
|
||||||
{
|
{
|
||||||
accessorKey: "name",
|
id: "name",
|
||||||
|
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const r = row.original as any
|
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",
|
accessorKey: "year",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||||
@@ -90,14 +129,7 @@ export default function VehiclesPage() {
|
|||||||
return val != null ? `${Number(val).toLocaleString()} mi` : "—"
|
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(),
|
actionsColumn(),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||||
import { SettingsForm } from "@/modules/settings/company/settings-form"
|
import { SettingsForm } from "@/modules/settings/company/settings-form"
|
||||||
|
|
||||||
export default function CompanySettingsPage() {
|
export default function CompanySettingsPage() {
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-3xl space-y-6 p-6">
|
<DashboardPage headerProps={{title:'Company Settings'}}>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold">Company Settings</h1>
|
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground text-sm">
|
||||||
Manage your workshop profile, contact details, and preferences.
|
Manage your workshop profile, contact details, and preferences.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<SettingsForm />
|
<SettingsForm />
|
||||||
</div>
|
</DashboardPage>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
|
|||||||
<ResourcePage<DepartmentsClient>
|
<ResourcePage<DepartmentsClient>
|
||||||
pageTitle="Departments"
|
pageTitle="Departments"
|
||||||
routeKey={DEPARTMENT_ROUTES.INDEX}
|
routeKey={DEPARTMENT_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search departments..."
|
||||||
getClient={(api) => api.departments}
|
getClient={(api) => api.departments}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
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>
|
<ResourcePage<InsuranceTypesClient>
|
||||||
pageTitle="Insurance Types"
|
pageTitle="Insurance Types"
|
||||||
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
|
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search insurance types..."
|
||||||
getClient={(api) => api.insuranceTypes}
|
getClient={(api) => api.insuranceTypes}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
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>
|
<ResourcePage<ShopTypesClient>
|
||||||
pageTitle="Shop Types"
|
pageTitle="Shop Types"
|
||||||
routeKey={SHOP_TYPE_ROUTES.INDEX}
|
routeKey={SHOP_TYPE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search shop types..."
|
||||||
getClient={(api) => api.shopTypes}
|
getClient={(api) => api.shopTypes}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
|
|||||||
@@ -55,6 +55,8 @@ export default function TaxesPage() {
|
|||||||
<ResourcePage<TaxesClient>
|
<ResourcePage<TaxesClient>
|
||||||
pageTitle="Tax & Rates"
|
pageTitle="Tax & Rates"
|
||||||
routeKey={TAX_ROUTES.INDEX}
|
routeKey={TAX_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search tax rates..."
|
||||||
getClient={(api) => api.taxes}
|
getClient={(api) => api.taxes}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
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 { Geist_Mono, Inter } from "next/font/google"
|
||||||
|
import NextTopLoader from "nextjs-toploader"
|
||||||
|
|
||||||
|
|
||||||
import "./globals.css"
|
|
||||||
import { QueryProvider } from "@/shared/components/query-provider"
|
import { QueryProvider } from "@/shared/components/query-provider"
|
||||||
import { ThemeProvider } from "@/shared/components/theme-provider"
|
import { ThemeProvider } from "@/shared/components/theme-provider"
|
||||||
import { Toaster } from "@/shared/components/ui/sonner"
|
import { Toaster } from "@/shared/components/ui/sonner"
|
||||||
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
|
import { ConfirmDialog } from "@/shared/components/confirm-dialog"
|
||||||
|
import { PromptDialog } from "@/shared/components/prompt-dialog"
|
||||||
import { NuqsAdapter } from "nuqs/adapters/next/app"
|
import { NuqsAdapter } from "nuqs/adapters/next/app"
|
||||||
import { cn } from "@/shared/lib/utils"
|
import { cn } from "@/shared/lib/utils"
|
||||||
|
import './globals.css'
|
||||||
|
|
||||||
const inter = Inter({ subsets: ["latin"], variable: "--font-sans" })
|
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({
|
const fontMono = Geist_Mono({
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
variable: "--font-mono",
|
variable: "--font-mono",
|
||||||
@@ -27,11 +35,13 @@ export default function RootLayout({
|
|||||||
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
|
className={cn("antialiased", fontMono.variable, "font-sans", inter.variable)}
|
||||||
>
|
>
|
||||||
<body>
|
<body>
|
||||||
|
<NextTopLoader color="var(--primary)" height={3} showSpinner={false} />
|
||||||
<NuqsAdapter>
|
<NuqsAdapter>
|
||||||
<ThemeProvider>
|
<ThemeProvider>
|
||||||
<QueryProvider>{children}</QueryProvider>
|
<QueryProvider>{children}</QueryProvider>
|
||||||
<Toaster />
|
<Toaster />
|
||||||
<ConfirmDialog />
|
<ConfirmDialog />
|
||||||
|
<PromptDialog />
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</NuqsAdapter>
|
</NuqsAdapter>
|
||||||
</body>
|
</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 }) {
|
function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
const isActive = item.isActive ?? pathname === item.href
|
const isActive = isItemActive(pathname, item)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
@@ -169,8 +180,8 @@ function SimpleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: bool
|
|||||||
|
|
||||||
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed: boolean }) {
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
const isChildActive = item.items?.some((sub) => pathname === sub.href)
|
const isChildActive = item.items?.some((sub) => isItemActive(pathname, sub))
|
||||||
const isActive = item.isActive ?? (pathname === item.href || isChildActive === true)
|
const isActive = item.isActive ?? (isItemActive(pathname, item) || isChildActive === true)
|
||||||
|
|
||||||
// Collapsed sidebar → flyout dropdown with sub-items
|
// Collapsed sidebar → flyout dropdown with sub-items
|
||||||
if (isCollapsed) {
|
if (isCollapsed) {
|
||||||
@@ -210,7 +221,7 @@ function CollapsibleNavItem({ item, isCollapsed }: { item: NavItem; isCollapsed:
|
|||||||
</DropdownMenuLabel>
|
</DropdownMenuLabel>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
{item.items?.map((sub) => {
|
{item.items?.map((sub) => {
|
||||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
const isSubActive = isItemActive(pathname, sub)
|
||||||
return (
|
return (
|
||||||
<DropdownMenuItem key={sub.href} asChild>
|
<DropdownMenuItem key={sub.href} asChild>
|
||||||
<Link
|
<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">
|
<CollapsibleContent className="overflow-hidden py-2 data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up">
|
||||||
<SidebarMenuSub>
|
<SidebarMenuSub>
|
||||||
{item.items?.map((sub) => {
|
{item.items?.map((sub) => {
|
||||||
const isSubActive = sub.isActive ?? pathname === sub.href
|
const isSubActive = isItemActive(pathname, sub)
|
||||||
return (
|
return (
|
||||||
<SidebarMenuSubItem key={sub.href}>
|
<SidebarMenuSubItem key={sub.href}>
|
||||||
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
|
<SidebarMenuSubButton asChild isActive={isSubActive} className="dashboard-nav-sub-item my-0.5">
|
||||||
|
|||||||
@@ -68,14 +68,22 @@ export default function DashboardDetailsPageLayout({
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{(avatarSrc || avatarFallback) && (
|
{(avatarSrc || avatarFallback) && (
|
||||||
<a rel="preload" target="_blank" href={avatarSrc} >
|
avatarSrc ? (
|
||||||
<Avatar className="size-14">
|
<a target="_blank" rel="noopener noreferrer" href={avatarSrc}>
|
||||||
{avatarSrc && <AvatarImage src={avatarSrc} alt={title} />}
|
<Avatar className="size-14">
|
||||||
<AvatarFallback>
|
<AvatarImage src={avatarSrc} alt={title} />
|
||||||
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
<AvatarFallback>
|
||||||
</AvatarFallback>
|
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||||
</Avatar>
|
</AvatarFallback>
|
||||||
</a>
|
</Avatar>
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<Avatar className="size-14">
|
||||||
|
<AvatarFallback>
|
||||||
|
{avatarFallback ?? title.charAt(0).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
)
|
||||||
)}
|
)}
|
||||||
{!avatarSrc && !avatarFallback && icon && (
|
{!avatarSrc && !avatarFallback && icon && (
|
||||||
<div className="flex items-center justify-center size-10 rounded-full bg-muted text-muted-foreground">
|
<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
|
<Link
|
||||||
key={tab.href}
|
key={tab.href}
|
||||||
href={tab.href}
|
href={tab.href}
|
||||||
|
prefetch
|
||||||
className={cn(
|
className={cn(
|
||||||
"relative inline-flex items-center justify-center px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors",
|
"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",
|
"text-muted-foreground hover:text-foreground",
|
||||||
|
|||||||
@@ -6,6 +6,12 @@ export type NavItem = {
|
|||||||
href: string
|
href: string
|
||||||
icon?: ReactNode
|
icon?: ReactNode
|
||||||
isActive?: boolean
|
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
|
badge?: string | number
|
||||||
items?: NavSubItem[]
|
items?: NavSubItem[]
|
||||||
}
|
}
|
||||||
@@ -15,6 +21,7 @@ export type NavSubItem = {
|
|||||||
href: string
|
href: string
|
||||||
icon?: ReactNode
|
icon?: ReactNode
|
||||||
isActive?: boolean
|
isActive?: boolean
|
||||||
|
matchPath?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type NavGroup = {
|
export type NavGroup = {
|
||||||
|
|||||||
@@ -57,14 +57,14 @@ export const navGroups: NavGroup[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Customer & Vehicles",
|
title: "Customer & Vehicles",
|
||||||
href: "/customer-vehicles",
|
href: "/sales/vehicles",
|
||||||
icon: <UsersIcon />,
|
icon: <UsersIcon />,
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
title: "Reports",
|
// title: "Reports",
|
||||||
href: "/reports",
|
// href: "/reports",
|
||||||
icon: <BarChart3Icon />,
|
// icon: <BarChart3Icon />,
|
||||||
},
|
// },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -75,8 +75,8 @@ export const navGroups: NavGroup[] = [
|
|||||||
href: "/calendars",
|
href: "/calendars",
|
||||||
icon: <CalendarIcon />,
|
icon: <CalendarIcon />,
|
||||||
items: [
|
items: [
|
||||||
{ title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
|
// { title: "Work Schedule", href: "/calendar/work-schedule/list", icon: <Clock3Icon /> },
|
||||||
{ title: "Appointments", href: "/calendar/appointment/list", icon: <CalendarCheck2Icon /> },
|
{ 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: "Vendor Credits", href: "/purchase/vendor-credit", icon: <ReceiptTextIcon /> },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
title: "CRM",
|
// title: "CRM",
|
||||||
href: "/crm",
|
// href: "/crm",
|
||||||
icon: <BriefcaseBusinessIcon />,
|
// icon: <BriefcaseBusinessIcon />,
|
||||||
items: [
|
// items: [
|
||||||
{ title: "Leads", href: "/crm/leads/list", icon: <GemIcon /> },
|
// { title: "Leads", href: "/crm/leads/list", icon: <GemIcon /> },
|
||||||
{ title: "Calls", href: "/crm/calls-follow-up/list", icon: <PhoneCallIcon /> },
|
// { title: "Calls", href: "/crm/calls-follow-up/list", icon: <PhoneCallIcon /> },
|
||||||
{ title: "Tasks", href: "/crm/tasks/list", icon: <ListTodoIcon /> },
|
// { title: "Tasks", href: "/crm/tasks/list", icon: <ListTodoIcon /> },
|
||||||
],
|
// ],
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
title: "Marketing",
|
// title: "Marketing",
|
||||||
href: "/marketing",
|
// href: "/marketing",
|
||||||
icon: <MegaphoneIcon />,
|
// icon: <MegaphoneIcon />,
|
||||||
items: [
|
// items: [
|
||||||
{ title: "Service Reminders", href: "/marketing/service-reminder/list", icon: <AlarmClockIcon /> },
|
// { title: "Service Reminders", href: "/marketing/service-reminder/list", icon: <AlarmClockIcon /> },
|
||||||
{ title: "Rating & Reviews", href: "/marketing/rating-review", icon: <StarIcon /> },
|
// { title: "Rating & Reviews", href: "/marketing/rating-review", icon: <StarIcon /> },
|
||||||
{ title: "Google Business Reviews", href: "/marketing/google-rating-review", icon: <AwardIcon /> },
|
// { title: "Google Business Reviews", href: "/marketing/google-rating-review", icon: <AwardIcon /> },
|
||||||
],
|
// ],
|
||||||
},
|
// },
|
||||||
{
|
// {
|
||||||
title: "Accountants",
|
// title: "Accountants",
|
||||||
href: "/accountants",
|
// href: "/accountants",
|
||||||
icon: <BookIcon />,
|
// icon: <BookIcon />,
|
||||||
items: [
|
// items: [
|
||||||
{ title: "Manual Journals", href: "/accountants/manual-journal", icon: <BookIcon /> },
|
// { title: "Manual Journals", href: "/accountants/manual-journal", icon: <BookIcon /> },
|
||||||
{ title: "Chart of Accounts", href: "/accountants/chart-of-account", icon: <GitBranchIcon /> },
|
// { title: "Chart of Accounts", href: "/accountants/chart-of-account", icon: <GitBranchIcon /> },
|
||||||
],
|
// ],
|
||||||
},
|
// },
|
||||||
{
|
{
|
||||||
title: "Employees",
|
title: "Employees",
|
||||||
href: "/productivity",
|
href: "/productivity",
|
||||||
@@ -144,10 +144,10 @@ export const navGroups: NavGroup[] = [
|
|||||||
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
|
{ title: "Employees", href: "/productivity/employees", icon: <UsersIcon /> },
|
||||||
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
|
{ title: "Time Clocks", href: "/productivity/time-clocks", icon: <TimerIcon /> },
|
||||||
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
|
{ title: "Time Sheets", href: "/productivity/timesheet", icon: <ClockIcon /> },
|
||||||
{ title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
// { title: "Payroll", href: "/productivity/payroll", icon: <WalletIcon /> },
|
||||||
{ title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
// { title: "Payments Made", href: "/productivity/employee-payments-made", icon: <HandCoinsIcon /> },
|
||||||
{ title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
// { title: "Shop Calendars", href: "/productivity/shop-calendars", icon: <CalendarDaysIcon /> },
|
||||||
{ title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
// { title: "Shop Timing", href: "/productivity/shop-timings", icon: <Clock3Icon /> },
|
||||||
{ title: "Holidays", href: "/productivity/holidays", icon: <CalendarIcon /> },
|
{ title: "Holidays", href: "/productivity/holidays", icon: <CalendarIcon /> },
|
||||||
{ title: "Tasks", href: "/productivity/tasks", icon: <ListTodoIcon /> },
|
{ title: "Tasks", href: "/productivity/tasks", icon: <ListTodoIcon /> },
|
||||||
],
|
],
|
||||||
@@ -161,7 +161,7 @@ export const navGroups: NavGroup[] = [
|
|||||||
{ title: "Parts", href: "/items/parts", icon: <WrenchIcon /> },
|
{ title: "Parts", href: "/items/parts", icon: <WrenchIcon /> },
|
||||||
{ title: "Expense Item", href: "/items/expense-item", icon: <WalletIcon /> },
|
{ title: "Expense Item", href: "/items/expense-item", icon: <WalletIcon /> },
|
||||||
{ title: "Service Group", href: "/items/service-group", icon: <PackageIcon /> },
|
{ 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 /> },
|
{ title: "Inventory Adjustments", href: "/items/adjustment", icon: <ListIcon /> },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -175,10 +175,12 @@ export const navGroups: NavGroup[] = [
|
|||||||
{ title: "Departments", href: "/settings/departments", icon: <Building2Icon /> },
|
{ title: "Departments", href: "/settings/departments", icon: <Building2Icon /> },
|
||||||
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
|
{ title: "Insurance Types", href: "/settings/insurance-types", icon: <ShieldIcon /> },
|
||||||
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
|
{ title: "Tax & Rates", href: "/settings/tax-rates", icon: <ReceiptTextIcon /> },
|
||||||
{ title: "Configurations", href: "/settings/configurations/preferences/sales", icon: <SettingsIcon /> },
|
{ title: "Make & Models", href: "/settings/make-and-models", icon: <CarIcon /> },
|
||||||
{ title: "Templates", href: "/settings/templates", icon: <ClipboardListIcon /> },
|
{ title: "Inspection Templates", href: "/settings/inspection-templates", icon: <ClipboardListIcon /> },
|
||||||
{ title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> },
|
{ title: "Configurations", href: "/settings/configurations/preferences/sales", matchPath: "/settings/configurations", icon: <SettingsIcon /> },
|
||||||
{ title: "Master", href: "/settings/master/body-type", icon: <ListIcon /> },
|
// { 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 { useRouter } from "next/navigation"
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
import { Button } from "@/shared/components/ui/button"
|
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 {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -15,6 +17,8 @@ import { Ellipsis, Pencil, Trash2, CheckCircle, Unlink } from "lucide-react"
|
|||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { useQueryClient } from "@tanstack/react-query"
|
import { useQueryClient } from "@tanstack/react-query"
|
||||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||||
|
import { useFormDialog } from "@/shared/components/form-dialog"
|
||||||
|
import { AppointmentForm } from "./appointment-form"
|
||||||
|
|
||||||
type AppointmentActionsProps = {
|
type AppointmentActionsProps = {
|
||||||
appointmentId: string
|
appointmentId: string
|
||||||
@@ -27,10 +31,7 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const editDialog = useFormDialog("appointment-details-edit")
|
||||||
const handleEdit = () => {
|
|
||||||
router.push(`/calendar/appointment/${appointmentId}/edit`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDelete = async () => {
|
const handleDelete = async () => {
|
||||||
setIsLoading(true)
|
setIsLoading(true)
|
||||||
@@ -75,50 +76,68 @@ export function AppointmentActions({ appointmentId, currentStatus, jobCardId }:
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenu>
|
||||||
<Button variant="ghost" size="icon" disabled={isLoading}>
|
<DropdownMenuTrigger asChild>
|
||||||
<Ellipsis className="size-4" />
|
<Button variant="ghost" size="icon" disabled={isLoading}>
|
||||||
</Button>
|
<Ellipsis className="size-4" />
|
||||||
</DropdownMenuTrigger>
|
</Button>
|
||||||
<DropdownMenuContent align="end">
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuItem onClick={handleEdit}>
|
<DropdownMenuContent align="end">
|
||||||
<Pencil className="size-4" />
|
<DropdownMenuItem onClick={() => editDialog.open(appointmentId)}>
|
||||||
Edit
|
<Pencil className="size-4" />
|
||||||
</DropdownMenuItem>
|
Edit
|
||||||
{currentStatus !== "confirmed" && (
|
</DropdownMenuItem>
|
||||||
|
{currentStatus !== "confirmed" && (
|
||||||
<DropdownMenuItem onClick={() => handleChangeStatus("confirmed")}>
|
<DropdownMenuItem onClick={() => handleChangeStatus("confirmed")}>
|
||||||
<CheckCircle className="size-4" />
|
<CheckCircle className="size-4" />
|
||||||
Confirm
|
Confirm
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
{currentStatus !== "completed" && (
|
{currentStatus !== "completed" && (
|
||||||
<DropdownMenuItem onClick={() => handleChangeStatus("completed")}>
|
<DropdownMenuItem onClick={() => handleChangeStatus("completed")}>
|
||||||
<CheckCircle className="size-4" />
|
<CheckCircle className="size-4" />
|
||||||
Mark Completed
|
Mark Completed
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
{currentStatus !== "cancelled" && (
|
{currentStatus !== "cancelled" && (
|
||||||
<DropdownMenuItem onClick={() => handleChangeStatus("cancelled")}>
|
<DropdownMenuItem onClick={() => handleChangeStatus("cancelled")}>
|
||||||
<CheckCircle className="size-4" />
|
<CheckCircle className="size-4" />
|
||||||
Cancel
|
Cancel
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
{jobCardId && (
|
{jobCardId && (
|
||||||
<>
|
<>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem onClick={handleUnlinkJobCard}>
|
<DropdownMenuItem onClick={handleUnlinkJobCard}>
|
||||||
<Unlink className="size-4" />
|
<Unlink className="size-4" />
|
||||||
Unlink Job Card
|
Unlink Job Card
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
<DropdownMenuItem variant="destructive" onClick={handleDelete}>
|
||||||
<Trash2 className="size-4" />
|
<Trash2 className="size-4" />
|
||||||
Delete
|
Delete
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</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,
|
RhfTextareaField,
|
||||||
RhfSelectField,
|
RhfSelectField,
|
||||||
RhfAsyncSelectField,
|
RhfAsyncSelectField,
|
||||||
|
RhfTimeField,
|
||||||
} from "@/shared/components/form"
|
} from "@/shared/components/form"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { useAuthApi } from "@/shared/useApi"
|
import { useAuthApi } from "@/shared/useApi"
|
||||||
@@ -40,8 +41,8 @@ export type AppointmentFormProps = {
|
|||||||
const DEFAULT_VALUES: AppointmentFormValues = {
|
const DEFAULT_VALUES: AppointmentFormValues = {
|
||||||
title: "",
|
title: "",
|
||||||
date: "",
|
date: "",
|
||||||
from_time: "",
|
from_time: "00:00:00",
|
||||||
to_time: "",
|
to_time: "00:00:00",
|
||||||
customer: null,
|
customer: null,
|
||||||
vehicle: null,
|
vehicle: null,
|
||||||
service_writer: null,
|
service_writer: null,
|
||||||
@@ -157,8 +158,8 @@ export function AppointmentForm({ resourceId, initialData, onSuccess }: Appointm
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<RhfTextField name="from_time" label="From Time" placeholder="HH:MM" type="time" />
|
<RhfTimeField name="from_time" label="From Time" placeholder="HH:MM" />
|
||||||
<RhfTextField name="to_time" label="To Time" placeholder="HH:MM" type="time" />
|
<RhfTimeField name="to_time" label="To Time" placeholder="HH:MM" />
|
||||||
</div>
|
</div>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,39 @@
|
|||||||
import { z } from "zod"
|
import { z } from "zod"
|
||||||
|
import { AppointmentStatus } from "@garage/api"
|
||||||
|
|
||||||
const relationFieldSchema = z
|
const relationFieldSchema = z
|
||||||
.object({ value: z.string(), label: z.string() })
|
.object({ value: z.string(), label: z.string() })
|
||||||
.nullable()
|
.nullable()
|
||||||
|
|
||||||
const APPOINTMENT_STATUS_OPTIONS = [
|
const APPOINTMENT_STATUS_OPTIONS = AppointmentStatus.map((v) => ({
|
||||||
{ value: "requested", label: "Requested" },
|
value: v,
|
||||||
{ value: "confirmed", label: "Confirmed" },
|
label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||||
{ value: "in_progress", label: "In Progress" },
|
}))
|
||||||
{ value: "completed", label: "Completed" },
|
|
||||||
{ value: "cancelled", label: "Cancelled" },
|
|
||||||
]
|
|
||||||
|
|
||||||
const appointmentFormSchema = z.object({
|
const appointmentFormSchema = z
|
||||||
title: z.string().min(1, "Title is required"),
|
.object({
|
||||||
date: z.string().min(1, "Date is required"),
|
title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
|
||||||
from_time: z.string().min(1, "Start time is required"),
|
date: z.string().min(1, "Date is required"),
|
||||||
to_time: z.string().min(1, "End time is required"),
|
from_time: z.string().min(1, "Start time is required"),
|
||||||
customer: relationFieldSchema,
|
to_time: z.string().min(1, "End time is required"),
|
||||||
vehicle: relationFieldSchema,
|
customer: relationFieldSchema,
|
||||||
service_writer: relationFieldSchema,
|
vehicle: relationFieldSchema,
|
||||||
technician: relationFieldSchema,
|
service_writer: relationFieldSchema.refine((val) => !!val?.value, "Service writer is required"),
|
||||||
department: relationFieldSchema,
|
technician: relationFieldSchema,
|
||||||
job_card: relationFieldSchema,
|
department: relationFieldSchema,
|
||||||
notes: z.string().optional(),
|
job_card: relationFieldSchema,
|
||||||
status: z.string().optional(),
|
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>
|
type AppointmentFormValues = z.infer<typeof appointmentFormSchema>
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { z } from "zod"
|
|||||||
|
|
||||||
const loginFormSchema = z.object({
|
const loginFormSchema = z.object({
|
||||||
email: z.string().trim().email("Enter a valid email address"),
|
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>
|
type LoginFormValues = z.infer<typeof loginFormSchema>
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ export function LoginForm({
|
|||||||
|
|
||||||
const { mutate, error, isPending: isSubmitting } = useMutation({
|
const { mutate, error, isPending: isSubmitting } = useMutation({
|
||||||
mutationFn: (values: LoginFormValues) => api.auth.login(values),
|
mutationFn: (values: LoginFormValues) => api.auth.login(values),
|
||||||
onSuccess: async (data) => {
|
onSuccess: async (data:any) => {
|
||||||
if (data.token && data.user) {
|
if (data.token && data.user) {
|
||||||
await login(data.token, data.user as Parameters<typeof login>[1])
|
await login(data.token, data.user as Parameters<typeof login>[1])
|
||||||
router.push("/")
|
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