# Tailoring Service Workflow and Audit

Last reviewed: 2026-08-18

## Purpose

This document records the Tailoring Service workflow, important technical findings, live-data observations, and the proposed improvement plan.

## Implemented Add Order Material Workflow (2026-08-18)

- Every window group selects its own fabric product and netting product.
- Every door group selects one product, which may be fabric or netting.
- Every mattress, pillow, and bolster group selects one product, which may be fabric or netting.
- Mattress, pillow, and bolster rows have an optional `زیر پوشی` checkbox. When enabled, it records a separate product, count, height, width, and total meterage.
- Window, door, mattress, pillow, and bolster sections are optional, but an order must contain at least one completed group.
- Door, bedding, and `زیر پوشی` meterage fields represent total meterage; they are not multiplied by item count.
- Product choices display Name — Color — Code — Available Stock.
- Material cost is calculated from each selected product's selling price and required meterage.
- Tailoring/service charge is entered separately.
- Grand total equals material total plus service charge; due equals grand total minus paid amount.
- Each detail stores its product ID and price snapshot. Creating, editing, and cancelling an order deducts, adjusts, or restores stock per selected product.

## Current Business Scope

The current application code accepts only `Curtain` as a new tailoring order type.

The project still contains legacy logic and historical data for:

- Suit
- Waistcoat
- Coat
- Pant
- Afghan Clothes
- Other older custom tailoring categories

These legacy paths should not be deleted until their historical data has been preserved or migrated.

## Current Main Workflow

```text
Create curtain order
        |
        v
Tailor receives order
        |
        v
Received -> In Progress -> Finished
                              |
                              v
                       Completed Orders
                         /           \
                        /             \
          Accept and Deliver        Re-order
                  |                    |
                  v                    v
          Delivered Orders      Pending / Re-ordered
                                      |
                                      v
                               Tailor fixes order
                                      |
                                      v
                                  Finished
```

### Order status fields

Two related status fields are currently used:

1. `tailoring_products.status`
   - `pending`
   - `completed`
   - `delivered`

2. `curtains.tailor_status`
   - `received`
   - `in_progress`
   - `reordered`
   - `finished`

When the tailor marks a curtain as `finished`, the parent tailoring order becomes `completed`. When the shop accepts it, the parent order becomes `delivered`.

## Current Menu Items

### Orders List

Shows active curtain orders whose parent status is `pending`.

This includes tailor states such as:

- Received
- In Progress
- Re-ordered

Available operations depend on permissions and include viewing, editing pending orders, printing, and deleting.

### Completed Orders

Shows curtain orders whose tailor marked the work as finished.

The shop can:

- View or print the order
- Accept and deliver it
- Send it back to the tailor with a required correction note
- View re-order history

### Delivered Orders

Shows accepted curtain orders with parent status `delivered`.

At present, delivery also forces the customer order to become fully paid. This behavior is identified as unsafe and should be changed.

### Add Order

Creates a curtain order containing:

- Existing customer selection
- Optional new-customer modal
- Automatically generated order code
- Completion date
- Total customer price
- Initial paid amount
- Calculated due amount
- Fabric product
- Netting product
- Window measurement groups
- Door measurement groups
- Mattress groups
- Pillow groups
- Bolster groups
- Sewing type
- Curtain model
- Assigned tailor
- Order notes

### Tailor List

Shows active tailors with:

- Name
- Email
- Phone
- Work category
- Curtain fee schedule
- Total/paid/unpaid legacy order counts
- Address
- Edit and archive/delete actions

Clicking a tailor row opens that tailor's order list.

### Tailor Monthly Summary

Shows, for a selected tailor and month:

- Accepted orders
- Received orders
- In-progress orders
- Re-ordered orders
- Opening due or credit
- Total earned
- Total paid
- Closing due
- Advance balance
- Fee breakdown per accepted order
- Payment history

The shop can record regular or advance tailor payments. These payments withdraw money from the main cash account.

### Add Tailor

Creates a tailor with:

- Name
- Email
- Phone
- Address
- Curtain category
- Fabric meter fee
- Netting meter fee
- Mattress fee
- Pillow fee
- Bolster fee
- Optional restricted tailor portal account

## Current Inventory Behavior

When a curtain order is created:

1. Required fabric meters are calculated from window panels, doors, and bedding meterage.
2. Required netting meters are calculated from windows and doors.
3. Available product stock is checked.
4. Fabric and netting quantities are deducted from product and warehouse stock.

When a pending order is edited:

- Old material usage is restored.
- New material usage is deducted.
- Only the net difference affects stock.

When an order is cancelled/deactivated:

- Deducted curtain material is restored when `stock_synced` is true.

### Legacy inventory concern

New orders persist product IDs on every curtain detail. Older orders created before the per-section migration may still depend on their legacy fabric/netting names until they are edited and saved in the new format.

## Current Customer Payment Behavior

### Initial payment

When an order is created with an initial payment:

- The payment is added to the main cash account.
- The order's paid and due values are stored.

### Additional payment during pending-order editing

- Increasing the paid amount deposits only the difference.
- Decreasing it creates a refund/correction withdrawal.

### Delivery behavior requiring correction

When the shop clicks `Accept & Deliver`, the application currently:

1. Reads the full remaining due amount.
2. Deposits that amount into the main cash account.
3. Sets paid amount equal to total price.
4. Sets due amount to zero.
5. Marks the order delivered.

This happens without confirming that the customer actually paid. Delivery and payment should become separate operations.

## Current Tailor Payment Behavior

Tailor fees are calculated from:

- Fabric meters multiplied by the tailor's fabric-meter fee
- Netting meters multiplied by the tailor's netting-meter fee
- Mattress count multiplied by the mattress fee
- Pillow count multiplied by the pillow fee
- Bolster count multiplied by the bolster fee

An order contributes to tailor earnings only after the shop accepts it and `accepted_at` is set.

Regular and advance payments are stored in `tailor_payments` and posted as withdrawals from the main cash account.

### Historical accounting concern

Fee rates are read from the tailor's current profile. Rates are not copied into each order. Editing a tailor's rates can therefore recalculate historical earnings and change old monthly summaries.

## Re-order Workflow

1. Tailor marks an order finished.
2. Order appears in Completed Orders.
3. Shop chooses Re-order and enters a required note.
4. A `curtain_reorders` record is created.
5. Parent order returns to `pending`.
6. Curtain tailor status becomes `reordered`.
7. Tailor sees the correction note in the portal.
8. Tailor can only move a re-ordered job directly to `finished`.
9. The latest unresolved re-order record receives `resolved_at`.

## Tailor Portal

A tailor may optionally have a linked user account.

Tailor users are restricted to:

- My Orders
- Updating their own assigned curtain statuses
- My Monthly Summary
- Printing their own order/summary
- Their own profile and password

They cannot access the main administration pages.

## Live Data Snapshot

Snapshot taken during the audit on 2026-08-17/18:

- 19 total historical tailoring orders
- 5 active historical tailoring orders
- 0 curtain orders
- 11 active tailors
- 0 active tailors linked to portal users
- 0 tailor payment records
- 0 curtain re-order records
- 0 curtain detail records

The five active orders are legacy non-curtain types. Current Orders, Completed, and Delivered screens filter strictly for `Curtain`, so these active legacy orders are not visible on those pages.

## Confirmed Risks and Defects

### 1. Delivery incorrectly implies full payment

Delivery automatically records the entire remaining customer balance as cash received.

### 2. Historical tailor earnings are not stable

Changing current tailor rates recalculates previous accepted orders.

### 3. Tailor deletion can damage order history

Single deletion removes related work records, while bulk deletion only deactivates the tailor. The two operations are inconsistent. Tailors with history should only be archived.

### 4. Legacy active orders are hidden

Active non-curtain orders do not appear in any current order list.

### 5. Legacy material links can be name-dependent

New detail rows persist product IDs and price snapshots. Only older orders that have not yet been migrated through the edit form may still depend on product names.

### 6. Automatic pricing is incomplete

The implemented customer total is:

```text
Sum of each detail's meterage x selected product selling price
+ separately entered tailoring/service charge
```

The service charge is intentionally entered manually. It does not yet derive itself from the assigned tailor's fee schedule or automatically add a shop-margin rule.

### 7. Server-side validation is insufficient

Important curtain measurements, product IDs, tailor ID, numeric totals, and the relationship between paid and total amounts are not fully validated on the server.

### 8. Permissions are inconsistent

- The menu uses `Tailoring-add`.
- Add Order checks `products-add`.
- Some save/delete endpoints do not consistently enforce tailoring permissions.
- Some protection depends on hiding UI buttons.

### 9. Broken or obsolete routes exist

- A route references a missing `deleteOrderBySelection` method.
- A legacy GET route changes an order's paid state.
- That legacy payment action does not create a financial transaction.
- `productComplete()` exists but is not connected to an active route.

### 10. Add-customer behavior is inconsistent

The Tailoring Add Order modal still uses the older large customer form and City requirement rather than the simplified Name, Email, Phone, and Address workflow. Its custom-field code also contains invalid logic.

### 11. Considerable duplicated legacy code remains

Pending, completed, and delivered screens duplicate large amounts of table, modal, and JavaScript code. The controller and forms still include Suit, Coat, Pant, Waistcoat, and Afghan Clothes logic even though new orders reject those types.

### 12. No tailoring-specific automated tests exist

There are no automated tests covering stock, payments, delivery, re-orders, tailor earnings, or permissions.

## Positive Existing Behavior

- Curtain stock is managed in meters.
- Stock differences are synchronized during pending-order edits.
- Cancelling a synchronized curtain order restores material stock.
- Initial and additional customer payments use the main cash account.
- Tailor payments use the main cash account.
- Most financial and stock operations use database transactions.
- Re-order notes and resolution history are preserved.
- Tailor portal access is restricted to the linked tailor's work.

## Recommended Implementation Plan

### Phase 1: Protect and normalize data

1. Confirm that all future tailoring orders are curtain-only.
2. Add a Legacy Orders view or migrate the five active legacy orders.
3. Replace destructive tailor deletion with archive-only behavior.
4. Store permanent fabric and netting product IDs on each order.
5. Snapshot material prices and tailor fee rates on every order.

### Phase 2: Correct financial workflow

1. Separate `Deliver Order` from `Record Customer Payment`.
2. Allow delivery with remaining due when appropriate.
3. Record only money actually received.
4. Keep order paid/due totals synchronized with financial transactions.
5. Preserve immutable historical tailor earnings.

### Phase 3: Simplify navigation and UI

Replace the three order pages with one `Curtain Orders` page using tabs:

- Active
- Ready
- Delivered
- Re-ordered

Organize Add Order into four clear steps or sections:

1. Customer
2. Materials and measurements
3. Tailor and completion date
4. Price and payment

Use the same existing/new customer workflow already used on Add Sale.

### Phase 4: Remove obsolete code safely

After legacy data is protected:

1. Remove unused Suit/Coat/Pant/Wasitcoat/Afghan Clothes form sections.
2. Remove dead routes and methods.
3. Consolidate duplicated order-list queries and Blade views.
4. Normalize permission checks.

### Phase 5: Add automated protection

Add tests for:

- Creating an order and deducting stock
- Editing measurements and adjusting stock by the difference
- Cancelling and restoring stock
- Initial and additional customer payments
- Delivery with paid and unpaid balances
- Tailor status transitions
- Re-order and resolution history
- Tailor fee snapshots and monthly balances
- Regular and advance tailor payments
- Permissions and tailor portal isolation

## Decisions Required Before Major Refactoring

1. Will the business permanently support only curtain tailoring?
2. Should delivery allow a remaining customer due?
3. Should payment be entered manually at delivery, or through a separate Record Payment action?
4. How should the five active legacy orders be preserved: a Legacy Orders page or a data migration?
