Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c55be5052 | ||
|
|
0d591b9807 | ||
|
|
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.
@@ -74,6 +74,7 @@ Create `apps/dashboard/modules/<feature>/<feature>-form.tsx`:
|
||||
5. Use `useFormMutation()` for submit with automatic validation error mapping
|
||||
6. Render with `Rhform` + `RhfTextField` / `RhfSelectField` / `RhfAsyncSelectField` etc.
|
||||
7. Include error alert, submit button with loading/edit states
|
||||
8. For every required schema/backend field, pass `required` to the rendered form field component so required UI indicators and consistency are preserved
|
||||
|
||||
### Step 5: Create Page Component
|
||||
|
||||
@@ -111,13 +112,44 @@ Create `apps/dashboard/app/(authenticated)/<section>/<feature>/page.tsx`:
|
||||
| Form component | `<PascalFeature>Form` | `JobCardForm` |
|
||||
| Page component | `<PascalFeature>Page` (default export) | `JobCardsPage` |
|
||||
|
||||
### Relation Fields (Foreign Keys)
|
||||
### Relation Fields — Choosing the Right Component
|
||||
|
||||
**Two patterns exist. Pick the right one before building any relational field.**
|
||||
|
||||
#### Simple FK → `RhfAsyncSelectField`
|
||||
|
||||
Use for single-record foreign keys within the same domain or to a simple lookup/reference entity.
|
||||
|
||||
Examples: invoice → customer, bill → vendor, part → category, service → unit type, job card → vehicle, PO → department, any `*_type` or `*_terms` relation.
|
||||
|
||||
- Stored in form as `{ value: string, label: string } | null`
|
||||
- Use `toRelation(id, name)` to convert API data → form value
|
||||
- Use `toId(relation)` to convert form value → API payload
|
||||
- Schema uses `relationFieldSchema = z.object({ value: z.string(), label: z.string() }).nullable()`
|
||||
- Rendered with `<RhfAsyncSelectField>` (fetches options via React Query)
|
||||
|
||||
#### Cross-Domain Line Items → `RhfResourceField` (resource-selector skill)
|
||||
|
||||
Use when the relationship involves a **join table with extra fields** (quantity, rate, description) or the related items are from a **fully separate domain with its own CRUD page** and multiple records can be linked.
|
||||
|
||||
Examples: adding parts to a bill, linking services to an invoice, attaching expense items to a PO.
|
||||
|
||||
**→ Read the `resource-selector` SKILL before implementing these fields.**
|
||||
|
||||
Ready-to-use selector fields (import directly — do not re-implement):
|
||||
|
||||
| Component | Import path | For |
|
||||
|---|---|---|
|
||||
| `PartsSelectorField` | `@/modules/parts/parts-selector-field` | Parts line items |
|
||||
| `ServicesSelectorField` | `@/modules/services/services-selector-field` | Service line items |
|
||||
| `ExpenseItemsSelectorField` | `@/modules/expense-items/expense-items-selector-field` | Expense line items |
|
||||
|
||||
```tsx
|
||||
// Schema: use an array sub-schema with part_id / service_id / expense_id
|
||||
part_items: z.array(z.object({ part_id: z.number(), title: z.string(), quantity: z.number(), rate: z.number(), description: z.string().optional() })).optional()
|
||||
|
||||
// Form: render inside <FieldGroup>
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
```
|
||||
|
||||
### Async Select Pattern
|
||||
|
||||
@@ -144,8 +176,24 @@ const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) =
|
||||
| `RhfTextareaField` | Multi-line text |
|
||||
| `RhfCheckboxField` | Boolean toggles |
|
||||
| `RhfSelectField` | Static option dropdowns |
|
||||
| `RhfAsyncSelectField` | Server-fetched single-select combobox |
|
||||
| `RhfAsyncSelectField` | Server-fetched single FK combobox (same-domain relation) |
|
||||
| `RhfAsyncMultiSelectField` | Server-fetched multi-select combobox |
|
||||
| `RhfResourceField` | Cross-domain multi-select with join table extra fields (parts, services, expenses) — see resource-selector skill |
|
||||
| `RhfDateField` | Date picker — see date-time-pickers skill |
|
||||
| `RhfTimeField` | Time picker — see date-time-pickers skill |
|
||||
|
||||
### Required Prop Rule (Important)
|
||||
|
||||
When a field is required by schema or backend validation, always pass the `required` prop on the matching form component.
|
||||
|
||||
- Applies to all controls that support it, including custom selectors (for example `RhfCustomerSelectField`, `RhfVehicleSelectField`) and standard fields (`RhfTextField`, `RhfSelectField`, etc.)
|
||||
- Do not rely on schema-only required validation; keep UI required indicator (`*`) in sync with validation requirements
|
||||
|
||||
```tsx
|
||||
<RhfTextField name="title" label="Title" required />
|
||||
<RhfCustomerSelectField name="customer" required />
|
||||
<RhfVehicleSelectField name="vehicle" required customer_id={customer?.value} />
|
||||
```
|
||||
|
||||
### Imports Cheat Sheet
|
||||
|
||||
|
||||
@@ -37,11 +37,18 @@ import { <RESOURCE>_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
// Static select options (if needed):
|
||||
// const STATUS_OPTIONS = [
|
||||
// { value: "active", label: "Active" },
|
||||
// { value: "inactive", label: "Inactive" },
|
||||
// ]
|
||||
// ALWAYS derive select options from API enums imported from "@garage/api".
|
||||
// NEVER hardcode enum values inline — they must stay in sync with the backend.
|
||||
//
|
||||
// Pattern: import the enum array, then .map() to produce { value, label } pairs.
|
||||
//
|
||||
// const STATUS_OPTIONS = SomeStatus.map((v) => ({
|
||||
// value: v,
|
||||
// label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
|
||||
// }))
|
||||
//
|
||||
// If no matching enum exists in packages/api/src/contracts/enums.ts, add it there first,
|
||||
// then import and use it here.
|
||||
|
||||
// ── Props ──
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# Invoice Pattern Skill
|
||||
|
||||
This skill defines the standard for implementing invoice-like forms (Invoice, Estimate, Job Card, Purchase Order, Bill, etc.) in the carage-erp dashboard. All such forms must follow this pattern for layout, discount/tax handling, and summary calculation. The current Invoice form is the canonical reference.
|
||||
|
||||
---
|
||||
|
||||
## 1. Layout
|
||||
- **Two-column grid:**
|
||||
- **Main column (9/12):**
|
||||
- Subject, invoice number/title
|
||||
- Status select, Discount Type select
|
||||
- Conditional Transaction Discount field
|
||||
- Line item selectors: Parts, Services, Expense Items (with optional line-level discount)
|
||||
- Notes, Terms & Conditions
|
||||
- Submit button
|
||||
- **Sidebar column (3/12):**
|
||||
- Invoice date, Due date
|
||||
- Customer, Vehicle selectors
|
||||
- Tax select (see below)
|
||||
- Department, Payment Terms, Invoice Sequence, Insurance fields
|
||||
- Summary card (see below)
|
||||
|
||||
## 2. Discount Implementation
|
||||
- **Discount Type:**
|
||||
- Field: `discount` (enum: 'no', 'line_item_level', 'transaction_level')
|
||||
- Select field in main column
|
||||
- **Transaction-level Discount:**
|
||||
- Field: `discount_amount` (number)
|
||||
- Only shown when `discount === "transaction_level"`
|
||||
- **Line-level Discount:**
|
||||
- Each line item (parts, services, expenses) has `discount_amount` field
|
||||
- Only shown when `discount === "line_item_level"`
|
||||
- **Payload Mapping:**
|
||||
- Only include `discount_amount` at transaction level if `discount === "transaction_level"`
|
||||
- Only include per-line `discount_amount` if `discount === "line_item_level"`
|
||||
|
||||
## 3. Tax Type Implementation
|
||||
- **Tax Field:**
|
||||
- Field: `tax` (relationFieldSchema: `{ value: string, label: string } | null`)
|
||||
- Uses `RhfAsyncSelectField` in sidebar
|
||||
- `mapOption`: `{ value: String(item.id), label: `${item.title} (${item.rate}%)` }`
|
||||
- The selected tax's rate is parsed from the label string in the summary (regex: `/\((\d+(?:\.\d+)?)%\)/`)
|
||||
|
||||
## 4. Summary Implementation
|
||||
- **Summary Card:**
|
||||
- Always rendered in the sidebar below the Details card
|
||||
- Uses `InvoiceFormSummary` (form-aware adapter)
|
||||
- `InvoiceFormSummary` flattens all line items, reads discount/tax fields, and passes them to `useDocumentTotals` hook
|
||||
- `useDocumentTotals` (pure hook) computes subtotal, discounts, tax, and total
|
||||
- `DocumentTotalsSummary` (pure display component) renders the summary
|
||||
|
||||
---
|
||||
|
||||
## Reference: Invoice Form
|
||||
- See `apps/dashboard/modules/invoices/invoice-form.tsx` for the canonical implementation.
|
||||
- Schema: `apps/dashboard/modules/invoices/invoice.schema.ts`
|
||||
- Summary logic: `apps/dashboard/modules/invoices/invoice-form-summary.tsx`, `shared/hooks/use-document-totals.ts`, `shared/components/document-totals-summary.tsx`
|
||||
|
||||
---
|
||||
|
||||
## Required for All Invoice-like Forms
|
||||
- Follow the above layout and field conventions
|
||||
- Use the same discount/tax logic and summary calculation
|
||||
- Use the same field and payload mapping patterns
|
||||
- Use the same summary component structure
|
||||
|
||||
---
|
||||
|
||||
## Example: Tax Field (in sidebar)
|
||||
```tsx
|
||||
<RhfAsyncSelectField
|
||||
name="tax"
|
||||
label="Tax"
|
||||
placeholder="Select tax rate"
|
||||
queryKey={[TAX_ROUTES.INDEX]}
|
||||
listFn={() => api.taxes.list()}
|
||||
mapOption={(item: any) => ({
|
||||
value: String(item.id),
|
||||
label: item.title ? `${item.title} (${item.rate}%)` : `#${item.id}`,
|
||||
})}
|
||||
{...STORE_OBJECT}
|
||||
/>
|
||||
```
|
||||
|
||||
## Example: Discount Type Select (in main column)
|
||||
```tsx
|
||||
<RhfSelectField name="discount" label="Discount Type" options={DISCOUNT_OPTIONS} />
|
||||
```
|
||||
|
||||
## Example: Summary Card
|
||||
```tsx
|
||||
<div className="mt-4">
|
||||
<InvoiceFormSummary />
|
||||
</div>
|
||||
```
|
||||
@@ -0,0 +1,258 @@
|
||||
---
|
||||
name: resource-filters
|
||||
description: "Add advanced filtering to resource list pages using a drawer/sheet with RHF forms and nuqs query params. Use when: adding filters to a ResourcePage, creating a filter drawer for any list page, implementing advanced search with URL-persisted filter state, adding query-param-based filtering to a CRUD page."
|
||||
---
|
||||
|
||||
# Resource Filters
|
||||
|
||||
Add URL-persisted advanced filtering to any ResourcePage or data table list. Filters live in a right-side Sheet drawer, powered by React Hook Form (RHF) and synced to URL query params via nuqs.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to add filters or advanced filters to a list/index page
|
||||
- User wants URL-shareable filter state on a resource page
|
||||
- User asks to filter by relations, dates, or boolean flags on any data table
|
||||
- User wants a filter drawer/dialog for any CRUD listing
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ useFilterParams (generic hook) │ ← Manages RHF form + nuqs URL sync
|
||||
│ • schema + defaults │
|
||||
│ • paramsParsers (nuqs) │
|
||||
│ • mapParamsToFormValues │
|
||||
│ • mapFormValuesToParams │
|
||||
│ Returns: form, appliedParams, │
|
||||
│ open/close/submit/reset, │
|
||||
│ activeFilterCount │
|
||||
└──────────────┬──────────────────┘
|
||||
│
|
||||
┌──────────┴──────────┐
|
||||
│ │
|
||||
┌───▼───────┐ ┌────────▼──────────┐
|
||||
│FilterDrawer│ │ ResourcePage │
|
||||
│(Sheet UI) │ │ extraParams={ │
|
||||
│ │ │ ...appliedParams│
|
||||
│ <Fields /> │ │ ...quickFilters │
|
||||
│ Apply/Reset│ │ } │
|
||||
└────────────┘ └───────────────────┘
|
||||
```
|
||||
|
||||
## File Locations
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `shared/hooks/use-filter-params.ts` | Generic hook — form + nuqs state sync |
|
||||
| `shared/components/filter-drawer.tsx` | `FilterDrawer` sheet + `FilterTrigger` button |
|
||||
| `modules/<feature>/<feature>-filters.tsx` | Feature-specific schema, parsers, mappers, fields |
|
||||
|
||||
## Procedure
|
||||
|
||||
### Step 1: Create the filter config file
|
||||
|
||||
Create `modules/<feature>/<feature>-filters.tsx` with:
|
||||
|
||||
1. **Zod schema** — all filter fields. Use `relationField` for foreign-key selects, `z.string().optional()` for dates, `z.boolean().optional()` for flags.
|
||||
2. **Default values** — matching the schema (null for relations, `""` for strings, `false` for booleans).
|
||||
3. **nuqs parsers** — `parseAsInteger` for relation IDs, `parseAsString` for dates/text, `parseAsBoolean` for flags.
|
||||
4. **`mapParamsToFormValues`** — URL params → form values. Use `toRelation(id)` for relation fields.
|
||||
5. **`mapFormValuesToParams`** — form values → URL params. Use `toId(relation)` for relation fields.
|
||||
6. **Config export** — `UseFilterParamsOptions<T>` object with schema, defaults, parsers, mappers.
|
||||
7. **Fields component** — renders RHF fields inside the drawer.
|
||||
|
||||
#### Template
|
||||
|
||||
```tsx
|
||||
"use client"
|
||||
|
||||
import { z } from "zod"
|
||||
import { parseAsInteger, parseAsString, parseAsBoolean } from "nuqs"
|
||||
import { toRelation, toId, type RelationFieldValue } from "@/shared/lib/utils"
|
||||
import {
|
||||
RhfAsyncSelectField,
|
||||
RhfDateField,
|
||||
RhfCheckboxField,
|
||||
RhfSelectField,
|
||||
} from "@/shared/components/form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { SOME_ROUTES } from "@garage/api"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import type { UseFilterParamsOptions } from "@/shared/hooks/use-filter-params"
|
||||
|
||||
// ── Schema ──
|
||||
|
||||
const relationField = z.object({ value: z.string(), label: z.string() }).nullable().optional()
|
||||
|
||||
const filterSchema = z.object({
|
||||
some_relation_id: relationField,
|
||||
some_date: z.string().optional(),
|
||||
some_flag: z.boolean().optional(),
|
||||
})
|
||||
|
||||
type FilterValues = z.infer<typeof filterSchema>
|
||||
|
||||
// ── Defaults ──
|
||||
|
||||
const defaultValues: FilterValues = {
|
||||
some_relation_id: null,
|
||||
some_date: "",
|
||||
some_flag: false,
|
||||
}
|
||||
|
||||
// ── nuqs Parsers ──
|
||||
|
||||
const paramsParsers = {
|
||||
some_relation_id: parseAsInteger,
|
||||
some_date: parseAsString,
|
||||
some_flag: parseAsBoolean,
|
||||
}
|
||||
|
||||
// ── Mappers ──
|
||||
|
||||
function mapParamsToFormValues(params: Record<string, any>): Partial<FilterValues> {
|
||||
return {
|
||||
some_relation_id: params.some_relation_id ? toRelation(params.some_relation_id) : null,
|
||||
some_date: params.some_date ?? "",
|
||||
some_flag: params.some_flag ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
function mapFormValuesToParams(values: FilterValues): Record<string, any> {
|
||||
return {
|
||||
some_relation_id: toId(values.some_relation_id as RelationFieldValue) ?? null,
|
||||
some_date: values.some_date || null,
|
||||
some_flag: values.some_flag || null,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Filter Config ──
|
||||
|
||||
export const featureFilterConfig: UseFilterParamsOptions<FilterValues> = {
|
||||
schema: filterSchema,
|
||||
defaultValues,
|
||||
paramsParsers,
|
||||
mapParamsToFormValues,
|
||||
mapFormValuesToParams,
|
||||
}
|
||||
|
||||
// ── Filter Fields Component ──
|
||||
|
||||
export function FeatureFilterFields() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<>
|
||||
<RhfAsyncSelectField
|
||||
name="some_relation_id"
|
||||
label="Some Relation"
|
||||
queryKey={[SOME_ROUTES.INDEX]}
|
||||
listFn={() => api.someResource.list( )}
|
||||
mapOption={(item: any) => ({ value: String(item.id), label: item.name })}
|
||||
placeholder="All"
|
||||
/>
|
||||
|
||||
<RhfDateField name="some_date" label="Some Date" />
|
||||
|
||||
<RhfCheckboxField name="some_flag" label="Some Flag" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Integrate into the page
|
||||
|
||||
In the page component:
|
||||
|
||||
```tsx
|
||||
import { useFilterParams } from '@/shared/hooks/use-filter-params'
|
||||
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
|
||||
import { featureFilterConfig, FeatureFilterFields } from '@/modules/<feature>/<feature>-filters'
|
||||
|
||||
export default function FeaturePage() {
|
||||
const filter = useFilterParams(featureFilterConfig)
|
||||
|
||||
// Combine drawer filters with any quick filters (tabs, search, etc.)
|
||||
const extraParams = useMemo(() => {
|
||||
const params: Record<string, unknown> = { ...filter.appliedParams }
|
||||
// Add quick filters if present
|
||||
if (search) params.search = search
|
||||
if (statusFilter !== "all") params.status = statusFilter
|
||||
return params
|
||||
}, [filter.appliedParams, search, statusFilter])
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourcePage
|
||||
extraParams={extraParams}
|
||||
headerProps={({ ... }) => ({
|
||||
title: "Feature",
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<FilterTrigger
|
||||
onClick={filter.open}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
/>
|
||||
{/* other actions like FormDialog */}
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
{/* columns, tableHeader, etc. */}
|
||||
/>
|
||||
|
||||
<FilterDrawer
|
||||
form={filter.form}
|
||||
isOpen={filter.isOpen}
|
||||
onOpenChange={(open) => { if (!open) filter.close() }}
|
||||
onSubmit={filter.onSubmit}
|
||||
onReset={filter.reset}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
title="Filter Features"
|
||||
>
|
||||
<FeatureFilterFields />
|
||||
</FilterDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Key Conventions
|
||||
|
||||
### Field Types
|
||||
|
||||
| Filter Type | Schema | nuqs Parser | Form Component | Default |
|
||||
|---|---|---|---|---|
|
||||
| Foreign key (select) | `relationField` (nullable object) | `parseAsInteger` | `RhfAsyncSelectField` | `null` |
|
||||
| Date | `z.string().optional()` | `parseAsString` | `RhfDateField` | `""` |
|
||||
| Boolean flag | `z.boolean().optional()` | `parseAsBoolean` | `RhfCheckboxField` | `false` |
|
||||
| Enum select | `z.string().optional()` | `parseAsString` | `RhfSelectField` | `""` |
|
||||
| Text/search | `z.string().optional()` | `parseAsString` | `RhfTextField` | `""` |
|
||||
| Comma-separated IDs | `z.string().optional()` | `parseAsString` | custom / `RhfTextField` | `""` |
|
||||
|
||||
### Relation Field Mapping
|
||||
|
||||
- **URL → Form**: `toRelation(params.field_id)` produces `{ value: "5", label: "5" }`. The async select resolves the display label from loaded options.
|
||||
- **Form → URL**: `toId(values.field_id)` extracts the numeric ID.
|
||||
- Import `toRelation`, `toId`, and `RelationFieldValue` from `@/shared/lib/utils`.
|
||||
|
||||
### Section Grouping
|
||||
|
||||
Group related filters with `<Separator />` and section labels:
|
||||
```tsx
|
||||
<Separator />
|
||||
<p className="text-sm font-medium text-muted-foreground pt-2">Section Name</p>
|
||||
```
|
||||
|
||||
### Pagination Reset
|
||||
|
||||
The `useFilterParams` hook automatically resets the `page` query param to `1` when filters are applied or reset, preventing empty-page issues.
|
||||
|
||||
### Quick Filters vs Drawer Filters
|
||||
|
||||
- **Quick filters** (status tabs, search input) live directly in `tableHeader` and are managed via `useState` or separate nuqs params on the page.
|
||||
- **Drawer filters** (advanced) are managed by `useFilterParams` and rendered inside `FilterDrawer`.
|
||||
- Both are merged into `extraParams` with `useMemo`.
|
||||
|
||||
## Reference Implementation
|
||||
|
||||
See `modules/job-cards/job-card-filters.tsx` and `app/(authenticated)/sales/job-cards/page.tsx` for the complete working example.
|
||||
@@ -0,0 +1,315 @@
|
||||
---
|
||||
name: resource-selector
|
||||
description: "Use RhfResourceField and ResourceSelectorDialog for cross-domain relational line-item fields in forms. Use when: linking parts/services/expense-items to invoices, bills, purchase orders, or estimates; adding line-item tables with qty/rate/description; picking multiple records from a separate domain entity. Do NOT use for simple FK relations like 'customer type' or 'payment terms' — use RhfAsyncSelectField for those."
|
||||
---
|
||||
|
||||
# Resource Selector (Cross-Domain Relations)
|
||||
|
||||
Use `RhfResourceField` + `ResourceSelectorDialog` when a form needs to pick **one or more records from a different domain** and store them as an **editable line-item array with extra data** (quantity, rate, description, etc.).
|
||||
|
||||
## Decision: RhfResourceField vs RhfAsyncSelectField
|
||||
|
||||
| Situation | Use |
|
||||
|---|---|
|
||||
| Linking parts / services / expense items to a bill, invoice, PO, or estimate | **`RhfResourceField`** |
|
||||
| Picking multiple cross-domain items that need per-row extra fields (qty, rate) | **`RhfResourceField`** |
|
||||
| Simple FK: invoice → customer, PO → vendor, job card → vehicle | **`RhfAsyncSelectField`** |
|
||||
| Simple FK: insurance type, payment terms, category, department, unit type | **`RhfAsyncSelectField`** |
|
||||
| Single-record lookup within the same domain | **`RhfAsyncSelectField`** |
|
||||
|
||||
**Rule:** If the relationship involves a **join table with extra fields** (quantity, rate, description, chart_of_account) or the related items are from a **fully separate domain with its own CRUD page**, use `RhfResourceField`. Otherwise use `RhfAsyncSelectField`.
|
||||
|
||||
### Domain Boundary Examples
|
||||
|
||||
```
|
||||
Cross-domain (use RhfResourceField): Simple FK (use RhfAsyncSelectField):
|
||||
Invoice ←→ Parts Invoice → Customer
|
||||
Invoice ←→ Services Invoice → Payment Terms
|
||||
Bill ←→ Parts Bill → Vendor
|
||||
Bill ←→ Services Bill → Department
|
||||
Bill ←→ Expense Items Part → Category
|
||||
PO ←→ Parts Service → Unit Type
|
||||
Estimate ←→ Services Job Card → Vehicle
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
| File | Purpose |
|
||||
|---|---|
|
||||
| `shared/components/resource-selector/resource-selector-dialog.tsx` | Generic dialog wrapping `CrudResource` with multi-row selection + Confirm/Cancel |
|
||||
| `shared/components/resource-selector/rhf-resource-field.tsx` | RHF field: Card with trigger → opens dialog → renders items via `renderItems` callback |
|
||||
| `modules/<domain>/<domain>-columns.tsx` | Shared column definitions reused by both the domain page and selector dialogs |
|
||||
| `modules/<domain>/<domain>-selector-field.tsx` | Self-contained wrapper for a specific domain (e.g. `PartsSelectorField`) |
|
||||
|
||||
## Procedure
|
||||
|
||||
### Step 1: Create / Reuse Domain Columns File
|
||||
|
||||
If the domain already has a page, extract shared columns to `modules/<domain>/<domain>-columns.tsx`. This avoids duplication between the list page and the selector dialog.
|
||||
|
||||
```tsx
|
||||
// modules/parts/parts-columns.tsx
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
|
||||
export const partColumns = {
|
||||
title: {
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => <span className="font-medium">{(row.original as any).title || "—"}</span>,
|
||||
},
|
||||
purchasePrice: {
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
// ... more columns
|
||||
} satisfies Record<string, ColumnDef<any, any>>
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
// CRITICAL: use `satisfies Record<string, ColumnDef<any, any>>`
|
||||
// NOT `as ColumnDef<unknown>` — the latter causes type errors in ResourceSelectorDialog
|
||||
```
|
||||
|
||||
### Step 2: Define the Item Shape in the Schema
|
||||
|
||||
Add a sub-schema for the line items inside the form schema:
|
||||
|
||||
```tsx
|
||||
// In <resource>.schema.ts
|
||||
const billPartItemSchema = z.object({
|
||||
part_id: z.number(),
|
||||
title: z.string(), // display only, not sent to API
|
||||
quantity: z.number().min(1),
|
||||
rate: z.number().min(0),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
|
||||
const billFormSchema = z.object({
|
||||
// ... other fields
|
||||
part_items: z.array(billPartItemSchema).optional(),
|
||||
service_items: z.array(billServiceItemSchema).optional(),
|
||||
})
|
||||
```
|
||||
|
||||
### Step 3: Create the Selector Field Component
|
||||
|
||||
Create `modules/<domain>/<domain>-selector-field.tsx`:
|
||||
|
||||
```tsx
|
||||
"use client"
|
||||
|
||||
import type { FieldValues, FieldPath } from "react-hook-form"
|
||||
import { Trash2 } from "lucide-react"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import {
|
||||
Table, TableHeader, TableBody,
|
||||
TableHead, TableRow, TableCell,
|
||||
} from "@/shared/components/ui/table"
|
||||
import { RhfResourceField } from "@/shared/components/resource-selector"
|
||||
import { partColumns } from "./parts-columns"
|
||||
import { PARTS_ROUTES } from "@garage/api"
|
||||
import type { PartsClient } from "@garage/api"
|
||||
|
||||
type PartItem = {
|
||||
part_id: number
|
||||
title: string
|
||||
quantity: number
|
||||
rate: number
|
||||
description?: string
|
||||
}
|
||||
|
||||
type Constraint = PartItem[] | undefined
|
||||
|
||||
export type PartsSelectorFieldProps<
|
||||
TValues extends FieldValues,
|
||||
TName extends FieldPath<TValues>,
|
||||
> = {
|
||||
name: TName & (TValues[TName] extends Constraint ? TName : never)
|
||||
label?: string
|
||||
triggerLabel?: string
|
||||
}
|
||||
|
||||
export function PartsSelectorField<
|
||||
TValues extends FieldValues,
|
||||
TName extends FieldPath<TValues>,
|
||||
>({ name, label = "Parts", triggerLabel = "Add Parts" }: PartsSelectorFieldProps<TValues, TName>) {
|
||||
return (
|
||||
<RhfResourceField<TValues, TName, PartsClient>
|
||||
name={name}
|
||||
label={label}
|
||||
triggerLabel={triggerLabel}
|
||||
itemKey="part_id" // deduplicate by this key when re-selecting
|
||||
dialogProps={{
|
||||
title: "Select Parts",
|
||||
crudProps: {
|
||||
routeKey: PARTS_ROUTES.INDEX,
|
||||
getClient: (api) => api.parts,
|
||||
columns: [
|
||||
partColumns.title,
|
||||
partColumns.partNumber,
|
||||
partColumns.purchasePrice,
|
||||
partColumns.stock,
|
||||
],
|
||||
},
|
||||
}}
|
||||
mapSelected={(row) => {
|
||||
const r = row as any
|
||||
return {
|
||||
part_id: r.id,
|
||||
title: r.title || "",
|
||||
quantity: 1,
|
||||
rate: Number(r.purchase_price) || 0,
|
||||
description: "",
|
||||
} as any
|
||||
}}
|
||||
renderItems={(items, { remove, update }) => (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Part</TableHead>
|
||||
<TableHead className="w-24">Qty</TableHead>
|
||||
<TableHead className="w-28">Rate</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead className="w-12" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{((items as PartItem[] | undefined) ?? []).map((item, index) => (
|
||||
<TableRow key={item.part_id}>
|
||||
<TableCell className="font-medium">{item.title}</TableCell>
|
||||
<TableCell>
|
||||
<Input type="number" min={1} value={item.quantity}
|
||||
onChange={(e) => update(index, { ...item, quantity: Number(e.target.value) || 1 } as any)}
|
||||
className="h-8 w-20" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input type="number" min={0} step={0.01} value={item.rate}
|
||||
onChange={(e) => update(index, { ...item, rate: Number(e.target.value) || 0 } as any)}
|
||||
className="h-8 w-24" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input value={item.description ?? ""}
|
||||
onChange={(e) => update(index, { ...item, description: e.target.value } as any)}
|
||||
placeholder="Optional description" className="h-8" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button type="button" variant="ghost" size="icon-sm" onClick={() => remove(index)}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Step 4: Wire into the Form
|
||||
|
||||
```tsx
|
||||
// In <resource>-form.tsx
|
||||
|
||||
// 1. Import
|
||||
import { PartsSelectorField } from "@/modules/parts/parts-selector-field"
|
||||
import { ServicesSelectorField } from "@/modules/services/services-selector-field"
|
||||
|
||||
// 2. Add to DEFAULT_VALUES
|
||||
const DEFAULT_VALUES = {
|
||||
// ...
|
||||
part_items: [],
|
||||
service_items: [],
|
||||
}
|
||||
|
||||
// 3. Map from API → form (in mapToFormValues)
|
||||
part_items: (d.parts ?? []).map((p: any) => ({
|
||||
part_id: p.part_id ?? p.id,
|
||||
title: p.part?.title ?? p.title ?? "",
|
||||
quantity: Number(p.quantity) || 1,
|
||||
rate: Number(p.rate) || 0,
|
||||
description: p.description ?? "",
|
||||
})),
|
||||
|
||||
// 4. Map from form → API payload (in mapFormToPayload)
|
||||
part_items: (values.part_items ?? []).map((item) => ({
|
||||
part_id: item.part_id,
|
||||
quantity: item.quantity,
|
||||
rate: item.rate,
|
||||
description: item.description || undefined,
|
||||
})),
|
||||
|
||||
// 5. Render inside <FieldGroup>
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
<ServicesSelectorField<MyFormValues, "service_items"> name="service_items" />
|
||||
```
|
||||
|
||||
## Existing Selector Fields (Ready to Use)
|
||||
|
||||
These are already built. Import and use directly — do NOT re-implement from scratch:
|
||||
|
||||
| Component | File | `itemKey` | Notes |
|
||||
|---|---|---|---|
|
||||
| `PartsSelectorField` | `modules/parts/parts-selector-field.tsx` | `part_id` | qty + rate + description editable |
|
||||
| `ServicesSelectorField` | `modules/services/services-selector-field.tsx` | `service_id` | qty + rate + description editable |
|
||||
| `ExpenseItemsSelectorField` | `modules/expense-items/expense-items-selector-field.tsx` | `expense_id` | qty + rate + description editable |
|
||||
|
||||
**Usage:**
|
||||
```tsx
|
||||
import { PartsSelectorField } from "@/modules/parts/parts-selector-field"
|
||||
import { ServicesSelectorField } from "@/modules/services/services-selector-field"
|
||||
import { ExpenseItemsSelectorField } from "@/modules/expense-items/expense-items-selector-field"
|
||||
|
||||
// Inside <FieldGroup>:
|
||||
<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />
|
||||
<ServicesSelectorField<MyFormValues, "service_items"> name="service_items" />
|
||||
<ExpenseItemsSelectorField<MyFormValues, "expense_items"> name="expense_items" />
|
||||
```
|
||||
|
||||
## API Props Reference
|
||||
|
||||
### `RhfResourceField`
|
||||
|
||||
| Prop | Type | Required | Description |
|
||||
|---|---|---|---|
|
||||
| `name` | `FieldPath<TValues>` | ✅ | RHF field name; value is an array |
|
||||
| `label` | `string` | ✅ | Card heading |
|
||||
| `triggerLabel` | `string` | | Button label (defaults to `label`) |
|
||||
| `mapSelected` | `(row) => ItemShape` | ✅ | Maps a selected table row to the form item shape |
|
||||
| `renderItems` | `(items, helpers) => ReactNode` | ✅ | Renders the editable item table |
|
||||
| `dialogProps` | object | ✅ | Config for the selector dialog (see below) |
|
||||
| `itemKey` | `string` | | Field used for deduplication. Defaults to `"id"` |
|
||||
|
||||
### `dialogProps`
|
||||
|
||||
```ts
|
||||
{
|
||||
title: string // Dialog heading
|
||||
crudProps: {
|
||||
routeKey: ApiPath // e.g. PARTS_ROUTES.INDEX
|
||||
getClient: (api) => client // e.g. (api) => api.parts
|
||||
columns: ColumnDef[] // Subset of domain columns to show
|
||||
}
|
||||
rowKey?: keyof Item // Selection identity key (defaults to "id")
|
||||
}
|
||||
```
|
||||
|
||||
### `renderItems` helpers
|
||||
|
||||
| Helper | Signature | Description |
|
||||
|---|---|---|
|
||||
| `remove` | `(index: number) => void` | Remove item at index |
|
||||
| `update` | `(index: number, item) => void` | Replace item at index |
|
||||
| `replace` | `(items) => void` | Replace entire array |
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Column type error**: Always use `satisfies Record<string, ColumnDef<any, any>>` on the columns object. Using `as ColumnDef<unknown>` per-entry causes type errors in the selector dialog.
|
||||
- **itemKey mismatch**: The `itemKey` on `RhfResourceField` must match the field name in your item shape (e.g. `"part_id"`, not `"id"`).
|
||||
- **Pre-fill in create mode**: `useResourceForm` uses a shallow spread for initial data. Pre-fill the field with already-shaped items (not raw API shape) to avoid empty arrays. See the `mapToFormValues` pattern above.
|
||||
- **Selector field generic parameters**: Always pass both type params when using a selector field in a form: `<PartsSelectorField<MyFormValues, "part_items"> name="part_items" />`.
|
||||
@@ -11,6 +11,7 @@ node_modules
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.prod
|
||||
|
||||
# Testing
|
||||
coverage
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
# Garage ERP — Feature Gap Plan vs. Industry Leaders
|
||||
|
||||
> Comparison of the current Reparee Garage ERP against established automotive
|
||||
> workshop management platforms (GarageBox, Tekmetric, Shopmonkey, AutoLeap,
|
||||
> Garage Hive, Mitchell 1 Manager SE, MaxxTraxx, Workshop Software).
|
||||
>
|
||||
> Goal: list what does **not** yet exist in this codebase, group it by impact,
|
||||
> and give each gap an implementation hint so it can be picked up later.
|
||||
|
||||
---
|
||||
|
||||
## 1. What Reparee already has (baseline)
|
||||
|
||||
Captured from the current backend (`reparee_backend/`) controllers/models and
|
||||
dashboard navigation (`apps/dashboard/config/navGroups.tsx`):
|
||||
|
||||
**Sales & service workflow**
|
||||
- Customers (with notes, types, referral sources, import/export)
|
||||
- Vehicles (owners, makes/models, body types, fuel, transmission, colors,
|
||||
documents, mileage history, import/export)
|
||||
- Inspections + Inspection Templates (categories, checkpoints, labels)
|
||||
- Public share link for inspections (token-based, rate-limited)
|
||||
- Estimates → Job Cards → Invoices (services, parts, expense items, internal
|
||||
notes, labels, document attachments)
|
||||
- Credit Notes
|
||||
- Payments Received
|
||||
- Appointments (calendar)
|
||||
|
||||
**Purchases**
|
||||
- Vendors (addresses, status, credits)
|
||||
- Expenses & Expense Items
|
||||
- Purchase Orders (with internal notes, labels)
|
||||
- Bills
|
||||
- Payments Made
|
||||
- Vendor Credits
|
||||
|
||||
**Items / inventory**
|
||||
- Services and Service Groups (with includes/pricing/parts)
|
||||
- Parts (with categories, unit types)
|
||||
- Inventory Adjustments
|
||||
- Labor Rates, Taxes
|
||||
|
||||
**HR / productivity**
|
||||
- Employees (with documents, certifications, avatar, performance, permissions)
|
||||
- Departments, Roles (with `permission.check` middleware on every route)
|
||||
- Leave Requests + Leave Balance
|
||||
- Payroll Runs + Entries + Slips
|
||||
- Tasks, Task Sections, Task Types, TimeSheet
|
||||
- Shop Calendar, Shop Timing, Holidays
|
||||
|
||||
**Platform**
|
||||
- PDF generation via `DocumentPrintController` + Blade templates
|
||||
- Document share tokens
|
||||
- Settings (company, including logo + Terms & Conditions in `privacy_policy`)
|
||||
- i18n EN/AR with RTL
|
||||
- OpenAPI client (`packages/api/`) regenerated from backend spec
|
||||
|
||||
**Sidebar shows planned-but-disabled groups** (commented out in
|
||||
`navGroups.tsx`): CRM (leads/calls/tasks), Marketing (service reminders,
|
||||
ratings/reviews, Google reviews), Accountants (manual journals, chart of
|
||||
accounts), Reports, Payroll, Integrations, Templates.
|
||||
|
||||
---
|
||||
|
||||
## 2. Priority matrix
|
||||
|
||||
| Tier | Meaning |
|
||||
|------|---------|
|
||||
| **P0** | Table-stakes for a modern garage SaaS — competitors all ship it, customers ask first |
|
||||
| **P1** | Significant value-add, expected by mid-market shops |
|
||||
| **P2** | Differentiators / nice-to-haves |
|
||||
| **P3** | Long-tail integrations and advanced workflows |
|
||||
|
||||
---
|
||||
|
||||
## 3. P0 — Table-stakes gaps
|
||||
|
||||
### 3.1 Reporting & Analytics dashboard
|
||||
**Status:** No `/reports` route exists; sidebar entry is commented out. A
|
||||
`/` dashboard page exists but is not analytics-rich.
|
||||
|
||||
**What competitors ship:**
|
||||
- Revenue by day/week/month, by service category, by technician
|
||||
- Open jobs / WIP value, ARO (Average Repair Order), gross profit %
|
||||
- Aging receivables (already implicit in invoices, no view)
|
||||
- Parts margin, labor margin
|
||||
- Technician productivity (billed hours vs. clocked hours)
|
||||
- Inventory turnover, stock-outs
|
||||
- Customer retention / first-visit vs. repeat
|
||||
|
||||
**Plan:**
|
||||
- New backend controllers: `ReportController` exposing aggregations
|
||||
(revenue, AR aging, technician utilization, inventory turnover).
|
||||
- New dashboard area: `apps/dashboard/app/(authenticated)/reports/`
|
||||
with sub-routes per report.
|
||||
- Re-use TanStack Query + a chart lib already approved (or ask before adding
|
||||
recharts / visx). KPIs on home page should pull from the same endpoints.
|
||||
|
||||
### 3.2 Service Reminders (mileage- and time-based)
|
||||
**Status:** `Vehicle` has mileage logs (`VehicleMileAndKm`) and documents
|
||||
have expiry dates, but no reminder engine. Sidebar Marketing group is
|
||||
commented out.
|
||||
|
||||
**What competitors ship:**
|
||||
- "Next service in 5,000 km" rules per vehicle/service
|
||||
- Insurance / registration / inspection expiry reminders
|
||||
- Auto-send via email/SMS X days before due
|
||||
- Customer can click to book
|
||||
|
||||
**Plan:**
|
||||
- New model: `ServiceReminderRule` (per vehicle or template per make/model:
|
||||
due_at_date, due_at_mileage, service_group_id, channel).
|
||||
- Scheduled job (Laravel scheduler) that scans daily and queues notifications.
|
||||
- Channel adapters wired to the notification stack from §3.3.
|
||||
- UI under `productivity` or new `marketing/` area.
|
||||
|
||||
### 3.3 Customer notifications (Email / SMS / WhatsApp)
|
||||
**Status:** No notification channels found beyond document share links. No
|
||||
`Notification` or messaging tables in models.
|
||||
|
||||
**What competitors ship:**
|
||||
- Twilio/Vonage SMS, WhatsApp Business API
|
||||
- Two-way SMS thread per customer/job (Tekmetric, Shopmonkey)
|
||||
- Templated estimate-ready / job-ready / pickup-ready messages
|
||||
- Inbox view of all customer conversations
|
||||
|
||||
**Plan:**
|
||||
- Add `notification_channels` config + adapter interface
|
||||
(`App\Services\Notifications\Channel`).
|
||||
- Provider drivers behind feature flags (SMS via Twilio/MessageBird, email
|
||||
via existing Laravel mail, WhatsApp via Meta Cloud API).
|
||||
- Tables: `customer_messages` (inbound + outbound), `notification_templates`
|
||||
(subject/body, locale, type).
|
||||
- Dashboard inbox under `/sales/customers/[id]/messages` + global `/inbox`.
|
||||
|
||||
### 3.4 Customer-facing portal (estimate approval, history)
|
||||
**Status:** Only `PublicInspectionController` exists for public viewing.
|
||||
Estimates and invoices have no customer-side approval flow.
|
||||
|
||||
**What competitors ship:**
|
||||
- Customer logs in (or magic-link) and sees: vehicles, history, estimates,
|
||||
invoices, upcoming appointments.
|
||||
- One-click approve / decline / partial-approve on estimate line items
|
||||
(digital authorization with audit trail).
|
||||
- Pay invoice via portal.
|
||||
|
||||
**Plan:**
|
||||
- Reuse `DocumentShare` token pattern, broaden into a `customer_portal_token`.
|
||||
- New `PublicEstimateController` mirroring `PublicInspectionController`,
|
||||
with POST endpoints for approve/decline per line item.
|
||||
- Persist signature/IP/timestamp on `EstimateAuthorisationHistory` (model
|
||||
already exists — confirm fields cover approvals from portal).
|
||||
- Frontend: new public route group `app/portal/` (no auth, token-scoped).
|
||||
|
||||
### 3.5 Online payments
|
||||
**Status:** `PaymentMode` table exists, payments are recorded manually. No
|
||||
gateway integration.
|
||||
|
||||
**What competitors ship:**
|
||||
- Stripe / Square / regional gateway integration
|
||||
- "Pay invoice" link inside email/SMS
|
||||
- Saved cards, partial payments, tips
|
||||
- Reconciliation back to `PaymentRecieved`
|
||||
|
||||
**Plan:**
|
||||
- Pluggable gateway driver under `App\Services\Payments\`.
|
||||
- New endpoint `POST /api/invoices/{id}/payment-link` returns hosted URL.
|
||||
- Webhook handler that creates `PaymentRecieved` rows on capture.
|
||||
- Frontend `pay/[token]` page bundled with the portal in §3.4.
|
||||
|
||||
### 3.6 Audit log
|
||||
**Status:** No audit/activity table found.
|
||||
|
||||
**What competitors ship:** Who changed what, when, on every business
|
||||
record. Required for shops with multiple staff.
|
||||
|
||||
**Plan:**
|
||||
- Adopt `spatie/laravel-activitylog` (request before adding the dep) or
|
||||
hand-roll a polymorphic `activity_log` table.
|
||||
- Log on estimate/job-card/invoice state transitions, permission changes,
|
||||
payment events.
|
||||
- Read-only view at `/settings/activity-log`.
|
||||
|
||||
### 3.7 Workflow / Kanban board for Job Cards
|
||||
**Status:** Job Cards live in a list view. No status pipeline UI.
|
||||
|
||||
**What competitors ship:** Drag-and-drop columns ("Checked-in", "Awaiting
|
||||
Parts", "In Progress", "QC", "Ready for Pickup"). Drives the shop's day.
|
||||
|
||||
**Plan:**
|
||||
- Add `job_card_status` (enum or FK to `job_card_statuses` table editable
|
||||
in settings).
|
||||
- Backend: status transition endpoint with allowed-transition guard.
|
||||
- Frontend: new `/sales/job-cards/board` route using dnd-kit (already in
|
||||
the React ecosystem; confirm dep). Cards link to existing detail page.
|
||||
|
||||
### 3.8 Vehicle service history (per VIN, cross-customer)
|
||||
**Status:** History is currently scoped via the vehicle's job cards, but
|
||||
there is no consolidated "vehicle history" tab summarizing services,
|
||||
inspections, mileage, and recommendations together.
|
||||
|
||||
**Plan:**
|
||||
- New endpoint `GET /api/vehicles/{id}/timeline` merging job cards,
|
||||
inspections, recommendations, document expiries, mileage events into a
|
||||
single chronological feed.
|
||||
- Tab on the vehicle detail page rendering the timeline.
|
||||
|
||||
### 3.9 Recommended / deferred work tracking
|
||||
**Status:** `FastShopRecommendation` and `ShopRecommendation` models exist
|
||||
but there is no "deferred services" view that follows the vehicle across
|
||||
visits.
|
||||
|
||||
**Plan:**
|
||||
- Extend recommendations with `status` (open/accepted/declined/expired) and
|
||||
`next_followup_at`.
|
||||
- Surface on vehicle detail, estimate creation ("pull deferred items"), and
|
||||
in service-reminder logic (§3.2).
|
||||
|
||||
---
|
||||
|
||||
## 4. P1 — Significant value-add
|
||||
|
||||
### 4.1 Technician time tracking on job cards (clock in/out per labor line)
|
||||
**Status:** Generic `TimeSheet` exists but is not bound to job-card lines.
|
||||
The sidebar already shows "Time Clocks" — confirm whether implemented or
|
||||
stubbed.
|
||||
|
||||
**Plan:**
|
||||
- New table `job_card_labor_time` (job_card_service_id, employee_id,
|
||||
started_at, stopped_at).
|
||||
- Mobile-friendly start/stop UI on the job-card page (tap-and-go).
|
||||
- Feed billed-vs-clocked into the productivity report (§3.1).
|
||||
|
||||
### 4.2 Estimate templates / service packages with menus
|
||||
**Status:** Service Groups exist (`ServiceGroup`, `ServiceGroupService`,
|
||||
`ServiceGroupPart`, `ServiceGroupPricing`). Gap: no canned "menus" UI
|
||||
(e.g., "30k-mile service" preset that drops services + parts + labor onto
|
||||
an estimate in one click).
|
||||
|
||||
**Plan:**
|
||||
- Repurpose Service Groups as menus; add a "Add menu" picker on the
|
||||
estimate editor that expands the group into individual lines (so they
|
||||
can still be edited).
|
||||
|
||||
### 4.3 Customer digital signature on documents
|
||||
**Status:** Documents print to PDF; no signature capture.
|
||||
|
||||
**Plan:**
|
||||
- Add a signature pad component (svg path → PNG) on the customer portal
|
||||
approval screen (§3.4) and in-shop tablet flow.
|
||||
- Persist as a `document_signatures` row (signer name, type, timestamp,
|
||||
IP/UA, image blob in storage).
|
||||
- Embed signature in printed PDF.
|
||||
|
||||
### 4.4 Parts barcode / QR scanning
|
||||
**Status:** Parts have SKUs but no barcode field or scan UI.
|
||||
|
||||
**Plan:**
|
||||
- Add `barcode` column to `parts`.
|
||||
- Use the device camera (BarcodeDetector API) on the inventory adjustment
|
||||
and job-card "Add part" dialogs.
|
||||
|
||||
### 4.5 Tablet / shop-floor UI
|
||||
**Status:** UI is desktop-first.
|
||||
|
||||
**Plan:**
|
||||
- Audit job-card detail, inspection editor, and time-clock screens for
|
||||
touch targets and one-hand portrait use.
|
||||
- Optional dedicated route `/floor/[job-card]` with a stripped-down layout.
|
||||
|
||||
### 4.6 Photos & videos on inspections (with public share)
|
||||
**Status:** `InspectionCheckPointAttachment` and `InspectionAttachment`
|
||||
models exist — confirm whether the share link renders attachments.
|
||||
|
||||
**Plan:**
|
||||
- Verify the public inspection view (`PublicInspectionController@show`)
|
||||
exposes media URLs with signed access.
|
||||
- Add front-camera capture in the inspection editor for fast photo-taking.
|
||||
|
||||
### 4.7 Multi-location / branch support
|
||||
**Status:** `Settings` is single-tenant; no `branch_id` scoping on
|
||||
business records.
|
||||
|
||||
**Plan:** This is a bigger lift. Phased:
|
||||
1. Add `branches` table and `branch_id` FK on the major aggregates
|
||||
(job_cards, invoices, vehicles, parts, employees).
|
||||
2. Default to a single seeded branch for existing deployments.
|
||||
3. Add branch selector in header and scope queries via global scope.
|
||||
|
||||
### 4.8 Custom fields
|
||||
**Status:** No custom-field infrastructure.
|
||||
|
||||
**Plan:**
|
||||
- New `custom_field_definitions` (entity_type, key, label, type, options)
|
||||
and `custom_field_values` (polymorphic).
|
||||
- Render dynamically on customer/vehicle/job-card forms.
|
||||
|
||||
### 4.9 Marketing campaigns
|
||||
**Status:** Sidebar has the group commented out.
|
||||
|
||||
**Plan:**
|
||||
- Reuse §3.3 channels.
|
||||
- New `marketing_campaigns` (name, audience filter, template_id, schedule)
|
||||
and `marketing_sends` (per-recipient log).
|
||||
- Audience builder uses the customer/vehicle filters already in the table
|
||||
views.
|
||||
|
||||
### 4.10 Ratings & reviews capture
|
||||
**Plan:**
|
||||
- Post-pickup auto-message asking for a rating (1–5) and free text.
|
||||
- If 4–5, deep-link to Google review URL (configurable in settings).
|
||||
- Internal review wall + ability to publish to a public testimonials
|
||||
endpoint.
|
||||
|
||||
### 4.11 Accounting export (QuickBooks / Xero / Zoho)
|
||||
**Status:** No GL / chart of accounts (sidebar group is disabled).
|
||||
|
||||
**Plan (lightweight first):**
|
||||
- CSV export of invoices, payments, bills, payments-made tagged with
|
||||
configurable account codes.
|
||||
- Later: OAuth integration with QuickBooks Online / Xero APIs.
|
||||
|
||||
### 4.12 Tire & wheel module (heavy in GarageBox, Tekmetric)
|
||||
**Plan:** Tire size lookup, DOT tracking, storage racks (off-season tire
|
||||
storage is a common revenue line in cold-climate markets). Skip unless
|
||||
target market needs it.
|
||||
|
||||
### 4.13 Warranty tracking on parts and services
|
||||
**Plan:**
|
||||
- Add `warranty_months` / `warranty_km` on parts and services.
|
||||
- Show "under warranty" badge when re-invoicing the same VIN within the
|
||||
window. Block billing or flag for review.
|
||||
|
||||
### 4.14 Fleet customer accounts
|
||||
**Plan:**
|
||||
- Allow a customer to own many vehicles already supported, but add a
|
||||
"fleet" customer type with: bulk PO upload, monthly statement instead of
|
||||
per-invoice billing, optional driver/vehicle list.
|
||||
|
||||
### 4.15 Online appointment booking widget
|
||||
**Plan:**
|
||||
- Public route `/book` that surfaces shop services + free calendar slots
|
||||
(derived from `ShopTiming` and existing appointments).
|
||||
- Creates a draft `Appointment` + customer/vehicle if new.
|
||||
- Embed snippet for the shop's marketing site.
|
||||
|
||||
---
|
||||
|
||||
## 5. P2 — Differentiators
|
||||
|
||||
### 5.1 VIN decoder integration (NHTSA free API + paid Carfax)
|
||||
- NHTSA `vpic.nhtsa.dot.gov/api/` is free, no auth — wire it into the
|
||||
vehicle create form to auto-fill make/model/year/engine from VIN.
|
||||
- Carfax/AutoCheck for paid history reports (US/CA).
|
||||
|
||||
### 5.2 OEM repair info integration (Mitchell 1, AllData, Identifix, Haynes)
|
||||
- Big lift, paid feeds. Out of scope for v1; design the parts/services
|
||||
data model so labor times can be imported.
|
||||
|
||||
### 5.3 Parts catalog integrations (WorldPac, NAPA PROLink, PartsTech)
|
||||
- Real-time pricing + availability + ordering from inside a job card.
|
||||
- Phase 1: PartsTech (aggregator) since it covers the most vendors.
|
||||
|
||||
### 5.4 Two-way calendar sync (Google / Microsoft)
|
||||
- iCal feed for read-only first.
|
||||
- Full two-way sync via Google Calendar API later.
|
||||
|
||||
### 5.5 AI-assisted estimate writer
|
||||
- "Customer says: knocking noise on left front when braking" → suggested
|
||||
service lines + parts list from history of similar jobs. Useful and
|
||||
novel; defer until enough invoice data exists.
|
||||
|
||||
### 5.6 Mobile apps (technician + customer)
|
||||
- React Native (or PWA first) sharing `@garage/api`.
|
||||
- Technician: today's jobs, start/stop labor, take photos, mark complete.
|
||||
- Customer: portal features (§3.4) packaged as an app.
|
||||
|
||||
### 5.7 OBD-II / telematics integration
|
||||
- Long tail. Plan only the data model now (`vehicle_telemetry_events`).
|
||||
|
||||
### 5.8 Loyalty / gift cards / membership plans
|
||||
- "Service plan: 2 oil changes/year + 10% off for $X/mo".
|
||||
- Recurring billing on top of §3.5.
|
||||
|
||||
### 5.9 Discounts and promo codes at line-item or document level
|
||||
- Currently no promo entity. Add `discounts` (code, type, %/amount, scope,
|
||||
expiry, usage cap) with hook in estimate/invoice totals.
|
||||
|
||||
### 5.10 Multi-currency
|
||||
- `Settings` is implicitly single-currency. Add currency on documents and a
|
||||
daily rates table if shops need cross-border invoicing.
|
||||
|
||||
---
|
||||
|
||||
## 6. P3 — Long-tail / future
|
||||
|
||||
- Insurance claim workflow (estimator → adjuster handoff, photos packet,
|
||||
EMS export).
|
||||
- Inventory replenishment automation (min/max → auto PO draft).
|
||||
- Bay / lift management (assign job card to a bay; show bay utilization).
|
||||
- AI photo damage assessment for inspections.
|
||||
- Recall lookup (NHTSA recall API by VIN).
|
||||
- TPMS / tire pressure history per vehicle.
|
||||
- Public price-list / "instant quote" widget.
|
||||
- Webhook system for third-party integrators.
|
||||
- Bring-your-own-domain customer portal branding.
|
||||
- Backup export of entire tenant data (GDPR-friendly).
|
||||
|
||||
---
|
||||
|
||||
## 7. Cross-cutting platform work
|
||||
|
||||
These aren't a single feature, but unlock many of the above:
|
||||
|
||||
1. **Background job runner** — Laravel Horizon + Redis if not already set
|
||||
up; required for §3.2, §3.3, §4.9.
|
||||
2. **Storage policy** — confirm S3-compatible storage so signatures,
|
||||
media, and PDFs scale.
|
||||
3. **Feature flag system** — many of the above are tenant-gated; even a
|
||||
simple `tenant_features` table beats hard-coded toggles.
|
||||
4. **OpenAPI coverage** — every new backend endpoint must add an
|
||||
annotation so `packages/api` stays in sync (already a project
|
||||
convention).
|
||||
5. **Permission seeds** — every new route requires a matching permission
|
||||
(project rule: routes are gated by `permission.check`).
|
||||
6. **Lang pairs** — every `lang/en/*.php` key must have a matching
|
||||
`lang/ar/*.php` key (project rule).
|
||||
7. **PDF template** — every new printable type needs an entry in
|
||||
`DocumentPrintController::TYPES` plus a Blade template under
|
||||
`resources/views/pdf/`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Suggested phased roadmap
|
||||
|
||||
A pragmatic build order that maximizes early customer value and reuses
|
||||
infrastructure:
|
||||
|
||||
**Phase 1 — "Looks competitive"** (P0 core)
|
||||
- Reporting dashboard (§3.1)
|
||||
- Workflow board for job cards (§3.7)
|
||||
- Audit log (§3.6)
|
||||
- Vehicle timeline (§3.8)
|
||||
- Recommended / deferred work tracking (§3.9)
|
||||
|
||||
**Phase 2 — "Talks to the customer"**
|
||||
- Notifications channel (§3.3) — SMS + email first
|
||||
- Customer portal w/ estimate approval (§3.4)
|
||||
- Online payments (§3.5)
|
||||
- Service reminders (§3.2)
|
||||
- Ratings & reviews capture (§4.10)
|
||||
|
||||
**Phase 3 — "Runs the shop floor"**
|
||||
- Technician time tracking on labor (§4.1)
|
||||
- Estimate menus / service packages UI (§4.2)
|
||||
- Photos on inspections, end-to-end (§4.6)
|
||||
- Customer digital signature (§4.3)
|
||||
- Tablet / shop-floor UI polish (§4.5)
|
||||
|
||||
**Phase 4 — "Scales the business"**
|
||||
- Multi-location (§4.7)
|
||||
- Custom fields (§4.8)
|
||||
- Marketing campaigns (§4.9)
|
||||
- Online booking widget (§4.15)
|
||||
- Accounting exports (§4.11)
|
||||
|
||||
**Phase 5 — "Differentiators"**
|
||||
- VIN decoder (§5.1)
|
||||
- Parts catalog integrations (§5.3)
|
||||
- Calendar sync (§5.4)
|
||||
- Loyalty / memberships (§5.8)
|
||||
- Mobile apps (§5.6)
|
||||
|
||||
---
|
||||
|
||||
## 9. Open questions to confirm before starting
|
||||
|
||||
1. Target market geography — drives gateway choice (Stripe vs. local), SMS
|
||||
provider, accounting integration (QuickBooks vs. Zoho vs. Tally), and
|
||||
whether tire/snow modules matter.
|
||||
2. Is multi-tenancy single-DB (current) or DB-per-tenant?
|
||||
3. Are Horizon + Redis available in production today?
|
||||
4. Is there an approved chart library, or does adding one need a green
|
||||
light? (CLAUDE.md says no new deps without approval.)
|
||||
5. Should the customer portal share auth with the dashboard (Sanctum) or
|
||||
use a token-only public route like inspections do today?
|
||||
@@ -0,0 +1,551 @@
|
||||
# Reparee → Garage Box Feature Parity — Implementation Roadmap
|
||||
|
||||
> **Purpose of this doc.** Single source of truth for closing the gap between Reparee's current dashboard and Garage Box. Captures the gap analysis, the canonical Reparee patterns to mimic, and a per-phase implementation spec detailed enough for a fresh agent to pick up any phase and ship it without re-discovering conventions.
|
||||
|
||||
> **Status (2026-05-21).** Phase 1 (Integrations placeholder) is the only phase ready to execute. Phases 2–8 are spec'd here but not started. Pick one, re-open it in a focused planning session, and implement.
|
||||
|
||||
---
|
||||
|
||||
## 0. Reading order
|
||||
|
||||
1. **Part A — Gap analysis** (what's missing and why).
|
||||
2. **Part B — Project conventions cheatsheet** (the patterns every phase MUST follow).
|
||||
3. **Part C — Phase index** (the at-a-glance table).
|
||||
4. **Part D — Per-phase implementation specs** (Phases 1–8, in recommended build order).
|
||||
|
||||
---
|
||||
|
||||
## Part A — Gap analysis (Garage Box vs Reparee)
|
||||
|
||||
Legend: ✅ exists ⚠️ partial / different location ❌ missing
|
||||
|
||||
### Already covered
|
||||
- **Sales** (Customers, Vehicles, Inspections, Estimates, Job Cards, Invoices, Payments Received, Credit Notes) — ✅
|
||||
- **Purchases** (Vendors, Expenses, POs, Bills, Payments Made, Vendor Credits) — ✅
|
||||
- **Employees / Productivity** (Employees, Time Clocks, Time Sheets, Payroll, Shop Calendars, Shop Timing, Holidays, Tasks, Leave Requests) — ✅ (Reparee adds Leave Requests beyond Garage Box)
|
||||
- **Items** (Services, Parts, Expense Item, Service Group, Inventory Adjustments) — ✅
|
||||
- **Settings** Company / Shop Types / Tax & Rates / Configurations — ✅
|
||||
|
||||
### Gaps
|
||||
| Garage Box | Status in Reparee | Phase |
|
||||
|---|---|---|
|
||||
| Settings → Integrations | ❌ → placeholder | **Phase 1** |
|
||||
| Settings → Master (hub for body types + make & model + other lookups) | ❌ as a hub (data scattered) | **Phase 2** |
|
||||
| Settings → Templates (notification template library, ~35 templates × 4 channels) | ⚠️ only inspection templates | **Phase 3** |
|
||||
| Reports (top-level module) | ❌ | **Phase 4** |
|
||||
| CRM (Leads pipeline, Calls log + calendar, Tasks pipeline) | ❌ (Reparee has only productivity tasks, not CRM tasks) | **Phase 5** |
|
||||
| Marketing (Service Reminders, Rating & Reviews, Google Business Reviews) | ❌ | **Phase 6** |
|
||||
| Settings → Integrations (real connectors: Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp) | ❌ | **Phase 7** |
|
||||
| Accountants (Chart of Accounts + Manual Journals + default account wiring) | ❌ | **Phase 8** |
|
||||
|
||||
### Cross-cutting Garage Box conventions to mimic
|
||||
- **Pipelines** (Leads, Tasks) have user-editable column **sections** (add / rename / reorder). Default sections seeded on first run.
|
||||
- **`+ Label`** chip on every record (taxonomy / colored tags).
|
||||
- **Configurable doc-number sequences** with a gear icon next to the `#` field (`LD-000001`, `CL-000001`, `TK-000001`, `JN-000001`, etc.).
|
||||
- **Notification templates** are channel-aware (SMS / WhatsApp / Email / Push) with per-channel toggles.
|
||||
- **Per-row Department filter** is universal — every list view has a Department dropdown in the toolbar.
|
||||
|
||||
---
|
||||
|
||||
## Part B — Project conventions cheatsheet (MUST follow in every phase)
|
||||
|
||||
> Every phase below assumes these patterns. Don't re-invent.
|
||||
|
||||
### B1. Frontend module structure
|
||||
- **Modules live at** `garage-erp/apps/dashboard/modules/<area>/`.
|
||||
- Each resource gets: `<resource>-form.tsx`, `<resource>.schema.ts` (Zod), optional `<resource>-actions.tsx`, optional inline section components (e.g. `<resource>-services-section.tsx`).
|
||||
- **Reference**: `garage-erp/apps/dashboard/modules/estimates/` is the canonical example. Mirror its file layout for any new resource.
|
||||
|
||||
### B2. Routes (Next.js App Router)
|
||||
- List page: `app/(authenticated)/<area>/<resource>/page.tsx` (`"use client"` + `ResourcePage<Client>`).
|
||||
- Detail page: `app/(authenticated)/<area>/<resource>/[id]/page.tsx` (async server component, uses `getServerApi()` + `DashboardPage`).
|
||||
- Sub-tabs of a detail (e.g. notes, documents): `[id]/<subroute>/page.tsx`.
|
||||
- **Reference**: `app/(authenticated)/sales/estimates/page.tsx` (list) + `[id]/page.tsx` (detail).
|
||||
|
||||
### B3. Tables & row actions
|
||||
- Use TanStack Table via `ResourcePage` wrapper.
|
||||
- Row actions via `actionsColumn({ extraItems: (row) => [...] })`.
|
||||
- Print buttons via `useDocumentPrint(type, id)` from `apps/dashboard/shared/hooks/use-document-print.ts`.
|
||||
|
||||
### B4. Forms
|
||||
- React Hook Form 7 + Zod 4. Schema lives in `<resource>.schema.ts`.
|
||||
- Use `useResourceForm<FormValues, ApiPayload>({ schema, resourceId, initialize, mapToFormValues })` from `apps/dashboard/shared/hooks/`.
|
||||
- Mutations: `useFormMutation` for create/update; invalidate via `tableQuery.invalidateQuery()` or the resource's query key.
|
||||
|
||||
### B5. Sidebar navigation
|
||||
- Single source: `garage-erp/apps/dashboard/config/navGroups.tsx` — hard-coded, **no i18n layer**.
|
||||
- Add a new group entry or a sub-item; pick a `lucide-react` icon already imported (or add to the import block at top of file).
|
||||
|
||||
### B6. API client (`@garage/api`)
|
||||
- All clients extend `CrudClient<INDEX_ROUTE, BY_ID_ROUTE>` (path: `packages/api/src/clients/<name>.ts`).
|
||||
- After backend changes, **regenerate**: `pnpm --filter @garage/api generate` (runs `generate:openapi && generate:types`).
|
||||
- The generated files in `packages/api/` are NOT hand-edited; only the thin client wrappers are.
|
||||
|
||||
### B7. Backend routes
|
||||
- **Legacy string controller resolution** in `reparee_backend/routes/api.php`:
|
||||
```php
|
||||
Route::get('/leads', 'LeadController@index');
|
||||
Route::post('/leads', 'LeadController@store');
|
||||
// etc.
|
||||
```
|
||||
- **Every route is gated** by `permission.check` middleware (auto-applied group-wide).
|
||||
|
||||
### B8. Backend controllers
|
||||
- Standard CRUD shape: `index`, `show`, `store`, `update`, `destroy` returning `JsonResponse`.
|
||||
- Path: `reparee_backend/app/Http/Controllers/Api/<Name>Controller.php`.
|
||||
- Use `vyuldashev/laravel-openapi` annotations so OpenAPI spec stays in sync (mirror `EstimateController`).
|
||||
|
||||
### B9. Models & migrations
|
||||
- Models in `reparee_backend/app/Models/`. Use `$fillable`, `$casts`, relations.
|
||||
- Migrations: `php artisan make:migration create_<table>_table` → standard `Schema::create` with `$table->id()` + `timestamps()`.
|
||||
|
||||
### B10. Permissions
|
||||
- Permissions are **columns on the `roles` table**: `can_{view|create|update|delete}_{resource}`.
|
||||
- To add a new resource:
|
||||
1. Create a migration that adds the four boolean columns to `roles` (default `false`).
|
||||
2. Update `database/seeders/RoleSeeder.php` so Super Admin gets `true` for all new columns (it auto-discovers `can_*` columns — verify).
|
||||
3. The `permission.check` middleware reads the column name from the route name; ensure route is named `<resource>.<ability>` or matches its existing convention.
|
||||
- **Reference migration**: `2026_04_06_120000_create_roles_table_and_refactor_employee_permissions.php`.
|
||||
|
||||
### B11. i18n (backend)
|
||||
- Pairs required: every new key in `lang/en/<file>.php` MUST have the matching `lang/ar/<file>.php` key in the same change.
|
||||
- Use `__('api.<area>.<key>')` in controllers and responses.
|
||||
- Dashboard nav labels are NOT translated (hard-coded in `navGroups.tsx`).
|
||||
|
||||
### B12. Document-print (PDF)
|
||||
- Single entry: `POST /api/document-print` → `DocumentPrintController@handle`.
|
||||
- To add a printable type:
|
||||
1. Add string to `DocumentPrintController::TYPES`.
|
||||
2. Add `payload<Type>()` method on the controller.
|
||||
3. Add `resources/views/pdf/document-print-<type>.blade.php`.
|
||||
4. Add the type to the `DocumentPrintType` union in `packages/api/src/clients/document-print.ts`.
|
||||
|
||||
### B13. Pipeline-with-sections precedent
|
||||
- `TaskSection` model + `task-section-form.tsx` already exist. Fields: `title`, `arrangement` (sort order), `is_default`.
|
||||
- Reuse this pattern for `LeadSection`, `CallSection` (if needed), `JournalSection`, etc.
|
||||
|
||||
### B14. House rules (from `CLAUDE.md`)
|
||||
- Never `git commit / push / tag / reset --hard / rebase` — stop at file edits.
|
||||
- Don't add new dependencies without explicit approval.
|
||||
- After edits, run `pnpm --filter dashboard typecheck`, `pnpm --filter dashboard lint`, and `php -l` on changed PHP files, then report results.
|
||||
- Match existing conventions before introducing new patterns.
|
||||
|
||||
---
|
||||
|
||||
## Part C — Phase index
|
||||
|
||||
| # | Phase | Effort | Backend changes | Frontend changes | Depends on |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Integrations placeholder | XS (1 hr) | none | 2 files | — |
|
||||
| 2 | Settings → Master hub | S (1 day) | none (regroup) | 1 layout + tabs | — |
|
||||
| 3 | Notification Templates library | M (3 days) | new table + CRUD + permission | full module | — |
|
||||
| 4 | Reports (4 reports locked) | M (1 wk) | 4 aggregation endpoints | reports module + 4 reports w/ Recharts | reads existing data |
|
||||
| 5 | CRM (Leads, Calls, Tasks-CRM) | XL (2–3 wks) | 3 resources + sections + permissions + i18n | 3 modules + pipelines | reuses TaskSection pattern |
|
||||
| 6 | Marketing (Reminders email+SMS, Reviews) | L (1–2 wks) | reminder engine + Twilio integration + reviews | 3 sub-pages | needs Phase 3 (templates); Twilio composer dep |
|
||||
| 7 | ~~Integrations (real)~~ | DEFERRED | — | — | — |
|
||||
| 8A | Accountants — COA + Manual Journals | L (1.5 wks) | ledger UI only, no auto-post | 3 sub-pages | — |
|
||||
| 8B | Accountants — auto-posting | L (1–2 wks) | observers on Invoice/Bill/Payment/Expense + reversal | linkage panels on source docs | requires 8A stable |
|
||||
|
||||
---
|
||||
|
||||
## Part D — Per-phase implementation specs
|
||||
|
||||
# Phase 1 — Settings → Integrations (Coming Soon)
|
||||
|
||||
**Goal.** Add an Integrations entry under Settings that renders a "Coming soon" placeholder.
|
||||
|
||||
### Backend
|
||||
None.
|
||||
|
||||
### Frontend
|
||||
1. **Edit** `garage-erp/apps/dashboard/config/navGroups.tsx` (around line 183):
|
||||
- There is already a commented-out entry:
|
||||
```tsx
|
||||
// { title: "Integrations", href: "/settings/integrations/providers", icon: <PlugZapIcon /> }
|
||||
```
|
||||
- Uncomment it but change `href` to `/settings/integrations` (single page, no sub-tabs yet).
|
||||
- Insert between `Inspection Templates` and `Configurations`. Confirm `PlugZapIcon` is in the top-of-file imports; if not, add `PlugZapIcon` to the `lucide-react` import.
|
||||
|
||||
2. **Create** `garage-erp/apps/dashboard/app/(authenticated)/settings/integrations/page.tsx`:
|
||||
- Use `DashboardPage` with `headerProps={{ title: "Integrations" }}` (match `settings/insurance-types/page.tsx`).
|
||||
- Centered `Empty` block (from `@/shared/components/ui/empty`):
|
||||
- `EmptyMedia`: `<PlugZapIcon className="size-12 text-muted-foreground" />`
|
||||
- `EmptyTitle`: "Coming soon"
|
||||
- `EmptyDescription`: "Connect WhatsApp, payments, accounting and email providers. Available in an upcoming release."
|
||||
|
||||
### Verification
|
||||
1. `pnpm --filter dashboard dev`.
|
||||
2. Sidebar → Settings expands → new "Integrations" entry visible between Inspection Templates and Configurations.
|
||||
3. Click → page renders with the Empty state.
|
||||
4. `pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`.
|
||||
|
||||
### Out of scope
|
||||
Sub-tabs (Providers / Integrations), any provider logic, backend.
|
||||
|
||||
---
|
||||
|
||||
# Phase 2 — Settings → Master hub
|
||||
|
||||
**Goal.** Group existing lookup data screens under one "Master" sidebar entry with tabs, matching Garage Box's UX.
|
||||
|
||||
### Tabs (in order)
|
||||
1. Body Types (existing `/settings/...`)
|
||||
2. Make & Model (existing `/settings/make-and-models`)
|
||||
3. Insurance Types (existing `/settings/insurance-types`)
|
||||
4. Departments (existing `/settings/departments`)
|
||||
5. Shop Types (move from top-level OR alias)
|
||||
6. Vehicle Transmissions, Fuel Types, Colors, Unit Types, Payment Terms, Payment Modes, Labor Rates, Reasons, Referral Sources, Document Types, Labels — surface those that currently lack a dedicated screen.
|
||||
|
||||
### Backend
|
||||
None new. Verify every tab's data source has a controller in `app/Http/Controllers/Api/` (most already do: `MakeAndModelController`, `InsuranceTypeController`, `DepartmentController`, `VehicleBodyTypeController`, `VehicleTransmissionController`, `VehicleFuelTypeController`, `VehicleColorController`, `UnitTypeController`, `PaymentTermController`, `PaymentModeController`, `LaborRateController`, `ReasonController`, `ReferralSourceController`, `DocumentTypeController`, `LabelController`).
|
||||
|
||||
### Frontend
|
||||
1. **Create** `app/(authenticated)/settings/master/layout.tsx` with a `Tabs` header (use existing `Tabs` from `packages/ui`) and the 11+ tab labels above.
|
||||
2. **Create** `app/(authenticated)/settings/master/page.tsx` that redirects to `./body-types`.
|
||||
3. **Create** `app/(authenticated)/settings/master/<each-tab>/page.tsx`. Each is a thin wrapper that imports and renders the existing module list component from `modules/settings/<existing-folder>/`.
|
||||
4. **Edit** `config/navGroups.tsx`: add `{ title: "Master", href: "/settings/master", icon: <DatabaseIcon /> }` after Integrations. **Keep** the existing top-level entries (Insurance Types, Departments, Make & Models) in the Settings list — they coexist as aliases for backwards-compat (per Part F decision).
|
||||
|
||||
### Verification
|
||||
1. Sidebar → Settings → Master → tabs render and each tab CRUDs correctly.
|
||||
2. Direct URL `/settings/master/insurance-types` works.
|
||||
3. Removed/aliased entries still resolve to the same screen.
|
||||
|
||||
---
|
||||
|
||||
# Phase 3 — Notification Templates library
|
||||
|
||||
**Goal.** Manage ~35 notification templates (per Garage Box screenshot 16) with per-channel toggles and bodies. Required for Phase 6 (Marketing) and any reminder/automation.
|
||||
|
||||
### Data model
|
||||
| Table | Columns |
|
||||
|---|---|
|
||||
| `notification_templates` | `id`, `key` (unique e.g. `appointment_created`), `title`, `description` (nullable), `created_at`, `updated_at` |
|
||||
| `notification_template_channels` | `id`, `notification_template_id` (FK), `channel` enum(`sms`,`whatsapp`,`email`,`push`), `enabled` bool, `subject` (nullable, for email), `body` text, `created_at`, `updated_at` |
|
||||
|
||||
Seed all template `key`s from this list (extracted from Garage Box image 16):
|
||||
- `appointment_assigned`, `appointment_cancelled`, `appointment_confirmed`, `appointment_create`, `appointment_no_shows`, `appointment_reminder`, `appointment_requested`, `appointment_reschedule`, `appointment_unconfirmed`
|
||||
- `attendance_details`, `attendance_reminder`
|
||||
- `call_assigned`, `call_cancelled`, `call_completed`, `call_rescheduled`, `call_scheduled`
|
||||
- `estimate_approved_by_admin`, `estimate_approved_by_customer`, `estimate_send`
|
||||
- `job_card_customer`, `job_card_technician`
|
||||
- `login_otp`
|
||||
- `new_lead_notification`
|
||||
- `part_requisition_create`
|
||||
- `purchase_order_create`
|
||||
- `ratings_reviews_link`
|
||||
- `salary_change_notification`
|
||||
- `send_customer_statement`, `send_inspection`, `send_invoice`, `send_vendor_statement`
|
||||
- `service_reminder_cancelled`, `service_reminder_reschedule`, `service_reminder_scheduled`, `service_reminder_send`
|
||||
- `work_request_form_send`, `workorder_create`
|
||||
|
||||
### Backend
|
||||
- `NotificationTemplateController` (`index`, `show`, `update` only — templates are seeded, not user-created).
|
||||
- Routes (string-resolution style):
|
||||
```php
|
||||
Route::get('/notification-templates', 'NotificationTemplateController@index');
|
||||
Route::get('/notification-templates/{key}', 'NotificationTemplateController@show');
|
||||
Route::put('/notification-templates/{key}', 'NotificationTemplateController@update');
|
||||
```
|
||||
- Permissions: `can_view_notification_templates`, `can_update_notification_templates` (skip create/delete — seed-managed).
|
||||
- Lang keys in `lang/en/api.php` + `lang/ar/api.php` under `notification_templates`.
|
||||
|
||||
### Frontend
|
||||
1. **Module** `apps/dashboard/modules/notification-templates/` with `notification-template-row.tsx`, `notification-template-edit-dialog.tsx`, `notification-template.schema.ts`.
|
||||
2. **Route** `app/(authenticated)/settings/templates/notifications/page.tsx` — TanStack Table with columns: Title, SMS (✓/—), WhatsApp, Email, Push, Actions.
|
||||
3. **Sidebar entry**: `config/navGroups.tsx` add `{ title: "Templates", href: "/settings/templates/notifications", icon: <FileTextIcon /> }` between Inspection Templates and Integrations. (Or restructure existing `/settings/templates` if free.)
|
||||
4. **Edit dialog**: tabs per channel, body editor with **variable picker** (e.g. `{{customer.name}}`, `{{vehicle.plate}}`, `{{appointment.date}}`). Variables list lives in a `notification-template-variables.ts` constants file co-located with the module.
|
||||
5. **API client**: `packages/api/src/clients/notification-templates.ts` extends `CrudClient`.
|
||||
|
||||
### Verification
|
||||
1. Seeded list shows all 35+ rows.
|
||||
2. Toggle a channel → persists.
|
||||
3. Edit body → re-render shows updated body.
|
||||
4. Backend `__('api.notification_templates.updated')` returns Arabic when locale is `ar`.
|
||||
|
||||
---
|
||||
|
||||
# Phase 4 — Reports
|
||||
|
||||
**Goal.** Top-level Reports module with categorized reports across Sales, Purchases, Inventory, Employees, Accountants.
|
||||
|
||||
### Reports to ship (v1 — locked per Part F)
|
||||
1. **Sales by Customer** — revenue grouped by customer with date range + department filter.
|
||||
2. **Invoices Aging** — outstanding invoices bucketed 0–30 / 31–60 / 61–90 / 90+ days.
|
||||
3. **Technician Productivity** — hours logged vs billable per technician, derived from `TimeSheet` + job-card service rows.
|
||||
4. **Inventory Valuation + Low-Stock** — current stock value by part + list of parts under reorder threshold.
|
||||
|
||||
All other reports candidates (Sales by Service/Vehicle, Payments Summary, Estimates Conversion, Purchases by Vendor, Bills Aging, Stock Movement, Attendance, Payroll, Job Card Turnaround/Status) are deferred to a follow-up phase. Architect the reports module so adding the 5th report is trivial.
|
||||
|
||||
### Charting
|
||||
Use **Recharts** via the already-installed wrapper `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency. Wrapper exports `ChartContainer`, `ChartTooltip`, `ChartTooltipContent`, etc. — mimic shadcn's chart usage docs.
|
||||
|
||||
### Backend
|
||||
- `app/Http/Controllers/Api/Reports/` directory — one controller per report category (`SalesReportController`, `PurchasesReportController`, etc.).
|
||||
- Each report = single GET endpoint accepting `from`, `to`, optional `department_id`, `customer_id`, etc. Returns aggregated rows.
|
||||
- Use Eloquent + `selectRaw` aggregations. Index any frequently-grouped columns via migration.
|
||||
- Routes grouped under `/api/reports/...`. New permission per category: `can_view_reports_sales`, `can_view_reports_purchases`, ...
|
||||
- **No new models or tables** — pure read aggregation over existing data.
|
||||
- Lang keys for report titles in `lang/en/reports.php` + `lang/ar/reports.php`.
|
||||
|
||||
### Frontend
|
||||
1. **Module** `apps/dashboard/modules/reports/` with:
|
||||
- `report-card.tsx` (preview tile in the index).
|
||||
- `report-filters.tsx` (date range, department, customer/vendor).
|
||||
- One subdirectory per category: `sales/`, `purchases/`, `inventory/`, `employees/`, `job-cards/`. Each contains a `<report-name>-report.tsx` data view.
|
||||
2. **Routes**:
|
||||
- `app/(authenticated)/reports/page.tsx` — index grid of report cards grouped by category.
|
||||
- `app/(authenticated)/reports/<category>/<slug>/page.tsx` — individual report view with filters + table + export buttons.
|
||||
3. **Sidebar**: add a new top-level group `{ title: "Reports", href: "/reports", icon: <BarChart3Icon /> }` after Items/Employees in `navGroups.tsx`.
|
||||
4. **Export**: reuse `useDocumentPrint` pattern for PDF; for Excel use existing `maatwebsite/excel` backend integration (add new export classes in `app/Exports/Reports/`).
|
||||
5. **Charts**: prefer `recharts` if already in `packages/ui` dependencies; otherwise propose to user before adding.
|
||||
|
||||
### Verification
|
||||
1. Each report renders with sample data filtered by date range.
|
||||
2. PDF export uses the same layout shell as other prints (`resources/views/pdf/layouts/document.blade.php`).
|
||||
3. Excel export downloads a valid `.xlsx`.
|
||||
4. Permissions block access when role lacks `can_view_reports_<category>`.
|
||||
|
||||
---
|
||||
|
||||
# Phase 5 — CRM (Leads, Calls, Tasks-CRM)
|
||||
|
||||
**Goal.** Add the missing CRM module with three pipelines: Leads, Calls, Tasks (distinct from existing productivity tasks). Mirrors Garage Box screenshots 1–8.
|
||||
|
||||
### Sub-phase 5a — Leads
|
||||
|
||||
#### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `lead_sections` | `id`, `title`, `arrangement`, `is_default`, `kind` enum(`open`,`won`,`lost`) (kind drives default behavior). Reuse `TaskSection` pattern. |
|
||||
| `leads` | `id`, `number` (unique, e.g. `LD-000001`), `title`, `date`, `lead_owner_id` (FK users), `referral_source_id` (FK), `lead_status_id` (FK), `department_id`, `description`, `lead_section_id` (FK), `customer_id` (nullable), `vehicle_id` (nullable), salutation, first/last/company name, phone, email, address fields, vehicle fields (make, model, plate, body_type_id). |
|
||||
| `lead_services` | pivot to services |
|
||||
| `lead_parts` | pivot to parts |
|
||||
| `lead_labels` | pivot to `labels` table |
|
||||
|
||||
#### Backend
|
||||
- `LeadController`, `LeadSectionController`, `LeadServiceController`, `LeadPartController` (mirror Estimate's split).
|
||||
- Permissions: `can_view_leads`, `can_create_leads`, `can_update_leads`, `can_delete_leads`, plus `can_manage_lead_sections`.
|
||||
- Number sequence: reuse `InvoiceSequenceController` pattern (add `LeadSequenceController`).
|
||||
- Lang keys under `lang/en/api.php` `leads` section + `lang/ar/api.php`.
|
||||
- OpenAPI annotations on each method.
|
||||
|
||||
#### Frontend
|
||||
- **Module** `apps/dashboard/modules/leads/` with `lead-form.tsx`, `lead.schema.ts`, `lead-pipeline.tsx` (Kanban view), `lead-actions.tsx`, inline sections for services/parts.
|
||||
- **Routes** `app/(authenticated)/crm/leads/page.tsx` (Kanban + table toggle), `[id]/page.tsx` (detail).
|
||||
- **Sidebar** new group `{ title: "CRM", icon: <UsersIcon />, items: [Leads, Calls, Tasks] }` after Purchases in `navGroups.tsx`.
|
||||
- **Pipeline UI**: Kanban with `@dnd-kit` (check if already in deps before adding). Each column = a `LeadSection`. "+ Section" button opens a section dialog (reuse `task-section-form.tsx` pattern).
|
||||
- **API client** `packages/api/src/clients/leads.ts`.
|
||||
|
||||
### Sub-phase 5b — Calls
|
||||
|
||||
#### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `calls` | `id`, `number` (`CL-000001`), `call_for` (polymorphic morphs to Customer/Lead), `vehicle_id`, `status` enum(`requested`,`scheduled`,`completed`,`cancelled`), `type` enum(`inbound`,`outbound`), `subject`, `call_owner_id`, `call_date`, `from_time`, `to_time`, `department_id`, `purpose_id` (FK to lookup), `agenda` text, `outcome_id` (nullable FK), `description`, `duration_minutes`, `duration_seconds`, `voice_recording_path`, `send_notification` bool. |
|
||||
| `call_reminders` | `id`, `call_id`, `unit` int, `unit_type` enum(`minute`,`hour`,`day`), `event` enum(`before`,`after`), `channel` enum(`sms`,`email`,`whatsapp`). |
|
||||
| `call_purposes`, `call_outcomes` | lookups |
|
||||
|
||||
#### Backend
|
||||
- `CallController` (CRUD + special endpoints: `complete`, `cancel`, `reschedule`).
|
||||
- `CallReminderController` (nested).
|
||||
- Reminder dispatcher: a Laravel scheduled job in `app/Console/Commands/SendDueCallReminders.php` runs every minute, sends pending reminders via the relevant notification template (Phase 3) through the provider configured in Phase 7. If Phase 7 not yet shipped, log-only.
|
||||
- Permissions: standard four + `can_log_calls`, `can_complete_calls`.
|
||||
|
||||
#### Frontend
|
||||
- **Module** `apps/dashboard/modules/calls/` with `call-form.tsx` (schedule), `call-log-form.tsx` (log), `call.schema.ts`, `call-calendar.tsx`.
|
||||
- **Routes** `app/(authenticated)/crm/calls/page.tsx` (table + tabs Requested/Scheduled/Completed/Cancelled), `crm/calls/calendar/page.tsx` (month view), `[id]/page.tsx`.
|
||||
|
||||
### Sub-phase 5c — Tasks (CRM)
|
||||
|
||||
**Approach locked per Part F: Option A — extend existing `tasks` table.**
|
||||
|
||||
#### Migration
|
||||
Add to the existing `tasks` table:
|
||||
- `context` enum (`productivity`, `crm`), default `productivity`, NOT NULL.
|
||||
- `customer_id` nullable FK to `customers`.
|
||||
- `vehicle_id` nullable FK to `vehicles`.
|
||||
- Index on `(context, status)` for the pipeline filter.
|
||||
|
||||
#### Backend
|
||||
- Backfill existing rows to `context = 'productivity'`.
|
||||
- All existing `TaskController` queries get a `->where('context', 'productivity')` filter so `/productivity/tasks` keeps showing only what it shows today.
|
||||
- Add `CrmTaskController` (thin) that scopes to `context = 'crm'` and exposes the same CRUD + section endpoints. Reuse the `TaskSection` table for sections (add a `context` column there too, same enum).
|
||||
- Permissions: introduce `can_view_crm_tasks`, `can_create_crm_tasks`, `can_update_crm_tasks`, `can_delete_crm_tasks` separate from the existing productivity-task permissions.
|
||||
|
||||
#### Frontend
|
||||
- New module `apps/dashboard/modules/crm-tasks/` mirroring Leads pipeline pattern (Kanban with sections).
|
||||
- Route `app/(authenticated)/crm/tasks/page.tsx` (Kanban + table toggle).
|
||||
- Re-use schema fragments from `modules/tasks/` where possible — extract shared bits to a `modules/tasks/shared/` if duplication grows.
|
||||
|
||||
### Verification (Phase 5 overall)
|
||||
1. Pipeline drag-and-drop persists section + arrangement.
|
||||
2. New lead with vehicle info creates a corresponding draft Customer + Vehicle (or links existing) — confirm desired behavior.
|
||||
3. Call scheduled with a 10-min reminder → cron job fires at expected time.
|
||||
4. Number sequences advance correctly when a record is created.
|
||||
|
||||
---
|
||||
|
||||
# Phase 6 — Marketing (Service Reminders + Reviews)
|
||||
|
||||
**Goal.** Automate service reminders based on mileage / time, plus collect and surface customer reviews.
|
||||
|
||||
### Service Reminders
|
||||
- New table `service_reminders`: `id`, `customer_id`, `vehicle_id`, `reminder_type` (`mileage` / `time`), `interval_value`, `interval_unit`, `last_triggered_at`, `next_due_at`, `status` enum(`scheduled`,`sent`,`cancelled`), `channels` JSON (subset of `['email','sms']`).
|
||||
- Scheduled command `app/Console/Commands/SendDueServiceReminders.php` runs daily; sends via Phase 3 templates (`service_reminder_send`).
|
||||
- **Channels (per Part F)**: **Email** via Laravel `Mail::to(...)->send(...)` using the configured mail sender; **SMS** via Twilio.
|
||||
- Install `twilio/sdk` (Composer) — flag this dependency add for user approval per CLAUDE.md house rules.
|
||||
- Add a `NotificationDispatcher` service in `app/Services/Notifications/` with `sendEmail()` and `sendSms()` methods. Reads Twilio credentials from `config/services.php` (`twilio.sid`, `twilio.token`, `twilio.from`) which read from `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`).
|
||||
- WhatsApp/Push channel toggles render but are disabled with a "Requires integration" tooltip — wiring up to providers happens in deferred Phase 7.
|
||||
- Frontend: `app/(authenticated)/marketing/service-reminders/page.tsx` — list with status tabs, "Create reminder" form with Email + SMS channel checkboxes.
|
||||
|
||||
### Rating & Reviews
|
||||
- New table `customer_reviews`: `id`, `customer_id`, `job_card_id`, `rating` 1–5, `comment`, `submitted_at`, `source` enum(`internal`,`google`).
|
||||
- Public-facing review form already partially served by `PublicInspectionController` pattern — extend with `PublicReviewController`.
|
||||
- After job-card completion, fire `ratings_reviews_link` template (Phase 3).
|
||||
- Frontend list at `app/(authenticated)/marketing/reviews/page.tsx`.
|
||||
|
||||
### Google Business Reviews
|
||||
- Read-only sync via Google Business Profile API (requires Phase 7 Google integration).
|
||||
- Background job polls every 6 h.
|
||||
- Render in same Reviews list with `source = google` badge.
|
||||
|
||||
### Sidebar
|
||||
- Add CRM-style group `{ title: "Marketing", icon: <MegaphoneIcon />, items: [Service Reminders, Reviews, Google Reviews] }` after CRM.
|
||||
|
||||
### Verification
|
||||
1. Create a mileage-based reminder → next_due_at calculated.
|
||||
2. Cron tick at due time → template send is recorded (or logged if Phase 7 incomplete).
|
||||
3. Submit a public review → appears in admin list.
|
||||
|
||||
---
|
||||
|
||||
# Phase 7 — Integrations (real connectors) — DEFERRED
|
||||
|
||||
**Status (per Part F decision): NOT IN ROADMAP.** The Phase 1 "Coming soon" placeholder is the long-term state for now. Twilio (SMS) and Laravel mail (email) used by Phase 6 are configured via `.env` only — no user-facing integrations UI.
|
||||
|
||||
Keep this spec as reference for when integrations become a priority later.
|
||||
|
||||
**Goal (when revived).** Replace the Phase 1 placeholder with a real Providers/Integrations page connecting Google, Microsoft, Zoho, Interakt, Respond, Vonage, Geidea, MSG91, Wati, Xero, WhatsApp. Twilio also moves into the UI at that point.
|
||||
|
||||
### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `integration_providers` | seeded list: `id`, `key` (slug), `name`, `purpose`, `icon_path`, `auth_type` (`oauth2`/`api_key`/`webhook`), `is_active`. |
|
||||
| `integration_connections` | per-tenant connection: `id`, `provider_id`, `credentials` (encrypted JSON), `status` (`connected`/`disconnected`/`error`), `last_synced_at`. |
|
||||
|
||||
### Backend
|
||||
- `IntegrationProviderController` (list), `IntegrationConnectionController` (CRUD + `connect`, `disconnect`, `test`).
|
||||
- One service class per provider in `app/Services/Integrations/<Provider>/`. Each implements a common contract `IntegrationDriver` with `connect()`, `disconnect()`, `sendMessage()`, `pullData()`.
|
||||
- OAuth callback routes: `/integrations/{provider}/callback`.
|
||||
- Permissions: `can_manage_integrations`.
|
||||
- Lang keys for connection status messages.
|
||||
|
||||
### Frontend
|
||||
- **Replace** the Phase 1 placeholder page with `app/(authenticated)/settings/integrations/page.tsx` showing a `Tabs` of "Providers" (catalog) + "Integrations" (connected list).
|
||||
- **Provider catalog tile** with "Connect" button → opens OAuth popup or credentials dialog.
|
||||
- Update `navGroups.tsx`: `href: "/settings/integrations/providers"` (the original commented-out path).
|
||||
|
||||
### Verification
|
||||
1. Connect Google → OAuth popup → callback persists tokens → "Connected" badge appears.
|
||||
2. Test SMS via Vonage → message delivered (in sandbox).
|
||||
3. Disconnect → credentials zeroed.
|
||||
|
||||
### Out of scope for first cut
|
||||
Real-time webhook handlers for each provider (do them incrementally, one provider per follow-up PR).
|
||||
|
||||
---
|
||||
|
||||
# Phase 8 — Accountants
|
||||
|
||||
**Goal.** Introduce a real general ledger. Split into two sub-phases per Part F: ship the ledger UI first (8A), wire auto-posting into existing modules afterward (8B).
|
||||
|
||||
## Phase 8A — Chart of Accounts + Manual Journals + Default Configuration
|
||||
|
||||
Ship the standalone ledger. No existing controllers are touched. Users can manually post journal entries; nothing auto-posts.
|
||||
|
||||
### Data model
|
||||
| Table | Key columns |
|
||||
|---|---|
|
||||
| `chart_of_accounts` | `id`, `name`, `code` (nullable), `account_type` enum(`asset`,`liability`,`equity`,`income`,`expense`,`cogs`), `parent_id` (nullable, for sub-accounts), `is_system` bool (lock icon in UI), `note`. |
|
||||
| `journals` | `id`, `number` (`JN-000001`), `date`, `reference`, `notes`, `total_amount` (must balance), `posted_by`, `posted_at`. |
|
||||
| `journal_lines` | `id`, `journal_id`, `account_id`, `debit`, `credit`, `description`. Constraint: sum(debit) == sum(credit) per journal. |
|
||||
| `default_account_settings` | single-row config table for: `sales_account_id`, `purchase_account_id`, `inventory_account_id`, `adjustment_account_id`, `customer_advance_account_id`, `deposit_to_account_id`, `vendor_advance_account_id`, `paid_through_account_id`, `purchase_discount_account_id`, `expense_account_id`. |
|
||||
|
||||
### Seed
|
||||
Seed ~80 standard accounts matching Garage Box screenshot 9 (Accounts Payable, Accounts Receivable, Advance Tax, … VAT Payable). Mark system accounts (`is_system = true`).
|
||||
|
||||
### Backend (8A only)
|
||||
- `ChartOfAccountController`, `JournalController`, `DefaultAccountSettingsController`.
|
||||
- Permissions: `can_view_accountants`, `can_manage_chart_of_accounts`, `can_post_journals`.
|
||||
- OpenAPI annotations.
|
||||
- **No changes to existing controllers** in this sub-phase — Invoices/Bills/Payments/Expenses are untouched.
|
||||
|
||||
### Frontend
|
||||
- **Sidebar group** `{ title: "Accountants", icon: <BookOpenIcon />, items: [Manual Journals, Chart Of Accounts] }` after Purchases.
|
||||
- **Module** `apps/dashboard/modules/accountants/` with `chart-of-account-list.tsx`, `chart-of-account-form.tsx`, `journal-form.tsx` (multi-line debit/credit with running balance check), `default-account-settings-form.tsx`.
|
||||
- **Routes**: `app/(authenticated)/accountants/chart-of-accounts/page.tsx`, `accountants/manual-journals/page.tsx`, `[id]/page.tsx`.
|
||||
|
||||
### Verification (8A)
|
||||
1. Seed list matches Garage Box exactly (account names + types).
|
||||
2. Create a manual journal with unbalanced lines → backend rejects.
|
||||
3. Default Configuration dialog persists.
|
||||
4. Invoices/Bills/Payments/Expenses still work unchanged (no regression).
|
||||
|
||||
## Phase 8B — Auto-posting + cross-doc linking
|
||||
|
||||
Wire the ledger into operational modules. **Only start after 8A is stable in production.**
|
||||
|
||||
### Backend
|
||||
- New service `app/Services/Accounting/JournalPoster.php` with methods like `postInvoice(Invoice $i)`, `postBill(Bill $b)`, `postPaymentReceived(...)`, `postPaymentMade(...)`, `postExpense(...)`.
|
||||
- Hook into existing controllers via Eloquent `created` / `updated` model observers (cleaner than editing every controller). Observers live in `app/Observers/`, registered in `EventServiceProvider`.
|
||||
- Each posted journal gets a `source_type` + `source_id` morphable pair so it links back to the originating document.
|
||||
- Reversal logic: when a source doc is deleted or voided, post the reverse journal (don't soft-delete the original).
|
||||
- New permission: `can_post_automatic_journals` (default true for finance roles).
|
||||
|
||||
### Frontend
|
||||
- On Invoice / Bill / Payment / Expense detail pages: add a "Journal Entry" panel showing the posted journal lines (read-only) with a deep link to `/accountants/manual-journals/<id>`.
|
||||
- On Journal detail: show "Source Document" link back to the originating doc.
|
||||
|
||||
### Verification (8B)
|
||||
1. Create an Invoice → Journal auto-posts (debit AR, credit Sales, credit Tax).
|
||||
2. Edit Invoice amount → existing journal reversed + new one posted.
|
||||
3. Delete Invoice → reversal posted; original journal preserved for audit.
|
||||
4. Default Configuration changes are respected on next post.
|
||||
5. Audit trail: every Journal has a non-null `source_type`/`source_id` when auto-posted.
|
||||
|
||||
---
|
||||
|
||||
## Part E — Cross-cutting follow-ups (every phase finishes with)
|
||||
|
||||
1. Run **`pnpm --filter dashboard typecheck && pnpm --filter dashboard lint`** — must pass.
|
||||
2. Run **`php -l`** on every changed PHP file.
|
||||
3. Regenerate API client if backend changed: **`pnpm --filter @garage/api generate`**.
|
||||
4. Update lang pairs (`lang/en/*.php` + `lang/ar/*.php`).
|
||||
5. Update permission migration + seeder for any new permission columns.
|
||||
6. Use the `code-review-graph` MCP `detect_changes_tool` + `get_review_context_tool` before opening the PR to self-review.
|
||||
7. Update `claude-timeline/YYYY-MM-DD.md` with a one-line note about the phase shipped (per global memory rule).
|
||||
8. **Do not commit** — leave the diff for the user to review.
|
||||
|
||||
---
|
||||
|
||||
## Part F — Resolved decisions (2026-05-21)
|
||||
|
||||
All open questions answered by the user. These are now binding for the phases referenced.
|
||||
|
||||
- **Phase 2 (Master)** → **Keep top-level entries as aliases.** Insurance Types, Departments, Make & Models remain in the Settings sidebar AND appear under Master tabs. Backwards-compat for bookmarks. No redirects, no removals.
|
||||
- **Phase 4 (Reports) — charts** → **Use Recharts (already installed)** via the existing wrapper at `garage-erp/apps/dashboard/shared/components/ui/chart.tsx`. No new dependency.
|
||||
- **Phase 4 (Reports) — v1 scope** → ship exactly these four reports:
|
||||
1. Sales by Customer
|
||||
2. Invoices Aging (0–30 / 31–60 / 61–90 / 90+ days)
|
||||
3. Technician Productivity (hours logged vs billable per technician)
|
||||
4. Inventory Valuation + Low-Stock
|
||||
All other reports listed in Phase 4 are deferred.
|
||||
- **Phase 5c (CRM Tasks)** → **Extend the existing `tasks` table** (Option A). Add `context` enum (`productivity` | `crm`), nullable `customer_id`, nullable `vehicle_id`. All existing task queries get a `context = 'productivity'` filter.
|
||||
- **Phase 6 (Marketing reminders) — channels** → **Email + SMS in v1; WhatsApp deferred.**
|
||||
- Email sends via Laravel's configured mail sender (`config/mail.php`) — works out of the box, no Integrations UI required.
|
||||
- SMS sends via **Twilio**. Configured server-side via `.env` (`TWILIO_SID`, `TWILIO_TOKEN`, `TWILIO_FROM`) — not surfaced in the Integrations page yet.
|
||||
- WhatsApp channel toggles are visible but disabled with a "Requires integration" tooltip.
|
||||
- **Phase 7 (Integrations real)** → **Stays "coming soon."** The Phase 1 placeholder is the long-term state for now. Twilio + Laravel mail are configured server-side only; no user-facing connector UI in this roadmap. Phase 7's detailed spec is preserved as a future reference but no work is planned.
|
||||
- **Phase 8 (Accountants)** → **Split into two sub-phases:**
|
||||
- **Phase 8A**: Chart of Accounts + Manual Journals + Default Configuration UI. No automatic posting from other modules.
|
||||
- **Phase 8B**: Auto-post journals on Invoice / Bill / Payment / Expense create + link from each source doc to its posted journal entry. Big blast radius — ship only after 8A is stable.
|
||||
@@ -5,11 +5,12 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon, ExternalLinkIcon } from "lucide-react"
|
||||
import { CalendarCheck2Icon, ClipboardListIcon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -26,6 +27,9 @@ export default function AppointmentsPage() {
|
||||
<ResourcePage<AppointmentsClient>
|
||||
pageTitle="Appointments"
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
@@ -77,7 +81,7 @@ export default function AppointmentsPage() {
|
||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||
return (
|
||||
<Badge className={colorClass}>
|
||||
{status?.replace("_", " ") ?? "—"}
|
||||
{formatEnum(status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
@@ -86,22 +90,14 @@ export default function AppointmentsPage() {
|
||||
id: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const jobCardId = (row.original as any).job_card_id
|
||||
if (!jobCardId) return <span className="text-muted-foreground">—</span>
|
||||
const item = row.original as any
|
||||
const jobCardId = item.job_card_id ?? item.job_card?.id
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
router.push(`/sales/job-cards/${jobCardId}`)
|
||||
}}
|
||||
>
|
||||
<ClipboardListIcon className="size-3" />
|
||||
#{jobCardId}
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Button>
|
||||
<RelationLink
|
||||
href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -201,15 +201,20 @@ export default function InventoryAdjustmentsPage() {
|
||||
<ResourcePage<InventoryAdjustmentsClient>
|
||||
pageTitle="Inventory Adjustments"
|
||||
routeKey={INVENTORY_ADJUSTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search adjustments..."
|
||||
getClient={(api) => api.inventoryAdjustments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inventory Adjustment">
|
||||
{(resourceId) => (
|
||||
<FormDialog
|
||||
title="Inventory Adjustment"
|
||||
classNames={{ dialogContent: "lg:min-w-4xl" }}
|
||||
>
|
||||
{(resourceId, { close }) => (
|
||||
<InventoryAdjustmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => { invalidateQuery(); close() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ExpenseItemForm } from "@/modules/expense-items/expense-item-form"
|
||||
import { EXPENSE_ITEM_ROUTES } from "@garage/api"
|
||||
import type { ExpenseItemsClient } from "@garage/api"
|
||||
|
||||
export default function ExpenseItemPage() {
|
||||
return (
|
||||
<ResourcePage<ExpenseItemsClient>
|
||||
pageTitle="Expense Items"
|
||||
routeKey={EXPENSE_ITEM_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expense items..."
|
||||
getClient={(api) => api.expenseItems}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Expense Item">
|
||||
{(resourceId, { close }) => (
|
||||
<ExpenseItemForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "item_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Item Name" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Purchase Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_chart_of_account",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Chart of Account" />,
|
||||
cell: ({ row }) => (row.original as any).purchase_chart_of_account || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<span className={active ? "text-green-600" : "text-muted-foreground"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +1,37 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { PartForm } from "@/modules/parts/part-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { partColumns } from "@/modules/parts/parts-columns"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { PARTS_ROUTES } from "@garage/api"
|
||||
import type { PartsClient } from "@garage/api"
|
||||
|
||||
export default function PartsPage() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<ResourcePage<PartsClient>
|
||||
pageTitle="Parts"
|
||||
routeKey={PARTS_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search parts..."
|
||||
getClient={(api) => api.parts}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.parts.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Parts"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.parts.exportData(filters)}
|
||||
fileName="parts"
|
||||
/>
|
||||
<FormDialog title="Part">
|
||||
{(resourceId) => (
|
||||
<PartForm
|
||||
@@ -25,72 +41,21 @@ export default function PartsPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
return (
|
||||
<div>
|
||||
<span className="font-medium">{r.title || "—"}</span>
|
||||
{r.sku && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{r.sku}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "part_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Part #" />,
|
||||
cell: ({ row }) => (row.original as any).part_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "manufactured_by",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Manufacturer" />,
|
||||
cell: ({ row }) => (row.original as any).manufactured_by || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "selling_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Sell Price" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).selling_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "purchase_price",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).purchase_price
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<Badge variant={active ? "default" : "secondary"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
partColumns.title,
|
||||
partColumns.partNumber,
|
||||
partColumns.manufacturer,
|
||||
partColumns.sellingPrice,
|
||||
partColumns.purchasePrice,
|
||||
partColumns.stock,
|
||||
partColumns.status,
|
||||
partColumns.createdAt,
|
||||
actionsColumn(),
|
||||
]}
|
||||
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ServiceGroupPage() {
|
||||
<ResourcePage<ServiceGroupsClient>
|
||||
pageTitle="Service Groups"
|
||||
routeKey={SERVICE_GROUP_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search service groups..."
|
||||
getClient={(api) => api.serviceGroups}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -3,18 +3,35 @@
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ServiceForm } from "@/modules/services/service-form"
|
||||
import { SERVICE_ROUTES } from "@garage/api"
|
||||
import type { ServicesClient } from "@garage/api"
|
||||
|
||||
export default function ServicesPage() {
|
||||
const api = useAuthApi()
|
||||
|
||||
return (
|
||||
<ResourcePage<ServicesClient>
|
||||
pageTitle="Services"
|
||||
routeKey={SERVICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search services..."
|
||||
getClient={(api) => api.services}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.services.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Services"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.services.exportData(filters)}
|
||||
fileName="services"
|
||||
/>
|
||||
<FormDialog title="Service">
|
||||
{(resourceId) => (
|
||||
<ServiceForm
|
||||
@@ -24,6 +41,7 @@ export default function ServicesPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -48,7 +66,7 @@ export default function ServicesPage() {
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).description
|
||||
return val
|
||||
? <span className="max-w-[200px] truncate block">{val}</span>
|
||||
? <span className="max-w-50 truncate block">{val}</span>
|
||||
: "—"
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { DashboardHeader } from "@/base/components/layout/dashboard";
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page";
|
||||
import { DashboardContent } from "@/modules/home/dashboard-content";
|
||||
import { DashboardFiltersToolbar } from "@/modules/home/dashboard-filters-toolbar";
|
||||
|
||||
export default function page() {
|
||||
return (
|
||||
<DashboardPage headerProps={{title: "Dashboard"}} >
|
||||
<DashboardPage headerProps={{ title: "Dashboard", actions: <DashboardFiltersToolbar /> }} >
|
||||
<DashboardContent />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -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> : "—"
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { Plus, Trash2, ExternalLinkIcon, AwardIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EmployeeCertificationForm } from "@/modules/employees/employee-certification-form"
|
||||
|
||||
type CertRow = {
|
||||
id: number
|
||||
name: string
|
||||
issuer?: string | null
|
||||
certificate_number?: string | null
|
||||
issued_date?: string | null
|
||||
expiry_date?: string | null
|
||||
file_url?: string | null
|
||||
is_expired?: boolean
|
||||
notes?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
export default function EmployeeCertificationsPage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
const queryKey = ["employee-certifications", employeeId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.employees.listCertifications(employeeId) as Promise<{ data: CertRow[] | { data: CertRow[] } }>,
|
||||
})
|
||||
|
||||
const rows: CertRow[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.employees.destroyCertification(employeeId, String(id)),
|
||||
onSuccess: () => {
|
||||
toast.success("Certification deleted")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => toast.error("Failed to delete"),
|
||||
})
|
||||
|
||||
async function handleDelete(row: CertRow) {
|
||||
const ok = await confirm({
|
||||
title: "Delete certification?",
|
||||
description: `Permanently delete "${row.name}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate(row.id)
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CertRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<AwardIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "issuer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issuer" />,
|
||||
cell: ({ row }) => row.original.issuer ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "certificate_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cert #" />,
|
||||
cell: ({ row }) => {
|
||||
const v = row.original.certificate_number
|
||||
return v ? <span className="font-mono text-xs">{v}</span> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "issued_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiry_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{formatDate(row.original.expiry_date)}</span>
|
||||
{row.original.is_expired && <Badge variant="destructive">Expired</Badge>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex justify-end gap-1">
|
||||
{row.original.file_url && (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLinkIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Certifications",
|
||||
actions: (
|
||||
<Button size="sm" onClick={() => setOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Certification
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Certification</DialogTitle>
|
||||
</DialogHeader>
|
||||
<EmployeeCertificationForm
|
||||
employeeId={employeeId}
|
||||
onSuccess={() => {
|
||||
setOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
onCancel={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { Plus, Trash2, ExternalLinkIcon, FileTextIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EmployeeDocumentForm } from "@/modules/employees/employee-document-form"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type DocRow = {
|
||||
id: number
|
||||
name: string
|
||||
type: string
|
||||
file_url?: string
|
||||
issued_date?: string | null
|
||||
expiry_date?: string | null
|
||||
notes?: string | null
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function isExpired(value: unknown) {
|
||||
if (!value || typeof value !== "string") return false
|
||||
const d = new Date(value)
|
||||
return !Number.isNaN(d.getTime()) && d.getTime() < Date.now()
|
||||
}
|
||||
|
||||
export default function EmployeeDocumentsPage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const queryKey = ["employee-documents", employeeId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.employees.listDocuments(employeeId) as Promise<{ data: DocRow[] | { data: DocRow[] } }>,
|
||||
})
|
||||
|
||||
const rows: DocRow[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: number) => api.employees.destroyDocument(employeeId, String(id)),
|
||||
onSuccess: () => {
|
||||
toast.success("Document deleted")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => toast.error("Failed to delete document"),
|
||||
})
|
||||
|
||||
async function handleDelete(row: DocRow) {
|
||||
const ok = await confirm({
|
||||
title: "Delete document?",
|
||||
description: `Permanently delete "${row.name}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate(row.id)
|
||||
}
|
||||
|
||||
const columns: ColumnDef<DocRow>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<FileTextIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium">{row.original.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => <Badge variant="outline">{formatEnum(row.original.type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: "issued_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Issued" />,
|
||||
cell: ({ row }) => formatDate(row.original.issued_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "expiry_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry" />,
|
||||
cell: ({ row }) => {
|
||||
const v = row.original.expiry_date
|
||||
if (!v) return "—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{formatDate(v)}</span>
|
||||
{isExpired(v) && <Badge variant="destructive">Expired</Badge>}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex justify-end gap-1">
|
||||
{row.original.file_url && (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a href={row.original.file_url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLinkIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={deleteMutation.isPending}
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Documents",
|
||||
actions: (
|
||||
<Button size="sm" onClick={() => setOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Upload Document
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Document</DialogTitle>
|
||||
</DialogHeader>
|
||||
<EmployeeDocumentForm
|
||||
employeeId={employeeId}
|
||||
onSuccess={() => {
|
||||
setOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
onCancel={() => setOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -28,6 +28,13 @@ export default async function layout(props: {
|
||||
actions={<EmployeeActions employeeId={id} />}
|
||||
tabs={[
|
||||
{ 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}/documents`, label: 'Documents' },
|
||||
{ href: `/productivity/employees/${id}/certifications`, label: 'Certifications' },
|
||||
{ href: `/productivity/employees/${id}/leave`, label: 'Leave' },
|
||||
{ href: `/productivity/employees/${id}/payroll`, label: 'Payroll' },
|
||||
{ href: `/productivity/employees/${id}/performance`, label: 'Performance' },
|
||||
{ href: `/productivity/employees/${id}/permissions`, label: 'Permissions' },
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useEmployee } from "@/modules/employees/employee-context"
|
||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
||||
import type { LeaveRequestsClient } from "@garage/api"
|
||||
import { CalendarIcon, PlaneIcon, ActivityIcon } from "lucide-react"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Balance = {
|
||||
annual_total: number
|
||||
annual_used: number
|
||||
annual_remaining: number
|
||||
sick_total: number
|
||||
sick_used: number
|
||||
sick_remaining: number
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
||||
if (status === "approved") return "default"
|
||||
if (status === "rejected") return "destructive"
|
||||
if (status === "cancelled") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
function BalanceCard({ icon: Icon, label, used, total, remaining }: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
used: number
|
||||
total: number
|
||||
remaining: number
|
||||
}) {
|
||||
const pct = total > 0 ? Math.min(100, (used / total) * 100) : 0
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<Icon className="size-4" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold">{remaining}<span className="ml-1 text-sm font-normal text-muted-foreground">/ {total}</span></div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{used} used</p>
|
||||
<div className="mt-2 h-2 w-full overflow-hidden rounded bg-muted">
|
||||
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default function EmployeeLeavePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const employee = useEmployee()
|
||||
|
||||
const balanceQuery = useQuery({
|
||||
queryKey: ["employee-leave-balance", employeeId],
|
||||
queryFn: () => api.employees.getLeaveBalance(employeeId) as Promise<{ data: Balance }>,
|
||||
})
|
||||
|
||||
const balance = (balanceQuery.data as any)?.data as Balance | undefined
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{balance && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-2 px-4 pt-4">
|
||||
<BalanceCard
|
||||
icon={PlaneIcon}
|
||||
label="Annual Leave"
|
||||
used={Number(balance.annual_used)}
|
||||
total={Number(balance.annual_total)}
|
||||
remaining={Number(balance.annual_remaining)}
|
||||
/>
|
||||
<BalanceCard
|
||||
icon={ActivityIcon}
|
||||
label="Sick Leave"
|
||||
used={Number(balance.sick_used)}
|
||||
total={Number(balance.sick_total)}
|
||||
remaining={Number(balance.sick_remaining)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ResourcePage<LeaveRequestsClient>
|
||||
pageTitle="Leave History"
|
||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
||||
getClient={(api) => api.leaveRequests}
|
||||
extraParams={{ employee_id: employeeId }}
|
||||
header={null}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="New Leave Request">
|
||||
{() => (
|
||||
<LeaveRequestForm
|
||||
presetEmployee={{ id: employeeId, label: employee?.label ?? "" }}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
balanceQuery.refetch()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={() => [
|
||||
{
|
||||
accessorKey: "leave_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="size-4 text-muted-foreground" />
|
||||
<Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "days",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "reason",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Reason" />,
|
||||
cell: ({ row }) => (row.original as any).reason ?? "—",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Slip = {
|
||||
id: number
|
||||
payroll_run?: { id?: number; reference?: string; period_start?: string; period_end?: string; status?: string }
|
||||
hours_worked: number
|
||||
base_salary: number
|
||||
commission_amount: number
|
||||
allowances: number
|
||||
deductions: number
|
||||
net_pay: number
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function fmt(v: unknown) {
|
||||
const n = Number(v)
|
||||
if (!Number.isFinite(n)) return "—"
|
||||
return n.toFixed(2)
|
||||
}
|
||||
|
||||
function statusVariant(status: string | undefined): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function EmployeePayrollPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: employeeId } = use(params)
|
||||
const api = useAuthApi()
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["employee-payroll-slips", employeeId],
|
||||
queryFn: () => api.employees.listPayrollSlips(employeeId) as Promise<{ data: Slip[] | { data: Slip[] } }>,
|
||||
})
|
||||
|
||||
const rows: Slip[] = Array.isArray((data as any)?.data)
|
||||
? (data as any).data
|
||||
: ((data as any)?.data?.data ?? [])
|
||||
|
||||
const columns: ColumnDef<Slip>[] = [
|
||||
{
|
||||
accessorKey: "payroll_run",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Run" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.payroll_run
|
||||
return r?.reference ?? (r?.id ? `#${r.id}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "period",
|
||||
header: () => <span>Period</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original.payroll_run
|
||||
if (!r) return "—"
|
||||
return `${formatDate(r.period_start)} → ${formatDate(r.period_end)}`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "hours_worked",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
||||
cell: ({ row }) => fmt(row.original.hours_worked),
|
||||
},
|
||||
{
|
||||
accessorKey: "base_salary",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
||||
cell: ({ row }) => fmt(row.original.base_salary),
|
||||
},
|
||||
{
|
||||
accessorKey: "commission_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
||||
cell: ({ row }) => fmt(row.original.commission_amount),
|
||||
},
|
||||
{
|
||||
accessorKey: "deductions",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
||||
cell: ({ row }) => fmt(row.original.deductions),
|
||||
},
|
||||
{
|
||||
accessorKey: "net_pay",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
||||
cell: ({ row }) => <span className="font-semibold">{fmt(row.original.net_pay)}</span>,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.payroll_run?.status
|
||||
if (!s) return "—"
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage headerProps={{ title: "Payroll Slips" }}>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{ page: 1, pageSize: rows.length || 10, pageCount: 1, total: rows.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { ClockIcon, WrenchIcon, CheckCircle2Icon, TimerIcon, PercentIcon } from "lucide-react"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Field, FieldLabel } from "@/shared/components/ui/field"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
|
||||
type PerfData = {
|
||||
period: { from: string; to: string }
|
||||
hours_worked: number
|
||||
jobs_total: number
|
||||
jobs_completed: number
|
||||
avg_job_duration_hours: number
|
||||
completion_rate: number
|
||||
}
|
||||
|
||||
function StatCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
suffix,
|
||||
}: {
|
||||
icon: React.ComponentType<{ className?: string }>
|
||||
label: string
|
||||
value: string | number
|
||||
suffix?: string
|
||||
}) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<Icon className="size-4" />
|
||||
{label}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold">
|
||||
{value}
|
||||
{suffix && <span className="ml-1 text-base font-normal text-muted-foreground">{suffix}</span>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function firstOfMonth() {
|
||||
const d = new Date()
|
||||
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function lastOfMonth() {
|
||||
const d = new Date()
|
||||
return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export default function EmployeePerformancePage() {
|
||||
const { id: employeeId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const [fromInput, setFromInput] = useState(firstOfMonth())
|
||||
const [toInput, setToInput] = useState(lastOfMonth())
|
||||
const [from, setFrom] = useState(fromInput)
|
||||
const [to, setTo] = useState(toInput)
|
||||
|
||||
const { data, isLoading, isFetching } = useQuery({
|
||||
queryKey: ["employee-performance", employeeId, from, to],
|
||||
queryFn: () => api.employees.performance(employeeId, { from, to }) as Promise<{ data: PerfData }>,
|
||||
})
|
||||
|
||||
const perf = useMemo(() => (data as any)?.data as PerfData | undefined, [data])
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: perf ? `Performance · ${perf.period.from} → ${perf.period.to}` : "Performance",
|
||||
actions: (
|
||||
<div className="flex items-end gap-2">
|
||||
<Field>
|
||||
<FieldLabel>From</FieldLabel>
|
||||
<Input type="date" value={fromInput} onChange={(e) => setFromInput(e.target.value)} />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>To</FieldLabel>
|
||||
<Input type="date" value={toInput} onChange={(e) => setToInput(e.target.value)} />
|
||||
</Field>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={isFetching}
|
||||
onClick={() => {
|
||||
setFrom(fromInput)
|
||||
setTo(toInput)
|
||||
}}
|
||||
>
|
||||
{isFetching ? "Loading..." : "Apply"}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{isLoading && !perf ? (
|
||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
||||
) : !perf ? (
|
||||
<p className="text-sm text-muted-foreground">No data.</p>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
|
||||
<StatCard icon={ClockIcon} label="Hours Worked" value={perf.hours_worked.toFixed(2)} suffix="h" />
|
||||
<StatCard icon={WrenchIcon} label="Jobs Assigned" value={perf.jobs_total} />
|
||||
<StatCard icon={CheckCircle2Icon} label="Jobs Completed" value={perf.jobs_completed} />
|
||||
<StatCard icon={TimerIcon} label="Avg Job Duration" value={perf.avg_job_duration_hours.toFixed(2)} suffix="h" />
|
||||
<StatCard icon={PercentIcon} label="Completion Rate" value={perf.completion_rate} suffix="%" />
|
||||
</div>
|
||||
)}
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -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,23 +1,89 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ImportDataButton } from "@/shared/components/import-data-button"
|
||||
import { ExportDataButton } from "@/shared/components/export-data-button"
|
||||
import { EmployeeForm } from "@/modules/employees/employee-form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { EMPLOYEE_ROUTES } 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 { 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() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
const [typeFilter, setTypeFilter] = useState<string>("all")
|
||||
|
||||
const extraParams = useMemo(() => {
|
||||
if (typeFilter === "all") return undefined
|
||||
return { type: typeFilter }
|
||||
}, [typeFilter])
|
||||
|
||||
return (
|
||||
<ResourcePage<EmployeesClient>
|
||||
pageTitle="Employees"
|
||||
routeKey={EMPLOYEE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search employees..."
|
||||
statusFilter={{ statuses: ["active", "inactive"] }}
|
||||
extraParams={extraParams}
|
||||
getClient={(api) => api.employees}
|
||||
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 }) => ({
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.employees.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Employees"
|
||||
onDownloadSample={() => api.employees.downloadImportSample() as Promise<Blob>}
|
||||
sampleFileName="employees-import-sample"
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.employees.exportData(filters)}
|
||||
fileName="employees"
|
||||
/>
|
||||
<FormDialog title="Employee">
|
||||
{(resourceId) => (
|
||||
<EmployeeForm
|
||||
@@ -27,6 +93,7 @@ export default function EmployeesPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -34,8 +101,16 @@ export default function EmployeesPage() {
|
||||
accessorKey: "first_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }) => {
|
||||
const { first_name, last_name } = row.original
|
||||
return `${first_name ?? ""} ${last_name ?? ""}`.trim()
|
||||
const r = row.original as any
|
||||
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 +120,32 @@ export default function EmployeesPage() {
|
||||
{
|
||||
accessorKey: "phone",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Phone" />,
|
||||
cell: ({ row }) => (row.original as any).phone ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "position",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Position" />,
|
||||
accessorKey: "type",
|
||||
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",
|
||||
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",
|
||||
@@ -62,7 +154,7 @@ export default function EmployeesPage() {
|
||||
const status = row.original.status
|
||||
return (
|
||||
<span className={status === "active" ? "text-green-600" : "text-red-600"}>
|
||||
{status}
|
||||
{formatEnum(status)}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -12,6 +12,8 @@ export default function HolidayYearsPage() {
|
||||
<ResourcePage<HolidayYearsClient>
|
||||
pageTitle="Holiday Years"
|
||||
routeKey={HOLIDAY_YEAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search holidays..."
|
||||
getClient={(api) => api.holidayYears}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { LeaveRequestForm } from "@/modules/leave-requests/leave-request-form"
|
||||
import { LEAVE_REQUEST_ROUTES } from "@garage/api"
|
||||
import type { LeaveRequestsClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { useQueryClient } from "@tanstack/react-query"
|
||||
import { toast } from "sonner"
|
||||
import { CheckIcon, XIcon } from "lucide-react"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
import { usePermissions } from "@/shared/hooks/use-permissions"
|
||||
|
||||
type LeaveRow = {
|
||||
id: number
|
||||
leave_type: string
|
||||
start_date?: string
|
||||
end_date?: string
|
||||
days?: number
|
||||
status: string
|
||||
reason?: string | null
|
||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
|
||||
if (status === "approved") return "default"
|
||||
if (status === "rejected") return "destructive"
|
||||
if (status === "cancelled") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function LeaveRequestsPage() {
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const perms = usePermissions()
|
||||
|
||||
async function handleDecision(id: number, action: "approve" | "reject") {
|
||||
const ok = await confirm({
|
||||
title: action === "approve" ? "Approve request?" : "Reject request?",
|
||||
description: `This will mark the leave request as ${action}d.`,
|
||||
confirmLabel: action === "approve" ? "Approve" : "Reject",
|
||||
variant: action === "approve" ? "default" : "destructive",
|
||||
})
|
||||
if (!ok) return
|
||||
const promise = action === "approve"
|
||||
? api.leaveRequests.approve(String(id))
|
||||
: api.leaveRequests.reject(String(id))
|
||||
toast.promise(promise, {
|
||||
loading: action === "approve" ? "Approving..." : "Rejecting...",
|
||||
success: action === "approve" ? "Approved" : "Rejected",
|
||||
error: "Failed",
|
||||
})
|
||||
await promise
|
||||
queryClient.invalidateQueries({ queryKey: [LEAVE_REQUEST_ROUTES.INDEX] })
|
||||
}
|
||||
|
||||
return (
|
||||
<ResourcePage<LeaveRequestsClient>
|
||||
pageTitle="Leave Requests"
|
||||
routeKey={LEAVE_REQUEST_ROUTES.INDEX}
|
||||
getClient={(api) => api.leaveRequests}
|
||||
statusFilter={{
|
||||
statuses: ["pending", "approved", "rejected", "cancelled"],
|
||||
paramKey: "status",
|
||||
allLabel: "All",
|
||||
}}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: perms.canCreate("leave_requests") ? (
|
||||
<FormDialog title="Leave Request">
|
||||
{(resourceId) => (
|
||||
<LeaveRequestForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
) : null,
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = (row.original as any).employee
|
||||
if (!e) return "—"
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "leave_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Type" />,
|
||||
cell: ({ row }) => <Badge variant="outline">{formatEnum((row.original as any).leave_type)}</Badge>,
|
||||
},
|
||||
{
|
||||
accessorKey: "start_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).start_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "end_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).end_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "days",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Days" />,
|
||||
cell: ({ row }) => (row.original as any).days ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "decide",
|
||||
header: () => <span className="sr-only">Decide</span>,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as LeaveRow
|
||||
if (r.status !== "pending" || !perms.canUpdate("leave_requests")) return null
|
||||
return (
|
||||
<div className="flex justify-end gap-1">
|
||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "approve")}>
|
||||
<CheckIcon className="size-4 text-green-600" />
|
||||
</Button>
|
||||
<Button size="icon" variant="ghost" onClick={() => handleDecision(r.id, "reject")}>
|
||||
<XIcon className="size-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { toast } from "sonner"
|
||||
import { CheckCircle2Icon, RefreshCwIcon, BanknoteIcon, Trash2, DownloadIcon } from "lucide-react"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type Entry = {
|
||||
id: number
|
||||
employee_id: number
|
||||
employee?: { id?: number; first_name?: string; last_name?: string; email?: string }
|
||||
hours_worked: number
|
||||
overtime_hours: number
|
||||
base_salary: number
|
||||
commission_amount: number
|
||||
allowances: number
|
||||
deductions: number
|
||||
net_pay: number
|
||||
note?: string | null
|
||||
}
|
||||
|
||||
type Run = {
|
||||
id: number
|
||||
reference?: string
|
||||
period_start: string
|
||||
period_end: string
|
||||
status: "draft" | "finalized" | "paid"
|
||||
entries: Entry[]
|
||||
note?: string | null
|
||||
finalized_at?: string | null
|
||||
paid_at?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function fmtCurrency(value: unknown) {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return "—"
|
||||
return n.toFixed(2)
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function PayrollRunPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: runId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
|
||||
const queryKey = ["payroll-run", runId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.payroll.show(runId) as Promise<{ data: Run; totals: Record<string, number> }>,
|
||||
})
|
||||
|
||||
const run = (data as any)?.data as Run | undefined
|
||||
const totals = (data as any)?.totals as Record<string, number> | undefined
|
||||
|
||||
const refetch = () => queryClient.invalidateQueries({ queryKey })
|
||||
|
||||
const finalizeMutation = useMutation({
|
||||
mutationFn: () => api.payroll.finalize(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Run finalized")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to finalize"),
|
||||
})
|
||||
|
||||
const regenerateMutation = useMutation({
|
||||
mutationFn: () => api.payroll.regenerate(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Entries regenerated")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to regenerate"),
|
||||
})
|
||||
|
||||
const markPaidMutation = useMutation({
|
||||
mutationFn: () => api.payroll.markPaid(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Marked as paid")
|
||||
refetch()
|
||||
},
|
||||
onError: () => toast.error("Failed to mark paid"),
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: () => api.payroll.destroy(runId),
|
||||
onSuccess: () => {
|
||||
toast.success("Run deleted")
|
||||
router.push("/productivity/payroll")
|
||||
},
|
||||
onError: () => toast.error("Failed to delete"),
|
||||
})
|
||||
|
||||
async function handleDelete() {
|
||||
const ok = await confirm({
|
||||
title: "Delete payroll run?",
|
||||
description: "This permanently removes the run and all its entries.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (ok) deleteMutation.mutate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<Entry>[] = [
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = row.original.employee
|
||||
if (!e) return `#${row.original.employee_id}`
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "hours_worked",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Hours" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.hours_worked),
|
||||
},
|
||||
{
|
||||
accessorKey: "base_salary",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Base" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.base_salary),
|
||||
},
|
||||
{
|
||||
accessorKey: "commission_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Commission" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.commission_amount),
|
||||
},
|
||||
{
|
||||
accessorKey: "allowances",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Allowances" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.allowances),
|
||||
},
|
||||
{
|
||||
accessorKey: "deductions",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Deductions" />,
|
||||
cell: ({ row }) => fmtCurrency(row.original.deductions),
|
||||
},
|
||||
{
|
||||
accessorKey: "net_pay",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Net Pay" />,
|
||||
cell: ({ row }) => <span className="font-semibold">{fmtCurrency(row.original.net_pay)}</span>,
|
||||
},
|
||||
{
|
||||
id: "slip",
|
||||
header: () => <span className="sr-only">Slip</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<a
|
||||
href={`/api/payroll/runs/${runId}/entries/${row.original.id}/slip`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Download slip PDF"
|
||||
>
|
||||
<DownloadIcon className="size-4" />
|
||||
</a>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
if (isLoading && !run) {
|
||||
return <DashboardPage>Loading...</DashboardPage>
|
||||
}
|
||||
|
||||
if (!run) {
|
||||
return <DashboardPage>Run not found.</DashboardPage>
|
||||
}
|
||||
|
||||
const entries = run.entries ?? []
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: `${run.reference ?? `Payroll #${run.id}`} · ${formatDate(run.period_start)} → ${formatDate(run.period_end)}`,
|
||||
actions: (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={statusVariant(run.status)}>{formatEnum(run.status)}</Badge>
|
||||
{run.status === "draft" && (
|
||||
<>
|
||||
<Button size="sm" variant="outline" disabled={regenerateMutation.isPending} onClick={() => regenerateMutation.mutate()}>
|
||||
<RefreshCwIcon className="size-4" />
|
||||
Regenerate
|
||||
</Button>
|
||||
<Button size="sm" disabled={finalizeMutation.isPending} onClick={() => finalizeMutation.mutate()}>
|
||||
<CheckCircle2Icon className="size-4" />
|
||||
Finalize
|
||||
</Button>
|
||||
<Button size="sm" variant="destructive" disabled={deleteMutation.isPending} onClick={handleDelete}>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{run.status === "finalized" && (
|
||||
<Button size="sm" disabled={markPaidMutation.isPending} onClick={() => markPaidMutation.mutate()}>
|
||||
<BanknoteIcon className="size-4" />
|
||||
Mark Paid
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{totals && (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5 mb-4">
|
||||
{[
|
||||
{ label: "Gross Base", value: totals.gross_base },
|
||||
{ label: "Commission", value: totals.commission },
|
||||
{ label: "Allowances", value: totals.allowances },
|
||||
{ label: "Deductions", value: totals.deductions },
|
||||
{ label: "Net Total", value: totals.net_pay },
|
||||
].map((t) => (
|
||||
<Card key={t.label}>
|
||||
<CardHeader className="pb-1">
|
||||
<CardTitle className="text-xs font-medium text-muted-foreground">{t.label}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-lg font-semibold">{fmtCurrency(t.value)}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={entries}
|
||||
pagination={{ page: 1, pageSize: entries.length || 10, pageCount: 1, total: entries.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={false}
|
||||
/>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { PayrollRunForm } from "@/modules/payroll/payroll-run-form"
|
||||
import { PAYROLL_ROUTES } from "@garage/api"
|
||||
import type { PayrollClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
type RunRow = {
|
||||
id: number
|
||||
reference?: string | null
|
||||
period_start?: string
|
||||
period_end?: string
|
||||
status: string
|
||||
entries_count?: number
|
||||
generated_at?: string | null
|
||||
finalized_at?: string | null
|
||||
paid_at?: string | null
|
||||
}
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function statusVariant(status: string): "default" | "secondary" | "outline" {
|
||||
if (status === "paid") return "default"
|
||||
if (status === "finalized") return "outline"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
export default function PayrollPage() {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<ResourcePage<PayrollClient>
|
||||
pageTitle="Payroll"
|
||||
routeKey={PAYROLL_ROUTES.RUNS_INDEX}
|
||||
getClient={(api) => api.payroll}
|
||||
statusFilter={{
|
||||
statuses: ["draft", "finalized", "paid"],
|
||||
paramKey: "status",
|
||||
}}
|
||||
onRowClick={(row) => router.push(`/productivity/payroll/${(row as any).id}`)}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Payroll Run">
|
||||
{() => (
|
||||
<PayrollRunForm
|
||||
onSuccess={(runId) => {
|
||||
invalidateQuery()
|
||||
if (runId) router.push(`/productivity/payroll/${runId}`)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "reference",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Reference" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{(row.original as any).reference ?? `#${(row.original as any).id}`}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "period_start",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Period Start" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).period_start),
|
||||
},
|
||||
{
|
||||
accessorKey: "period_end",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Period End" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).period_end),
|
||||
},
|
||||
{
|
||||
accessorKey: "entries_count",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Entries" />,
|
||||
cell: ({ row }) => (row.original as any).entries_count ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const s = (row.original as any).status as string
|
||||
return <Badge variant={statusVariant(s)}>{formatEnum(s)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "finalized_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Finalized" />,
|
||||
cell: ({ row }) => formatDate((row.original as any).finalized_at),
|
||||
},
|
||||
actionsColumn({ onEdit: undefined }),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export default function ShopCalendarsPage() {
|
||||
<ResourcePage<ShopCalendarsClient>
|
||||
pageTitle="Shop Calendars"
|
||||
routeKey={SHOP_CALENDAR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop calendars..."
|
||||
getClient={(api) => api.shopCalendars}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -13,6 +13,8 @@ export default function ShopTimingsPage() {
|
||||
<ResourcePage<ShopTimingsClient>
|
||||
pageTitle="Shop Timings"
|
||||
routeKey={SHOP_TIMING_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop timings..."
|
||||
getClient={(api) => api.shopTimings}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -4,13 +4,16 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
|
||||
export default function TasksPage() {
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Tasks",
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"use client"
|
||||
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { LogInIcon, LogOutIcon, TimerIcon, SearchIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { Avatar, AvatarFallback } from "@/shared/components/ui/avatar"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { EMPLOYEE_ROUTES } from "@garage/api"
|
||||
|
||||
type Employee = {
|
||||
id: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
email?: string
|
||||
designation?: string
|
||||
department?: { id?: number; name?: string }
|
||||
track_attendance?: boolean
|
||||
has_active_time_sheet?: boolean
|
||||
active_time_sheet?: { id?: number; clock_in?: string; date?: string } | null
|
||||
status?: string
|
||||
}
|
||||
|
||||
function initialsOf(first?: string | null, last?: string | null) {
|
||||
const f = (first ?? "").trim()[0] ?? ""
|
||||
const l = (last ?? "").trim()[0] ?? ""
|
||||
return (f + l).toUpperCase() || "?"
|
||||
}
|
||||
|
||||
function formatTime(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
return value.length >= 5 ? value.slice(0, 5) : value
|
||||
}
|
||||
|
||||
export default function TimeClocksPage() {
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [search, setSearch] = useState("")
|
||||
|
||||
const employeesQuery = useQuery({
|
||||
queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }],
|
||||
queryFn: () => api.employees.list({ per_page: 100, status: "active" } as any) as Promise<{ data: Employee[] }>,
|
||||
})
|
||||
|
||||
const employees: Employee[] = useMemo(() => {
|
||||
const rows: Employee[] = (employeesQuery.data as any)?.data ?? []
|
||||
if (!search) return rows
|
||||
const q = search.toLowerCase()
|
||||
return rows.filter((e) => {
|
||||
const name = `${e.first_name ?? ""} ${e.last_name ?? ""}`.toLowerCase()
|
||||
return name.includes(q) || (e.email ?? "").toLowerCase().includes(q)
|
||||
})
|
||||
}, [employeesQuery.data, search])
|
||||
|
||||
const refetch = () => queryClient.invalidateQueries({ queryKey: [EMPLOYEE_ROUTES.INDEX, "time-clocks", { per_page: 100, status: "active" }] })
|
||||
|
||||
const clockInMutation = useMutation({
|
||||
mutationFn: (employeeId: number) => api.timeSheets.clockIn({ employee_id: employeeId } as any),
|
||||
onSuccess: () => {
|
||||
toast.success("Clocked in")
|
||||
refetch()
|
||||
},
|
||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock in"),
|
||||
})
|
||||
|
||||
const clockOutMutation = useMutation({
|
||||
mutationFn: (timeSheetId: number) => api.timeSheets.clockOut({ time_sheet_id: timeSheetId } as any),
|
||||
onSuccess: () => {
|
||||
toast.success("Clocked out")
|
||||
refetch()
|
||||
},
|
||||
onError: (err: any) => toast.error(err?.payload?.message ?? err?.message ?? "Failed to clock out"),
|
||||
})
|
||||
|
||||
return (
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: "Time Clocks",
|
||||
actions: (
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search employees..."
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{employeesQuery.isLoading ? (
|
||||
<p className="text-sm text-muted-foreground">Loading...</p>
|
||||
) : employees.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No employees found.</p>
|
||||
) : (
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{employees.map((emp) => {
|
||||
const fullName = `${emp.first_name ?? ""} ${emp.last_name ?? ""}`.trim() || emp.email
|
||||
const isClockedIn = !!emp.has_active_time_sheet
|
||||
const activeId = emp.active_time_sheet?.id
|
||||
const clockedInAt = emp.active_time_sheet?.clock_in
|
||||
|
||||
return (
|
||||
<Card key={emp.id}>
|
||||
<CardContent className="flex items-center justify-between gap-3 p-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Avatar size="lg">
|
||||
<AvatarFallback>{initialsOf(emp.first_name, emp.last_name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium truncate">{fullName}</div>
|
||||
<div className="text-xs text-muted-foreground truncate">
|
||||
{emp.designation ?? emp.department?.name ?? emp.email}
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
{isClockedIn ? (
|
||||
<Badge variant="default" className="gap-1">
|
||||
<TimerIcon className="size-3" />
|
||||
Since {formatTime(clockedInAt)}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Idle</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isClockedIn && activeId ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={clockOutMutation.isPending}
|
||||
onClick={() => clockOutMutation.mutate(activeId)}
|
||||
>
|
||||
<LogOutIcon className="size-4" />
|
||||
Clock Out
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={clockInMutation.isPending}
|
||||
onClick={() => clockInMutation.mutate(emp.id)}
|
||||
>
|
||||
<LogInIcon className="size-4" />
|
||||
Clock In
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { TIME_SHEET_ROUTES } from "@garage/api"
|
||||
import type { TimeSheetsClient } from "@garage/api"
|
||||
import { ClockIcon } from "lucide-react"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
function formatDate(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
const d = new Date(value)
|
||||
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString()
|
||||
}
|
||||
|
||||
function formatTime(value: unknown) {
|
||||
if (!value || typeof value !== "string") return "—"
|
||||
return value.length >= 5 ? value.slice(0, 5) : value
|
||||
}
|
||||
|
||||
const ACTIVITY_VARIANT: Record<string, "default" | "secondary" | "outline"> = {
|
||||
general: "secondary",
|
||||
order: "default",
|
||||
task: "outline",
|
||||
}
|
||||
|
||||
export default function TimeSheetsPage() {
|
||||
return (
|
||||
<ResourcePage<TimeSheetsClient>
|
||||
pageTitle="Time Sheets"
|
||||
routeKey={TIME_SHEET_ROUTES.INDEX}
|
||||
getClient={(api) => api.timeSheets}
|
||||
statusFilter={{
|
||||
statuses: ["general", "order", "task"],
|
||||
paramKey: "activity_type",
|
||||
allLabel: "All",
|
||||
}}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClockIcon className="size-4 text-muted-foreground" />
|
||||
<span>{formatDate((row.original as any).date)}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "employee",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Employee" />,
|
||||
cell: ({ row }) => {
|
||||
const e = (row.original as any).employee
|
||||
if (!e) return "—"
|
||||
return `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim() || e.email || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_in",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock In" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_in)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "clock_out",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Clock Out" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).clock_out)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "duration",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Duration" />,
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{formatTime((row.original as any).duration)}</span>,
|
||||
},
|
||||
{
|
||||
accessorKey: "activity_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Activity" />,
|
||||
cell: ({ row }) => {
|
||||
const t = (row.original as any).activity_type ?? "general"
|
||||
return <Badge variant={ACTIVITY_VARIANT[t] ?? "secondary"}>{formatEnum(t)}</Badge>
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "calculated_total_cost",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Cost" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).calculated_total_cost
|
||||
if (v == null) return "—"
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n.toFixed(2) : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn({ onEdit: undefined }),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { formatDate, 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() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
pageTitle="Bills"
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
onRowClick={(row) => router.push(`/purchase/bill/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Bill">
|
||||
<FormDialog classNames={{ dialogContent: "lg:min-w-6xl" }} title="Bill">
|
||||
{(resourceId) => (
|
||||
<BillForm
|
||||
resourceId={resourceId}
|
||||
@@ -33,41 +47,73 @@ export default function BillsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Total" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).total
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Balance Due" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).balance_due
|
||||
return v != null && v !== "" ? <Money value={v} /> : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
accessorKey: "vendor",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill Date" />,
|
||||
cell: ({ row }) => {
|
||||
const value = (row.original as any).bill_date
|
||||
return value ? new Date(value).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ row }) => formatDate((row.original as any).bill_date) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_due_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||
cell: ({ row }) => {
|
||||
const value = (row.original as any).bill_due_date
|
||||
return value ? new Date(value).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ row }) => formatDate((row.original as any).bill_due_date) || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{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 { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { EXPENSE_ROUTES } from "@garage/api"
|
||||
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
|
||||
import type { ExpensesClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
export default function ExpensesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
return (
|
||||
<ResourcePage<ExpensesClient>
|
||||
pageTitle="Expenses"
|
||||
routeKey={EXPENSE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search expenses..."
|
||||
statusFilter={{ statuses: ExpenseStatus }}
|
||||
getClient={(api) => api.expenses}
|
||||
onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Expense">
|
||||
<FormDialog
|
||||
title="Expense"
|
||||
classNames={{ dialogContent: "lg:min-w-6xl" }}
|
||||
>
|
||||
{(resourceId) => (
|
||||
<ExpenseForm
|
||||
resourceId={resourceId}
|
||||
@@ -38,39 +54,62 @@ export default function ExpensesPage() {
|
||||
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
accessorKey: "vendor",
|
||||
header: () => "Vendor",
|
||||
cell: ({ row }) => {
|
||||
const vendor = (row.original as any).vendor
|
||||
return (
|
||||
<RelationLink
|
||||
href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={vendor?.company_name || getFullName(vendor) || vendor?.name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "expense_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).expense_date
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
cell: ({ row }) => formatDate((row.original as any).expense_date),
|
||||
},
|
||||
{
|
||||
accessorKey: "total",
|
||||
header: () => "Total",
|
||||
cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "balance_due",
|
||||
header: () => "Balance Due",
|
||||
cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
const variantMap: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
draft: "secondary",
|
||||
open: "default",
|
||||
un_paid: "destructive",
|
||||
partially_paid: "secondary",
|
||||
paid: "default",
|
||||
}
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status || "—"}
|
||||
<Badge variant={variantMap[status] ?? "outline"}>
|
||||
{formatEnum(status) || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
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() : "—"
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
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"
|
||||
|
||||
import { useState, useRef } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import {
|
||||
Paperclip,
|
||||
@@ -32,8 +33,12 @@ import {
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { PAYMENT_MADE_ROUTES } from "@garage/api"
|
||||
import type { PaymentMadesClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
// ── Attachment helpers ──
|
||||
|
||||
@@ -208,10 +213,13 @@ function AttachmentsDialog({
|
||||
type PaymentMadeItem = {
|
||||
id: number
|
||||
payment_number?: string
|
||||
vendor?: { id?: number | string; company_name?: string | null; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
vendor_name?: string
|
||||
employee?: { id?: number | string; first_name?: string | null; last_name?: string | null; name?: string | null } | null
|
||||
employee_name?: string
|
||||
payment_for?: string
|
||||
payment_made?: string | number
|
||||
payment_mode?: { name?: string | null; title?: string | null } | null
|
||||
payment_mode_name?: string
|
||||
payment_date?: string
|
||||
paid_through?: string
|
||||
@@ -220,6 +228,8 @@ type PaymentMadeItem = {
|
||||
}
|
||||
|
||||
export default function PaymentsMadePage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
const [attachmentTarget, setAttachmentTarget] = useState<{
|
||||
id: string
|
||||
ref: string
|
||||
@@ -230,14 +240,21 @@ export default function PaymentsMadePage() {
|
||||
<ResourcePage<PaymentMadesClient>
|
||||
pageTitle="Payments Made"
|
||||
routeKey={PAYMENT_MADE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => api.paymentMades}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
onRowClick={(row) => router.push(`/purchase/payments-made/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Record Payment">
|
||||
{(resourceId) => (
|
||||
{(resourceId, { close }) => (
|
||||
<PaymentMadeForm
|
||||
resourceId={resourceId}
|
||||
onSuccess={invalidateQuery}
|
||||
initialData={selectedItem}
|
||||
onSuccess={() => {
|
||||
invalidateQuery()
|
||||
close()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -262,11 +279,27 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const isVendor =
|
||||
item.vendor?.company_name ||
|
||||
getFullName(item.vendor) ||
|
||||
item.vendor?.name ||
|
||||
item.vendor_name
|
||||
const label =
|
||||
isVendor ||
|
||||
getFullName(item.employee) ||
|
||||
item.employee?.name ||
|
||||
item.employee_name
|
||||
const href = isVendor && item.vendor?.id
|
||||
? `/purchase/vendor/${item.vendor.id}`
|
||||
: item.employee?.id
|
||||
? `/productivity/employees/${item.employee.id}`
|
||||
: null
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.vendor_name || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={href}
|
||||
icon={isVendor ? Building2 : UserIcon}
|
||||
label={label}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -309,10 +342,15 @@ export default function PaymentsMadePage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentMadeItem
|
||||
const label =
|
||||
item.payment_mode?.name ||
|
||||
item.payment_mode?.title ||
|
||||
item.payment_mode_name ||
|
||||
"—"
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
||||
<span className="capitalize">{label}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
@@ -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"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form"
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, Printer } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
|
||||
export default function PurchaseOrdersPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
pageTitle="Purchase Orders"
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
onRowClick={(row) => router.push(`/purchase/purchase-order/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Purchase Order">
|
||||
{(resourceId) => (
|
||||
<FormDialog classNames={{ dialogContent: "min-w-6xl" }} title="Purchase Order">
|
||||
{(resourceId, { close }) => (
|
||||
<PurchaseOrderForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={() => { invalidateQuery(); close()}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -39,7 +50,16 @@ export default function PurchaseOrdersPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
@@ -65,7 +85,15 @@ export default function PurchaseOrdersPage() {
|
||||
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 { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
|
||||
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
|
||||
import { VENDOR_CREDIT_ROUTES, VendorCreditStatus } from "@garage/api"
|
||||
import type { VendorCreditsClient } from "@garage/api"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
export default function VendorCreditsPage() {
|
||||
return (
|
||||
<ResourcePage<VendorCreditsClient>
|
||||
pageTitle="Vendor Credits"
|
||||
routeKey={VENDOR_CREDIT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendor credits..."
|
||||
statusFilter={{ statuses: VendorCreditStatus }}
|
||||
getClient={(api) => api.vendorCredits}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
@@ -35,12 +42,30 @@ export default function VendorCreditsPage() {
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.bill?.id ? `/purchase/bill/${item.bill.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill?.bill_number || item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_credit_date",
|
||||
@@ -55,7 +80,7 @@ export default function VendorCreditsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
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(),
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DashboardDetailsPage } from "@/base/components/layout/dashboard"
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorActions } from "@/modules/vendors/vendor-actions"
|
||||
import { VendorProvider } from "@/modules/vendors/vendor-context"
|
||||
import React from "react"
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
const company = vendor?.company_name as string | undefined
|
||||
const fullName = [vendor?.first_name, vendor?.last_name].filter(Boolean).join(" ").trim()
|
||||
const title = company || fullName || "Vendor Details"
|
||||
const isActive = vendor?.is_active ?? vendor?.status === "active"
|
||||
|
||||
return (
|
||||
<VendorProvider vendor={{ id, label: title }}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
title={title}
|
||||
description={vendor?.email ?? vendor?.phone ?? undefined}
|
||||
backHref="/purchase/vendor"
|
||||
actions={<VendorActions vendorId={id} isActive={Boolean(isActive)} />}
|
||||
tabs={[
|
||||
{ href: `/purchase/vendor/${id}`, label: "Details" },
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</VendorProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getServerApi } from "@garage/api/server"
|
||||
import { VendorGeneralInfo } from "@/modules/vendors/vendor-general-info"
|
||||
|
||||
export default async function VendorDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
// The OpenAPI schema doesn't yet describe GET /api/vendors/{id} (only PUT/DELETE),
|
||||
// so cast through `any` here until the schema is regenerated.
|
||||
const response = (await api.vendors.getById(id)) as { data?: Record<string, any> }
|
||||
const vendor = response?.data
|
||||
|
||||
if (!vendor) {
|
||||
return <div className="text-muted-foreground p-6">Vendor not found.</div>
|
||||
}
|
||||
|
||||
return <VendorGeneralInfo vendor={vendor} />
|
||||
}
|
||||
+42
-1
@@ -1,18 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import { Power } from "lucide-react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { VendorForm } from "@/modules/vendors/vendor-form"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { VENDOR_ROUTES } from "@garage/api"
|
||||
import type { VendorsClient } from "@garage/api"
|
||||
|
||||
export default function VendorsPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<VendorsClient>
|
||||
pageTitle="Vendors"
|
||||
routeKey={VENDOR_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vendors..."
|
||||
getClient={(api) => api.vendors}
|
||||
onRowClick={(row) => router.push(`/purchase/vendor/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Vendor">
|
||||
@@ -46,6 +56,18 @@ export default function VendorsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Email" />,
|
||||
cell: ({ row }) => (row.original as any).email || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const isActive = Boolean((row.original as any).is_active)
|
||||
return (
|
||||
<Badge variant={isActive ? "default" : "outline"}>
|
||||
{isActive ? "Active" : "Inactive"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
@@ -54,7 +76,26 @@ export default function VendorsPage() {
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => {
|
||||
const isActive = Boolean((row as any).is_active)
|
||||
return [
|
||||
{
|
||||
label: isActive ? "Deactivate" : "Activate",
|
||||
icon: Power,
|
||||
onClick: async () => {
|
||||
try {
|
||||
await api.vendors.toggleStatus({ id: Number((row as any).id) } as any)
|
||||
toast.success(isActive ? "Vendor deactivated." : "Vendor activated.")
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast.error("Failed to update vendor status.")
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
},
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { CreditNoteDocumentForm } from "@/modules/credit-notes/credit-note-document-form"
|
||||
|
||||
type CreditNoteAttachment = {
|
||||
id: number
|
||||
name?: string
|
||||
url?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export default function CreditNoteDocumentsPage() {
|
||||
const { id: creditNoteId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
const queryKey = ["credit-note-attachments", creditNoteId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const response = await api.creditNotes.show(creditNoteId)
|
||||
return (response as any)?.data ?? response
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (attachmentId: number) =>
|
||||
api.creditNotes.deleteAttachment(creditNoteId, { attachment_id: attachmentId }),
|
||||
onSuccess: () => {
|
||||
toast.success("Attachment deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete attachment.")
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = async (attachment: CreditNoteAttachment) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Attachment",
|
||||
description: `Are you sure you want to delete "${attachment.name || "this attachment"}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (confirmed) {
|
||||
deleteMutation.mutate(attachment.id)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CreditNoteAttachment>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ getValue, row }) => {
|
||||
const name = getValue<string>()
|
||||
const url = row.original.url
|
||||
if (url) {
|
||||
return (
|
||||
<a href={url} target="_blank" rel="noopener noreferrer" className="text-primary underline">
|
||||
{name || "Attachment"}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return name || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
title="Delete attachment"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
]
|
||||
|
||||
const attachments: CreditNoteAttachment[] = (data as any)?.attachments ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 lg:p-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Attachment
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={attachments}
|
||||
pagination={{ page: 1, pageSize: 15, pageCount: 1, total: attachments.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Attachment</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreditNoteDocumentForm
|
||||
creditNoteId={creditNoteId}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { CreditNoteActions } from '@/modules/credit-notes/credit-note-actions'
|
||||
import { CreditNoteProvider } from '@/modules/credit-notes/credit-note-context'
|
||||
import { ReceiptTextIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
|
||||
export default async function CreditNoteDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const creditNote = await api.creditNotes.show(id)
|
||||
const data = (creditNote as any)?.data ?? creditNote
|
||||
const title = data?.subject || data?.credit_invoice || 'Credit Note Details'
|
||||
|
||||
return (
|
||||
<CreditNoteProvider creditNote={{ id, label: title }}>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
title={title}
|
||||
description={data?.credit_invoice ? `Credit Note #: ${data.credit_invoice}` : undefined}
|
||||
icon={<ReceiptTextIcon className="size-5" />}
|
||||
backHref="/sales/credit-notes"
|
||||
actions={<CreditNoteActions creditNoteId={id} />}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/credit-notes/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
{
|
||||
href: `/sales/credit-notes/${id}/documents`,
|
||||
label: 'Documents'
|
||||
},
|
||||
{
|
||||
href: `/sales/credit-notes/${id}/notes`,
|
||||
label: 'Notes'
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</DashboardDetailsPage>
|
||||
</CreditNoteProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { CreditNoteNoteForm } from "@/modules/credit-notes/credit-note-note-form"
|
||||
|
||||
type CreditNoteNote = {
|
||||
id: number
|
||||
note?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export default function CreditNoteNotesPage() {
|
||||
const { id: creditNoteId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
const queryKey = ["credit-note-notes", creditNoteId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
const response = await api.creditNotes.show(creditNoteId)
|
||||
return (response as any)?.data ?? response
|
||||
},
|
||||
})
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (noteId: number) =>
|
||||
api.creditNotes.deleteInternalNote(creditNoteId, { note_id: noteId } as never),
|
||||
onSuccess: () => {
|
||||
toast.success("Note deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete note.")
|
||||
},
|
||||
})
|
||||
|
||||
const handleDelete = async (note: CreditNoteNote) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Note",
|
||||
description: "Are you sure you want to delete this note?",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (confirmed) {
|
||||
deleteMutation.mutate(note.id)
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CreditNoteNote>[] = [
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val || "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
cell: ({ row }) => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
title="Delete note"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
</Button>
|
||||
),
|
||||
enableSorting: false,
|
||||
},
|
||||
]
|
||||
|
||||
const notes: CreditNoteNote[] = (data as any)?.internal_notes ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4 lg:p-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Add Note
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={notes}
|
||||
pagination={{ page: 1, pageSize: 15, pageCount: 1, total: notes.length }}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add Note</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CreditNoteNoteForm
|
||||
creditNoteId={creditNoteId}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { CreditNoteGeneralInfo } from '@/modules/credit-notes/credit-note-general-info'
|
||||
|
||||
export default async function CreditNoteDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const response = await api.creditNotes.show(id)
|
||||
const creditNote = (response as any)?.data ?? response
|
||||
|
||||
return (
|
||||
<div className="p-4 lg:p-6">
|
||||
<CreditNoteGeneralInfo creditNote={creditNote} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,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"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
extraParams={{ customer_id: customerId }}
|
||||
header={null}
|
||||
|
||||
@@ -4,6 +4,9 @@ import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import { CustomerForm } from '@/modules/customers/customer-form'
|
||||
import { CUSTOMER_ROUTES } from '@garage/api'
|
||||
import type { CustomersClient } from '@garage/api'
|
||||
@@ -11,14 +14,29 @@ import { Building2Icon, UserIcon } from 'lucide-react'
|
||||
|
||||
export default function CustomersPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<CustomersClient>
|
||||
pageTitle='Customers'
|
||||
routeKey={CUSTOMER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search customers..."
|
||||
getClient={(api) => api.customers}
|
||||
onRowClick={(row) => router.push(`/sales/customers/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<div className='flex items-center gap-2'>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.customers.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Customers"
|
||||
onDownloadSample={() => api.customers.downloadImportSample()}
|
||||
sampleFileName='customers-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.customers.exportData(filters)}
|
||||
fileName='customers'
|
||||
/>
|
||||
<FormDialog title="Customer">
|
||||
{(resourceId) => (
|
||||
<CustomerForm
|
||||
@@ -28,6 +46,7 @@ export default function CustomersPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
|
||||
@@ -2,8 +2,12 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { EstimateActions } from '@/modules/estimates/estimate-actions'
|
||||
import { EstimateProvider } from '@/modules/estimates/estimate-context'
|
||||
import { CreateInvoiceFromEstimateButton } from '@/modules/estimates/create-invoice-from-estimate-button'
|
||||
import { CreateJobCardFromEstimateButton } from '@/modules/estimates/create-job-card-from-estimate-button'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
|
||||
export default async function layout(props: {
|
||||
params: Promise<{ id: string }>
|
||||
@@ -11,25 +15,36 @@ export default async function layout(props: {
|
||||
}) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const estimate = await api.estimates.getById(id)
|
||||
const estimate = await api.estimates.show(id)
|
||||
|
||||
const estimateData = (estimate as any)?.data
|
||||
const estimateData = estimate?.data
|
||||
const title = estimateData?.title || estimateData?.estimate_number || `Estimate #${id}`
|
||||
const estimateLabel = estimateData?.estimate_number
|
||||
? `${estimateData.estimate_number}${estimateData.title ? ` — ${estimateData.title}` : ''}`
|
||||
: title
|
||||
|
||||
if (!estimateData) {
|
||||
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<EstimateProvider estimate={{ id, label: estimateLabel }}>
|
||||
<EstimateProvider estimate={estimateData}>
|
||||
<DashboardDetailsPage
|
||||
className="p-0 lg:p-0"
|
||||
icon={<FileTextIcon className="size-5" />}
|
||||
title={title}
|
||||
description={
|
||||
estimateData?.date ? `Date: ${estimateData.date}` : undefined
|
||||
estimateData?.date ? `Date: ${formatDate(estimateData.date)}` : undefined
|
||||
}
|
||||
backHref="/sales/estimates"
|
||||
actions={<EstimateActions estimateId={id} />}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<CreateInvoiceFromEstimateButton />
|
||||
<CreateJobCardFromEstimateButton />
|
||||
<ShareDocumentButton type="estimate" id={id} />
|
||||
<EstimateActions estimateId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{ href: `/sales/estimates/${id}`, label: 'Details' },
|
||||
]}
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { EstimateGeneralInfo } from '@/modules/estimates/estimate-general-info'
|
||||
import { EstimateServicesSection } from '@/modules/estimates/estimate-services-section'
|
||||
import { EstimatePartsSection } from '@/modules/estimates/estimate-parts-section'
|
||||
import { EstimateExpenseItemsSection } from '@/modules/estimates/estimate-expense-items-section'
|
||||
import { EstimateTotalsSummary } from '@/modules/estimates/estimate-totals-summary'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const estimate = await api.estimates.getById(id)
|
||||
const estimate = await api.estimates.show(id)
|
||||
|
||||
const estimateData = (estimate as any)?.data
|
||||
const estimateData = estimate?.data
|
||||
|
||||
if (!estimateData) {
|
||||
return <div className="text-muted-foreground p-4">Estimate not found.</div>
|
||||
@@ -15,7 +19,14 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="grid gap-6">
|
||||
<EstimateGeneralInfo estimate={estimateData} />
|
||||
<EstimateServicesSection estimateId={id} />
|
||||
<EstimatePartsSection estimateId={id} />
|
||||
<EstimateExpenseItemsSection estimateId={id} />
|
||||
<EstimateTotalsSummary />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { Car, FileTextIcon } from 'lucide-react'
|
||||
import { Button } from '@/shared/components/ui/button'
|
||||
import { Car, FileTextIcon, Printer, UserIcon } from 'lucide-react'
|
||||
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||
import Link from 'next/link'
|
||||
import { formatDate } from '@/shared/utils/formatters'
|
||||
import { getVehicleLabel } from '@/modules/vehicles/utils/getVehicleLabel'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function EstimatesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
return (
|
||||
<ResourcePage<EstimatesClient>
|
||||
pageTitle="Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
onRowClick={(row) => router.push(`/sales/estimates/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Estimate">
|
||||
@@ -36,7 +46,7 @@ export default function EstimatesPage() {
|
||||
const item = row.original
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline">
|
||||
<Link href={`/sales/estimates/${item.id}`} className="flex items-center gap-2 hover:underline" onClick={(e) => e.stopPropagation()}>
|
||||
<FileTextIcon className="text-muted-foreground h-4 w-4" />
|
||||
<span>{item.title}</span>
|
||||
</Link>
|
||||
@@ -51,22 +61,39 @@ export default function EstimatesPage() {
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item: any = row.original
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle_id",
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original
|
||||
return <Button variant="outline" asChild size="sm">
|
||||
<Link href={`/sales/vehicles/${item.vehicle_id}`}>
|
||||
<Car/> Go to vehicle
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
const item: any = row.original
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vehicle?.id ? `/sales/vehicles/${item.vehicle.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item.vehicle as any)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original
|
||||
return formatDate(item.date)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "has_insurance",
|
||||
@@ -84,7 +111,15 @@ export default function EstimatesPage() {
|
||||
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"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -1,589 +1,458 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState, useRef, useCallback } from "react"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Label } from "@/shared/components/ui/label"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/shared/components/ui/select"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Plus,
|
||||
Ellipsis,
|
||||
Pencil,
|
||||
Trash2,
|
||||
CheckCircle2,
|
||||
AlertTriangle,
|
||||
XCircle,
|
||||
MinusCircle,
|
||||
CircleDot,
|
||||
Paperclip,
|
||||
FileUp,
|
||||
FileText,
|
||||
FileImage,
|
||||
File,
|
||||
X,
|
||||
Car,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
CircleCheck,
|
||||
FileSignature,
|
||||
Gauge,
|
||||
Image as ImageIcon,
|
||||
Loader2,
|
||||
Share2,
|
||||
StickyNote,
|
||||
User,
|
||||
} from "lucide-react"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
|
||||
// ── Types ──
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/shared/components/ui/card"
|
||||
import { Progress } from "@/shared/components/ui/progress"
|
||||
import { Separator } from "@/shared/components/ui/separator"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import {
|
||||
CheckpointFillDialog,
|
||||
isCheckpointComplete,
|
||||
type Checkpoint,
|
||||
type Severity,
|
||||
} from "@/modules/inspections/checkpoint-fill-dialog"
|
||||
import { SignaturePad } from "@/modules/inspections/signature-pad"
|
||||
import { InspectionShareDialog } from "@/modules/inspections/inspection-share-dialog"
|
||||
|
||||
type CheckpointItem = {
|
||||
type Inspection = {
|
||||
id: number
|
||||
inspection_id?: number
|
||||
name?: string
|
||||
description?: string
|
||||
record_type?: string
|
||||
condition_rate?: number
|
||||
file?: string
|
||||
status?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
title: string
|
||||
order_number?: string | null
|
||||
status?: string | null
|
||||
odometer?: number | null
|
||||
template?: { id: number; name: string } | null
|
||||
customer?: { first_name?: string; last_name?: string } | null
|
||||
vehicle?: { make?: string; model?: string; year?: string | number; license_plate?: string } | null
|
||||
check_points: Checkpoint[]
|
||||
technician_signature_url?: string | null
|
||||
customer_signature_url?: string | null
|
||||
}
|
||||
|
||||
// ── Constants ──
|
||||
|
||||
const CHECKPOINT_STATUSES = [
|
||||
{ value: "passed", label: "Passed", icon: CheckCircle2, color: "bg-green-100 text-green-800" },
|
||||
{ value: "need_attention", label: "Need Attention", icon: AlertTriangle, color: "bg-yellow-100 text-yellow-800" },
|
||||
{ value: "failed", label: "Failed", icon: XCircle, color: "bg-red-100 text-red-800" },
|
||||
{ value: "not_applicable", label: "Not Applicable", icon: MinusCircle, color: "bg-gray-100 text-gray-800" },
|
||||
{ value: "not_inspected", label: "Not Inspected", icon: CircleDot, color: "bg-blue-100 text-blue-800" },
|
||||
] as const
|
||||
|
||||
const RECORD_TYPES = [
|
||||
{ value: "record_conditions", label: "Record Conditions" },
|
||||
{ value: "record_audio", label: "Record Audio" },
|
||||
{ value: "record_video", label: "Record Video" },
|
||||
{ value: "capture_photo", label: "Capture Photo" },
|
||||
] as const
|
||||
|
||||
function formatStatus(status?: string) {
|
||||
if (!status) return "Not Inspected"
|
||||
return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
const SEVERITY_DOT: Record<Severity, string> = {
|
||||
good: "bg-emerald-500 shadow-emerald-500/30",
|
||||
attention: "bg-amber-500 shadow-amber-500/30",
|
||||
critical: "bg-rose-500 shadow-rose-500/30",
|
||||
na: "bg-slate-400 shadow-slate-400/30",
|
||||
not_inspected: "bg-muted shadow-none",
|
||||
}
|
||||
const SEVERITY_LABEL: Record<Severity, string> = {
|
||||
good: "Good",
|
||||
attention: "Attention",
|
||||
critical: "Critical",
|
||||
na: "N/A",
|
||||
not_inspected: "Not inspected",
|
||||
}
|
||||
const SEVERITY_BADGE: Record<Severity, "default" | "secondary" | "destructive" | "outline"> = {
|
||||
good: "default",
|
||||
attention: "secondary",
|
||||
critical: "destructive",
|
||||
na: "outline",
|
||||
not_inspected: "outline",
|
||||
}
|
||||
|
||||
function getStatusConfig(status?: string) {
|
||||
return CHECKPOINT_STATUSES.find((s) => s.value === status) || CHECKPOINT_STATUSES[4]
|
||||
function groupBySection(cps: Checkpoint[]) {
|
||||
const map = new Map<string, Checkpoint[]>()
|
||||
for (const cp of cps) {
|
||||
const key = cp.section_name || "Other"
|
||||
if (!map.has(key)) map.set(key, [])
|
||||
map.get(key)!.push(cp)
|
||||
}
|
||||
return Array.from(map.entries()).map(([name, items]) => ({ name, items }))
|
||||
}
|
||||
|
||||
// ── Checkpoint Form Dialog ──
|
||||
|
||||
function CheckpointFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
inspectionId,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
inspectionId: string
|
||||
checkpoint?: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
export default function InspectionCheckpointsPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [name, setName] = useState(checkpoint?.name ?? "")
|
||||
const [description, setDescription] = useState(checkpoint?.description ?? "")
|
||||
const [recordType, setRecordType] = useState(checkpoint?.record_type ?? "record_conditions")
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
|
||||
const isEditing = !!checkpoint
|
||||
const [data, setData] = useState<Inspection | null>(null)
|
||||
const [initialLoad, setInitialLoad] = useState(true)
|
||||
const [refetching, setRefetching] = useState(false)
|
||||
const [activeIndex, setActiveIndex] = useState<number | null>(null)
|
||||
const [shareOpen, setShareOpen] = useState(false)
|
||||
const [mode, setMode] = useState<"all" | "wizard">("all")
|
||||
const [wizardSectionIdx, setWizardSectionIdx] = useState(0)
|
||||
const [signing, setSigning] = useState<{ who: "technician" | "customer" } | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!name.trim()) {
|
||||
toast.error("Name is required")
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
const load = useCallback(async () => {
|
||||
const isFirst = !data
|
||||
if (isFirst) setInitialLoad(true)
|
||||
else setRefetching(true)
|
||||
try {
|
||||
const payload = {
|
||||
inspection_id: Number(inspectionId),
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
record_type: recordType,
|
||||
const res = await api.inspections.showOne(id)
|
||||
setData(res.data as Inspection)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to load inspection")
|
||||
} finally {
|
||||
setInitialLoad(false)
|
||||
setRefetching(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id])
|
||||
|
||||
const patchCheckpoint = useCallback((checkpointId: number, patch: Partial<Checkpoint>) => {
|
||||
setData((prev) => {
|
||||
if (!prev) return prev
|
||||
return {
|
||||
...prev,
|
||||
check_points: prev.check_points.map((c) =>
|
||||
c.id === checkpointId ? { ...c, ...patch } : c
|
||||
),
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const sections = useMemo(() => data ? groupBySection(data.check_points ?? []) : [], [data])
|
||||
const flatCheckpoints = useMemo(() => sections.flatMap((s) => s.items), [sections])
|
||||
|
||||
const totals = useMemo(() => {
|
||||
const t = { good: 0, attention: 0, critical: 0, na: 0, not_inspected: 0 }
|
||||
for (const cp of data?.check_points ?? []) {
|
||||
const s = (cp.severity as Severity) ?? "not_inspected"
|
||||
t[s]++
|
||||
}
|
||||
return t
|
||||
}, [data])
|
||||
|
||||
const setSeverity = async (cp: Checkpoint, severity: Severity) => {
|
||||
patchCheckpoint(cp.id, { severity })
|
||||
try {
|
||||
await api.inspections.updateCheckpoint(String(cp.id), { severity } as any)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save")
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
const promise = api.inspections.updateCheckpoint(String(checkpoint.id), payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Updating checkpoint...",
|
||||
success: "Checkpoint updated",
|
||||
error: "Failed to update checkpoint",
|
||||
})
|
||||
await promise
|
||||
} else {
|
||||
const promise = api.inspections.createCheckpoint(payload)
|
||||
toast.promise(promise, {
|
||||
loading: "Creating checkpoint...",
|
||||
success: "Checkpoint created",
|
||||
error: "Failed to create checkpoint",
|
||||
})
|
||||
await promise
|
||||
}
|
||||
onSuccess()
|
||||
onOpenChange(false)
|
||||
const handleSign = async (who: "technician" | "customer", dataUrl: string) => {
|
||||
setSigning({ who })
|
||||
try {
|
||||
await api.inspections.sign(id, who, dataUrl)
|
||||
toast.success(who === "technician" ? "Technician signature saved" : "Customer signature saved")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.payload?.message ?? "Failed to save signature")
|
||||
} finally {
|
||||
setIsPending(false)
|
||||
setSigning(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (initialLoad) {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex items-center justify-center">
|
||||
<div className="flex items-center gap-2 text-muted-foreground text-sm">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading inspection…
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!data) return <div className="p-6 text-muted-foreground">Inspection not found</div>
|
||||
|
||||
const vehicleLine = data.vehicle
|
||||
? [data.vehicle.year, data.vehicle.make, data.vehicle.model].filter(Boolean).join(" ")
|
||||
: "—"
|
||||
const customerName = data.customer ? `${data.customer.first_name ?? ""} ${data.customer.last_name ?? ""}`.trim() : "—"
|
||||
const totalCount = data.check_points.length
|
||||
const inspectedCount = totalCount - totals.not_inspected
|
||||
const progress = totalCount > 0 ? Math.round((inspectedCount / totalCount) * 100) : 0
|
||||
|
||||
const wizardSection = sections[wizardSectionIdx]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Checkpoint" : "Add Checkpoint"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="grid gap-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-name">Name *</Label>
|
||||
<Input
|
||||
id="cp-name"
|
||||
placeholder="e.g. Engine Oil Level"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<div className="max-w-5xl mx-auto p-3 sm:p-6 space-y-4">
|
||||
{/* Header */}
|
||||
<Card>
|
||||
<CardHeader className="gap-3">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<Link href={`/sales/inspections/${id}`}>
|
||||
<Button variant="ghost" size="sm" className="-ms-2">
|
||||
<ChevronLeft className="size-4" /> Back to inspection
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2">
|
||||
{refetching && <Loader2 className="size-3.5 animate-spin text-muted-foreground" />}
|
||||
<Button variant="outline" size="sm" onClick={() => setShareOpen(true)}>
|
||||
<Share2 className="size-4" /> Share with customer
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-description">Description</Label>
|
||||
<Textarea
|
||||
id="cp-description"
|
||||
placeholder="Check oil level and condition"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="cp-record-type">Record Type</Label>
|
||||
<Select value={recordType} onValueChange={setRecordType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{RECORD_TYPES.map((rt) => (
|
||||
<SelectItem key={rt.value} value={rt.value}>
|
||||
{rt.label}
|
||||
</SelectItem>
|
||||
<Separator />
|
||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||
<div className="min-w-0">
|
||||
<CardDescription className="uppercase tracking-wide text-[11px]">Inspection</CardDescription>
|
||||
<CardTitle className="text-2xl">{data.title}</CardTitle>
|
||||
<div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground flex-wrap">
|
||||
<span className="inline-flex items-center gap-1.5"><User className="size-3.5" /> {customerName}</span>
|
||||
<span className="inline-flex items-center gap-1.5"><Car className="size-3.5" /> {vehicleLine}</span>
|
||||
{data.vehicle?.license_plate && (
|
||||
<Badge variant="outline" className="font-mono">{data.vehicle.license_plate}</Badge>
|
||||
)}
|
||||
{data.odometer != null && (
|
||||
<span className="inline-flex items-center gap-1.5"><Gauge className="size-3.5" /> {Number(data.odometer).toLocaleString()} km</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3">
|
||||
{/* Progress */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Progress</span>
|
||||
<span className="tabular-nums">{inspectedCount} / {totalCount} ({progress}%)</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
</div>
|
||||
|
||||
{/* Severity tally */}
|
||||
<div className="flex items-center gap-2 flex-wrap mt-3">
|
||||
{(["good", "attention", "critical", "na", "not_inspected"] as Severity[]).map((s) => (
|
||||
<Badge key={s} variant={SEVERITY_BADGE[s]} className="gap-1.5">
|
||||
<span className={`size-1.5 rounded-full ${SEVERITY_DOT[s].split(" ")[0]}`} />
|
||||
{totals[s]} {SEVERITY_LABEL[s]}
|
||||
</Badge>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button type="submit" disabled={isPending}>
|
||||
{isEditing ? <Pencil className="size-4" /> : <Plus className="size-4" />}
|
||||
{isPending
|
||||
? (isEditing ? "Updating..." : "Creating...")
|
||||
: (isEditing ? "Update Checkpoint" : "Create Checkpoint")}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Attachments Dialog ──
|
||||
|
||||
function getFileIcon(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
if (["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")) return FileImage
|
||||
if (ext === "pdf") return FileText
|
||||
return File
|
||||
}
|
||||
|
||||
function getFileName(url: string) {
|
||||
try {
|
||||
return decodeURIComponent(url.split("/").pop() ?? "Attachment")
|
||||
} catch {
|
||||
return url.split("/").pop() ?? "Attachment"
|
||||
}
|
||||
}
|
||||
|
||||
function isImageUrl(url: string) {
|
||||
const ext = url.split(".").pop()?.toLowerCase()
|
||||
return ["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(ext ?? "")
|
||||
}
|
||||
|
||||
function CheckpointAttachmentsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
checkpoint,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
checkpoint: CheckpointItem | null
|
||||
onSuccess: () => void
|
||||
}) {
|
||||
const api = useAuthApi()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
const handleUpload = useCallback(async (file: globalThis.File) => {
|
||||
if (!checkpoint) return
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const promise = api.inspections.uploadCheckpointMedia(
|
||||
String(checkpoint.id),
|
||||
{ file },
|
||||
)
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment...",
|
||||
success: "Attachment uploaded",
|
||||
error: "Failed to upload attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) fileInputRef.current.value = ""
|
||||
}
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!checkpoint) return
|
||||
const promise = api.inspections.deleteCheckpointMedia(String(checkpoint.id))
|
||||
toast.promise(promise, {
|
||||
loading: "Removing attachment...",
|
||||
success: "Attachment removed",
|
||||
error: "Failed to remove attachment",
|
||||
})
|
||||
await promise
|
||||
onSuccess()
|
||||
}, [api, checkpoint, onSuccess])
|
||||
|
||||
const hasFile = !!checkpoint?.file
|
||||
const FileIcon = checkpoint?.file ? getFileIcon(checkpoint.file) : File
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Attachments — {checkpoint?.name}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Current attachment */}
|
||||
{hasFile ? (
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 min-w-0 ">
|
||||
{isImageUrl(checkpoint.file!) ? (
|
||||
<img
|
||||
src={checkpoint.file!}
|
||||
alt="Checkpoint attachment"
|
||||
className="size-12 rounded-md object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-md bg-muted">
|
||||
<FileIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex flex-col gap-0.5 max-w-48">
|
||||
<a
|
||||
href={checkpoint.file!}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="truncate text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
{getFileName(checkpoint.file!)}
|
||||
</a>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Current attachment
|
||||
{/* Legend */}
|
||||
<div className="mt-3 rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
|
||||
<span className="font-medium text-foreground">Tap a dot to mark:</span>
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => (
|
||||
<span key={s} className="inline-flex items-center gap-1.5">
|
||||
<span className={`size-3 rounded-full ${SEVERITY_DOT[s].split(" ")[0]} shadow-md`} />
|
||||
{SEVERITY_LABEL[s]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="shrink-0 text-destructive hover:text-destructive"
|
||||
onClick={handleDelete}
|
||||
title="Remove attachment"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-muted-foreground">
|
||||
<Paperclip className="size-8" />
|
||||
<span className="text-sm">No attachments yet</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mode tabs */}
|
||||
{totalCount > 0 && (
|
||||
<Tabs value={mode} onValueChange={(v) => setMode(v as any)} className="w-full">
|
||||
<TabsList className="w-full sm:w-auto">
|
||||
<TabsTrigger value="all">All sections</TabsTrigger>
|
||||
<TabsTrigger value="wizard">Wizard</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{/* Upload area */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,audio/*,video/*"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
}}
|
||||
/>
|
||||
{/* Sections */}
|
||||
{totalCount === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-10 text-center">
|
||||
<CircleCheck className="size-8 mx-auto text-muted-foreground/60 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
This inspection has no checkpoints yet. It was probably created from an empty template.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : mode === "all" ? (
|
||||
sections.map((section) => (
|
||||
<Card key={section.name}>
|
||||
<CardHeader className="py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">{section.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
{section.items.filter(isCheckpointComplete).length} / {section.items.length} done
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{section.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
wizardSection && (() => {
|
||||
const pendingItems = wizardSection.items.filter((cp) => !isCheckpointComplete(cp))
|
||||
const sectionDone = pendingItems.length === 0
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="py-3 gap-1">
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<CardTitle className="text-base">{wizardSection.name}</CardTitle>
|
||||
<Badge variant="outline" className="font-normal">
|
||||
Section {wizardSectionIdx + 1} / {sections.length}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
<ul className="divide-y">
|
||||
{wizardSection.items.map((cp) => (
|
||||
<CheckpointRow key={cp.id} cp={cp} onSeverity={setSeverity} onOpen={() => setActiveIndex(flatCheckpoints.findIndex((c) => c.id === cp.id))} />
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
<div className="px-4 py-3 border-t bg-muted/30 space-y-2">
|
||||
{!sectionDone && (
|
||||
<div className="flex items-start gap-2 text-xs text-amber-900">
|
||||
<AlertTriangle className="size-3.5 mt-0.5 shrink-0 text-amber-600" />
|
||||
<div>
|
||||
<span className="font-medium">{pendingItems.length} pending.</span>{' '}
|
||||
Each checkpoint needs a finding and its required recording before you can move on.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={isUploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<FileUp className="size-4" />
|
||||
{isUploading
|
||||
? "Uploading..."
|
||||
: hasFile
|
||||
? "Replace Attachment"
|
||||
: "Add Attachment"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Main Page ──
|
||||
|
||||
export default function InspectionCheckpointsPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: inspectionId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [formOpen, setFormOpen] = useState(false)
|
||||
const [editingCheckpoint, setEditingCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
const [attachmentsCheckpoint, setAttachmentsCheckpoint] = useState<CheckpointItem | null>(null)
|
||||
|
||||
const queryKey = [INSPECTION_ROUTES.CHECKPOINTS, inspectionId]
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.inspections.listCheckpoints({ inspection_id: inspectionId } as never),
|
||||
})
|
||||
|
||||
const invalidate = () => {
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
}
|
||||
|
||||
// ── Status change mutation ──
|
||||
const changeStatusMutation = useMutation({
|
||||
mutationFn: ({ checkpointId, status }: { checkpointId: number; status: string }) =>
|
||||
api.inspections.changeCheckpointStatus({
|
||||
inspection_id: Number(inspectionId),
|
||||
inspection_check_point_id: String(checkpointId),
|
||||
name: "", // required by API type but server uses checkpoint id from context
|
||||
record_type: "record_conditions",
|
||||
status,
|
||||
} as never),
|
||||
onSuccess: () => invalidate(),
|
||||
})
|
||||
|
||||
// ── Delete checkpoint mutation ──
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (checkpointId: string) => api.inspections.destroyCheckpoint(checkpointId),
|
||||
onSuccess: () => {
|
||||
toast.success("Checkpoint deleted")
|
||||
invalidate()
|
||||
},
|
||||
onError: () => toast.error("Failed to delete checkpoint"),
|
||||
})
|
||||
|
||||
const handleEdit = (checkpoint: CheckpointItem) => {
|
||||
setEditingCheckpoint(checkpoint)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEditingCheckpoint(null)
|
||||
setFormOpen(true)
|
||||
}
|
||||
|
||||
const handleStatusChange = (checkpointId: number, status: string) => {
|
||||
const promise = changeStatusMutation.mutateAsync({ checkpointId, status, })
|
||||
toast.promise(promise, {
|
||||
loading: "Updating status...",
|
||||
success: `Status changed to ${formatStatus(status)}`,
|
||||
error: "Failed to update status",
|
||||
})
|
||||
}
|
||||
|
||||
const checkpoints = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
const pagination = {
|
||||
page: meta?.current_page ?? 1,
|
||||
pageSize: meta?.per_page ?? 15,
|
||||
pageCount: meta?.last_page ?? 1,
|
||||
total: meta?.total ?? 0,
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Name" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-medium">{item.name}</span>
|
||||
{item.description && (
|
||||
<span className="text-xs text-muted-foreground">{item.description}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "record_type",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Record Type" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const rt = RECORD_TYPES.find((r) => r.value === item.record_type)
|
||||
return rt?.label ?? item.record_type ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
const config = getStatusConfig(item.status)
|
||||
return (
|
||||
<Badge className={config.color}>
|
||||
<config.icon className="mr-1 size-3" />
|
||||
{formatStatus(item.status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "condition_rate",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Condition" />,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return item.condition_rate != null ? `${item.condition_rate}/10` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "attachments",
|
||||
header: () => <span className="text-xs">Attachments</span>,
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
onClick={() => setAttachmentsCheckpoint(item)}
|
||||
disabled={wizardSectionIdx === 0}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.max(0, i - 1))}
|
||||
>
|
||||
<Paperclip className="size-3.5" />
|
||||
{item.file ? (
|
||||
<Badge variant="secondary" className="px-1.5 py-0 text-xs">1</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">0</span>
|
||||
)}
|
||||
<ChevronLeft className="size-4" /> Previous
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }: any) => {
|
||||
const item = row.original as CheckpointItem
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<Ellipsis className="size-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{CHECKPOINT_STATUSES.map((s) => (
|
||||
<DropdownMenuItem
|
||||
key={s.value}
|
||||
onClick={() => handleStatusChange(item.id, s.value)}
|
||||
disabled={item.status === s.value}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={wizardSectionIdx >= sections.length - 1 || !sectionDone}
|
||||
onClick={() => setWizardSectionIdx((i) => Math.min(sections.length - 1, i + 1))}
|
||||
>
|
||||
<s.icon className="size-4" />
|
||||
{s.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => handleEdit(item)}>
|
||||
<Pencil className="size-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => deleteMutation.mutate(String(item.id))}
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<h3 className="text-lg font-semibold">Checkpoints</h3>
|
||||
<Button onClick={handleAdd} size="sm">
|
||||
<Plus className="size-4" />
|
||||
Add Checkpoint
|
||||
Next <ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={checkpoints}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => {}}
|
||||
isLoading={isLoading}
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
})()
|
||||
)}
|
||||
|
||||
{/* Signatures */}
|
||||
{totalCount > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3 flex-row items-center gap-2">
|
||||
<FileSignature className="size-4 text-muted-foreground" />
|
||||
<CardTitle className="text-base">Sign-off</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="gap-3 grid grid-cols-1 md:grid-cols-2">
|
||||
<SignaturePad
|
||||
label="Technician signature"
|
||||
existingUrl={data.technician_signature_url}
|
||||
saving={signing?.who === "technician"}
|
||||
onSave={(d) => handleSign("technician", d)}
|
||||
/>
|
||||
<CheckpointFormDialog
|
||||
open={formOpen}
|
||||
onOpenChange={(open) => {
|
||||
setFormOpen(open)
|
||||
if (!open) setEditingCheckpoint(null)
|
||||
}}
|
||||
inspectionId={inspectionId}
|
||||
checkpoint={editingCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
<SignaturePad
|
||||
label="Customer signature"
|
||||
existingUrl={data.customer_signature_url}
|
||||
saving={signing?.who === "customer"}
|
||||
onSave={(d) => handleSign("customer", d)}
|
||||
/>
|
||||
<CheckpointAttachmentsDialog
|
||||
open={!!attachmentsCheckpoint}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setAttachmentsCheckpoint(null)
|
||||
}}
|
||||
checkpoint={attachmentsCheckpoint}
|
||||
onSuccess={invalidate}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<CheckpointFillDialog
|
||||
open={activeIndex !== null}
|
||||
onOpenChange={(o) => { if (!o) setActiveIndex(null) }}
|
||||
checkpoints={flatCheckpoints}
|
||||
activeIndex={activeIndex}
|
||||
onIndexChange={setActiveIndex}
|
||||
onSaved={load}
|
||||
onPatch={patchCheckpoint}
|
||||
/>
|
||||
</DashboardPage>
|
||||
|
||||
<InspectionShareDialog
|
||||
open={shareOpen}
|
||||
onOpenChange={setShareOpen}
|
||||
inspectionId={id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CheckpointRow({
|
||||
cp,
|
||||
onSeverity,
|
||||
onOpen,
|
||||
}: {
|
||||
cp: Checkpoint
|
||||
onSeverity: (cp: Checkpoint, s: Severity) => void
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const current = (cp.severity as Severity) ?? "not_inspected"
|
||||
const attachments = cp.attachments ?? cp.media ?? []
|
||||
const photoCount = attachments.filter((m) => m.media_type === "photo").length
|
||||
const complete = isCheckpointComplete(cp)
|
||||
return (
|
||||
<li
|
||||
className={`px-3 sm:px-4 py-3 transition-colors hover:bg-muted/30 ${!complete ? "bg-amber-50/40" : ""}`}
|
||||
>
|
||||
<div className="flex items-start gap-3 flex-wrap sm:flex-nowrap">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex-1 min-w-0 text-left group"
|
||||
>
|
||||
<div className="font-medium text-sm flex items-center gap-2">
|
||||
<span className="group-hover:text-primary transition">{cp.name}</span>
|
||||
{!complete && (
|
||||
<Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{cp.technician_notes && (
|
||||
<div className="flex items-start gap-1 text-xs text-muted-foreground mt-1">
|
||||
<StickyNote className="size-3 mt-0.5 shrink-0" />
|
||||
<span className="italic line-clamp-1">{cp.technician_notes}</span>
|
||||
</div>
|
||||
)}
|
||||
{photoCount > 0 && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
|
||||
<ImageIcon className="size-3" /> {photoCount} photo{photoCount === 1 ? "" : "s"}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<div className="flex gap-2 justify-end shrink-0 w-full sm:w-auto">
|
||||
{(["good", "attention", "critical", "na"] as Severity[]).map((s) => {
|
||||
const active = current === s
|
||||
return (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); onSeverity(cp, s) }}
|
||||
aria-label={SEVERITY_LABEL[s]}
|
||||
title={SEVERITY_LABEL[s]}
|
||||
className={`size-10 sm:size-9 rounded-full transition shadow-md ${SEVERITY_DOT[s]} ${active ? "ring-2 ring-offset-2 ring-foreground/40 scale-105" : "opacity-60 hover:opacity-100"}`}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DashboardDetailsPage } from '@/base/components/layout/dashboard'
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionActions } from '@/modules/inspections/inspection-actions'
|
||||
import { InspectionProvider } from '@/modules/inspections/inspection-context'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
import React from 'react'
|
||||
|
||||
export default async function layout(props: {
|
||||
@@ -23,7 +24,12 @@ export default async function layout(props: {
|
||||
title={title}
|
||||
description={orderNumber ? `Order: ${orderNumber}` : undefined}
|
||||
backHref="/sales/inspections"
|
||||
actions={<InspectionActions inspectionId={id} status={status} />}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<ShareDocumentButton type="inspection" id={id} />
|
||||
<InspectionActions inspectionId={id} status={status} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/inspections/${id}`,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InspectionGeneralInfo } from '@/modules/inspections/inspection-general-info'
|
||||
import { InspectionDetailHeader } from '@/modules/inspections/inspection-detail-header'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
@@ -11,8 +12,11 @@ export default async function page(props: { params: Promise<{ id: string }> }) {
|
||||
return <div className="text-muted-foreground">Inspection not found.</div>
|
||||
}
|
||||
|
||||
const data = inspection.data as { title?: string }
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<InspectionDetailHeader inspectionId={id} title={data.title} />
|
||||
<InspectionGeneralInfo inspection={inspection.data} />
|
||||
</DashboardPage>
|
||||
)
|
||||
|
||||
@@ -1,25 +1,68 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES } from "@garage/api"
|
||||
import { InspectionFromTemplateForm } from "@/modules/inspections/inspection-from-template-form"
|
||||
import { InspectionRowActions } from "@/modules/inspections/inspection-row-actions"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { ScrollArea } from "@/shared/components/ui/scroll-area"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import Link from "next/link"
|
||||
import { Car, ClipboardList, ListChecks, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
const STATUS_BADGE_CLASS: Record<string, string> = {
|
||||
in_progress: "bg-amber-100 text-amber-800",
|
||||
completed: "bg-emerald-100 text-emerald-800",
|
||||
cancelled: "bg-rose-100 text-rose-800",
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
in_progress: "In Progress",
|
||||
completed: "Completed",
|
||||
cancelled: "Cancelled",
|
||||
}
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
const [fromTemplateOpen, setFromTemplateOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<ResourcePage<InspectionsClient>
|
||||
pageTitle="Inspections"
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inspection">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/settings/inspection-templates">
|
||||
<ListChecks className="size-4" />
|
||||
Manage templates
|
||||
</Link>
|
||||
</Button>
|
||||
<Button size="sm" variant="default" onClick={() => setFromTemplateOpen(true)}>
|
||||
<ClipboardList className="size-4" />
|
||||
New from template
|
||||
</Button>
|
||||
<FormDialog title="Inspection" classNames={{ trigger: "" }}>
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
@@ -28,19 +71,55 @@ export default function InspectionsPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
<Dialog open={fromTemplateOpen} onOpenChange={setFromTemplateOpen}>
|
||||
<DialogContent className="min-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl font-bold">
|
||||
New inspection from template
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="max-h-[80vh] px-4">
|
||||
<InspectionFromTemplateForm
|
||||
onSuccess={(id) => {
|
||||
setFromTemplateOpen(false)
|
||||
invalidateQuery()
|
||||
if (id) router.push(`/sales/inspections/${id}/checkpoints`)
|
||||
}}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
columns={({ openEdit, deleteItem }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{r.title ?? "—"}</span>
|
||||
{r.order_number && (
|
||||
<span className="text-xs text-muted-foreground">{r.order_number}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return c ? `${c.first_name ?? ""} ${c.last_name ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -48,27 +127,51 @@ export default function InspectionsPage() {
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return v ? `${v.make ?? ""} ${v.model ?? ""}`.trim() : "—"
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inspection_category",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
|
||||
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
|
||||
cell: ({ row }) => {
|
||||
const ic = (row.original as any).inspection_category
|
||||
return ic?.inspection_name ?? ic?.name ?? "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
const status = (row.original as any).status as string | undefined
|
||||
if (!status) return "—"
|
||||
const cls = STATUS_BADGE_CLASS[status] ?? "bg-gray-100 text-gray-700"
|
||||
return (
|
||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
||||
{status ?? "—"}
|
||||
<span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
|
||||
{STATUS_LABEL[status] ?? status}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">Actions</span>,
|
||||
enableSorting: false,
|
||||
enableHiding: false,
|
||||
cell: ({ row }) => (
|
||||
<InspectionRowActions
|
||||
inspection={row.original as any}
|
||||
onEdit={() => openEdit(row.original as any)}
|
||||
onDelete={() => deleteItem(String((row.original as any).id))}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -4,6 +4,8 @@ import { InvoiceActions } from '@/modules/invoices/invoice-actions'
|
||||
import { InvoiceProvider } from '@/modules/invoices/invoice-context'
|
||||
import { ReceiptIcon } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import InvoiceStatusBadge from '@/modules/invoices/invoice-status-badge'
|
||||
import { ShareDocumentButton } from '@/shared/components/share-document-button'
|
||||
|
||||
export default async function InvoiceDetailLayout(props: { params: Promise<{ id: string }>, children: React.ReactNode }) {
|
||||
const { id } = await props.params
|
||||
@@ -13,19 +15,26 @@ export default async function InvoiceDetailLayout(props: { params: Promise<{ id:
|
||||
const title = data?.subject || data?.invoice_number || 'Invoice Details'
|
||||
|
||||
return (
|
||||
<InvoiceProvider invoice={{ id, label: title }}>
|
||||
<InvoiceProvider invoice={data}>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
title={title}
|
||||
description={data?.invoice_number ? `Invoice #: ${data.invoice_number}` : undefined}
|
||||
icon={<ReceiptIcon className="size-5" />}
|
||||
backHref="/sales/invoice"
|
||||
actions={<InvoiceActions invoiceId={id} />}
|
||||
actions={
|
||||
<div className="flex space-x-2 items-center">
|
||||
|
||||
<InvoiceStatusBadge invoice={{id, status:data?.status}} />
|
||||
<ShareDocumentButton type="invoice" id={id} />
|
||||
<InvoiceActions invoiceId={id} />
|
||||
</div>
|
||||
}
|
||||
tabs={[
|
||||
{
|
||||
href: `/sales/invoice/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
|
||||
{
|
||||
href: `/sales/invoice/${id}/documents`,
|
||||
label: 'Documents'
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { InvoiceGeneralInfo } from '@/modules/invoices/invoice-general-info'
|
||||
import { InvoicePartsSection } from '@/modules/invoices/invoice-parts-section'
|
||||
import { InvoiceServicesSection } from '@/modules/invoices/invoice-services-section'
|
||||
import { InvoiceExpensesSection } from '@/modules/invoices/invoice-expenses-section'
|
||||
import { InvoiceTotalsSummary } from '@/modules/invoices/invoice-totals-summary'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
import InvoicePaymentsSection from '@/modules/invoices/invoice-payments-section'
|
||||
|
||||
|
||||
export default async function InvoiceDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
@@ -14,7 +20,14 @@ export default async function InvoiceDetailPage(props: { params: Promise<{ id: s
|
||||
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<InvoiceGeneralInfo invoice={data} />
|
||||
<div className="grid gap-6">
|
||||
<InvoiceGeneralInfo />
|
||||
<InvoicePartsSection parts={data.invoice_parts} />
|
||||
<InvoiceServicesSection services={data.invoice_services} />
|
||||
<InvoiceExpensesSection expenses={data.invoice_expenses} />
|
||||
<InvoicePaymentsSection></InvoicePaymentsSection>
|
||||
<InvoiceTotalsSummary />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,36 +1,101 @@
|
||||
"use client"
|
||||
|
||||
import { Car, Printer, UserIcon } from "lucide-react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InvoiceForm } from "@/modules/invoices/invoice-form"
|
||||
import { INVOICE_ROUTES } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { formatDate, formatEnum } from "@/shared/utils/formatters"
|
||||
import { INVOICE_ROUTES, InvoiceStatus } from "@garage/api"
|
||||
import type { InvoicesClient } from "@garage/api"
|
||||
import { Money } from "@/shared/components/money"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
|
||||
type InvoiceItem = {
|
||||
id: number
|
||||
subject?: string
|
||||
invoice_title?: string
|
||||
invoice_number?: string
|
||||
customer_name?: string
|
||||
status?: string
|
||||
invoice_date?: string
|
||||
due_date?: string
|
||||
created_at?: string
|
||||
total?: number | string
|
||||
balance_due?: number | string
|
||||
customer?: {
|
||||
id?: number | string
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
company_name?: string
|
||||
phone?: string
|
||||
} | null
|
||||
vehicle?: {
|
||||
make?: string
|
||||
model?: string
|
||||
sub_model?: string
|
||||
year?: number | string
|
||||
license_plate?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
function getCustomerLabel(item: InvoiceItem): string {
|
||||
const firstName = item.customer?.first_name?.trim()
|
||||
const lastName = item.customer?.last_name?.trim()
|
||||
const fullName = [firstName, lastName].filter(Boolean).join(" ").trim()
|
||||
|
||||
return fullName || item.customer_name || item.customer?.company_name || "—"
|
||||
}
|
||||
|
||||
function getVehicleLabel(item: InvoiceItem): string {
|
||||
const vehicle = item.vehicle
|
||||
if (!vehicle) return "—"
|
||||
|
||||
const core = [vehicle.make, vehicle.model, vehicle.sub_model].filter(Boolean).join(" ")
|
||||
const suffix = [vehicle.year, vehicle.license_plate].filter(Boolean).join(" • ")
|
||||
|
||||
if (core && suffix) return `${core} (${suffix})`
|
||||
return core || suffix || "—"
|
||||
}
|
||||
|
||||
function getDueMeta(dueDate?: string) {
|
||||
if (!dueDate) return { text: "No due date", tone: "muted" as const }
|
||||
|
||||
const due = new Date(dueDate)
|
||||
if (isNaN(due.getTime())) return { text: "Invalid due date", tone: "muted" as const }
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
due.setHours(0, 0, 0, 0)
|
||||
|
||||
const days = Math.ceil((due.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
if (days < 0) return { text: `${Math.abs(days)} day(s) overdue`, tone: "danger" as const }
|
||||
if (days === 0) return { text: "Due today", tone: "warning" as const }
|
||||
if (days <= 3) return { text: `Due in ${days} day(s)`, tone: "warning" as const }
|
||||
|
||||
return { text: `Due in ${days} day(s)`, tone: "ok" as const }
|
||||
}
|
||||
|
||||
export default function InvoicesPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<InvoicesClient>
|
||||
pageTitle="Invoices"
|
||||
routeKey={INVOICE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search invoices..."
|
||||
statusFilter={{ statuses: InvoiceStatus }}
|
||||
getClient={(api) => api.invoices}
|
||||
onRowClick={(row) => router.push(`/sales/invoice/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Invoice">
|
||||
<FormDialog classNames={{dialogContent:'lg:min-w-6xl'}} title="Invoice">
|
||||
{(resourceId) => (
|
||||
<InvoiceForm
|
||||
resourceId={resourceId}
|
||||
@@ -44,15 +109,64 @@ export default function InvoicesPage() {
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "subject",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Subject" />,
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const title = item.subject || item.invoice_title || "Untitled invoice"
|
||||
|
||||
return (
|
||||
<div className="min-w-[220px]">
|
||||
<p className="font-medium leading-none">{title}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{item.invoice_number || "No invoice number"}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
|
||||
return (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{item.invoice_number || "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getCustomerLabel(item)}
|
||||
meta={item.customer?.phone}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const vehicleId = (item.vehicle as any)?.id
|
||||
return (
|
||||
<RelationLink
|
||||
href={vehicleId ? `/sales/vehicles/${vehicleId}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(item)}
|
||||
meta={item.vehicle?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
@@ -60,29 +174,81 @@ export default function InvoicesPage() {
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const status = item.status
|
||||
const colorMap: Record<string, string> = {
|
||||
draft: "text-muted-foreground",
|
||||
open: "text-blue-600",
|
||||
paid: "text-green-600",
|
||||
overdue: "text-red-600",
|
||||
void: "text-gray-400",
|
||||
const classMap: Record<string, string> = {
|
||||
draft: "bg-slate-100 text-slate-700",
|
||||
open: "bg-blue-100 text-blue-700",
|
||||
paid: "bg-emerald-100 text-emerald-700",
|
||||
over_due: "bg-red-100 text-red-700",
|
||||
un_paid: "bg-orange-100 text-orange-700",
|
||||
partially_paid: "bg-amber-100 text-amber-700",
|
||||
void: "bg-zinc-100 text-zinc-700",
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={colorMap[status ?? ""] ?? ""}>
|
||||
{status ? status.charAt(0).toUpperCase() + status.slice(1) : "—"}
|
||||
</span>
|
||||
<Badge variant="outline" className={classMap[status ?? ""] ?? ""}>
|
||||
{formatEnum(status) || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
return formatDate(item.invoice_date)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "due_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Due Date" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as InvoiceItem
|
||||
const dueMeta = getDueMeta(item.due_date)
|
||||
const toneClassMap = {
|
||||
danger: "text-red-600",
|
||||
warning: "text-amber-600",
|
||||
ok: "text-emerald-600",
|
||||
muted: "text-muted-foreground",
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p className="font-medium leading-none">{formatDate(item.due_date)}</p>
|
||||
<p className={`mt-1 text-xs ${toneClassMap[dueMeta.tone]}`}>
|
||||
{dueMeta.text}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
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"
|
||||
|
||||
import { useEffect } from "react"
|
||||
import { use } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { AppointmentForm } from "@/modules/appointments/appointment-form"
|
||||
import { APPOINTMENT_ROUTES } from "@garage/api"
|
||||
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
|
||||
import type { AppointmentsClient } from "@garage/api"
|
||||
import { CalendarCheck2Icon, ClockIcon } from "lucide-react"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
requested: "bg-yellow-100 text-yellow-800",
|
||||
@@ -27,15 +31,48 @@ export default function JobCardAppointmentsPage({
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const jobCard = useJobCard()
|
||||
|
||||
const defaultJobCard = jobCard
|
||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
||||
useEffect(() => {
|
||||
if (searchParams.get("create") !== "1") return
|
||||
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
params.delete("create")
|
||||
params.set("dialog", "true")
|
||||
|
||||
router.replace(`${pathname}?${params.toString()}`)
|
||||
}, [pathname, router, searchParams])
|
||||
|
||||
const jc = jobCard as any
|
||||
const defaultJobCard = jc
|
||||
? { value: String(jc.id), label: jc.label || jc.title || `Job Card` }
|
||||
: null
|
||||
|
||||
const appointmentDefaults = jc
|
||||
? {
|
||||
job_card_id: jc.id,
|
||||
job_card_title: jc.title || `Job Card #${jc.id}`,
|
||||
customer_id: jc.customer?.id,
|
||||
customer_name: getFullName(jc.customer),
|
||||
vehicle_id: jc.vehicle?.id,
|
||||
vehicle_name: getVehicleLabel(jc.vehicle),
|
||||
service_writer_id: jc.service_writer?.id,
|
||||
service_writer_name: getFullName(jc.service_writer),
|
||||
technician_id: jc.primary_technician?.id,
|
||||
technician_name: getFullName(jc.primary_technician),
|
||||
department_id: jc.department?.id,
|
||||
department_name: jc.department?.name,
|
||||
}
|
||||
: { job_card: defaultJobCard }
|
||||
|
||||
return (
|
||||
<ResourcePage<AppointmentsClient>
|
||||
routeKey={APPOINTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search appointments..."
|
||||
statusFilter={{ statuses: AppointmentStatus }}
|
||||
getClient={(api) => api.appointments}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,8 +83,8 @@ export default function JobCardAppointmentsPage({
|
||||
{(resourceId) => (
|
||||
<AppointmentForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
||||
initialData={selectedItem ?? appointmentDefaults}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery(); router.refresh() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
@@ -89,7 +126,7 @@ export default function JobCardAppointmentsPage({
|
||||
const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
|
||||
return (
|
||||
<Badge className={colorClass}>
|
||||
{status?.replace("_", " ") ?? "—"}
|
||||
{formatEnum(status)}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useParams, useRouter } from "next/navigation"
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
||||
import { useState, useRef } from "react"
|
||||
import { useState, useRef, useTransition } from "react"
|
||||
import { Plus, Trash2, FileIcon, ImageIcon, FileTextIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -10,7 +10,7 @@ import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Card, CardContent } from "@/shared/components/ui/card"
|
||||
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||
import { ApiError, JOB_CARD_ROUTES } from "@garage/api"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { CONSTANTS } from "@/config/constants"
|
||||
@@ -22,10 +22,68 @@ function getFileIcon(mimeType?: string) {
|
||||
return FileIcon
|
||||
}
|
||||
|
||||
const ALLOWED_HINT = "Allowed: images, PDF, Office docs, audio, video."
|
||||
|
||||
function describeAttachmentError(rawMessage: string, filename: string): string {
|
||||
const msg = rawMessage.toLowerCase()
|
||||
if (msg.includes("must be a file of type") || msg.includes("mimes")) {
|
||||
return `${filename}: unsupported file type. ${ALLOWED_HINT}`
|
||||
}
|
||||
if (msg.includes("may not be greater") || msg.includes("max")) {
|
||||
return `${filename}: exceeds 5 MB limit.`
|
||||
}
|
||||
if (msg.includes("must be a file")) {
|
||||
return `${filename}: invalid file.`
|
||||
}
|
||||
return `${filename}: ${rawMessage}`
|
||||
}
|
||||
|
||||
function showUploadError(err: unknown, files: File[]) {
|
||||
if (!(err instanceof ApiError)) {
|
||||
toast.error("Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const validation = err.validationErrors
|
||||
if (!validation || Object.keys(validation).length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const messages: string[] = []
|
||||
for (const [key, msgs] of Object.entries(validation)) {
|
||||
const firstMsg = Array.isArray(msgs) ? msgs[0] : String(msgs)
|
||||
if (!firstMsg) continue
|
||||
|
||||
const match = key.match(/^attachments\.(\d+)$/)
|
||||
if (match) {
|
||||
const idx = Number(match[1])
|
||||
const filename = files[idx]?.name ?? `File #${idx + 1}`
|
||||
messages.push(describeAttachmentError(firstMsg, filename))
|
||||
} else if (key === "attachments") {
|
||||
messages.push(firstMsg)
|
||||
} else {
|
||||
messages.push(firstMsg)
|
||||
}
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
toast.error(err.payload?.message ?? "Failed to upload attachment(s)")
|
||||
return
|
||||
}
|
||||
|
||||
const shown = messages.slice(0, 3)
|
||||
const extra = messages.length - shown.length
|
||||
shown.forEach((m) => toast.error(m))
|
||||
if (extra > 0) toast.error(`...and ${extra} more`)
|
||||
}
|
||||
|
||||
export default function JobCardAttachmentsPage() {
|
||||
const { id: jobCardId } = useParams<{ id: string }>()
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const [isRefreshing, startRefreshTransition] = useTransition()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
@@ -41,6 +99,7 @@ export default function JobCardAttachmentsPage() {
|
||||
onSuccess: () => {
|
||||
toast.success("Attachment deleted successfully.")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
startRefreshTransition(() => router.refresh())
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to delete attachment.")
|
||||
@@ -63,17 +122,19 @@ export default function JobCardAttachmentsPage() {
|
||||
const files = e.target.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const fileList = Array.from(files)
|
||||
setIsUploading(true)
|
||||
const promise = api.jobCards.addAttachment(jobCardId, Array.from(files))
|
||||
toast.promise(promise, {
|
||||
loading: "Uploading attachment(s)...",
|
||||
success: "Attachment(s) uploaded successfully",
|
||||
error: "Failed to upload attachment(s)",
|
||||
})
|
||||
const loadingToast = toast.loading("Uploading attachment(s)...")
|
||||
|
||||
try {
|
||||
await promise
|
||||
await api.jobCards.addAttachment(jobCardId, fileList)
|
||||
toast.dismiss(loadingToast)
|
||||
toast.success("Attachment(s) uploaded successfully")
|
||||
queryClient.invalidateQueries({ queryKey })
|
||||
startRefreshTransition(() => router.refresh())
|
||||
} catch (err) {
|
||||
toast.dismiss(loadingToast)
|
||||
showUploadError(err, fileList)
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
if (fileInputRef.current) {
|
||||
|
||||
@@ -6,9 +6,13 @@ import { Badge } from "@/shared/components/ui/badge"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import { BillForm } from "@/modules/bills/bill-form"
|
||||
import { BILL_ROUTES } from "@garage/api"
|
||||
import { BILL_ROUTES, BillStatus } from "@garage/api"
|
||||
import type { BillsClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { formatEnum } from "@/shared/utils/formatters"
|
||||
|
||||
export default function JobCardBillsPage({
|
||||
params,
|
||||
@@ -25,6 +29,9 @@ export default function JobCardBillsPage({
|
||||
return (
|
||||
<ResourcePage<BillsClient>
|
||||
routeKey={BILL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search bills..."
|
||||
statusFilter={{ statuses: BillStatus }}
|
||||
getClient={(api) => api.bills}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +53,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "bill_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
|
||||
cell: ({ row }) => (row.original as any).bill_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/bill/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.bill_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +71,16 @@ export default function JobCardBillsPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "bill_date",
|
||||
@@ -78,7 +103,7 @@ export default function JobCardBillsPage({
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{status || "—"}</Badge>
|
||||
return <Badge variant={status === "paid" ? "default" : "secondary"}>{formatEnum(status)}</Badge>
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardExpenseItemForm } from "@/modules/job-cards/job-card-expense-item-form"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
// TODO: expense items invalidation is not working properly when create new expense item line. Need to investigate why and fix it.
|
||||
|
||||
export default function JobCardExpenseItemsPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const queryKey = ["job-card-expense-items", jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getExpenseItems(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey , refetchType:'all'}).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete this expense item?",
|
||||
description: `Remove "${row.expense_item?.item_name ?? "this expense item"}" from the job card?`,
|
||||
})
|
||||
if (!confirmed) return
|
||||
const promise = api.jobCards.deleteExpenseItem(jobCardId, row.id)
|
||||
toast.promise(promise, {
|
||||
loading: "Deleting...",
|
||||
success: "Expense item deleted",
|
||||
error: "Failed to delete expense item",
|
||||
})
|
||||
await promise
|
||||
invalidate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: "expense_item.item_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expense Item" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original.expense_item
|
||||
return item ? (
|
||||
<div>
|
||||
<span className="font-medium">{item.item_name}</span>
|
||||
{item.sku && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{item.sku}</span>
|
||||
)}
|
||||
</div>
|
||||
) : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Qty" />,
|
||||
cell: ({ row }) => row.original.quantity ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "rate",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||
cell: ({ row }) => row.original.department?.name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Description" />,
|
||||
cell: ({ row }) => row.original.description || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Added" />,
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditItem(row.original)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
<div className="flex justify-end">
|
||||
<Dialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setDialogOpen(open)
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => setEditItem(null)}>
|
||||
<Plus className="me-2 h-4 w-4" />
|
||||
Add Expense Item
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editItem ? "Edit Expense Item" : "Add Expense Item"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<JobCardExpenseItemForm
|
||||
jobCardId={jobCardId}
|
||||
jobCardExpenseItemId={editItem?.id ?? null}
|
||||
initialData={editItem}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
invalidate()
|
||||
}}
|
||||
onCancel={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{
|
||||
page: 1,
|
||||
pageSize: rows.length || 15,
|
||||
pageCount: 1,
|
||||
total: rows.length,
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { use } from "react"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { ExpenseForm } from "@/modules/expenses/expense-form"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { EXPENSE_ROUTES } from "@garage/api"
|
||||
import type { ExpensesClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
|
||||
export default function JobCardExpensesPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const jobCard = useJobCard()
|
||||
|
||||
const defaultJobCard = jobCard
|
||||
? { value: String((jobCard as any).id), label: (jobCard as any).label || (jobCard as any).title || `Job Card` }
|
||||
: null
|
||||
|
||||
return (
|
||||
<ResourcePage<ExpensesClient>
|
||||
routeKey={EXPENSE_ROUTES.INDEX}
|
||||
getClient={(api) => api.expenses}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
tableHeader={({ invalidateQuery, selectedItem, closeDialog }) => (
|
||||
<div className="flex justify-end">
|
||||
|
||||
<FormDialog title="Expense">
|
||||
{(resourceId) => (
|
||||
<ExpenseForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? { job_card: defaultJobCard }}
|
||||
onSuccess={() => { closeDialog(); invalidateQuery() }}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
)}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "invoice_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
|
||||
cell: ({ row }) => (row.original as any).invoice_number || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "expense_date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).expense_date
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return (
|
||||
<Badge variant={status === "paid" ? "default" : "secondary"}>
|
||||
{status || "—"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client"
|
||||
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { InspectionForm } from "@/modules/inspections/inspection-form"
|
||||
import { INSPECTION_ROUTES, InspectionStatus } from "@garage/api"
|
||||
import type { InspectionsClient } from "@garage/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Car, UserIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
import { getVehicleLabel } from "@/modules/vehicles/utils/getVehicleLabel"
|
||||
|
||||
export default function InspectionsPage() {
|
||||
const router = useRouter()
|
||||
const jobCard = useJobCard()
|
||||
return (
|
||||
<ResourcePage<InspectionsClient>
|
||||
pageTitle="Inspections"
|
||||
extraParams={{job_card_id: jobCard?.id}}
|
||||
routeKey={INSPECTION_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search inspections..."
|
||||
statusFilter={{ statuses: InspectionStatus }}
|
||||
getClient={(api) => api.inspections}
|
||||
onRowClick={(row) => router.push(`/sales/inspections/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Inspection">
|
||||
{(resourceId) => (
|
||||
<InspectionForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem ?? {job_card: {value: jobCard?.id, label: jobCard?.title || `Job Card #${jobCard?.id}`}}}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Title" />,
|
||||
},
|
||||
{
|
||||
accessorKey: "customer",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const c = (row.original as any).customer
|
||||
return (
|
||||
<RelationLink
|
||||
href={c?.id ? `/sales/customers/${c.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(c)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const v = (row.original as any).vehicle
|
||||
return (
|
||||
<RelationLink
|
||||
href={v?.id ? `/sales/vehicles/${v.id}` : null}
|
||||
icon={Car}
|
||||
label={getVehicleLabel(v as any)}
|
||||
meta={v?.license_plate}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "inspection_category",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Category" />,
|
||||
cell: ({ row }) => (row.original as any).inspection_category?.name ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const status = (row.original as any).status
|
||||
return (
|
||||
<span className={status === "completed" ? "text-green-600" : "text-yellow-600"}>
|
||||
{status ?? "—"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -12,11 +12,11 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
|
||||
const jobCard = await api.jobCards.show(id).then(res => res.data)
|
||||
const jobCard:any = await api.jobCards.show(id).then(res => res.data)
|
||||
|
||||
const title = jobCard?.title || 'Job Card Details'
|
||||
const status = jobCard?.status || 'draft'
|
||||
const docs = jobCard?.documents
|
||||
const attachmentsCount = jobCard?.attachment_files?.length ?? jobCard?.documents?.length ?? 0
|
||||
|
||||
return (
|
||||
<JobCardProvider jobCard={{ ...jobCard }}>
|
||||
@@ -35,34 +35,53 @@ export default async function JobCardDetailLayout(props: { params: Promise<{ id:
|
||||
href: `/sales/job-cards/${id}`,
|
||||
label: 'Details'
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/parts`,
|
||||
label: `Parts (${jobCard?.parts_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/services`,
|
||||
label: `Services (${jobCard?.services_count })`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/expense-items`,
|
||||
label: `Expense Items (${jobCard?.expense_items_count || 0})`
|
||||
},
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// TODO: Needs refactor from API side then refactor in frontend
|
||||
{
|
||||
href: `/sales/job-cards/${id}/attachments`,
|
||||
label: `Attachments (${docs?.length || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/purchase-orders`,
|
||||
label: `Purchase Orders (${jobCard?.purchase_orders_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/bills`,
|
||||
label: `Bills (${jobCard?.bills_count || 0})`
|
||||
label: `Attachments (${attachmentsCount})`
|
||||
},
|
||||
|
||||
{
|
||||
href: `/sales/job-cards/${id}/appointments`,
|
||||
label: `Appointments (${jobCard?.appointments_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/expenses`,
|
||||
label: `Expenses (${jobCard?.expenses_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/tasks`,
|
||||
label: `Tasks (${jobCard?.tasks_count || 0})`
|
||||
},
|
||||
{
|
||||
href: `/sales/job-cards/${id}/parts`,
|
||||
label: `Parts (${jobCard?.parts_count || 0})`
|
||||
},
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/inspections`,
|
||||
// label: `Inspections (${(jobCard as any)?.inspections_count || 0})`
|
||||
// },
|
||||
|
||||
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/tasks`,
|
||||
// label: `Tasks (${jobCard?.tasks_count || 0})`
|
||||
// },
|
||||
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/purchase-orders`,
|
||||
// label: `Purchase Orders (${jobCard?.purchase_orders_count || 0})`
|
||||
// },
|
||||
// {
|
||||
// href: `/sales/job-cards/${id}/bills`,
|
||||
// label: `Bills (${jobCard?.bills_count || 0})`
|
||||
// },
|
||||
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
import { getServerApi } from '@garage/api/server'
|
||||
import { JobCardGeneralInfo } from '@/modules/job-cards/job-card-general-info'
|
||||
import DashboardPage from '@/base/components/layout/dashboard/dashboard-page'
|
||||
|
||||
export default async function JobCardDetailPage(props: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await props.params
|
||||
const api = await getServerApi()
|
||||
const jobCard = await api.jobCards.show(id)
|
||||
const data = (jobCard as any)?.data ?? jobCard
|
||||
|
||||
if (!data) {
|
||||
return <div className="text-muted-foreground">Job card not found.</div>
|
||||
}
|
||||
|
||||
export default async function JobCardDetailPage() {
|
||||
return (
|
||||
<DashboardPage header={null}>
|
||||
<JobCardGeneralInfo jobCard={data} />
|
||||
<JobCardGeneralInfo />
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
@@ -24,6 +25,7 @@ import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardPartForm } from "@/modules/job-cards/job-card-part-form"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { JOB_CARD_ROUTES } from "@garage/api"
|
||||
|
||||
export default function JobCardPartsPage({
|
||||
params,
|
||||
@@ -33,7 +35,8 @@ export default function JobCardPartsPage({
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const queryKey = ["job-card-parts", jobCardId]
|
||||
const router = useRouter()
|
||||
const queryKey = [JOB_CARD_ROUTES.GET_PARTS, jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
@@ -41,11 +44,12 @@ export default function JobCardPartsPage({
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getParts(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey })
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey, type: 'all', refetchType: 'all' },).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
@@ -93,9 +97,17 @@ export default function JobCardPartsPage({
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax",
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax || "—",
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
|
||||
@@ -8,6 +8,9 @@ import { PurchaseOrderForm } from "@/modules/purchase-orders/purchase-order-form
|
||||
import { PURCHASE_ORDER_ROUTES } from "@garage/api"
|
||||
import type { PurchaseOrdersClient } from "@garage/api"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
import { RelationLink } from "@/shared/components/relation-link"
|
||||
import { Building2, FileTextIcon } from "lucide-react"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
export default function JobCardPurchaseOrdersPage({
|
||||
params,
|
||||
@@ -24,6 +27,8 @@ export default function JobCardPurchaseOrdersPage({
|
||||
return (
|
||||
<ResourcePage<PurchaseOrdersClient>
|
||||
routeKey={PURCHASE_ORDER_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search purchase orders..."
|
||||
getClient={(api) => api.purchaseOrders}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
@@ -46,7 +51,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Order #" />,
|
||||
cell: ({ row }) => (row.original as any).order_number || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.id ? `/purchase/purchase-order/${item.id}` : null}
|
||||
icon={FileTextIcon}
|
||||
label={item.order_number}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
@@ -55,7 +69,16 @@ export default function JobCardPurchaseOrdersPage({
|
||||
{
|
||||
accessorKey: "vendor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
|
||||
cell: ({ row }) => (row.original as any).vendor_name || "—",
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.vendor?.id ? `/purchase/vendor/${item.vendor.id}` : null}
|
||||
icon={Building2}
|
||||
label={item.vendor?.company_name || getFullName(item.vendor) || item.vendor_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "order_date",
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"use client"
|
||||
|
||||
import { use, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { ColumnHeader, DataTable } from "@/shared/data-view/table-view"
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { toast } from "sonner"
|
||||
import { Ellipsis, Plus } from "lucide-react"
|
||||
import type { ColumnDef } from "@tanstack/react-table"
|
||||
import { JobCardServiceForm } from "@/modules/job-cards/job-card-service-form"
|
||||
import { formatDate } from "@/shared/utils/formatters"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
|
||||
// TODO: services invalidation is not working properly when create new service line. Need to investigate why and fix it.
|
||||
|
||||
export default function JobCardServicesPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id: jobCardId } = use(params)
|
||||
const api = useAuthApi()
|
||||
const queryClient = useQueryClient()
|
||||
const router = useRouter()
|
||||
const queryKey = ["job-card-services", jobCardId]
|
||||
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editItem, setEditItem] = useState<any | null>(null)
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey,
|
||||
queryFn: () => api.jobCards.getServices(jobCardId),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
const rows = (data as any)?.data ?? []
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey , refetchType:'all'}).then(() => router.refresh())
|
||||
|
||||
async function handleDelete(row: any) {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete this service?",
|
||||
description: `Remove service "${row.service?.labor_name ?? "this service"}" from the job card?`,
|
||||
})
|
||||
if (!confirmed) return
|
||||
const promise = api.jobCards.deleteService(jobCardId, row.id)
|
||||
toast.promise(promise, {
|
||||
loading: "Deleting...",
|
||||
success: "Service deleted",
|
||||
error: "Failed to delete service",
|
||||
})
|
||||
await promise
|
||||
invalidate()
|
||||
}
|
||||
|
||||
const columns: ColumnDef<any>[] = [
|
||||
{
|
||||
accessorKey: "service.labor_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Service" />,
|
||||
cell: ({ row }) => {
|
||||
const service = row.original.service
|
||||
return service ? (
|
||||
<div>
|
||||
<span className="font-medium">{service.labor_name}</span>
|
||||
{service.service_code && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">{service.service_code}</span>
|
||||
)}
|
||||
</div>
|
||||
) : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "rate_type",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate Type" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate_type
|
||||
if (!val) return "—"
|
||||
return (
|
||||
<Badge variant="outline">
|
||||
{val === "flat_rate" ? "Flat Rate" : val === "hourly" ? "Hourly" : val}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "quantity",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Qty" />,
|
||||
cell: ({ row }) => row.original.quantity ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "rate",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.rate
|
||||
return val != null ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "labor_rate.title",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Labor Rate" />,
|
||||
cell: ({ row }) => {
|
||||
const lr = row.original.labor_rate
|
||||
return lr ? `${lr.title} ($${Number(lr.rate).toFixed(2)})` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "working_hours",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Working Hrs" />,
|
||||
cell: ({ row }) => row.original.working_hours ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "labor_hours",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Labor Hrs" />,
|
||||
cell: ({ row }) => row.original.labor_hours ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "discount_amount",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Discount" />,
|
||||
cell: ({ row }) => {
|
||||
const val = row.original.discount_amount
|
||||
return val != null && val > 0 ? `$${Number(val).toFixed(2)}` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "tax_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Tax" />,
|
||||
cell: ({ row }) => row.original.tax_id ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "department.name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Department" />,
|
||||
cell: ({ row }) => row.original.department?.name || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "description",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Description" />,
|
||||
cell: ({ row }) => row.original.description || "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Added" />,
|
||||
cell: ({ row }) => formatDate(row.original.created_at),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon">
|
||||
<Ellipsis className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditItem(row.original)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
>
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
<div className="flex justify-end">
|
||||
<Dialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setDialogOpen(open)
|
||||
if (!open) setEditItem(null)
|
||||
}}
|
||||
>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={() => setEditItem(null)}>
|
||||
<Plus className="me-2 h-4 w-4" />
|
||||
Add Service
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editItem ? "Edit Service" : "Add Service"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<JobCardServiceForm
|
||||
jobCardId={jobCardId}
|
||||
jobCardServiceId={editItem?.id ?? null}
|
||||
initialData={editItem}
|
||||
onSuccess={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
invalidate()
|
||||
}}
|
||||
onCancel={() => {
|
||||
setDialogOpen(false)
|
||||
setEditItem(null)
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
pagination={{
|
||||
page: 1,
|
||||
pageSize: rows.length || 15,
|
||||
pageCount: 1,
|
||||
total: rows.length,
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { TaskForm } from "@/modules/tasks/task-form"
|
||||
import { TASK_ROUTES } from "@garage/api"
|
||||
import { TASK_ROUTES, TaskStatus } from "@garage/api"
|
||||
import type { TasksClient } from "@garage/api"
|
||||
import { Badge } from "@/shared/components/ui/badge"
|
||||
import { useJobCard } from "@/modules/job-cards/job-card-context"
|
||||
@@ -26,6 +26,9 @@ export default function JobCardTasksPage({
|
||||
return (
|
||||
<ResourcePage<TasksClient>
|
||||
routeKey={TASK_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tasks..."
|
||||
statusFilter={{ statuses: TaskStatus }}
|
||||
getClient={(api) => api.tasks}
|
||||
extraParams={{ job_card_id: jobCardId }}
|
||||
header={null}
|
||||
|
||||
@@ -6,13 +6,14 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { JobCardForm } from '@/modules/job-cards/job-card-form'
|
||||
import { JOB_CARD_ROUTES, JobCardStatus } from '@garage/api'
|
||||
import type { JobCardsClient } from '@garage/api'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/shared/components/ui/tabs'
|
||||
import { ClipboardListIcon, SearchIcon } from 'lucide-react'
|
||||
import { ClipboardListIcon, Printer } from 'lucide-react'
|
||||
import { useDocumentPrint } from '@/shared/hooks/use-document-print'
|
||||
import { Badge } from '@/shared/components/ui/badge'
|
||||
import { Input } from '@/shared/components/ui/input'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { formatDate, formatEnum, formatNumber } from '@/shared/utils/formatters'
|
||||
import { useFilterParams } from '@/shared/hooks/use-filter-params'
|
||||
import { FilterDrawer, FilterTrigger } from '@/shared/components/filter-drawer'
|
||||
import { jobCardFilterConfig, JobCardFilterFields } from '@/modules/job-cards/job-card-filters'
|
||||
|
||||
type JobCardItem = {
|
||||
id: number
|
||||
@@ -34,38 +35,34 @@ const statusColorMap: Record<string, string> = {
|
||||
|
||||
export default function JobCardsPage() {
|
||||
const router = useRouter()
|
||||
const [searchInput, setSearchInput] = useState("")
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState<string>("check_in")
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSearch(searchInput), 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
const extraParams: Record<string, unknown> = {}
|
||||
if (search) extraParams.search = search
|
||||
if (statusFilter !== "all") extraParams.status = statusFilter
|
||||
const filter = useFilterParams(jobCardFilterConfig)
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<>
|
||||
<ResourcePage<JobCardsClient>
|
||||
|
||||
routeKey={JOB_CARD_ROUTES.INDEX}
|
||||
getClient={(api) => api.jobCards}
|
||||
extraParams={extraParams}
|
||||
searchable
|
||||
searchPlaceholder="Search job cards..."
|
||||
statusFilter={{ statuses: JobCardStatus }}
|
||||
extraParams={filter.appliedParams}
|
||||
onRowClick={(row) => router.push(`/sales/job-cards/${row.id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
title: "Job Cards",
|
||||
actions: (
|
||||
<FormDialog classNames={{ dialogContent: 'min-w-6xl' }} title="Job Card" >
|
||||
{(resourceId) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<FilterTrigger onClick={filter.open} activeFilterCount={filter.activeFilterCount} />
|
||||
<FormDialog classNames={{ dialogContent: 'xl:min-w-6xl' }} title="Job Card" >
|
||||
{(resourceId, {close}) => (
|
||||
<JobCardForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
onSuccess={()=>{ invalidateQuery(); close();}}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
@@ -82,11 +79,9 @@ export default function JobCardsPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
accessorKey: "order_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Order Number" />,
|
||||
|
||||
},
|
||||
{
|
||||
accessorKey: "check_in_date",
|
||||
@@ -124,32 +119,29 @@ export default function JobCardsPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
actionsColumn({
|
||||
extraItems: (row) => [
|
||||
{
|
||||
label: isPrinting ? "Printing..." : "Print",
|
||||
icon: Printer,
|
||||
onClick: (r) => print("job_card", String(r.id), "print"),
|
||||
},
|
||||
],
|
||||
}),
|
||||
]}
|
||||
/>
|
||||
|
||||
tableHeader={
|
||||
<div className="flex justify-between">
|
||||
<Tabs value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="all" >All</TabsTrigger>
|
||||
{JobCardStatus.map((status) => (
|
||||
<TabsTrigger key={status} value={status}>
|
||||
{formatEnum(status)}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<div className="relative w-64">
|
||||
<SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search job cards..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<FilterDrawer
|
||||
form={filter.form}
|
||||
isOpen={filter.isOpen}
|
||||
onOpenChange={(open) => { if (!open) filter.close() }}
|
||||
onSubmit={filter.onSubmit}
|
||||
onReset={filter.reset}
|
||||
activeFilterCount={filter.activeFilterCount}
|
||||
title="Filter Job Cards"
|
||||
>
|
||||
<JobCardFilterFields />
|
||||
</FilterDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
CreditCardIcon,
|
||||
HashIcon,
|
||||
Printer,
|
||||
UserIcon,
|
||||
ClipboardListIcon,
|
||||
} 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 = {
|
||||
id: number
|
||||
@@ -29,13 +34,19 @@ type PaymentReceivedItem = {
|
||||
}
|
||||
|
||||
export default function PaymentReceivedPage() {
|
||||
const router = useRouter()
|
||||
const { print, isPrinting } = useDocumentPrint()
|
||||
|
||||
return (
|
||||
<ResourcePage<{ list(query?: any): Promise<any>; destroy(id: string): Promise<any> }>
|
||||
routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search payments..."
|
||||
getClient={(api) => ({
|
||||
list: (query?: any) => api.paymentReceived.list(query),
|
||||
destroy: (id: string) => api.paymentReceived.destroy(id),
|
||||
})}
|
||||
onRowClick={(row) => router.push(`/sales/payment-received/${(row as any).id}`)}
|
||||
headerProps={({ invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Record Payment">
|
||||
@@ -63,29 +74,33 @@ export default function PaymentReceivedPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
accessorKey: "customer",
|
||||
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const customer = item.customer
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{item.customer_name || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "job_card_name",
|
||||
accessorKey: "job_card",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const label = item.job_card_number || item.job_card_name
|
||||
const item: any = row.original as unknown as PaymentReceivedItem
|
||||
const jobCard = item.job_card
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{label || "—"}</span>
|
||||
</div>
|
||||
<RelationLink
|
||||
href={jobCard?.id ? `/sales/job-cards/${jobCard.id}` : null}
|
||||
icon={ClipboardListIcon}
|
||||
label={jobCard?.title || item.job_card_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
@@ -111,14 +126,14 @@ export default function PaymentReceivedPage() {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "payment_mode_name",
|
||||
accessorKey: "payment_mode",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as unknown as PaymentReceivedItem
|
||||
const item:any = row.original as unknown as PaymentReceivedItem
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCardIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="capitalize">{item.payment_mode_name || "—"}</span>
|
||||
<span className="capitalize">{item.payment_mode?.title || "—"}</span>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
@@ -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 { type ColumnDef } from "@tanstack/react-table"
|
||||
import { useState } from "react"
|
||||
import { Plus, Trash2 } from "lucide-react"
|
||||
import { Download, ExternalLink, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
@@ -19,10 +19,27 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog"
|
||||
import { VehicleDocumentForm } from "@/modules/vehicles/vehicle-document-form"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
import { getFullName } from "@/shared/utils/getFullName"
|
||||
|
||||
type VehicleDocument = {
|
||||
id: number
|
||||
name: string
|
||||
document_number?: string
|
||||
document_type_id?: number
|
||||
document_type?: {
|
||||
id?: number
|
||||
name?: string
|
||||
} | null
|
||||
customer_id?: number
|
||||
customer?: {
|
||||
id?: number
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
name?: string
|
||||
} | null
|
||||
document_expire?: string
|
||||
document_file?: string
|
||||
document_file_url?: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -54,7 +71,7 @@ export default function VehicleDocumentsPage() {
|
||||
const handleDelete = async (doc: VehicleDocument) => {
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Document",
|
||||
description: `Are you sure you want to delete "${doc.name}"?`,
|
||||
description: `Are you sure you want to delete "${doc.document_number || `Document #${doc.id}`}"?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -65,16 +82,74 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
const columns: ColumnDef<VehicleDocument>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Name" />,
|
||||
accessorKey: "document_number",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Number" />,
|
||||
cell: ({ getValue, row }) => {
|
||||
const number = getValue<string>()
|
||||
const fallbackName = row.original.document_file?.split("/").pop()
|
||||
return number || fallbackName || `Document #${row.original.id}`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_type_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Document Type" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const typeName = row.original.document_type?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return typeName || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customer_id",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row, getValue }) => {
|
||||
const name = getFullName(row.original.customer as any) || row.original.customer?.name
|
||||
const value = getValue<number | undefined>()
|
||||
return name || (value ? `#${value}` : "—")
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "document_expire",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Expiry Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "file",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="File" />,
|
||||
cell: ({ row }) => {
|
||||
const url = row.original.document_file_url
|
||||
if (!url) return "No file"
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Open document"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
Open
|
||||
</a>
|
||||
<a
|
||||
href={url}
|
||||
download
|
||||
className="inline-flex items-center gap-1 text-primary underline"
|
||||
title="Download document"
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
Download
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Uploaded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -83,7 +158,10 @@ export default function VehicleDocumentsPage() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={() => handleDelete(row.original)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
handleDelete(row.original)
|
||||
}}
|
||||
title="Delete document"
|
||||
>
|
||||
<Trash2 className="size-4 text-destructive" />
|
||||
@@ -93,6 +171,15 @@ export default function VehicleDocumentsPage() {
|
||||
},
|
||||
]
|
||||
|
||||
const handleRowClick = (doc: VehicleDocument) => {
|
||||
if (doc.document_file_url) {
|
||||
window.open(doc.document_file_url, "_blank", "noopener,noreferrer")
|
||||
return
|
||||
}
|
||||
|
||||
toast.info("This document has no file to open.")
|
||||
}
|
||||
|
||||
const documents = (data as any)?.data ?? []
|
||||
const meta = (data as any)?.meta
|
||||
|
||||
@@ -105,21 +192,25 @@ export default function VehicleDocumentsPage() {
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-end">
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <div className="flex items-center justify-end">
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
Upload Document
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
}}
|
||||
columns={columns}
|
||||
data={documents}
|
||||
pagination={pagination}
|
||||
sorting={[]}
|
||||
onChange={() => { }}
|
||||
onRowClick={handleRowClick}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
@@ -8,8 +8,10 @@ import FormDialog from '@/shared/components/form-dialog'
|
||||
import { EstimateForm } from '@/modules/estimates/estimate-form'
|
||||
import { ESTIMATE_ROUTES } from '@garage/api'
|
||||
import type { EstimatesClient } from '@garage/api'
|
||||
import { FileTextIcon } from 'lucide-react'
|
||||
import { FileTextIcon, UserIcon } from 'lucide-react'
|
||||
import { useVehicle } from '@/modules/vehicles/vehicle-context'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
|
||||
export default function VehicleEstimatesPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id: vehicleId } = use(params)
|
||||
@@ -37,6 +39,8 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
}
|
||||
pageTitle="Vehicle Estimates"
|
||||
routeKey={ESTIMATE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search estimates..."
|
||||
getClient={(api) => api.estimates}
|
||||
extraParams={{ vehicle_id: vehicleId }}
|
||||
header={
|
||||
@@ -63,6 +67,16 @@ export default function VehicleEstimatesPage({ params }: { params: Promise<{ id:
|
||||
{
|
||||
accessorKey: "customer_name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }) => {
|
||||
const item = row.original as any
|
||||
return (
|
||||
<RelationLink
|
||||
href={item.customer?.id ? `/sales/customers/${item.customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(item.customer) || item.customer_name}
|
||||
/>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
|
||||
@@ -13,7 +13,6 @@ export default async function layout(props: { params: Promise<{ id: string }>, c
|
||||
return (
|
||||
<>
|
||||
<DashboardDetailsPage
|
||||
className='p-0 lg:p-0'
|
||||
avatarSrc={vehicle.data?.image_url || ""}
|
||||
// avatarSrc={vehicle.data?.image_url || ""}
|
||||
title={title}
|
||||
|
||||
@@ -25,11 +25,23 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "@/shared/components/ui/dropdown-menu"
|
||||
import { MileageForm } from "@/modules/vehicles/mileage-form"
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { formatDate, formatDateTime } from "@/shared/utils/formatters"
|
||||
|
||||
type MileageRecord = {
|
||||
id: number
|
||||
name: string
|
||||
vehicle_id?: number
|
||||
miles?: number | null
|
||||
fuel_level?: number | null
|
||||
date?: string | null
|
||||
time?: string | null
|
||||
note?: string | null
|
||||
vehicle?: {
|
||||
id?: number
|
||||
make?: string | null
|
||||
model?: string | null
|
||||
year?: number | null
|
||||
license_plate?: string | null
|
||||
} | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -64,9 +76,10 @@ export default function VehicleMileagePage() {
|
||||
})
|
||||
|
||||
const handleDelete = async (record: MileageRecord) => {
|
||||
const label = record.miles != null ? `${record.miles} mi` : `Record #${record.id}`
|
||||
const confirmed = await confirm({
|
||||
title: "Delete Mileage Record",
|
||||
description: `Are you sure you want to delete this mileage record?`,
|
||||
description: `Are you sure you want to delete ${label}?`,
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
@@ -87,16 +100,59 @@ export default function VehicleMileagePage() {
|
||||
|
||||
const columns: ColumnDef<MileageRecord>[] = [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Mileage" />,
|
||||
accessorKey: "miles",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Miles" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : value.toLocaleString()
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "fuel_level",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Fuel Level" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<number | null | undefined>()
|
||||
return value == null ? "—" : `${value}%`
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "date",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Date" />,
|
||||
cell: ({ getValue }) => formatDate(getValue<string | null | undefined>()),
|
||||
},
|
||||
{
|
||||
accessorKey: "time",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Time" />,
|
||||
cell: ({ getValue }) => {
|
||||
const value = getValue<string | null | undefined>()
|
||||
if (!value) return "—"
|
||||
if (value.includes("T")) {
|
||||
const timePart = value.split("T")[1]
|
||||
return timePart ? timePart.slice(0, 5) : "—"
|
||||
}
|
||||
return value.slice(0, 5)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "note",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Note" />,
|
||||
cell: ({ getValue }) => getValue<string | null | undefined>() || "—",
|
||||
},
|
||||
{
|
||||
id: "vehicle",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const vehicle = row.original.vehicle
|
||||
if (!vehicle) return "—"
|
||||
const details = [vehicle.make, vehicle.model, vehicle.year].filter(Boolean).join(" ")
|
||||
return details || vehicle.license_plate || "—"
|
||||
},
|
||||
enableSorting: false,
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Recorded At" />,
|
||||
cell: ({ getValue }) => {
|
||||
const val = getValue<string>()
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
cell: ({ getValue }) => formatDateTime(getValue<string | undefined>()),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
@@ -142,21 +198,16 @@ export default function VehicleMileagePage() {
|
||||
<div className="flex flex-col gap-4">
|
||||
|
||||
|
||||
<DashboardPage
|
||||
headerProps={{
|
||||
title: 'Mileage',
|
||||
actions: (
|
||||
<Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
>
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
slots={{
|
||||
actions: <Button onClick={handleCreate}>
|
||||
<Plus className="size-4" />
|
||||
Add Mileage
|
||||
</Button>
|
||||
}}
|
||||
columns={columns}
|
||||
data={records}
|
||||
pagination={pagination}
|
||||
@@ -166,7 +217,6 @@ export default function VehicleMileagePage() {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="min-w-md">
|
||||
|
||||
@@ -129,20 +129,28 @@ export default function VehicleOwnersPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardPage headerProps={{
|
||||
title: "Owners",
|
||||
actions: (
|
||||
<Button className="w-full" size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
),
|
||||
}}>
|
||||
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
|
||||
|
||||
<DataTable
|
||||
slots={{
|
||||
actions:
|
||||
<div className="flex justify-end">
|
||||
|
||||
<Button size={'lg'} onClick={() => setLinkDialogOpen(true)}>
|
||||
<Plus />
|
||||
Add Owner
|
||||
</Button>
|
||||
</div>,
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
columns={columns}
|
||||
data={owners}
|
||||
pagination={pagination}
|
||||
@@ -163,7 +171,6 @@ export default function VehicleOwnersPage() {
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DashboardPage >
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,23 +3,45 @@
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { ResourcePage } from '@/shared/data-view/resource-page'
|
||||
import { ColumnHeader } from '@/shared/data-view/table-view'
|
||||
import type { ColumnDef } from '@tanstack/react-table'
|
||||
import FormDialog from '@/shared/components/form-dialog'
|
||||
import { ImportDataButton } from '@/shared/components/import-data-button'
|
||||
import { ExportDataButton } from '@/shared/components/export-data-button'
|
||||
import { useAuthApi } from '@/shared/useApi'
|
||||
import type { CrudResourceColumnHelpers, ResourceItem } from '@/shared/data-view/resource-page'
|
||||
import { VehicleForm } from '@/modules/vehicles/vehicle-form'
|
||||
import { VEHICLE_ROUTES } from '@garage/api'
|
||||
import type { VehiclesClient } from '@garage/api'
|
||||
import { CarIcon } from 'lucide-react'
|
||||
import { CarIcon, UserIcon } from 'lucide-react'
|
||||
import { getFullName } from '@/shared/utils/getFullName'
|
||||
import { RelationLink } from '@/shared/components/relation-link'
|
||||
|
||||
export default function VehiclesPage() {
|
||||
const router = useRouter()
|
||||
const api = useAuthApi()
|
||||
return (
|
||||
<ResourcePage<VehiclesClient>
|
||||
pageTitle="Vehicles"
|
||||
routeKey={VEHICLE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search vehicles..."
|
||||
getClient={(api) => api.vehicles}
|
||||
onRowClick={(row) => router.push(`/sales/vehicles/${(row as any).id}`)}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Vehicle">
|
||||
<div className='flex items-center gap-2'>
|
||||
<ImportDataButton
|
||||
onImport={(file) => api.vehicles.importData(file)}
|
||||
onSuccess={invalidateQuery}
|
||||
entityLabel="Vehicles"
|
||||
onDownloadSample={() => api.vehicles.downloadImportSample()}
|
||||
sampleFileName='vehicles-import-sample'
|
||||
/>
|
||||
<ExportDataButton
|
||||
onExport={(filters) => api.vehicles.exportData(filters)}
|
||||
fileName='vehicles'
|
||||
/>
|
||||
<FormDialog title="Vehicle" classNames={{ dialogContent: 'lg:min-w-4xl' }}>
|
||||
{(resourceId) => (
|
||||
<VehicleForm
|
||||
resourceId={resourceId}
|
||||
@@ -28,11 +50,14 @@ export default function VehiclesPage() {
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
</div>
|
||||
),
|
||||
})}
|
||||
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
id: "name",
|
||||
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Vehicle" />,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original as any
|
||||
@@ -52,6 +77,20 @@ export default function VehiclesPage() {
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "customers",
|
||||
header: ({ column }: any) => <ColumnHeader column={column} title="Customer" />,
|
||||
cell: ({ row }: any) => {
|
||||
const customer = (row.original as any).customers?.[0]
|
||||
return (
|
||||
<RelationLink
|
||||
href={customer?.id ? `/sales/customers/${customer.id}` : null}
|
||||
icon={UserIcon}
|
||||
label={getFullName(customer)}
|
||||
/>
|
||||
)
|
||||
},
|
||||
} as any,
|
||||
{
|
||||
accessorKey: "year",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||
@@ -90,14 +129,7 @@ export default function VehiclesPage() {
|
||||
return val != null ? `${Number(val).toLocaleString()} mi` : "—"
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "created_at",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Created" />,
|
||||
cell: ({ row }) => {
|
||||
const val = (row.original as any).created_at
|
||||
return val ? new Date(val).toLocaleDateString() : "—"
|
||||
},
|
||||
},
|
||||
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
"use client"
|
||||
|
||||
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"
|
||||
import { SettingsForm } from "@/modules/settings/company/settings-form"
|
||||
|
||||
export default function CompanySettingsPage() {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6 p-6">
|
||||
<DashboardPage headerProps={{title:'Company Settings'}}>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Company Settings</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Manage your workshop profile, contact details, and preferences.
|
||||
</p>
|
||||
</div>
|
||||
<SettingsForm />
|
||||
</div>
|
||||
</DashboardPage>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function DepartmentsPage() {
|
||||
<ResourcePage<DepartmentsClient>
|
||||
pageTitle="Departments"
|
||||
routeKey={DEPARTMENT_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search departments..."
|
||||
getClient={(api) => api.departments}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { useParams } from "next/navigation"
|
||||
import { ChevronLeft, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { Textarea } from "@/shared/components/ui/textarea"
|
||||
import { Switch } from "@/shared/components/ui/switch"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import { prompt } from "@/shared/components/prompt-dialog"
|
||||
import { TemplateCheckpointEditDialog } from "@/modules/inspections/template-checkpoint-edit-dialog"
|
||||
import type {
|
||||
InspectionTemplate,
|
||||
InspectionTemplateSection,
|
||||
InspectionTemplateCheckPoint,
|
||||
InspectionSeverity,
|
||||
} from "@garage/api"
|
||||
|
||||
const SEVERITY_BADGE: Record<InspectionSeverity, { label: string; cls: string }> = {
|
||||
good: { label: "Good", cls: "bg-emerald-100 text-emerald-800" },
|
||||
attention: { label: "Attention", cls: "bg-amber-100 text-amber-800" },
|
||||
critical: { label: "Critical", cls: "bg-rose-100 text-rose-800" },
|
||||
na: { label: "N/A", cls: "bg-slate-100 text-slate-700" },
|
||||
not_inspected: { label: "Not inspected", cls: "bg-gray-100 text-gray-700" },
|
||||
}
|
||||
|
||||
const RECORD_TYPE_LABEL: Record<string, string> = {
|
||||
capture_photo: "Photo",
|
||||
record_video: "Video",
|
||||
record_audio: "Audio",
|
||||
record_conditions: "0–100",
|
||||
wire_frame: "Wireframe",
|
||||
none: "No media",
|
||||
}
|
||||
|
||||
export default function InspectionTemplateEditorPage() {
|
||||
const params = useParams<{ id: string }>()
|
||||
const id = params.id
|
||||
const api = useAuthApi()
|
||||
const [template, setTemplate] = useState<InspectionTemplate | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const [editing, setEditing] = useState<{
|
||||
section: InspectionTemplateSection
|
||||
checkpoint: InspectionTemplateCheckPoint | null
|
||||
} | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.show(id)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load template")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
const updateMeta = async (partial: Partial<InspectionTemplate>) => {
|
||||
if (!template) return
|
||||
try {
|
||||
const res = await api.inspectionTemplates.update(template.id, partial)
|
||||
setTemplate(res.data)
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to save")
|
||||
}
|
||||
}
|
||||
|
||||
const addSection = async () => {
|
||||
if (!template) return
|
||||
const name = await prompt({
|
||||
title: "New section",
|
||||
label: "Section name",
|
||||
placeholder: "e.g. Brakes",
|
||||
confirmLabel: "Add section",
|
||||
})
|
||||
if (!name) return
|
||||
const nextOrder = (template.sections?.length ?? 0) + 1
|
||||
try {
|
||||
await api.inspectionTemplates.createSection(template.id, { name, sort_order: nextOrder })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to add section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteSection = async (section: InspectionTemplateSection) => {
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete section "${section.name}"?`,
|
||||
description: "This will remove the section and all its checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroySection(template.id, section.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete section")
|
||||
}
|
||||
}
|
||||
|
||||
const renameSection = async (section: InspectionTemplateSection, name: string) => {
|
||||
if (!template || name === section.name) return
|
||||
try {
|
||||
await api.inspectionTemplates.updateSection(template.id, section.id, { name })
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to rename section")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCheckpoint = async (section: InspectionTemplateSection, cp: InspectionTemplateCheckPoint, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!template) return
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${cp.name}"?`,
|
||||
description: "This checkpoint will be removed from the template.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroyCheckpoint(template.id, section.id, cp.id)
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete checkpoint")
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="p-6 text-muted-foreground">Loading…</div>
|
||||
if (!template) return <div className="p-6 text-muted-foreground">Template not found</div>
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-4xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="/settings/inspection-templates">
|
||||
<Button variant="ghost" size="sm"><ChevronLeft className="size-4 mr-1" /> Back</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="rounded border p-4 space-y-3">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Name</label>
|
||||
<Input
|
||||
defaultValue={template.name}
|
||||
onBlur={(e) => e.currentTarget.value !== template.name && updateMeta({ name: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-5">
|
||||
<Switch
|
||||
checked={template.is_active}
|
||||
onCheckedChange={(checked) => updateMeta({ is_active: checked })}
|
||||
/>
|
||||
<span className="text-sm">{template.is_active ? "Active" : "Inactive"}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground">Description</label>
|
||||
<Textarea
|
||||
defaultValue={template.description ?? ""}
|
||||
rows={2}
|
||||
onBlur={(e) => e.currentTarget.value !== (template.description ?? "") && updateMeta({ description: e.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">Sections & Checkpoints</h2>
|
||||
<Button onClick={addSection} size="sm"><Plus className="size-4 mr-1" /> Add section</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{(template.sections ?? []).length === 0 && (
|
||||
<div className="rounded border-dashed border p-6 text-center text-sm text-muted-foreground">
|
||||
No sections yet. Add one to start building the checklist.
|
||||
</div>
|
||||
)}
|
||||
{(template.sections ?? []).map((section) => (
|
||||
<div key={section.id} className="rounded border">
|
||||
<div className="flex items-center gap-2 px-3 py-2 bg-muted/40">
|
||||
<Input
|
||||
defaultValue={section.name}
|
||||
onBlur={(e) => renameSection(section, e.currentTarget.value)}
|
||||
className="max-w-md h-8"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{(section.check_points ?? []).length} checkpoint{(section.check_points ?? []).length === 1 ? "" : "s"}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button size="sm" variant="ghost" onClick={() => setEditing({ section, checkpoint: null })}>
|
||||
<Plus className="size-4 mr-1" /> Checkpoint
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => deleteSection(section)}>
|
||||
<Trash2 className="size-4 text-red-600" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{(section.check_points ?? []).length === 0 && (
|
||||
<div className="p-3 text-sm text-muted-foreground">No checkpoints in this section.</div>
|
||||
)}
|
||||
{(section.check_points ?? []).map((cp) => {
|
||||
const sev = SEVERITY_BADGE[cp.severity_default] ?? SEVERITY_BADGE.not_inspected
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={cp.id}
|
||||
onClick={() => setEditing({ section, checkpoint: cp })}
|
||||
className="w-full text-left flex items-center gap-3 px-3 py-2 hover:bg-muted/30 transition"
|
||||
>
|
||||
<span className="text-xs text-muted-foreground w-6 text-right">
|
||||
{cp.sort_order}
|
||||
</span>
|
||||
<span className="flex-1 min-w-0 truncate text-sm font-medium">
|
||||
{cp.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground hidden sm:inline-block">
|
||||
{RECORD_TYPE_LABEL[cp.record_type] ?? cp.record_type}
|
||||
</span>
|
||||
<span className={`text-xs rounded-full px-2 py-0.5 ${sev.cls}`}>
|
||||
{sev.label}
|
||||
</span>
|
||||
<Pencil className="size-3.5 text-muted-foreground" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => deleteCheckpoint(section, cp, e)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
aria-label="Delete checkpoint"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<TemplateCheckpointEditDialog
|
||||
open={!!editing}
|
||||
onOpenChange={(o) => { if (!o) setEditing(null) }}
|
||||
templateId={template.id}
|
||||
sectionId={editing.section.id}
|
||||
checkpoint={editing.checkpoint}
|
||||
nextSortOrder={(editing.section.check_points?.length ?? 0) + 1}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { Copy, Pencil, Plus, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/shared/components/ui/button"
|
||||
import { Input } from "@/shared/components/ui/input"
|
||||
import { useAuthApi } from "@/shared/useApi"
|
||||
import { confirm } from "@/shared/components/confirm-dialog"
|
||||
import type { InspectionTemplate } from "@garage/api"
|
||||
|
||||
export default function InspectionTemplatesPage() {
|
||||
const api = useAuthApi()
|
||||
const [items, setItems] = useState<InspectionTemplate[]>([])
|
||||
const [search, setSearch] = useState("")
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState("")
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.inspectionTemplates.list(search ? { search } : undefined)
|
||||
setItems(res.data ?? [])
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to load templates")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [])
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!newName.trim()) return
|
||||
try {
|
||||
await api.inspectionTemplates.create({ name: newName.trim(), is_active: true })
|
||||
setNewName("")
|
||||
setCreating(false)
|
||||
toast.success("Template created")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to create template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDuplicate = async (id: number) => {
|
||||
try {
|
||||
await api.inspectionTemplates.duplicate(id)
|
||||
toast.success("Template duplicated")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to duplicate template")
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, name: string) => {
|
||||
const confirmed = await confirm({
|
||||
title: `Delete "${name}"?`,
|
||||
description: "This will remove the template and all its sections / checkpoints.",
|
||||
confirmLabel: "Delete",
|
||||
variant: "destructive",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await api.inspectionTemplates.destroy(id)
|
||||
toast.success("Template deleted")
|
||||
load()
|
||||
} catch (e: any) {
|
||||
toast.error(e?.message ?? "Failed to delete template")
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h1 className="text-2xl font-semibold">Inspection Templates</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && load()}
|
||||
className="w-56"
|
||||
/>
|
||||
<Button onClick={() => setCreating((c) => !c)}>
|
||||
<Plus className="size-4 mr-1" /> New template
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{creating && (
|
||||
<div className="flex items-center gap-2 rounded border p-3">
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder="Template name (e.g. Annual Safety)"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleCreate()}
|
||||
className="max-w-md"
|
||||
/>
|
||||
<Button onClick={handleCreate}>Create</Button>
|
||||
<Button variant="ghost" onClick={() => { setCreating(false); setNewName("") }}>Cancel</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted">
|
||||
<tr>
|
||||
<th className="text-left p-3">Name</th>
|
||||
<th className="text-left p-3">Sections</th>
|
||||
<th className="text-left p-3">Checkpoints</th>
|
||||
<th className="text-left p-3">Status</th>
|
||||
<th className="text-right p-3">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading…</td></tr>
|
||||
)}
|
||||
{!loading && items.length === 0 && (
|
||||
<tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No templates yet</td></tr>
|
||||
)}
|
||||
{!loading && items.map((t) => {
|
||||
const sectionCount = t.sections?.length ?? 0
|
||||
const cpCount = (t.sections ?? []).reduce((sum, s) => sum + (s.check_points?.length ?? 0), 0)
|
||||
return (
|
||||
<tr key={t.id} className="border-t hover:bg-muted/40">
|
||||
<td className="p-3 font-medium">{t.name}</td>
|
||||
<td className="p-3">{sectionCount}</td>
|
||||
<td className="p-3">{cpCount}</td>
|
||||
<td className="p-3">
|
||||
<span className={`inline-block rounded-full px-2 py-0.5 text-xs ${t.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}>
|
||||
{t.is_active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="p-3 text-right space-x-1">
|
||||
<Link href={`/settings/inspection-templates/${t.id}`}>
|
||||
<Button size="sm" variant="ghost"><Pencil className="size-4" /></Button>
|
||||
</Link>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDuplicate(t.id)}><Copy className="size-4" /></Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => handleDelete(t.id, t.name)}><Trash2 className="size-4 text-red-600" /></Button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export default function InsuranceTypesPage() {
|
||||
<ResourcePage<InsuranceTypesClient>
|
||||
pageTitle="Insurance Types"
|
||||
routeKey={INSURANCE_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search insurance types..."
|
||||
getClient={(api) => api.insuranceTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client"
|
||||
|
||||
import { MakeAndModelForm } from "@/modules/settings/make-and-models/make-and-model-form"
|
||||
import { ResourcePage } from "@/shared/data-view/resource-page"
|
||||
import { ColumnHeader } from "@/shared/data-view/table-view"
|
||||
import FormDialog from "@/shared/components/form-dialog"
|
||||
import { MAKE_AND_MODEL_ROUTES } from "@garage/api"
|
||||
import type { MakeAndModelsClient } from "@garage/api"
|
||||
|
||||
export default function MakeAndModelsPage() {
|
||||
return (
|
||||
<ResourcePage<MakeAndModelsClient>
|
||||
pageTitle="Make & Models"
|
||||
routeKey={MAKE_AND_MODEL_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search makes & models..."
|
||||
getClient={(api) => api.makeAndModels}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
<FormDialog title="Make & Model">
|
||||
{(resourceId) => (
|
||||
<MakeAndModelForm
|
||||
resourceId={resourceId}
|
||||
initialData={selectedItem}
|
||||
onSuccess={invalidateQuery}
|
||||
/>
|
||||
)}
|
||||
</FormDialog>
|
||||
),
|
||||
})}
|
||||
columns={({ actionsColumn }) => [
|
||||
{
|
||||
accessorKey: "make",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Make" />,
|
||||
cell: ({ row }) => (row.original as any).make ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "model",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Model" />,
|
||||
cell: ({ row }) => (row.original as any).model ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "year",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Year" />,
|
||||
cell: ({ row }) => (row.original as any).year ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "sub_model",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Sub Model" />,
|
||||
cell: ({ row }) => (row.original as any).sub_model ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "engine_size",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Engine Size" />,
|
||||
cell: ({ row }) => (row.original as any).engine_size ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "drivetrain",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Drivetrain" />,
|
||||
cell: ({ row }) => (row.original as any).drivetrain ?? "—",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: ({ column }) => <ColumnHeader column={column} title="Status" />,
|
||||
cell: ({ row }) => {
|
||||
const active = (row.original as any).is_active
|
||||
return (
|
||||
<span className={active ? "text-green-600" : "text-muted-foreground"}>
|
||||
{active ? "Active" : "Inactive"}
|
||||
</span>
|
||||
)
|
||||
},
|
||||
},
|
||||
actionsColumn(),
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ export default function ShopTypesPage() {
|
||||
<ResourcePage<ShopTypesClient>
|
||||
pageTitle="Shop Types"
|
||||
routeKey={SHOP_TYPE_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search shop types..."
|
||||
getClient={(api) => api.shopTypes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
@@ -55,6 +55,8 @@ export default function TaxesPage() {
|
||||
<ResourcePage<TaxesClient>
|
||||
pageTitle="Tax & Rates"
|
||||
routeKey={TAX_ROUTES.INDEX}
|
||||
searchable
|
||||
searchPlaceholder="Search tax rates..."
|
||||
getClient={(api) => api.taxes}
|
||||
headerProps={({ selectedItem, invalidateQuery }) => ({
|
||||
actions: (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user