Compare commits
58
Commits
c47f7c1b6a
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b145c1469 | ||
|
|
33da1204dd | ||
|
|
75e44f5b26 | ||
|
|
29d90b5e71 | ||
|
|
f9aac2db37 | ||
|
|
11d920ba6a | ||
|
|
0171daea38 | ||
|
|
a1c647a7b3 | ||
|
|
16fd7dd423 | ||
|
|
baa716b8ff | ||
|
|
97ad275588 | ||
|
|
fdce301495 | ||
|
|
c71b5a19ed | ||
|
|
3e229d0de1 | ||
|
|
a888157d33 | ||
|
|
6d6059330a | ||
|
|
cd66daa6b1 | ||
|
|
2505fccd5f | ||
|
|
019ea56e6f | ||
|
|
ccb9eacd86 | ||
|
|
4f0a2f790f | ||
|
|
2d6e3c5734 | ||
|
|
5570527e69 | ||
|
|
4bfd8c84a9 | ||
|
|
54d11f01b4 | ||
|
|
fcbba6247d | ||
|
|
05b55b5721 | ||
|
|
6b356d2855 | ||
|
|
464402f4d6 | ||
|
|
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 |
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,30 @@
|
|||||||
|
**/node_modules
|
||||||
|
**/.next
|
||||||
|
**/.turbo
|
||||||
|
**/dist
|
||||||
|
**/build
|
||||||
|
**/.git
|
||||||
|
**/.gitignore
|
||||||
|
**/.env
|
||||||
|
**/.env.local
|
||||||
|
**/.env.*.local
|
||||||
|
**/npm-debug.log
|
||||||
|
**/yarn-debug.log
|
||||||
|
**/yarn-error.log
|
||||||
|
**/*.log
|
||||||
|
**/cypress/videos
|
||||||
|
**/cypress/screenshots
|
||||||
|
**/.DS_Store
|
||||||
|
**/Thumbs.db
|
||||||
|
**/.idea
|
||||||
|
**/.vscode
|
||||||
|
**/coverage
|
||||||
|
**/.cache
|
||||||
|
**/.eslintcache
|
||||||
|
**/test-results
|
||||||
|
**/playwright-report
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
README.md
|
||||||
|
docs
|
||||||
|
*.pdf
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
NIXPACKS_NODE_VERSION=22
|
||||||
|
NEXT_PUBLIC_API_URL=http://reparee.test
|
||||||
@@ -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" />`.
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# Garage dashboard (garage-erp) — Coolify deploy
|
||||||
|
|
||||||
|
Domain: **tenant.reparee.com**
|
||||||
|
Build: Docker (multi-stage), Next.js standalone output
|
||||||
|
Port: **3000** inside container; Coolify maps to 80/443 + TLS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. New Application in Coolify
|
||||||
|
|
||||||
|
1. **+ New Resource → Application → Public Repository** (or GitHub App).
|
||||||
|
2. Repo: this monorepo. Branch: `main` (or whatever).
|
||||||
|
3. **Build Pack: Dockerfile**.
|
||||||
|
4. **Base Directory**: `garage-erp` (where the Dockerfile lives — relative to repo root).
|
||||||
|
- If `garage-erp` IS the repo root, leave blank.
|
||||||
|
5. **Dockerfile Location**: `Dockerfile` (default).
|
||||||
|
6. **Port**: `3000`.
|
||||||
|
|
||||||
|
## 2. Environment variables
|
||||||
|
|
||||||
|
Coolify → Application → **Environment Variables**. Add:
|
||||||
|
|
||||||
|
| Key | Value |
|
||||||
|
|---|---|
|
||||||
|
| `NEXT_PUBLIC_API_URL` | `https://api.reparee.com` |
|
||||||
|
| `NEXT_PUBLIC_SAAS_URL` | `https://reparee.com` |
|
||||||
|
| `NEXT_PUBLIC_GARAGE_HOST_PATTERN` | `*.reparee.com` |
|
||||||
|
| `NODE_ENV` | `production` |
|
||||||
|
| `HOSTNAME` | `0.0.0.0` |
|
||||||
|
| `PORT` | `3000` |
|
||||||
|
| `NEXT_TELEMETRY_DISABLED` | `1` |
|
||||||
|
|
||||||
|
> `NEXT_PUBLIC_*` values are **baked into the JS bundle at build time**. Changing them requires a redeploy, not just a restart.
|
||||||
|
|
||||||
|
## 3. Domain + TLS
|
||||||
|
|
||||||
|
Coolify → Application → **Domains** → add `https://tenant.reparee.com`. Coolify auto-provisions Let's Encrypt cert. DNS A record must already point to the Coolify server's public IP.
|
||||||
|
|
||||||
|
## 4. Healthcheck
|
||||||
|
|
||||||
|
Coolify → Application → **Healthcheck**:
|
||||||
|
|
||||||
|
- **Path**: `/api/proxy/health` — set this once the backend is reachable; otherwise `/` works for the first deploy.
|
||||||
|
- **Port**: `3000`
|
||||||
|
- **Interval**: 30s
|
||||||
|
- **Timeout**: 10s
|
||||||
|
|
||||||
|
## 5. Build options
|
||||||
|
|
||||||
|
- **Build pack**: Dockerfile
|
||||||
|
- **Custom build command**: leave blank (Dockerfile handles it)
|
||||||
|
- **Build args**: none required; all envs are runtime
|
||||||
|
|
||||||
|
## 6. Deploy
|
||||||
|
|
||||||
|
Click **Deploy**. Watch build logs:
|
||||||
|
|
||||||
|
- Stage 1 (`deps`): `pnpm install --frozen-lockfile` — ~2-4 min.
|
||||||
|
- Stage 3 (`builder`): `pnpm --filter @garage/dashboard build` — ~3-6 min. Watch for Next.js trace warnings; they are non-fatal.
|
||||||
|
- Stage 4 (`runner`): copies standalone output; tiny.
|
||||||
|
|
||||||
|
First build is slow. Subsequent builds reuse Docker layer cache.
|
||||||
|
|
||||||
|
## 7. Smoke test
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -I https://tenant.reparee.com
|
||||||
|
# → 200 OK + Set-Cookie not yet set (no session)
|
||||||
|
|
||||||
|
# Activation: full flow goes SaaS → /activate/handoff/{token}?ws=&api=
|
||||||
|
# Cookies expected after redirect: auth_token, auth_user, workspace_uuid, api_base_url
|
||||||
|
```
|
||||||
|
|
||||||
|
## 8. CORS / cookies sanity
|
||||||
|
|
||||||
|
The dashboard only sets cookies on its own origin (`tenant.reparee.com`). The Next.js server proxy at `/api/proxy/*` strips upstream `Set-Cookie` headers — Laravel cookies never reach the browser. Workspace context is read from cookies on every server-side proxy call.
|
||||||
|
|
||||||
|
Verify in browser DevTools after handoff:
|
||||||
|
|
||||||
|
- 4 cookies on `tenant.reparee.com`, all HttpOnly + SameSite=Strict + Secure.
|
||||||
|
- Network tab: all `XHR/fetch` go to `tenant.reparee.com/api/proxy/...`. **Zero direct calls** to `api.reparee.com` from the browser.
|
||||||
|
|
||||||
|
## 9. Logs
|
||||||
|
|
||||||
|
Coolify → Application → **Logs** tab streams container stdout/stderr. Next.js logs requests as `GET / 200 in 45ms` etc.
|
||||||
|
|
||||||
|
## 10. Rollback
|
||||||
|
|
||||||
|
Coolify → **Deployments** tab → pick a previous successful deployment → **Redeploy**.
|
||||||
|
|
||||||
|
## 11. Notes on monorepo
|
||||||
|
|
||||||
|
- The Dockerfile builds **only** the `@garage/dashboard` app. `@garage/api` is built as part of dashboard's `prebuild` hook (it generates OpenAPI types from `postman/collection.json`).
|
||||||
|
- If you split apps later (e.g. a separate admin app), copy the Dockerfile and change the `--filter @garage/dashboard` line.
|
||||||
|
- `output: 'standalone'` in `apps/dashboard/next.config.mjs` is required for the runner stage to work. Do not remove.
|
||||||
|
|
||||||
|
## 12. Cypress / e2e
|
||||||
|
|
||||||
|
Out of scope for the runtime container. If you want CI e2e runs:
|
||||||
|
|
||||||
|
- Use Coolify's **GitHub Actions integration** to run `pnpm test:e2e` in CI before the deploy webhook fires.
|
||||||
|
- Update `apps/dashboard/cypress.config.ts` to read `baseUrl` from env (currently hard-coded to `https://newgarage.yslootahtech.com`).
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
# Multi-stage Dockerfile for garage-erp dashboard (Coolify).
|
||||||
|
# Monorepo: turborepo + pnpm; @garage/dashboard depends on @garage/api.
|
||||||
|
# Build context = garage-erp/ (repo root for this app).
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# Stage 1: base — pnpm via corepack, shared layer
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
FROM node:22-alpine AS base
|
||||||
|
RUN corepack enable && corepack prepare pnpm@9.0.0 --activate
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# Stage 2: deps — install all workspace deps
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
FROM base AS deps
|
||||||
|
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
|
||||||
|
COPY apps/dashboard/package.json ./apps/dashboard/
|
||||||
|
COPY packages/api/package.json ./packages/api/
|
||||||
|
COPY packages/ui/package.json ./packages/ui/
|
||||||
|
COPY packages/eslint-config/package.json ./packages/eslint-config/
|
||||||
|
COPY packages/typescript-config/package.json ./packages/typescript-config/
|
||||||
|
# Force dev deps even when Coolify injects NODE_ENV=production at build time.
|
||||||
|
# Tailwind / postcss / next types are devDependencies — required by `next build`.
|
||||||
|
RUN NODE_ENV=development pnpm install --frozen-lockfile --prod=false
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# Stage 3: builder — build dashboard with standalone output
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
FROM base AS builder
|
||||||
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
|
COPY --from=deps /app/apps/dashboard/node_modules ./apps/dashboard/node_modules
|
||||||
|
COPY --from=deps /app/packages/api/node_modules ./packages/api/node_modules
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Build only the dashboard (turbo handles @garage/api codegen via prebuild hook)
|
||||||
|
RUN pnpm --filter @garage/dashboard build
|
||||||
|
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
# Stage 4: runner — minimal runtime, standalone Next.js
|
||||||
|
# ────────────────────────────────────────────────────────────
|
||||||
|
FROM node:22-alpine AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV HOSTNAME=0.0.0.0
|
||||||
|
|
||||||
|
# curl for Coolify healthcheck (busybox wget prefers IPv6 ::1 and fails)
|
||||||
|
RUN apk add --no-cache curl
|
||||||
|
|
||||||
|
RUN addgroup --system --gid 1001 nodejs && \
|
||||||
|
adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
|
# Standalone server + traced node_modules
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/standalone ./
|
||||||
|
# Static assets
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/static ./apps/dashboard/.next/static
|
||||||
|
# Public assets (logos, etc.)
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/public ./apps/dashboard/public
|
||||||
|
|
||||||
|
USER nextjs
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
# Standalone entry is at apps/dashboard/server.js after copy
|
||||||
|
CMD ["node", "apps/dashboard/server.js"]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Fallback backend URL — only used if the per-session `api_base_url` cookie
|
||||||
|
# is not set. The SaaS → /activate/[token] handoff sets that cookie, and the
|
||||||
|
# server proxy at /api/proxy/* forwards to whatever URL it contains.
|
||||||
|
NEXT_PUBLIC_API_URL=http://localhost:8001
|
||||||
|
|
||||||
|
# Used by the "Workspace session not found" page to link back to the SaaS.
|
||||||
|
NEXT_PUBLIC_SAAS_URL=http://localhost:8000
|
||||||
|
|
||||||
|
# Image remotePatterns wildcard for SaaS-provisioned subdomains.
|
||||||
|
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Committed prod env — Next.js bakes NEXT_PUBLIC_* into the bundle at build time.
|
||||||
|
# Only public URLs here. Secrets stay in Coolify env vars (runtime).
|
||||||
|
|
||||||
|
NEXT_PUBLIC_API_URL=https://api.reparee.com
|
||||||
|
NEXT_PUBLIC_SAAS_URL=https://reparee.com
|
||||||
|
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Production env — Coolify provides these at deploy time.
|
||||||
|
|
||||||
|
# Fallback backend URL — only used if the per-session `api_base_url` cookie
|
||||||
|
# is not set. SaaS handoff sets that cookie; server proxy uses it.
|
||||||
|
NEXT_PUBLIC_API_URL=https://api.reparee.com
|
||||||
|
|
||||||
|
# Used by "Workspace session not found" page CTA back to SaaS.
|
||||||
|
NEXT_PUBLIC_SAAS_URL=https://reparee.com
|
||||||
|
|
||||||
|
# Image remotePatterns wildcard for SaaS-provisioned subdomains.
|
||||||
|
NEXT_PUBLIC_GARAGE_HOST_PATTERN=*.reparee.com
|
||||||
|
|
||||||
|
# Forces Next to bind 0.0.0.0 in Docker. Coolify normally sets this.
|
||||||
|
HOSTNAME=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
NODE_ENV=production
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
|
||||||
|
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, CalendarDaysIcon, ClipboardListIcon, ClockIcon, ListIcon } from "lucide-react"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { Button } from "@/shared/components/ui/button"
|
import { Button } from "@/shared/components/ui/button"
|
||||||
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
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",
|
||||||
@@ -21,11 +25,50 @@ const STATUS_COLORS: Record<string, string> = {
|
|||||||
|
|
||||||
export default function AppointmentsPage() {
|
export default function AppointmentsPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const [view, setView] = useState<"list" | "calendar">("list")
|
||||||
|
|
||||||
|
const viewToggle = (
|
||||||
|
<div className="flex items-center justify-end gap-1 px-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={view === "list" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setView("list")}
|
||||||
|
>
|
||||||
|
<ListIcon className="me-1 size-4" /> List
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={view === "calendar" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setView("calendar")}
|
||||||
|
>
|
||||||
|
<CalendarDaysIcon className="me-1 size-4" /> Calendar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
|
||||||
|
if (view === "calendar") {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 p-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h1 className="text-xl font-semibold">Appointments</h1>
|
||||||
|
{viewToggle}
|
||||||
|
</div>
|
||||||
|
<AppointmentsCalendarView />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{viewToggle}
|
||||||
<ResourcePage<AppointmentsClient>
|
<ResourcePage<AppointmentsClient>
|
||||||
pageTitle="Appointments"
|
pageTitle="Appointments"
|
||||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||||
|
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 }) => ({
|
||||||
@@ -77,7 +120,7 @@ export default function AppointmentsPage() {
|
|||||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||||
return (
|
return (
|
||||||
<Badge className={colorClass}>
|
<Badge className={colorClass}>
|
||||||
{status?.replace("_", " ") ?? "—"}
|
{formatEnum(status)}
|
||||||
</Badge>
|
</Badge>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -86,27 +129,20 @@ 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>
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn(),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
import { redirect } from "next/navigation"
|
"use client"
|
||||||
|
|
||||||
|
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
|
||||||
|
|
||||||
export default function CalendarsPage() {
|
export default function CalendarsPage() {
|
||||||
return redirect("/calendar/appointment/list")
|
return (
|
||||||
|
<div className="space-y-4 p-4">
|
||||||
|
<h1 className="text-xl font-semibold">Calendar</h1>
|
||||||
|
<AppointmentsCalendarView />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,69 @@
|
|||||||
|
"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 { Money } from "@/shared/components/money"
|
||||||
|
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 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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(),
|
||||||
]}
|
]}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
|||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { ServiceGroupForm } from "@/modules/service-groups/service-group-form"
|
import { ServiceGroupForm } from "@/modules/service-groups/service-group-form"
|
||||||
|
import { Money } from "@/shared/components/money"
|
||||||
import { Badge } from "@/shared/components/ui/badge"
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
import { SERVICE_GROUP_ROUTES } from "@garage/api"
|
import { SERVICE_GROUP_ROUTES } from "@garage/api"
|
||||||
import type { ServiceGroupsClient } from "@garage/api"
|
import type { ServiceGroupsClient } from "@garage/api"
|
||||||
@@ -13,6 +14,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: (
|
||||||
@@ -48,7 +51,7 @@ export default function ServiceGroupPage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const val = (row.original as any).selling_price
|
const val = (row.original as any).selling_price
|
||||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
return val != null ? <Money value={val} /> : "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,27 +3,46 @@
|
|||||||
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 { Money } from "@/shared/components/money"
|
||||||
|
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 +67,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>
|
||||||
: "—"
|
: "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -57,7 +76,7 @@ export default function ServicesPage() {
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Price" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const val = (row.original as any).selling_price
|
const val = (row.original as any).selling_price
|
||||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
return val != null ? <Money value={val} /> : "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { DashboardLayout } from "@/base/components/layout/dashboard"
|
|||||||
import { useAuth } from "@/shared/hooks/use-auth"
|
import { useAuth } from "@/shared/hooks/use-auth"
|
||||||
import { navGroups } from "@/config/navGroups"
|
import { navGroups } from "@/config/navGroups"
|
||||||
import { getAuthCookies } from "@/modules/auth/auth.actions"
|
import { getAuthCookies } from "@/modules/auth/auth.actions"
|
||||||
|
import { OnboardingGate } from "@/shared/components/onboarding-gate"
|
||||||
import { redirect } from "next/navigation"
|
import { redirect } from "next/navigation"
|
||||||
|
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ export default async function AuthenticatedLayout({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}>
|
<DashboardLayout navGroups={navGroups} logo={<Logo />} user={userInfo}>
|
||||||
{children}
|
<OnboardingGate>{children}</OnboardingGate>
|
||||||
</DashboardLayout>
|
</DashboardLayout>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { use } from "react"
|
||||||
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
|
import { TIME_SHEET_ROUTES } from "@garage/api"
|
||||||
|
import type { TimeSheetsClient } from "@garage/api"
|
||||||
|
import { ClockIcon } from "lucide-react"
|
||||||
|
|
||||||
|
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
|
||||||
|
general: "secondary",
|
||||||
|
order: "default",
|
||||||
|
task: "outline",
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(value: unknown) {
|
||||||
|
if (!value || typeof value !== "string") return "—"
|
||||||
|
return value.length >= 5 ? value.slice(0, 5) : value
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(value: unknown) {
|
||||||
|
if (!value || typeof value !== "string") return "—"
|
||||||
|
const d = new Date(value)
|
||||||
|
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCost(value: unknown) {
|
||||||
|
if (value === null || value === undefined) return "—"
|
||||||
|
const n = Number(value)
|
||||||
|
if (!Number.isFinite(n)) return "—"
|
||||||
|
return n.toFixed(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmployeeAttendancePage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id: employeeId } = use(params)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResourcePage<TimeSheetsClient>
|
||||||
|
pageTitle="Attendance"
|
||||||
|
routeKey={TIME_SHEET_ROUTES.INDEX}
|
||||||
|
getClient={(api) => api.timeSheets}
|
||||||
|
extraParams={{ employee_id: employeeId }}
|
||||||
|
header={null}
|
||||||
|
statusFilter={{
|
||||||
|
statuses: ["general", "order", "task"],
|
||||||
|
paramKey: "activity_type",
|
||||||
|
allLabel: "All",
|
||||||
|
}}
|
||||||
|
columns={() => [
|
||||||
|
{
|
||||||
|
accessorKey: "date",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ClockIcon className="size-4 text-muted-foreground" />
|
||||||
|
<span>{formatDate((row.original as any).date)}</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "clock_in",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
|
||||||
|
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "clock_out",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
|
||||||
|
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "duration",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
|
||||||
|
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "activity_type",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const type = (row.original as any).activity_type ?? "general"
|
||||||
|
return <Badge variant={ACTIVITY_VARIANT[type] ?? "secondary"}>{type}</Badge>
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "calculated_total_cost",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||||
|
cell: ({ row }) => formatCost((row.original as any).calculated_total_cost),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "note",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const v = (row.original as any).note
|
||||||
|
return v ? <span className="text-sm">{v}</span> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -28,6 +28,8 @@ export default async function layout(props: {
|
|||||||
actions={<EmployeeActions employeeId={id} />}
|
actions={<EmployeeActions employeeId={id} />}
|
||||||
tabs={[
|
tabs={[
|
||||||
{ href: `/productivity/employees/${id}`, label: 'Details' },
|
{ href: `/productivity/employees/${id}`, label: 'Details' },
|
||||||
|
{ href: `/productivity/employees/${id}/attendance`, label: 'Attendance' },
|
||||||
|
{ href: `/productivity/employees/${id}/work-history`, label: 'Work History' },
|
||||||
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { use, useState } from "react"
|
||||||
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
|
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||||
|
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||||
|
import type { JobCardsClient } from "@garage/api"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
import { WrenchIcon } from "lucide-react"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
|
const ROLE_PARAM = {
|
||||||
|
technician: "primary_technician_id",
|
||||||
|
sales: "sales_person_id",
|
||||||
|
writer: "service_writer_id",
|
||||||
|
} as const
|
||||||
|
|
||||||
|
type RoleKey = keyof typeof ROLE_PARAM
|
||||||
|
|
||||||
|
function formatDate(value: unknown) {
|
||||||
|
if (!value || typeof value !== "string") return "—"
|
||||||
|
const d = new Date(value)
|
||||||
|
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" | "destructive" {
|
||||||
|
if (!status) return "secondary"
|
||||||
|
if (status === "completed" || status === "delivered") return "default"
|
||||||
|
if (status === "cancelled") return "destructive"
|
||||||
|
return "outline"
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function EmployeeWorkHistoryPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id: employeeId } = use(params)
|
||||||
|
const router = useRouter()
|
||||||
|
const [role, setRole] = useState<RoleKey>("technician")
|
||||||
|
const paramKey = ROLE_PARAM[role]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="px-4 pt-4">
|
||||||
|
<Tabs value={role} onValueChange={(v) => setRole(v as RoleKey)}>
|
||||||
|
<TabsList variant="line">
|
||||||
|
<TabsTrigger value="technician">As Technician</TabsTrigger>
|
||||||
|
<TabsTrigger value="sales">As Sales Person</TabsTrigger>
|
||||||
|
<TabsTrigger value="writer">As Service Writer</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ResourcePage<JobCardsClient>
|
||||||
|
key={role}
|
||||||
|
pageTitle="Work History"
|
||||||
|
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search by job number, plate, customer..."
|
||||||
|
getClient={(api) => api.jobCards}
|
||||||
|
extraParams={{ [paramKey]: employeeId }}
|
||||||
|
header={null}
|
||||||
|
onRowClick={(row) => router.push(`/sales/job-cards/${(row as any).id}`)}
|
||||||
|
columns={() => [
|
||||||
|
{
|
||||||
|
accessorKey: "order_number",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Job #" />,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<WrenchIcon className="size-4 text-muted-foreground" />
|
||||||
|
<span className="font-mono text-xs">{(row.original as any).order_number ?? "—"}</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "customer",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const c = (row.original as any).customer
|
||||||
|
if (!c) return "—"
|
||||||
|
return `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() || c.email || "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "vehicle",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const v = (row.original as any).vehicle
|
||||||
|
if (!v) return "—"
|
||||||
|
const display = `${v.make ?? ""} ${v.model ?? ""}`.trim()
|
||||||
|
return display || v.license_plate || "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "status",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const s = (row.original as any).status
|
||||||
|
return s ? <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "created_at",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Opened" />,
|
||||||
|
cell: ({ row }) => formatDate((row.original as any).created_at),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,21 +1,71 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useMemo, useState } from "react"
|
||||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||||
import FormDialog from "@/shared/components/form-dialog"
|
import FormDialog from "@/shared/components/form-dialog"
|
||||||
import { EmployeeForm } from "@/modules/employees/employee-form"
|
import { EmployeeForm } from "@/modules/employees/employee-form"
|
||||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||||
import type { EmployeesClient } from "@garage/api"
|
import type { EmployeesClient } from "@garage/api"
|
||||||
|
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
||||||
|
import { Badge } from "@/shared/components/ui/badge"
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/shared/components/ui/select"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
|
const TYPE_OPTIONS = [
|
||||||
|
{ value: "all", label: "All types" },
|
||||||
|
{ value: "employee", label: "Employee" },
|
||||||
|
{ value: "sales_person", label: "Sales Person" },
|
||||||
|
]
|
||||||
|
|
||||||
|
function initialsOf(first?: string | null, last?: string | null) {
|
||||||
|
const f = (first ?? "").trim()[0] ?? ""
|
||||||
|
const l = (last ?? "").trim()[0] ?? ""
|
||||||
|
return (f + l).toUpperCase() || "?"
|
||||||
|
}
|
||||||
|
|
||||||
export default function EmployeesPage() {
|
export default function EmployeesPage() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const [typeFilter, setTypeFilter] = useState<string>("all")
|
||||||
|
|
||||||
|
const extraParams = useMemo(() => {
|
||||||
|
if (typeFilter === "all") return undefined
|
||||||
|
return { type: typeFilter }
|
||||||
|
}, [typeFilter])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResourcePage<EmployeesClient>
|
<ResourcePage<EmployeesClient>
|
||||||
pageTitle="Employees"
|
pageTitle="Employees"
|
||||||
routeKey={EMPLOYEE_ROUTES.INDEX}
|
routeKey={EMPLOYEE_ROUTES.INDEX}
|
||||||
|
searchable
|
||||||
|
searchPlaceholder="Search employees..."
|
||||||
|
statusFilter={{ statuses: ["active", "inactive"] }}
|
||||||
|
extraParams={extraParams}
|
||||||
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}`)}
|
||||||
|
tableHeader={() => (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Select value={typeFilter} onValueChange={setTypeFilter}>
|
||||||
|
<SelectTrigger className="w-44">
|
||||||
|
<SelectValue placeholder="All types" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{TYPE_OPTIONS.map((o) => (
|
||||||
|
<SelectItem key={o.value} value={o.value}>
|
||||||
|
{o.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Employee">
|
<FormDialog title="Employee">
|
||||||
@@ -34,8 +84,16 @@ export default function EmployeesPage() {
|
|||||||
accessorKey: "first_name",
|
accessorKey: "first_name",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const { first_name, last_name } = row.original
|
const r = row.original as any
|
||||||
return `${first_name ?? ""} ${last_name ?? ""}`.trim()
|
const fullName = `${r.first_name ?? ""} ${r.last_name ?? ""}`.trim() || "—"
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Avatar size="sm">
|
||||||
|
<AvatarFallback>{initialsOf(r.first_name, r.last_name)}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<span className="font-medium">{fullName}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -45,15 +103,32 @@ export default function EmployeesPage() {
|
|||||||
{
|
{
|
||||||
accessorKey: "phone",
|
accessorKey: "phone",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
|
||||||
|
cell: ({ row }) => (row.original as any).phone ?? "—",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "position",
|
accessorKey: "type",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Position" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const t = (row.original as any).type
|
||||||
|
if (!t) return "—"
|
||||||
|
return <Badge variant="outline">{t === "sales_person" ? "Sales Person" : "Employee"}</Badge>
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "department",
|
accessorKey: "department",
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||||
cell: ({ row }) => (row.original as any).department?.name ?? "—",
|
cell: ({ row }) => {
|
||||||
|
const d = (row.original as any).department?.name
|
||||||
|
return d ? <Badge variant="secondary">{d}</Badge> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "role",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Role" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const r = (row.original as any).role?.name
|
||||||
|
return r ? <Badge variant="secondary">{r}</Badge> : "—"
|
||||||
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "status",
|
accessorKey: "status",
|
||||||
@@ -62,7 +137,7 @@ export default function EmployeesPage() {
|
|||||||
const status = row.original.status
|
const status = row.original.status
|
||||||
return (
|
return (
|
||||||
<span className={status === "active" ? "text-green-600" : "text-red-600"}>
|
<span className={status === "active" ? "text-green-600" : "text-red-600"}>
|
||||||
{status}
|
{formatEnum(status)}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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,36 @@
|
|||||||
"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, formatEnum } 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, Printer } from "lucide-react"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
|
||||||
export default function BillsPage() {
|
export default function BillsPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
|
|
||||||
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,41 +47,73 @@ 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"}>
|
||||||
|
{formatEnum(status)}
|
||||||
|
</Badge>
|
||||||
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("bill", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,34 @@ 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, Printer } from "lucide-react"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
|
||||||
export default function ExpensesPage() {
|
export default function ExpensesPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
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,39 +54,62 @@ 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>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
actionsColumn({
|
||||||
accessorKey: "created_at",
|
extraItems: (row) => [
|
||||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
{
|
||||||
cell: ({ row }) => {
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
const val = (row.original as any).created_at
|
icon: Printer,
|
||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
onClick: (r) => print("expense", String(r.id), "print"),
|
||||||
},
|
},
|
||||||
},
|
],
|
||||||
actionsColumn(),
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||||
|
import { getServerApi } from '@garage/api/server'
|
||||||
|
import { PaymentMadeActions } from '@/modules/payment-mades/payment-made-actions'
|
||||||
|
import { BanknoteIcon } from 'lucide-react'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
export default async function PaymentMadeDetailLayout(props: {
|
||||||
|
params: Promise<{ id: string }>
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
const { id } = await props.params
|
||||||
|
const api = await getServerApi()
|
||||||
|
const payment = await api.paymentMades.show(id)
|
||||||
|
const data = (payment as any)?.data ?? payment
|
||||||
|
const title = data?.payment_number || 'Payment Details'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardDetailsPage
|
||||||
|
title={title}
|
||||||
|
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
|
||||||
|
icon={<BanknoteIcon className="size-5" />}
|
||||||
|
backHref="/purchase/payments-made"
|
||||||
|
actions={<PaymentMadeActions paymentId={id} />}
|
||||||
|
tabs={[
|
||||||
|
{
|
||||||
|
href: `/purchase/payments-made/${id}`,
|
||||||
|
label: 'Details',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{props.children}
|
||||||
|
</DashboardDetailsPage>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { getServerApi } from '@garage/api/server'
|
||||||
|
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||||
|
import {
|
||||||
|
BadgeDollarSignIcon,
|
||||||
|
BriefcaseIcon,
|
||||||
|
Building2Icon,
|
||||||
|
CalendarIcon,
|
||||||
|
CreditCardIcon,
|
||||||
|
HashIcon,
|
||||||
|
} from 'lucide-react'
|
||||||
|
|
||||||
|
export default async function PaymentMadeDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await props.params
|
||||||
|
const api = await getServerApi()
|
||||||
|
const payment = await api.paymentMades.show(id)
|
||||||
|
const data = (payment as any)?.data ?? payment
|
||||||
|
|
||||||
|
if (!data) {
|
||||||
|
return <div className="text-muted-foreground">Payment not found.</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = data.payment_made != null
|
||||||
|
? Number(data.payment_made).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
const paymentDate = data.payment_date
|
||||||
|
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
const vendorLabel = data.vendor?.company_name
|
||||||
|
?? (data.vendor?.first_name ? `${data.vendor.first_name} ${data.vendor.last_name ?? ''}`.trim() : null)
|
||||||
|
?? data.vendor_name
|
||||||
|
?? (data.employee?.first_name ? `${data.employee.first_name} ${data.employee.last_name ?? ''}`.trim() : null)
|
||||||
|
?? data.employee_name
|
||||||
|
?? '—'
|
||||||
|
|
||||||
|
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardPage header={null}>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<HashIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Number</p>
|
||||||
|
<p className="font-medium">{data.payment_number || '—'}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<Building2Icon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Vendor / Employee</p>
|
||||||
|
<p className="font-medium">{vendorLabel}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<BriefcaseIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment For</p>
|
||||||
|
<p className="font-medium capitalize">{data.payment_for || '—'}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Amount</p>
|
||||||
|
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Mode</p>
|
||||||
|
<p className="font-medium capitalize">{paymentMode}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<CalendarIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Date</p>
|
||||||
|
<p className="font-medium">{paymentDate}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{data.payment_reference && (
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<HashIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Reference</p>
|
||||||
|
<p className="font-medium">{data.payment_reference}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{data.paid_through && (
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Paid Through</p>
|
||||||
|
<p className="font-medium">{data.paid_through}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{data.notes && (
|
||||||
|
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
|
||||||
|
<p className="text-xs text-muted-foreground mb-1">Notes</p>
|
||||||
|
<p className="text-sm">{data.notes}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DashboardPage>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useRef } from "react"
|
import { useState, useRef } from "react"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||||
import {
|
import {
|
||||||
Paperclip,
|
Paperclip,
|
||||||
@@ -32,8 +33,12 @@ 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, Printer } from "lucide-react"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
|
||||||
// ── Attachment helpers ──
|
// ── Attachment helpers ──
|
||||||
|
|
||||||
@@ -208,10 +213,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
|
||||||
@@ -220,6 +228,8 @@ type PaymentMadeItem = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PaymentsMadePage() {
|
export default function PaymentsMadePage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
const [attachmentTarget, setAttachmentTarget] = useState<{
|
const [attachmentTarget, setAttachmentTarget] = useState<{
|
||||||
id: string
|
id: string
|
||||||
ref: string
|
ref: string
|
||||||
@@ -230,14 +240,21 @@ 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 }) => ({
|
onRowClick={(row) => router.push(`/purchase/payments-made/${(row as any).id}`)}
|
||||||
|
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 +279,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 +342,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>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -360,7 +398,15 @@ export default function PaymentsMadePage() {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("payment_made", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -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,37 @@
|
|||||||
"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, Printer } from "lucide-react"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
|
||||||
export default function PurchaseOrdersPage() {
|
export default function PurchaseOrdersPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
|
|
||||||
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 +50,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",
|
||||||
@@ -65,7 +85,15 @@ export default function PurchaseOrdersPage() {
|
|||||||
return val ? new Date(val).toLocaleDateString() : "—"
|
return val ? new Date(val).toLocaleDateString() : "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("purchase_order", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,14 +5,21 @@ 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"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
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 +42,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",
|
||||||
@@ -55,7 +80,7 @@ export default function VendorCreditsPage() {
|
|||||||
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 === "closed" ? "secondary" : "default"}>{status || "—"}</Badge>
|
return <Badge variant={status === "closed" ? "secondary" : "default"}>{formatEnum(status)}</Badge>
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn(),
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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()
|
||||||
|
// Guard the fetch: a failed request (404/401/5xx) must not throw and crash
|
||||||
|
// the whole route — render the chrome with a fallback title instead.
|
||||||
|
let vendor: Record<string, any> | undefined
|
||||||
|
try {
|
||||||
|
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||||
|
vendor = response?.data
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load vendor ${id} (layout):`, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
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,24 @@
|
|||||||
|
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.
|
||||||
|
// Guard the fetch: a failed request (404/401/5xx) must degrade gracefully
|
||||||
|
// instead of throwing and white-screening the whole route.
|
||||||
|
let vendor: Record<string, any> | undefined
|
||||||
|
try {
|
||||||
|
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||||
|
vendor = response?.data
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load vendor ${id}:`, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
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,94 @@
|
|||||||
|
"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"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
import { Printer } from "lucide-react"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
|
||||||
|
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()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
|
|
||||||
|
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 ?? ""] ?? ""}>
|
||||||
|
{formatEnum(status)}
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "date",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||||
|
},
|
||||||
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("credit_note", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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 }) => [
|
||||||
|
|||||||
@@ -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,31 @@
|
|||||||
"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, Printer, UserIcon } from 'lucide-react'
|
||||||
import { Button } from '@/shared/components/ui/button'
|
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||||
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()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
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 +46,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 +61,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",
|
||||||
@@ -84,7 +111,15 @@ export default function EstimatesPage() {
|
|||||||
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
|
return item.created_at ? new Date(item.created_at).toLocaleDateString() : "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("estimate", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
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,36 +1,101 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { Car, Printer, UserIcon } from "lucide-react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
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() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<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 +109,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,29 +174,81 @@ 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>
|
||||||
|
)
|
||||||
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
{
|
||||||
|
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({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("invoice", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
"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"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
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 +31,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 +83,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>
|
||||||
@@ -89,7 +126,7 @@ export default function JobCardAppointmentsPage({
|
|||||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||||
return (
|
return (
|
||||||
<Badge className={colorClass}>
|
<Badge className={colorClass}>
|
||||||
{status?.replace("_", " ") ?? "—"}
|
{formatEnum(status)}
|
||||||
</Badge>
|
</Badge>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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 } 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,6 +99,7 @@ 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.")
|
||||||
@@ -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) {
|
||||||
|
|||||||
@@ -6,9 +6,13 @@ 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"
|
||||||
|
import { formatEnum } from "@/shared/utils/formatters"
|
||||||
|
|
||||||
export default function JobCardBillsPage({
|
export default function JobCardBillsPage({
|
||||||
params,
|
params,
|
||||||
@@ -25,6 +29,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 +53,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 +71,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",
|
||||||
@@ -78,7 +103,7 @@ export default function JobCardBillsPage({
|
|||||||
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"}>{formatEnum(status)}</Badge>
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn(),
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
"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 { Money } from "@/shared/components/money"
|
||||||
|
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 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "discount_amount",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const val = row.original.discount_amount
|
||||||
|
return val != null && val > 0 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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"
|
||||||
@@ -23,7 +24,9 @@ import { toast } from "sonner"
|
|||||||
import { Ellipsis, Plus } from "lucide-react"
|
import { Ellipsis, Plus } from "lucide-react"
|
||||||
import type { ColumnDef } from "@tanstack/react-table"
|
import type { ColumnDef } from "@tanstack/react-table"
|
||||||
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
||||||
|
import { Money } from "@/shared/components/money"
|
||||||
import { formatDate } from "@/shared/utils/formatters"
|
import { formatDate } from "@/shared/utils/formatters"
|
||||||
|
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||||
|
|
||||||
export default function JobCardPartsPage({
|
export default function JobCardPartsPage({
|
||||||
params,
|
params,
|
||||||
@@ -33,7 +36,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 +45,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({
|
||||||
@@ -89,13 +94,21 @@ export default function JobCardPartsPage({
|
|||||||
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const val = row.original.rate
|
const val = row.original.rate
|
||||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
return val != null ? <Money value={val} /> : "—"
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
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 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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,242 @@
|
|||||||
|
"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 { Money } from "@/shared/components/money"
|
||||||
|
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 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "labor_rate.title",
|
||||||
|
header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const lr = row.original.labor_rate
|
||||||
|
return lr ? <span>{lr.title} (<Money value={lr.rate} />)</span> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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 ? <Money value={val} /> : "—"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
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,14 @@ 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, Printer } from 'lucide-react'
|
||||||
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
|
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||||
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 +35,113 @@ 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 { print, isPrinting } = useDocumentPrint()
|
||||||
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({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("job_card", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
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>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||||
|
import { getServerApi } from '@garage/api/server'
|
||||||
|
import { PaymentReceivedActions } from '@/modules/payment-received/payment-received-actions'
|
||||||
|
import { BanknoteIcon } from 'lucide-react'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
export default async function PaymentReceivedDetailLayout(props: {
|
||||||
|
params: Promise<{ id: string }>
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
const { id } = await props.params
|
||||||
|
const api = await getServerApi()
|
||||||
|
const payment = await api.paymentReceived.show(id)
|
||||||
|
const data = (payment as any)?.data ?? payment
|
||||||
|
const title = data?.payment_number || 'Payment Details'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardDetailsPage
|
||||||
|
title={title}
|
||||||
|
description={data?.payment_number ? `Payment #: ${data.payment_number}` : undefined}
|
||||||
|
icon={<BanknoteIcon className="size-5" />}
|
||||||
|
backHref="/sales/payment-received"
|
||||||
|
actions={<PaymentReceivedActions paymentId={id} />}
|
||||||
|
tabs={[
|
||||||
|
{
|
||||||
|
href: `/sales/payment-received/${id}`,
|
||||||
|
label: 'Details',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{props.children}
|
||||||
|
</DashboardDetailsPage>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { getServerApi } from '@garage/api/server'
|
||||||
|
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||||
|
import {
|
||||||
|
BadgeDollarSignIcon,
|
||||||
|
CalendarIcon,
|
||||||
|
ClipboardListIcon,
|
||||||
|
CreditCardIcon,
|
||||||
|
HashIcon,
|
||||||
|
UserIcon,
|
||||||
|
} from 'lucide-react'
|
||||||
|
|
||||||
|
export default async function PaymentReceivedDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await props.params
|
||||||
|
const api = await getServerApi()
|
||||||
|
const payment = await api.paymentReceived.show(id)
|
||||||
|
const data = (payment as any)?.data ?? payment
|
||||||
|
|
||||||
|
if (!data) {
|
||||||
|
return <div className="text-muted-foreground">Payment not found.</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = data.amount_received != null
|
||||||
|
? Number(data.amount_received).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
const paymentDate = data.payment_date
|
||||||
|
? new Date(data.payment_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
const customerName = data.customer?.first_name
|
||||||
|
? `${data.customer.first_name} ${data.customer.last_name ?? ''}`.trim()
|
||||||
|
: data.customer?.company_name ?? data.customer_name ?? '—'
|
||||||
|
|
||||||
|
const jobCardLabel = data.job_card?.title ?? data.job_card_name ?? '—'
|
||||||
|
const paymentMode = data.payment_mode?.title ?? data.payment_mode?.name ?? data.payment_mode_name ?? '—'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardPage header={null}>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<HashIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Number</p>
|
||||||
|
<p className="font-medium">{data.payment_number || '—'}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<UserIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Customer</p>
|
||||||
|
<p className="font-medium">{customerName}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<ClipboardListIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Job Card</p>
|
||||||
|
<p className="font-medium">{jobCardLabel}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<BadgeDollarSignIcon className="size-5 text-emerald-600" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Amount Received</p>
|
||||||
|
<p className="font-semibold text-emerald-700 dark:text-emerald-400">{amount}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<CreditCardIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Mode</p>
|
||||||
|
<p className="font-medium capitalize">{paymentMode}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 rounded-lg border p-4">
|
||||||
|
<CalendarIcon className="size-5 text-muted-foreground" />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Payment Date</p>
|
||||||
|
<p className="font-medium">{paymentDate}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{data.note && (
|
||||||
|
<div className="sm:col-span-2 lg:col-span-3 rounded-lg border p-4">
|
||||||
|
<p className="text-xs text-muted-foreground mb-1">Note</p>
|
||||||
|
<p className="text-sm">{data.note}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DashboardPage>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -10,9 +10,14 @@ import {
|
|||||||
CalendarIcon,
|
CalendarIcon,
|
||||||
CreditCardIcon,
|
CreditCardIcon,
|
||||||
HashIcon,
|
HashIcon,
|
||||||
|
Printer,
|
||||||
UserIcon,
|
UserIcon,
|
||||||
ClipboardListIcon,
|
ClipboardListIcon,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
|
import { useRouter } from "next/navigation"
|
||||||
|
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||||
|
import { getFullName } from "@/shared/utils/getFullName"
|
||||||
|
import { RelationLink } from "@/shared/components/relation-link"
|
||||||
|
|
||||||
type PaymentReceivedItem = {
|
type PaymentReceivedItem = {
|
||||||
id: number
|
id: number
|
||||||
@@ -29,13 +34,19 @@ type PaymentReceivedItem = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function PaymentReceivedPage() {
|
export default function PaymentReceivedPage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const { print, isPrinting } = useDocumentPrint()
|
||||||
|
|
||||||
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),
|
||||||
})}
|
})}
|
||||||
|
onRowClick={(row) => router.push(`/sales/payment-received/${(row as any).id}`)}
|
||||||
headerProps={({ invalidateQuery }) => ({
|
headerProps={({ invalidateQuery }) => ({
|
||||||
actions: (
|
actions: (
|
||||||
<FormDialog title="Record Payment">
|
<FormDialog title="Record Payment">
|
||||||
@@ -63,29 +74,33 @@ 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 +126,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>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -158,7 +173,15 @@ export default function PaymentReceivedPage() {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actionsColumn(),
|
actionsColumn({
|
||||||
|
extraItems: (row) => [
|
||||||
|
{
|
||||||
|
label: isPrinting ? "Printing..." : "Print",
|
||||||
|
icon: Printer,
|
||||||
|
onClick: (r) => print("payment_received", String(r.id), "print"),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -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",
|
||||||
@@ -142,31 +198,25 @@ export default function VehicleMileagePage() {
|
|||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
|
|
||||||
|
|
||||||
<DashboardPage
|
|
||||||
headerProps={{
|
|
||||||
title: 'Mileage',
|
|
||||||
actions: (
|
|
||||||
<Button onClick={handleCreate}>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
Add Mileage
|
|
||||||
</Button>
|
|
||||||
),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
|
|
||||||
<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,41 +129,48 @@ export default function VehicleOwnersPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<DashboardPage headerProps={{
|
|
||||||
title: "Owners",
|
|
||||||
actions: (
|
|
||||||
<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,290 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react"
|
||||||
|
import Link from "next/link"
|
||||||
|
import { useParams } from "next/navigation"
|
||||||
|
import { ChevronLeft, Pencil, Plus, Save, 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 [name, setName] = useState("")
|
||||||
|
const [description, setDescription] = useState("")
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
|
||||||
|
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)
|
||||||
|
setName(res.data.name ?? "")
|
||||||
|
setDescription(res.data.description ?? "")
|
||||||
|
} 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 saveTemplate = async () => {
|
||||||
|
if (!template) return
|
||||||
|
setSaving(true)
|
||||||
|
try {
|
||||||
|
const res = await api.inspectionTemplates.update(template.id, { name, description })
|
||||||
|
setTemplate(res.data)
|
||||||
|
toast.success("Template saved")
|
||||||
|
} catch (e: any) {
|
||||||
|
toast.error(e?.message ?? "Failed to save")
|
||||||
|
} finally {
|
||||||
|
setSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const addSection = async () => {
|
||||||
|
if (!template) return
|
||||||
|
const name = await prompt({
|
||||||
|
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
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.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
|
||||||
|
value={description}
|
||||||
|
rows={2}
|
||||||
|
onChange={(e) => setDescription(e.target.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 className="sticky bottom-0 flex justify-end gap-2 border-t bg-background py-3">
|
||||||
|
<Button onClick={saveTemplate} disabled={saving}>
|
||||||
|
<Save className="size-4 mr-1" />
|
||||||
|
{saving ? "Saving…" : "Save"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,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: (
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import Link from "next/link"
|
||||||
|
import { AlertCircle, ShieldCheck } from "lucide-react"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Error UI for failed activation handoffs. The success path is handled by
|
||||||
|
* the sibling route.ts handler at /activate/[token] — it sets cookies on the
|
||||||
|
* response and redirects to "/". Errors redirect here with ?reason=… in the
|
||||||
|
* query string.
|
||||||
|
*
|
||||||
|
* The route.ts file takes precedence over this page for matching requests,
|
||||||
|
* but the page is still reachable via a redirect to
|
||||||
|
* /activate/[token]?error=1&reason=…
|
||||||
|
*/
|
||||||
|
export default async function ActivateErrorPage(props: {
|
||||||
|
searchParams: Promise<{ reason?: string; error?: string }>
|
||||||
|
}) {
|
||||||
|
const { reason } = await props.searchParams
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
|
||||||
|
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
|
||||||
|
<AlertCircle className="size-12 mx-auto text-rose-500" />
|
||||||
|
<h1 className="text-lg font-semibold">Activation failed</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{reason ?? "Could not exchange the handoff token."}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
|
||||||
|
<ShieldCheck className="size-3.5" />
|
||||||
|
Re-open the garage from the SaaS dashboard to get a fresh link.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
|
||||||
|
className="inline-block text-sm underline text-primary"
|
||||||
|
>
|
||||||
|
Back to SaaS
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SaaS → garage-erp handoff landing.
|
||||||
|
*
|
||||||
|
* URL shape:
|
||||||
|
* /activate/{handoff_token}?ws={workspace_uuid}&api={backend_url}
|
||||||
|
*
|
||||||
|
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
|
||||||
|
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
|
||||||
|
* api_base_url) on the redirect response and lands the user on /.
|
||||||
|
*
|
||||||
|
* Implemented as a Route Handler (not a Page) because Next.js disallows
|
||||||
|
* cookie writes inside Server Components — only Server Actions and Route
|
||||||
|
* Handlers can mutate cookies.
|
||||||
|
*/
|
||||||
|
export async function GET(
|
||||||
|
req: NextRequest,
|
||||||
|
ctx: { params: Promise<{ token: string }> },
|
||||||
|
) {
|
||||||
|
const { token } = await ctx.params
|
||||||
|
const url = new URL(req.url)
|
||||||
|
const ws = url.searchParams.get("ws")
|
||||||
|
const api = url.searchParams.get("api")
|
||||||
|
|
||||||
|
if (!ws || !api) {
|
||||||
|
return redirectToError(req, "Activation link is missing workspace or backend URL.")
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsed: URL
|
||||||
|
try {
|
||||||
|
parsed = new URL(api)
|
||||||
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||||
|
throw new Error("Backend URL must be http(s).")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return redirectToError(req, "Activation link has a malformed backend URL.")
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiBase = parsed.toString().replace(/\/$/, "")
|
||||||
|
const endpoint = `${apiBase}/api/saas/handoff/exchange`
|
||||||
|
|
||||||
|
let response: Response
|
||||||
|
try {
|
||||||
|
response = await fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
cache: "no-store",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "application/json",
|
||||||
|
"X-Workspace-UUID": ws,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
handoff_token: token,
|
||||||
|
saas_workspace_uuid: ws,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload: { token?: string; user?: any; message?: string } = {}
|
||||||
|
try {
|
||||||
|
payload = await response.json()
|
||||||
|
} catch {
|
||||||
|
// body is not JSON — fall through to error path
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || !payload.token || !payload.user) {
|
||||||
|
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const dest = new URL("/", req.url)
|
||||||
|
const res = NextResponse.redirect(dest, 302)
|
||||||
|
|
||||||
|
const isProd = process.env.NODE_ENV === "production"
|
||||||
|
const sevenDays = 60 * 60 * 24 * 7
|
||||||
|
const cookieOptions = {
|
||||||
|
path: "/",
|
||||||
|
sameSite: "strict" as const,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: isProd,
|
||||||
|
maxAge: sevenDays,
|
||||||
|
}
|
||||||
|
|
||||||
|
res.cookies.set("auth_token", payload.token, cookieOptions)
|
||||||
|
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
|
||||||
|
res.cookies.set("workspace_uuid", ws, cookieOptions)
|
||||||
|
res.cookies.set("api_base_url", apiBase, cookieOptions)
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirectToError(req: NextRequest, reason: string) {
|
||||||
|
const url = new URL("/activate/error", req.url)
|
||||||
|
url.searchParams.set("reason", reason)
|
||||||
|
return NextResponse.redirect(url, 302)
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import Link from "next/link"
|
||||||
|
import { AlertCircle, ShieldCheck } from "lucide-react"
|
||||||
|
|
||||||
|
export default async function ActivateErrorPage(props: {
|
||||||
|
searchParams: Promise<{ reason?: string }>
|
||||||
|
}) {
|
||||||
|
const { reason } = await props.searchParams
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-50 to-gray-100 p-6">
|
||||||
|
<div className="max-w-md w-full text-center space-y-3 bg-white rounded-xl shadow-sm border p-8">
|
||||||
|
<AlertCircle className="size-12 mx-auto text-rose-500" />
|
||||||
|
<h1 className="text-lg font-semibold">Activation failed</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{reason ?? "Could not exchange the handoff token."}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground pt-2 flex items-center justify-center gap-1.5">
|
||||||
|
<ShieldCheck className="size-3.5" />
|
||||||
|
Re-open the garage from the SaaS dashboard to get a fresh link.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
href={process.env.NEXT_PUBLIC_SAAS_URL ?? "/login"}
|
||||||
|
className="inline-block text-sm underline text-primary"
|
||||||
|
>
|
||||||
|
Back to SaaS
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SaaS → garage-erp handoff landing.
|
||||||
|
*
|
||||||
|
* URL shape:
|
||||||
|
* /activate/handoff/{handoff_token}?ws={workspace_uuid}&api={backend_url}
|
||||||
|
*
|
||||||
|
* Calls the backend's /api/saas/handoff/exchange with the token + workspace
|
||||||
|
* UUID, then sets four cookies (auth_token, auth_user, workspace_uuid,
|
||||||
|
* api_base_url) on the redirect response and lands the user on /.
|
||||||
|
*
|
||||||
|
* Implemented as a Route Handler (not a Page) because Next.js disallows
|
||||||
|
* cookie writes inside Server Components — only Server Actions and Route
|
||||||
|
* Handlers can mutate cookies.
|
||||||
|
*/
|
||||||
|
export async function GET(
|
||||||
|
req: NextRequest,
|
||||||
|
ctx: { params: Promise<{ token: string }> },
|
||||||
|
) {
|
||||||
|
const { token } = await ctx.params
|
||||||
|
const url = new URL(req.url)
|
||||||
|
const ws = url.searchParams.get("ws")
|
||||||
|
const api = url.searchParams.get("api")
|
||||||
|
|
||||||
|
if (!ws || !api) {
|
||||||
|
return redirectToError(req, "Activation link is missing workspace or backend URL.")
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsed: URL
|
||||||
|
try {
|
||||||
|
parsed = new URL(api)
|
||||||
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||||
|
throw new Error("Backend URL must be http(s).")
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return redirectToError(req, "Activation link has a malformed backend URL.")
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiBase = parsed.toString().replace(/\/$/, "")
|
||||||
|
const endpoint = `${apiBase}/api/saas/handoff/exchange`
|
||||||
|
|
||||||
|
let response: Response
|
||||||
|
try {
|
||||||
|
response = await fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
cache: "no-store",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "application/json",
|
||||||
|
"X-Workspace-UUID": ws,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
handoff_token: token,
|
||||||
|
saas_workspace_uuid: ws,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
return redirectToError(req, `Cannot reach garage backend: ${(err as Error).message}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload: { token?: string; user?: any; message?: string } = {}
|
||||||
|
try {
|
||||||
|
payload = await response.json()
|
||||||
|
} catch {
|
||||||
|
// body is not JSON — fall through to error path
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok || !payload.token || !payload.user) {
|
||||||
|
return redirectToError(req, payload.message ?? `Exchange failed (HTTP ${response.status})`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use a relative Location to keep the user on whichever host they came
|
||||||
|
// in on (127.0.0.1 vs localhost). NextResponse.redirect(new URL("/", req.url))
|
||||||
|
// resolves to the Next dev server's canonical host which can differ from
|
||||||
|
// the request's actual host, and cookies set here would not survive that
|
||||||
|
// cross-host redirect.
|
||||||
|
const res = new NextResponse(null, {
|
||||||
|
status: 302,
|
||||||
|
headers: { Location: "/" },
|
||||||
|
})
|
||||||
|
|
||||||
|
const isProd = process.env.NODE_ENV === "production"
|
||||||
|
const sevenDays = 60 * 60 * 24 * 7
|
||||||
|
const cookieOptions = {
|
||||||
|
path: "/",
|
||||||
|
sameSite: "strict" as const,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: isProd,
|
||||||
|
maxAge: sevenDays,
|
||||||
|
}
|
||||||
|
|
||||||
|
res.cookies.set("auth_token", payload.token, cookieOptions)
|
||||||
|
res.cookies.set("auth_user", JSON.stringify(payload.user), cookieOptions)
|
||||||
|
res.cookies.set("workspace_uuid", ws, cookieOptions)
|
||||||
|
res.cookies.set("api_base_url", apiBase, cookieOptions)
|
||||||
|
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirectToError(req: NextRequest, reason: string) {
|
||||||
|
const location = "/activate/error?reason=" + encodeURIComponent(reason)
|
||||||
|
return new NextResponse(null, {
|
||||||
|
status: 302,
|
||||||
|
headers: { Location: location },
|
||||||
|
})
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user