# Master Implementation Prompt
## Contract → Milestone → Invoice → Payment

You are working on the ERPFlow project.

Your task is to analyze, design, and implement the complete Contract → Milestone → Invoice → Payment workflow.

IMPORTANT:
Do NOT implement everything blindly in one step.

You must execute this task phase-by-phase.

For each phase:

1. First inspect the existing implementation.
2. Understand existing architecture and conventions.
3. Identify reusable components.
4. Implement ONLY that phase.
5. Run relevant tests.
6. Report what was changed.
7. STOP and wait for approval before moving to the next phase.

Do NOT automatically continue to the next phase.

---

# 1. CORE BUSINESS CONCEPT

The system has:

```text
Contract
   │
   ├── Milestone 1
   ├── Milestone 2
   ├── Milestone 3
   │
   └── Invoices
```

A Contract may have multiple Milestones.

However:

IMPORTANT:

A Milestone is NOT mandatory for every Invoice.

Invoice billing can happen in two different ways:

```text
1. Contract-wise Invoice
2. Milestone-wise Invoice
```

These are two different billing bases.

---

# 2. CONTRACT-WISE INVOICE

A Contract-wise Invoice is generated against the Contract itself.

Example:

```text
Contract Amount = 1,000,000

Invoice #1 = 300,000
Invoice #2 = 200,000
Invoice #3 = 500,000
```

These invoices do NOT have to be associated with any specific Milestone.

Therefore:

```text
Contract-wise Invoice
    → contract_id = required
    → milestone association = NOT required
```

Do NOT force every invoice to have a milestone.

---

# 3. MILESTONE-WISE INVOICE

A Milestone-wise Invoice is generated against one or more Milestones belonging to a Contract.

Example:

```text
Contract
│
├── Milestone A = 300,000
├── Milestone B = 400,000
└── Milestone C = 300,000
```

An invoice may contain:

```text
Invoice #101
    Milestone A = 150,000
    Milestone B = 200,000
```

Therefore:

- One Invoice may contain multiple Milestones.
- One Milestone may appear in multiple Invoices.
- Partial invoicing is allowed.
- A Milestone can be fully invoiced through one Invoice.
- A Milestone can be partially invoiced through multiple Invoices.

Example:

```text
Milestone A = 100,000

Invoice #1 = 40,000
Invoice #2 = 30,000
Invoice #3 = 30,000

Total invoiced = 100,000
Remaining = 0
```

The system must prevent:

```text
Total invoiced > Milestone amount
```

---

# 4. IMPORTANT DOMAIN RULE

Do NOT assume:

```text
Invoice → always → Milestone
```

Instead:

```text
Invoice
   │
   ├── Contract-wise
   │       └── Contract
   │
   └── Milestone-wise
           └── Contract
                 └── one or more Milestones
```

Contract is the primary business context.

Milestone is an optional billing source depending on invoice type.

---

# 5. INVOICE BILLING TYPE

Introduce/reuse an appropriate concept to identify invoice billing basis.

Conceptually:

```text
contract
milestone
```

Expected behavior:

### Contract-wise

```text
invoice_type = contract

contract_id = required

milestone allocation = optional/not required
```

### Milestone-wise

```text
invoice_type = milestone

contract_id = required

milestone allocation = required
```

Do not duplicate this concept if an equivalent existing concept already exists.

Use the existing ERPFlow architecture where possible.

---

# 6. PARTIAL INVOICE

Partial invoicing is supported.

For Milestone-wise invoicing:

```text
Milestone Amount
-
Previously Invoiced Amount
=
Remaining Invoiceable Amount
```

Example:

```text
Milestone = 500,000

Previously invoiced = 200,000

Remaining = 300,000
```

The user can invoice:

```text
100,000
```

Then:

```text
Remaining = 200,000
```

The system must reject:

```text
Invoice amount = 250,000
```

if only:

```text
Remaining = 200,000
```

is available.

---

# 7. MULTIPLE MILESTONES IN ONE INVOICE

The system must support:

```text
Invoice #500

Milestone A → 100,000
Milestone B → 150,000
Milestone C → 50,000

Invoice Total = 300,000
```

Each Milestone allocation must be tracked independently.

Do not simply store one aggregated amount and lose the Milestone-level allocation.

---

# 8. MANUAL INVOICE GENERATION

Manual invoice generation must support both:

### Option A

```text
Contract-wise Invoice
```

### Option B

```text
Milestone-wise Invoice
```

For Contract-wise:

```text
Select Contract
Enter/select invoiceable amount
Create Invoice
```

For Milestone-wise:

```text
Select Contract
Select one or more approved Milestones
Enter invoice amount per Milestone
Create Invoice
```

The system must validate:

- Contract exists
- User has permission
- Invoice type is valid
- Milestone belongs to the selected Contract
- Milestone is eligible for invoicing
- Requested amount does not exceed remaining invoiceable amount
- Invoice total is calculated correctly
- Duplicate/invalid allocation is prevented

Use database transactions.

---

# 9. AUTOMATIC INVOICE GENERATION

Automatic invoice generation must be supported where business configuration allows it.

For Milestone-based automatic invoicing:

```text
Milestone
   ↓
Approval
   ↓
Approved
   ↓
Automatic Invoice Generation
```

Rules:

1. Automatic generation happens only after successful approval.
2. It must not create duplicate invoices.
3. It must respect previous invoicing.
4. Fully invoiced Milestones must not generate another invoice.
5. Automatic and manual invoice generation must use the same core business logic.
6. Do not duplicate invoice-generation logic.
7. Use the existing event/listener/job architecture if available.
8. Failures must be safely handled and observable.

Do not assume that every approved Milestone must automatically generate an Invoice.

The behavior must respect the configured billing mode.

---

# 10. MILESTONE APPROVAL

Milestone approval and invoice generation are separate concepts.

A Milestone may have:

```text
Draft
Pending Approval
Approved
Rejected
```

or whatever equivalent statuses already exist.

Only an eligible/approved Milestone should be available for Milestone-wise invoicing if that is the existing business rule.

Do not create a second approval system.

Reuse the existing ERPFlow approval infrastructure.

---

# 11. PAYMENT

Payment is separate from invoicing.

The system must distinguish:

```text
Milestone Amount
Invoice Amount
Paid Amount
Outstanding Amount
```

These are different concepts.

Example:

```text
Milestone = 500,000

Invoice = 300,000

Payment = 100,000

Invoice Outstanding = 200,000
```

Payment must NOT reduce the Milestone's invoiceable amount.

Payment only affects invoice/payment balances.

---

# 12. PAYMENT FLOW

Expected relationship:

```text
Contract
   ↓
Invoice
   ↓
Payment
```

For Milestone invoices:

```text
Contract
   ↓
Milestone
   ↓
Invoice
   ↓
Payment
```

The payment system must follow the existing ERPFlow Finance/Payment architecture.

Do not introduce a parallel payment system.

Support existing partial-payment capabilities where applicable.

---

# 13. DATABASE DESIGN PRINCIPLES

Before changing the database:

1. Inspect all existing Contract tables.
2. Inspect all existing Milestone tables.
3. Inspect all existing Invoice tables.
4. Inspect Invoice Line/Item tables.
5. Inspect Payment tables.
6. Inspect approval tables.
7. Inspect Finance relationships.
8. Inspect existing invoice type/status fields.

Only create migrations when genuinely necessary.

Do NOT create duplicate tables for concepts that already exist.

Do NOT introduce unnecessary abstraction.

All monetary fields must use appropriate decimal precision.

Use:

- foreign keys
- indexes
- unique constraints where appropriate
- proper cascading/restrict behavior

Preserve existing data.

---

# 14. ARCHITECTURE

Follow the existing ERPFlow architecture.

Prefer:

```text
Controller
    ↓
Request / DTO
    ↓
Service Interface
    ↓
Service
    ↓
Repository Interface
    ↓
Repository
    ↓
Model
```

Rules:

- Controllers must remain thin.
- Business logic belongs in services/domain logic.
- Use interfaces where the project already follows that pattern.
- Do not introduce generic CRUD repositories.
- Do not introduce generic BaseRepository/BaseService.
- Do not introduce an unnecessary event bus.
- Use transactions for multi-step financial operations.
- Reuse existing domain services.
- Reuse existing approval infrastructure.
- Reuse existing Finance/Payment infrastructure.

---

# 15. API REQUIREMENTS

The final implementation should support APIs for:

### Contract

- Contract details
- Contract Milestones
- Contract invoices
- Contract invoice summary

### Milestone

- Milestone details
- Approval status
- Invoiceable amount
- Invoiced amount
- Remaining amount
- Related invoices

### Invoice

- Invoice list
- Invoice details
- Create Contract-wise Invoice
- Create Milestone-wise Invoice
- Invoice status
- Invoice total
- Payment status
- Outstanding amount

### Payment

- Payment history
- Payment status
- Outstanding amount

Follow existing API conventions.

Do not create duplicate endpoints if equivalent endpoints already exist.

---

# 16. FRONTEND REQUIREMENTS

The UI must clearly communicate the difference between:

```text
Contract-wise Invoice
```

and:

```text
Milestone-wise Invoice
```

For Milestone-wise Invoice creation:

```text
Contract
   ↓
Approved Milestones
   ↓
Select Milestones
   ↓
Enter invoice amount per Milestone
   ↓
Review
   ↓
Create Invoice
```

For Contract-wise Invoice:

```text
Contract
   ↓
Enter/select billing amount
   ↓
Review
   ↓
Create Invoice
```

Invoice details should show:

```text
Invoice Type
Contract
Milestones (if applicable)
Invoice Amount
Paid Amount
Outstanding Amount
Status
```

For a multi-Milestone invoice:

```text
Milestone A    100,000
Milestone B    200,000
Milestone C     50,000
-----------------------
Total          350,000
```

Do not show Milestone information for Contract-wise invoices when no Milestone is involved.

---

# 17. RBAC / PERMISSION

Inspect the existing permission system.

Implement appropriate permissions for:

- view Contract
- view Milestone
- approve Milestone
- create Invoice
- view Invoice
- manage Payment

Do not create arbitrary permission names if equivalent permissions already exist.

Follow existing ERPFlow RBAC conventions.

---

# 18. TEST REQUIREMENTS

Create/update tests for all important business scenarios.

### Scenario 1 — Contract-wise Invoice

```text
Contract
→ Create Contract-wise Invoice
→ Invoice created
→ No Milestone required
```

### Scenario 2 — Milestone-wise Invoice

```text
Contract
→ Approved Milestone
→ Create Milestone-wise Invoice
→ Invoice created
```

### Scenario 3 — Multiple Milestones

```text
Contract
→ Milestone A
→ Milestone B
→ One Invoice
→ Both Milestones allocated
```

### Scenario 4 — Partial Invoice

```text
Milestone = 100,000

Invoice #1 = 40,000
Remaining = 60,000
```

### Scenario 5 — Multiple Partial Invoices

```text
100,000

40,000
30,000
30,000

Remaining = 0
```

### Scenario 6 — Over-Invoicing

```text
Milestone = 100,000
Already invoiced = 70,000
Request = 40,000

Expected:
FAIL
```

### Scenario 7 — Unapproved Milestone

```text
Milestone = Pending Approval
Attempt Invoice

Expected:
FAIL
```

### Scenario 8 — Fully Invoiced Milestone

```text
Milestone = 100,000
Already invoiced = 100,000

Attempt another invoice

Expected:
FAIL
```

### Scenario 9 — Payment

```text
Invoice = 300,000
Payment = 100,000
Outstanding = 200,000
```

### Scenario 10 — Multiple Payments

```text
Invoice = 300,000

Payment 1 = 100,000
Payment 2 = 50,000
Payment 3 = 150,000

Outstanding = 0
```

### Scenario 11 — Contract-wise Invoice Has No Milestone

Verify that a Contract-wise Invoice can exist without any Milestone allocation.

### Scenario 12 — Milestone Belongs to Another Contract

Attempt to attach a Milestone from Contract B to an Invoice of Contract A.

Expected:

```text
FAIL
```

---

# 19. PHASE-WISE EXECUTION

You MUST execute the implementation in the following phases.

## PHASE 1 — READ-ONLY ANALYSIS

Inspect:

- Contract
- Milestone
- Invoice
- Invoice Lines
- Payment
- Approval
- Finance
- RBAC
- APIs
- Frontend

Do NOT modify anything.

Produce:

1. Current architecture
2. Existing components
3. Reusable components
4. Missing components
5. Database impact
6. API impact
7. Frontend impact
8. Permission impact
9. Risks
10. Implementation plan

Then STOP.

---

## PHASE 2 — DOMAIN & DATABASE

Implement only the required:

- migrations
- models
- relationships
- enums/value objects

Support:

```text
Contract-wise Invoice
Milestone-wise Invoice
```

Do not implement the complete invoice flow yet.

Run tests.

STOP.

---

## PHASE 3 — MILESTONE INVOICEABILITY

Implement:

- Milestone eligibility
- Approval integration
- Invoiced amount
- Remaining invoiceable amount
- Partial invoicing calculation
- Over-invoicing prevention

Run tests.

STOP.

---

## PHASE 4 — MANUAL INVOICE

Implement:

### Contract-wise

```text
Contract → Invoice
```

### Milestone-wise

```text
Contract
→ Multiple Milestones
→ Invoice
```

Support:

- partial invoice
- multiple milestones
- amount validation
- transactions
- permissions
- API

Run tests.

STOP.

---

## PHASE 5 — AUTOMATIC INVOICE

Implement automatic invoice generation where configured.

Use:

```text
Milestone Approval
→ Event/Listener/Job
→ Existing Invoice Generation Service
```

Do not duplicate business logic.

Prevent duplicates.

Run tests.

STOP.

---

## PHASE 6 — INVOICE MANAGEMENT UI/API

Implement:

- Invoice list
- Invoice details
- Contract relationship
- Milestone allocations
- Invoice type
- Amounts
- Status
- Payment summary

Clearly distinguish Contract-wise and Milestone-wise invoices.

Run tests.

STOP.

---

## PHASE 7 — PAYMENT

Integrate with existing Finance/Payment system.

Implement:

- Payment relationship
- Payment allocation
- Paid amount
- Outstanding amount
- Payment status

Do not alter Milestone invoiceable calculations based on payment.

Run tests.

STOP.

---

## PHASE 8 — END-TO-END VALIDATION

Run all relevant tests.

Validate:

```text
Contract
→ Milestone
→ Approval
→ Invoice
→ Payment
```

and:

```text
Contract
→ Contract-wise Invoice
→ Payment
```

and:

```text
Contract
→ Multiple Milestones
→ One Invoice
→ Multiple Payments
```

Also validate:

- partial invoice
- partial payment
- over-invoicing
- invalid Milestone
- duplicate automatic invoice
- authorization
- transaction rollback
- regression

Produce a final implementation report.

STOP.

---

# 20. CRITICAL SAFETY RULES

Before changing anything:

- Inspect existing code.
- Do not assume a table/model does not exist.
- Do not create duplicate functionality.
- Do not overwrite another developer's work.
- Do not perform broad refactoring.
- Do not change unrelated modules.
- Do not rename existing structures unless absolutely necessary.
- Do not modify existing behavior without proving the change is required.
- Keep changes small and focused.
- Run relevant tests after every phase.

If you discover an ambiguity or conflict in the existing implementation:

STOP and report it instead of guessing.

---

# 21. FINAL SUCCESS CRITERIA

The implementation is successful only when the system supports both:

```text
                    CONTRACT
                       │
             ┌─────────┴─────────┐
             │                   │
       CONTRACT-WISE        MILESTONE-WISE
          INVOICE               INVOICE
             │                   │
             │          ┌────────┼────────┐
             │          │        │        │
             │       MS-A      MS-B      MS-C
             │
             └──────────────┬──────────────┘
                            │
                         PAYMENT
```

And the following rules are guaranteed:

1. Contract-wise Invoice does NOT require a Milestone.
2. Milestone-wise Invoice requires valid Milestone allocation.
3. Multiple Milestones can belong to one Invoice.
4. One Milestone can belong to multiple invoices.
5. Partial invoicing is supported.
6. Over-invoicing is prevented.
7. Milestone approval rules are respected.
8. Automatic invoice generation does not create duplicates.
9. Payment is independent from Milestone invoiceability.
10. Invoice and Payment amounts remain mathematically consistent.
11. Existing ERPFlow architecture and conventions are preserved.
12. Existing functionality is not unnecessarily changed.

IMPORTANT:

Do not proceed from one phase to another automatically.

Complete the current phase, provide the implementation/report, and STOP.
Wait for explicit approval before starting the next phase.
