# Deduction Policy — Complete Implementation Prompt

You are working on the ERPFlow Laravel ERP codebase.

We already have an approved technical design for a **generic Deduction Policy system** inside the Payroll domain.

Your task is to implement the complete feature end-to-end, following the existing ERPFlow architecture and coding conventions.

---

# 1. PRIMARY OBJECTIVE

Implement a generic, extensible **Deduction Policy** system that supports:

- Attendance-based deductions
- Late-based deductions
- Fine/penalty policies
- Damage/loss deductions
- Other future deduction sources
- Fixed amount deductions
- Percentage-based deductions
- Day-based deductions
- Policy-driven automatic Employee Deduction creation
- Manual Employee Deduction creation
- Payroll installment/application through the existing deduction mechanism
- Active / Inactive / Archived policies
- Idempotent policy evaluation
- Calculation snapshots
- Proper auditability
- Future extensibility without creating a large rule-engine framework

The implementation must reuse the existing Payroll deduction infrastructure wherever possible.

---

# 2. IMPORTANT DEVELOPMENT RULE

Before changing any code:

1. Read the existing implementation.
2. Read:
   - Payroll deduction implementation
   - EmployeeDeductionService
   - EmployeeDeductionRepository
   - EmployeeDeduction model
   - EmployeeDeductionEntry
   - Payslip calculation/finalization
   - Salary structure components
   - Attendance policies
   - Attendance snapshots/metrics
   - Existing permission conventions
   - Existing CRUD/API patterns
   - Existing Job/Event conventions
   - Existing test structure
3. Compare the actual implementation with this specification.
4. Reuse existing conventions.
5. Do not introduce parallel implementations where existing functionality can be extended safely.

If the actual codebase conflicts with this specification, do NOT blindly force the design.

Prefer the existing ERPFlow architecture and report the conflict before making a destructive architectural change.

---

# 3. ARCHITECTURAL PRINCIPLE

The system must maintain three separate concepts:

## A. Deduction Policy

Defines:

> When and how a deduction should be generated.

Example:

> If an employee has at least 3 late occurrences in a calendar month, generate a deduction equivalent to 1 working day of basic salary.

Policy does NOT represent an actual employee debt.

---

## B. Employee Deduction / Obligation

Represents:

> The actual amount that an employee owes or needs to recover.

Existing `employee_deductions` should continue to be the main obligation table.

A policy evaluation may create an Employee Deduction.

Manual deductions may continue creating Employee Deductions directly.

---

## C. Employee Deduction Entry / Payroll Application

Represents:

> How much of an Employee Deduction was actually applied in a payroll run.

Continue using:

`employee_deduction_entries`

Do NOT replace the existing payroll application mechanism.

---

# 4. EXISTING DEDUCTION SYSTEM MUST REMAIN COMPATIBLE

The existing deduction types:

- loan
- advance
- fine
- other

must continue working.

Do not rename or remove them.

Do not convert the existing Employee Deduction system into a completely new architecture.

Existing functionality must continue to support:

- Manual deduction
- Installment deduction
- Remaining balance
- Completed status
- Cancelled status
- Payroll application
- Carry-forward
- Payslip generation
- Payslip regeneration
- Existing deduction entries
- Existing APIs

---

# 5. DATABASE DESIGN

## 5.1 Create `deduction_policies`

Create a new Payroll-owned table:

`deduction_policies`

Fields:

- id
- company_id
- source_type
- name
- code
- effective_date
- config
- status
- created_by
- updated_by
- created_at
- updated_at

Recommended types:

```text
source_type VARCHAR(40)
name VARCHAR(...)
code VARCHAR(...)
effective_date DATE
config JSON
status ENUM/string according to existing policy conventions
```

Do NOT blindly introduce ENUMs if the existing ERPFlow convention prefers string-backed enums.

Use the existing AttendancePolicy status conventions if applicable:

- Active
- Inactive
- Archived

Constraints:

```text
UNIQUE(company_id, source_type, code)
```

Add only useful indexes.

Do not create speculative indexes.

No soft delete unless the existing policy architecture explicitly requires it.

---

# 5.2 Extend `employee_deductions`

Add nullable fields:

- source
- deduction_policy_id
- origin_period_year
- origin_period_month
- origin_ref
- calculation_snapshot

Meaning:

### source

Examples:

```text
manual
policy
system
```

### deduction_policy_id

Nullable FK to:

`deduction_policies`

Manual deductions should have:

```text
source = manual
deduction_policy_id = null
```

Policy-generated deductions should have:

```text
source = policy
deduction_policy_id = <policy id>
```

### origin_period_year

Example:

```text
2026
```

### origin_period_month

Example:

```text
10
```

### origin_ref

Optional external/reference identifier.

Example:

```text
attendance:employee:123:2026-10
```

or another convention appropriate to the implementation.

### calculation_snapshot

JSON containing enough information to reproduce/explain how the deduction was calculated.

Example:

```json
{
    "policy_id": 10,
    "policy_code": "LATE-3-DAY",
    "period": "2026-10",
    "metric": {
        "late_count": 6
    },
    "inputs": {
        "basic_salary": 50000,
        "working_days": 26
    },
    "calculation": {
        "method": "day_based",
        "day_count": 2,
        "day_rate_base": "basic",
        "day_rate_divisor": "working_days"
    },
    "result": {
        "amount": 3846.15
    }
}
```

Do not store unnecessary duplicated data.

---

# 6. SOURCE TYPE VS DEDUCTION TYPE

These are different concepts.

## source_type

Defines where/why the deduction originated.

Examples:

```text
attendance_late
attendance_absence
fine
damage
other
```

## deduction_type

Defines the existing Payroll obligation category.

Examples:

```text
loan
advance
fine
other
```

DO NOT merge these two concepts.

For example:

```text
source_type = attendance_late
deduction_type = fine
```

is valid.

---

# 7. POLICY CONFIGURATION

Use a typed JSON configuration similar to the existing Attendance Policy architecture.

Do not create a huge generic rule engine.

A common configuration structure may contain:

```json
{
    "trigger": {},
    "calculation": {},
    "installment": {},
    "priority": 1,
    "stacking": "skip_if_exists",
    "notes": null
}
```

The exact structure should follow existing ERPFlow conventions where appropriate.

---

# 8. SUPPORTED CALCULATION METHODS

Implement:

### fixed_amount

Example:

```json
{
    "calculation_method": "fixed_amount",
    "fixed_amount": 1000
}
```

---

### percentage

Example:

```json
{
    "calculation_method": "percentage",
    "percentage": 5,
    "percentage_base": "basic"
}
```

Supported V1 bases:

```text
basic
gross
```

Do NOT implement `net_preview` in V1.

Reason:

Net salary may itself depend on deductions, which can create circular calculations.

---

### day_based

Example:

```json
{
    "calculation_method": "day_based",
    "day_count": 1,
    "day_rate_base": "basic",
    "day_rate_divisor": "working_days"
}
```

Supported bases:

```text
basic
gross
```

Supported divisors:

```text
working_days
calendar_days
fixed_30
```

Formula:

```text
daily_rate = base_amount / divisor
deduction = daily_rate × day_count
```

---

# 9. LATE POLICY

Implement the first real automatic policy:

```text
attendance_late
```

Example:

> 3 late occurrences = 1 day deduction.

Policy trigger:

```json
{
    "trigger": {
        "metric": "late_count",
        "operator": "gte",
        "threshold": 3,
        "period": "calendar_month"
    }
}
```

Calculation:

```json
{
    "calculation_method": "day_based",
    "day_count": 1,
    "day_rate_base": "basic",
    "day_rate_divisor": "working_days"
}
```

---

# 10. IMPORTANT LATE COUNT SEMANTICS

Do NOT interpret:

```text
threshold = 3
```

as:

> Any value >= 3 produces exactly one day.

Instead, V1 should support repeated threshold application.

Example:

```text
3 late  = 1 day
6 late  = 2 days
9 late  = 3 days
```

Conceptually:

```text
day_count = floor(late_count / threshold)
```

For:

```text
late_count = 2
```

result:

```text
0 days
```

For:

```text
late_count = 4
```

result:

```text
1 day
```

For:

```text
late_count = 8
```

result:

```text
2 days
```

Do not apply a deduction for the remaining incomplete threshold.

This behavior must be covered by tests.

---

# 11. ATTENDANCE INTEGRATION

Attendance must remain responsible for calculating attendance metrics.

Attendance should NOT know:

- salary
- deduction amount
- deduction policy
- payroll formulas
- EmployeeDeduction creation

Attendance only exposes metrics such as:

```text
late_count
late_minutes
early_leave_count
absent_days
```

The Payroll Deduction Policy evaluator consumes these metrics.

Prefer attendance snapshots/frozen-period data if already available.

Do not duplicate attendance calculation logic inside Payroll.

---

# 12. POLICY EFFECTIVE DATE

A policy should be eligible only when:

```text
effective_date <= evaluation period end
```

For V1:

- Treat policy eligibility at period level.
- Do not implement mid-month proration.
- Do not calculate partial-period policy amounts.

Document this behavior in code/tests where useful.

---

# 13. ACTIVE / INACTIVE / ARCHIVED

Implement:

### Active

Policy participates in evaluation.

### Inactive

Policy exists but is ignored by automatic evaluation.

### Archived

Policy is retained historically but ignored by automatic evaluation.

Follow existing Attendance Policy status transition conventions.

Do not allow unsafe mutation of immutable fields if existing policy conventions prevent it.

---

# 14. POLICY CRUD

Implement:

```text
GET    /api/v1/payroll/deduction-policies
POST   /api/v1/payroll/deduction-policies
GET    /api/v1/payroll/deduction-policies/{id}
PUT    /api/v1/payroll/deduction-policies/{id}
PATCH  /api/v1/payroll/deduction-policies/{id}/status
DELETE /api/v1/payroll/deduction-policies/{id}
```

Follow existing ERPFlow API conventions.

Implement:

- Form Requests
- Resource
- Validation
- Authorization
- Pagination/filtering if standard in existing policy APIs

Do not invent a new API style.

---

# 15. POLICY VALIDATION

Create typed validation/config rules following the Attendance Policy pattern.

At minimum support:

```text
attendance_late
fine
```

Validate:

- required fields
- source type
- trigger
- operators
- threshold
- calculation method
- calculation base
- divisor
- deduction type
- installment configuration
- unknown configuration keys

Reject invalid configuration early.

Do not silently accept malformed policy JSON.

---

# 16. FINE POLICY

Support a generic `fine` policy foundation.

V1 should support manual triggering/evaluation.

Example:

```text
Fine amount = 1000
```

or:

```text
Fine = 5% of basic
```

The policy should define calculation rules.

It should NOT require Attendance integration.

Do not automatically generate fines from arbitrary system events unless an existing event/source is already available.

---

# 17. DAMAGE / LOSS / OTHER

Prepare the architecture for:

```text
damage
other
```

Do not build complex automatic detection logic for these unless the existing codebase already has the required source events.

The framework must allow future evaluators to be added without changing the core deduction architecture.

---

# 18. EVALUATION SERVICE

Create a dedicated service for policy evaluation.

Suggested responsibility:

```text
DeductionPolicyEvaluationService
```

or follow existing ERPFlow naming conventions.

Responsibilities:

1. Find eligible active policies.
2. Validate effective date.
3. Resolve applicable employees.
4. Read source metrics.
5. Evaluate trigger.
6. Calculate deduction amount.
7. Create Employee Deduction obligation.
8. Store calculation snapshot.
9. Ensure idempotency.
10. Return evaluation summary.

The evaluator must NOT directly modify payslips.

---

# 19. EVALUATION FLOW

For attendance late:

```text
Attendance Period
        ↓
Attendance Snapshot / Metrics
        ↓
Deduction Policy Evaluation
        ↓
Trigger Check
        ↓
Calculation
        ↓
Employee Deduction
        ↓
Employee Deduction Entry
        ↓
Payslip
```

The evaluator stops after creating the Employee Deduction.

The existing payroll deduction application mechanism remains responsible for applying the obligation during payroll.

---

# 20. PERIOD EVALUATION API

Implement an evaluation endpoint following existing ERPFlow conventions.

Example:

```text
POST /api/v1/payroll/deduction-policies/evaluate
```

Request:

```json
{
    "year": 2026,
    "month": 10
}
```

Optionally support policy-specific evaluation:

```text
POST /api/v1/payroll/deduction-policies/{id}/evaluate
```

Do not introduce separate duplicate evaluation engines.

---

# 21. FREEZE GATE

Automatic attendance-based deduction evaluation should happen only when the relevant attendance period is finalized/frozen, if the existing Attendance module already supports that concept.

Do not invent a second attendance freeze mechanism.

If there is no existing freeze mechanism:

- inspect current Attendance workflow
- use the closest existing finalized/frozen state
- do not introduce a large new Attendance lifecycle just for deductions

Payroll must not calculate deductions from incomplete attendance data.

---

# 22. IDEMPOTENCY

Repeated evaluation must NOT create duplicate Employee Deductions.

For example:

Running:

```text
Evaluate October 2026
```

twice must not create two deductions.

Preferred uniqueness identity:

```text
company
employee
policy
period
```

If database-level partial uniqueness is not practical with the current DB/version/conventions, enforce it through the service/repository transactionally.

Cancelled deductions may be recreated if that is consistent with the existing lifecycle.

Do not allow accidental duplicates during concurrent evaluation.

---

# 23. TRANSACTION SAFETY

Policy evaluation must use database transactions where multiple related records are created/updated.

At minimum:

```text
Evaluate
→ create EmployeeDeduction
→ snapshot calculation
```

must be atomic.

If one operation fails, the transaction must not leave partial deduction data.

---

# 24. EMPLOYEE DEDUCTION CREATION

When generated by a policy:

```text
source = policy
deduction_policy_id = policy.id
```

Set:

```text
origin_period_year
origin_period_month
origin_ref
calculation_snapshot
```

Reuse the existing:

- total_amount
- remaining_balance
- installment_amount
- start_month
- start_year
- status

fields.

Do not create a second obligation table.

---

# 25. INSTALLMENT BEHAVIOR

Do not redesign payroll installment logic.

Reuse:

`EmployeeDeductionService::applyInstallment`

or the actual equivalent found in the repository.

Policy-generated deductions should enter the same payroll application pipeline as manual deductions.

Therefore:

```text
Policy generated deduction
```

and:

```text
Manual employee deduction
```

ultimately use the same payroll deduction application path.

---

# 26. PAYSLIP SAFETY

Do not rewrite:

- PayslipCalculatorService
- PayslipFinaliser
- deductions_breakdown
- net_pay
- payroll run deduction application

unless a minimal compatibility change is genuinely required.

Existing payslip behavior must remain unchanged.

Policy evaluation should happen BEFORE the deduction is consumed by payroll.

---

# 27. SALARY STRUCTURE

Do NOT replace:

```text
salary_structure_components
```

with deduction policies.

Salary structure deductions continue to represent recurring salary components.

Deduction Policy represents event/rule-driven deductions.

Both can coexist.

Example:

```text
Salary Structure Deduction
+
Attendance Late Policy Deduction
+
Loan Deduction
+
Fine
```

must all be possible without one system overwriting another.

---

# 28. TAX

Do not modify the income-tax deduction system.

Tax remains separate.

---

# 29. POLICY PRIORITY

Support an optional:

```text
priority
```

field in policy configuration if compatible with the design.

However, do not implement a complex rule conflict-resolution engine in V1.

If multiple policies generate independent deductions, they may coexist.

---

# 30. STACKING

Support:

```text
skip_if_exists
```

as the initial stacking behavior.

Example:

If the same policy has already generated a deduction for an employee and period:

```text
skip
```

Do not generate another obligation.

Future stacking modes may be added later.

---

# 31. MANUAL DEDUCTIONS

Existing manual deduction APIs must continue to work.

When manually created:

```text
source = manual
deduction_policy_id = null
```

Do not force users to create a policy for manual deductions.

---

# 32. EMPLOYEE DEDUCTION RESOURCE

Extend the existing Employee Deduction API/resource to expose policy metadata where useful.

Example:

```json
{
    "source": "policy",
    "policy": {
        "id": 10,
        "name": "Late Attendance Deduction",
        "code": "LATE-3-DAY"
    },
    "origin_period": "2026-10",
    "calculation_snapshot": {}
}
```

Do not break the existing response contract.

---

# 33. PERMISSIONS

Add permissions following existing Payroll permission conventions:

```text
payroll.deduction-policy-view
payroll.deduction-policy-manage
payroll.deduction-policy-evaluate
```

Use the actual permission naming convention already present in ERPFlow if different.

Evaluation should require the evaluate permission.

Existing employee deduction permissions remain unchanged.

---

# 34. FRONTEND

Implement the frontend only after the backend/domain implementation is stable.

Add:

```text
Payroll
  → Deduction Policies
```

Suggested UI:

### List

Columns:

- Name
- Code
- Source
- Effective Date
- Status
- Calculation
- Updated At
- Actions

### Create/Edit

Common fields:

- Source Type
- Name
- Code
- Effective Date
- Status

Source-specific configuration:

For Attendance Late:

- Metric
- Operator
- Threshold
- Period
- Calculation Method
- Base
- Divisor
- Deduction Type
- Stacking

For Fine:

- Calculation Method
- Amount / Percentage
- Base
- Deduction Type

Use existing ERPFlow UI components and patterns.

Do not introduce a new UI framework.

---

# 35. EVALUATION UI

Provide an operational UI if the existing Payroll UI conventions support it.

Allow authorized users to:

```text
Select period
→ Evaluate
→ View summary
```

Example result:

```text
Policies evaluated: 4
Employees checked: 320
Deductions created: 48
Skipped: 260
Already exists: 12
Errors: 0
```

Do not automatically execute evaluation merely by opening the page.

---

# 36. JOB / AUTOMATION

After the manual evaluation flow is stable, integrate with the appropriate existing Payroll/Attendance job/event lifecycle.

Preferred flow:

```text
Attendance period finalized/frozen
        ↓
Deduction policy evaluation
        ↓
Employee deductions created
        ↓
Payroll processing
```

If the existing architecture has an event such as:

```text
MonthlyAttendanceFrozen
```

use it.

Do not create duplicate scheduled mechanisms.

If no suitable event exists, create the smallest appropriate Job/Command using existing project conventions.

---

# 37. EVALUATION JOB

The automatic job must be:

- idempotent
- retry-safe
- transaction-safe
- observable
- non-destructive

Repeated job execution must not duplicate deductions.

---

# 38. TESTING

Implement comprehensive automated tests.

## Policy CRUD

Test:

- create
- read
- update
- status update
- archive
- delete behavior
- duplicate code
- company isolation
- permissions

---

## Config Validation

Test:

- valid attendance_late
- invalid metric
- invalid operator
- missing threshold
- invalid calculation method
- invalid base
- invalid divisor
- invalid deduction type
- unknown config keys

---

## Late Evaluation

Test:

```text
2 late → 0 deduction
3 late → 1 day
4 late → 1 day
5 late → 1 day
6 late → 2 days
8 late → 2 days
9 late → 3 days
```

Also test:

- inactive policy
- archived policy
- future policy
- expired/effective policy
- missing attendance snapshot
- employee without salary
- zero working days
- zero divisor
- multiple employees
- multiple policies

---

# 39. IDEMPOTENCY TESTS

Run the same evaluation twice.

Expected:

```text
First run:
1 deduction

Second run:
0 new deductions
```

Test concurrent/retry-safe behavior where practical.

---

# 40. PAYROLL REGRESSION TESTS

Existing payroll tests must continue to pass.

Specifically verify:

- loan deduction
- advance deduction
- fine deduction
- other deduction
- installment deduction
- completed deduction
- cancelled deduction
- carry-forward
- payslip regeneration
- deduction entry uniqueness

Policy-generated deductions must behave exactly like normal Employee Deductions once created.

---

# 41. ATTENDANCE REGRESSION

Existing Attendance tests must continue to pass.

Do not change:

- late calculation
- early leave calculation
- leave balance
- absence calculation
- attendance policy behavior

Attendance remains unaware of Payroll deduction formulas.

---

# 42. SECURITY / COMPANY ISOLATION

Every query must respect company scope.

A policy from Company A must never evaluate or create deductions for Company B.

Verify:

- policy listing
- policy lookup
- evaluation
- employee lookup
- deduction creation

against company boundaries.

---

# 43. AUDITABILITY

For every policy-generated deduction, it should be possible to answer:

```text
Which policy created this?
For which period?
What metric triggered it?
What inputs were used?
What formula was used?
What amount was calculated?
```

This is why:

```text
deduction_policy_id
origin_period_year
origin_period_month
calculation_snapshot
```

are important.

Do not depend exclusively on current policy configuration for historical explanation.

---

# 44. ERROR HANDLING

If one employee cannot be evaluated:

Do not silently corrupt the entire period.

Follow existing batch-processing conventions.

Prefer collecting evaluation results/errors where appropriate.

Example:

```text
Employee 101 → created
Employee 102 → created
Employee 103 → skipped
Employee 104 → error
```

The exact strategy should follow existing ERPFlow Job/Batch conventions.

---

# 45. DO NOT IMPLEMENT

Unless the existing codebase absolutely requires it, DO NOT introduce:

- Full generic rule engine
- Rule graph database
- Policy groups
- Complex policy assignment engine
- Approval workflow for every generated deduction
- Soft-delete rewrite
- New payroll calculation engine
- New payslip deduction engine
- Tax refactor
- Salary structure refactor
- Attendance calculation refactor
- Event bus abstraction
- Generic repository/base repository
- Generic CRUD framework
- Unrelated refactoring

Keep the implementation focused.

---

# 46. ARCHITECTURE

Follow the existing ERPFlow layering.

Preferred:

```text
Controller
    ↓
Service Interface
    ↓
Service
    ↓
Repository Interface
    ↓
Repository
    ↓
Model
```

For policy evaluation:

```text
Controller / Job
    ↓
Evaluation Service
    ↓
Policy Repository
    ↓
Evaluator / Strategy
    ↓
EmployeeDeductionService
    ↓
EmployeeDeductionRepository
```

Use interfaces where the existing Payroll architecture already does so.

Do not create abstractions only for theoretical future requirements.

---

# 47. STRATEGY DESIGN

The evaluator should be extensible.

Possible conceptual structure:

```text
DeductionPolicyEvaluatorInterface
```

with source-specific implementations such as:

```text
AttendanceLateEvaluator
FineEvaluator
```

However, follow the actual project convention.

Do not create an over-engineered strategy framework if a simpler implementation fits the codebase.

The important requirement is:

> Adding a future source such as `damage` should not require rewriting the core evaluation service.

---

# 48. RECOMMENDED IMPLEMENTATION ORDER

Implement in these phases internally, but complete the entire feature.

## Phase A — Foundation

- migration
- models
- enums
- config rules
- repository
- service
- CRUD API
- permissions
- tests

## Phase B — Attendance Late Evaluation

- evaluator
- metric integration
- late threshold calculation
- day-based calculation
- effective-date handling
- idempotency
- snapshot
- EmployeeDeduction creation
- evaluation API
- tests

## Phase C — Operations

- evaluation UI
- evaluation summary
- Job/Event integration
- freeze/finalization integration
- retry safety
- logging/observability
- permissions

## Phase D — Additional Sources

Implement the generic foundation for:

- fine
- damage
- other

Add automatic source integrations only where a real source/event exists.

Do not invent nonexistent source data.

---

# 49. DATABASE MIGRATION SAFETY

Before migration:

- inspect current MySQL version
- inspect migration conventions
- inspect foreign key conventions
- inspect JSON column conventions
- inspect enum/string conventions

Migration must be backward compatible.

Existing rows in:

```text
employee_deductions
```

must remain valid.

Existing API consumers must not break.

---

# 50. CODE QUALITY

Follow existing project standards:

- strict typing where existing project uses it
- Form Requests
- Resources
- DTOs only where existing architecture uses them
- transactions
- policies/authorization
- meaningful naming
- no business logic in controllers
- no business logic in models unless existing pattern requires it
- no duplicated payroll formulas
- no magic numbers
- no unnecessary comments

Keep controllers thin.

---

# 51. FINAL ACCEPTANCE SCENARIO

The following scenario MUST work end-to-end.

Policy:

```text
Name: Late Attendance Deduction
Code: LATE-3-DAY
Source: attendance_late
Trigger: late_count >= 3
Period: calendar_month
Calculation: day_based
Day Count: floor(late_count / 3)
Base: basic
Divisor: working_days
Deduction Type: fine
Stacking: skip_if_exists
Status: Active
```

Employee:

```text
Basic Salary = 50,000
Working Days = 25
Late Count = 6
```

Evaluation:

```text
floor(6 / 3) = 2 days
```

Daily rate:

```text
50,000 / 25 = 2,000
```

Deduction:

```text
2 × 2,000 = 4,000
```

System creates:

```text
EmployeeDeduction
total_amount = 4000
remaining_balance = 4000
source = policy
deduction_policy_id = <policy>
origin_period = 2026-10
calculation_snapshot = {...}
```

Then existing Payroll processing applies the deduction through the existing:

```text
EmployeeDeductionService
→ EmployeeDeductionEntry
→ Payslip
```

The policy evaluator must NOT directly modify the payslip.

---

# 52. FINAL VERIFICATION

Before declaring completion:

Run relevant:

```text
PHP tests
Feature tests
Unit tests
Payroll tests
Attendance tests
Frontend tests
Static analysis
Linting
```

Use the actual project commands.

Do not claim tests passed unless they actually passed.

If some existing unrelated tests fail:

- identify them
- determine whether they are pre-existing
- do not modify unrelated code just to make the suite green

---

# 53. FINAL REPORT

After implementation, provide a concise implementation report containing:

## 1. Summary

What was implemented.

## 2. Database Changes

List:

- new table
- modified table
- columns
- indexes
- constraints

## 3. Backend

List:

- models
- services
- repositories
- evaluators
- requests
- resources
- controllers
- jobs/events

## 4. API

List all new/changed endpoints.

## 5. Frontend

List pages/components/routes added.

## 6. Permissions

List permissions added.

## 7. Existing Behavior

Confirm how existing:

- loan
- advance
- fine
- other
- salary structure deduction
- tax
- carry-forward

continue to work.

## 8. Tests

Report:

```text
Passed
Failed
Skipped
```

with relevant test names/groups.

## 9. Risks / Limitations

Mention anything intentionally deferred.

## 10. Future Extension

Explain briefly how:

```text
damage
other
absence
```

can be added later without redesigning the core.

---

# MOST IMPORTANT CONSTRAINT

Do not treat this as permission to redesign ERPFlow.

The goal is:

> Build a generic Deduction Policy capability by extending and reusing the existing Payroll deduction infrastructure.

Keep:

```text
Policy
    ↓
Evaluation
    ↓
Employee Deduction
    ↓
Payroll Application
    ↓
Payslip
```

as the central architecture.

Do not collapse these responsibilities into one service.

Do not create a second deduction engine.

Do not modify unrelated modules unnecessarily.

Implement the complete feature carefully, test it thoroughly, and report exactly what changed.
