## 1. Preconditions

- [x] 1.1 Confirm with the customer the point recorded in Decision 1 of design.md: a `workday` request bypasses the overtime ratio entirely, so the same amount entered on an ordinary day and on a public holiday credits the same overtime workday. This is intended, but it is a departure from every other overtime record and should be acknowledged before implementation.
- [x] 1.2 Resolve the open question in design.md: is the `workday` mode offered on the manager-facing (`Employee/OvertimeRequestController`) endpoints as well as the admin ones? The employee-side `store()` attaches many accounts at once, each with its own shift and applied days, so the minimum-duration check of task 5.3 must then hold for every attached account rather than one.

## 2. Schema

- [x] 2.1 Add migration: `overtime_requests.input_mode` as a string defaulting to `time_range`, placed after `status`. Existing rows take the default; no backfill needed.
- [x] 2.2 Add migration: `overtime_requests.total_workday` as a decimal in minutes-of-workday, defaulting to `0`, matching the precision used by `timesheets.overtime_workday` (`DECIMAL(8,2)`).
- [x] 2.3 Confirm no migration is needed for `overtime_requests.to` — it is already nullable in `2023_10_03_103018_create_overtime_requests_table.php`.

## 3. Model

- [x] 3.1 Add `input_mode` and `total_workday` to `$fillable` on `app/Models/OvertimeRequest.php`.
- [x] 3.2 Add a `setTotalWorkdayAttribute` / `getTotalWorkdayAttribute` pair mirroring the existing `total_time` pair, so the field accepts and reports the `HH:MM` form used elsewhere.
- [x] 3.3 Add a scope that filters requests to one input mode, and expose the two mode names as a static array on the model alongside the existing conventions.
- [x] 3.4 Scope `getTotalOvertimeByAccount()` explicitly to `time_range` requests. A `workday` request leaves `total_time` at zero so it would not contribute anyway, but the scope must be explicit — see the double-counting risk in design.md.
- [x] 3.5 Add `getTotalOvertimeWorkdayByAccount()` alongside it, summing `total_workday` over approved `workday` requests for an account and date.

## 4. Timesheet calculation

- [x] 4.1 In `TimesheetCalculator::handleOvertime()`, read both aggregates into local variables `$time` (time-range duration) and `$workday` (entered overtime workday).
- [x] 4.2 Change the guard from `if ($time)` to cover either contribution, so a date carrying only `workday` requests is marked `is_recognized_overtime = 1`. Without this the entered amount never reaches payroll, which filters on that flag (`PayrollCalculator.php:265`).
- [x] 4.3 Compute `overtime_workday` as `$time * $overtimeRatio * $shiftWorkRatio + $workday`, reading from the local variables rather than from `$this->timesheet->overtime`. The existing read-back at `TimesheetCalculator.php:686` passes through an accessor that rounds to whole minutes — see the rounding constraint in Decision 3 of design.md.
- [x] 4.4 Compute `overtime` as `$time` plus the reversal of `$workday`, guarding against a zero product of the two ratios by contributing zero instead of dividing. `shifts.work_ratio` is nullable and defaults to `0` in the calculator; `overtime_ratio` is permitted to be `0` by `Setting.php:166`.
- [x] 4.5 Verify by inspection that no other branch of the calculator reads `$this->timesheet->overtime` back expecting it to equal the time-range duration alone.

## 5. Admin create endpoint

- [x] 5.1 In `Admin/OvertimeRequestController@store`, branch validation on the input mode: `time_range` keeps the existing `times.*.from` / `times.*.to` rules unchanged; `workday` validates an array of entries each carrying a date and an amount.
- [x] 5.2 Extract a single helper that resolves the overtime ratio and shift work ratio for one account on one date, mirroring the calculator's classification order — holiday via `Account::getHolidayByDate()`, then day off via `Helper::getWorkDayNameByDate()` against `Account::getAppliedDaysByShift()`, then the ordinary ratio. Both controllers use this one helper; see the cost noted in Decision 6 of design.md.
- [x] 5.3 For a `workday` entry, use that helper to reverse the entered amount into an overtime duration and refuse the entry when it falls below `min_minutes_recognized`. Refuse the entry outright when the two ratios make the reversal impossible. Discard the reversed value; it is never stored.
- [x] 5.4 Persist a `workday` entry with `from` set to the entered date, `to` left null, `total_time` at zero and `total_workday` carrying the amount.
- [x] 5.5 Skip the overlap check for `workday` entries entirely.
- [x] 5.6 Narrow the existing overlap check at `Admin/OvertimeRequestController.php:148` to `time_range` requests only — at the call site, not inside `OvertimeRequest::scopeFilterByRange()`. The scope is shared with the date-range filter on the request list; see Decision 4 of design.md.
- [x] 5.7 Narrow the overlap check in `storeByGroup` (`Admin/OvertimeRequestController.php:232`) the same way, for consistency, even though the method is currently unused.
- [x] 5.8 Update the OpenAPI annotation on `store` to describe the mode and the `workday` entry shape.

## 6. Manager create endpoint

Conditional on task 1.2.

- [x] 6.1 Apply the same validation branch to `Employee/OvertimeRequestController@store`.
- [x] 6.2 Narrow its overlap check at `Employee/OvertimeRequestController.php:142` to `time_range` requests, at the call site.
- [x] 6.3 Run the minimum-duration check of task 5.3 against every account the request attaches, not just one, since shifts and applied days differ per account.
- [x] 6.4 Update its OpenAPI annotation.

## 7. Summary endpoints

- [x] 7.1 Add `OvertimeRequest::sumOvertimeDuration($query, $accountIds = null)`: the duration of the `time_range` requests, plus `W / (r × w)` for the `workday` ones, both counted **per employee**. Derive nothing from timesheets — a request must count before one exists. A separate `total_workday_on_month` field was added first and then withdrawn; see Decision 8 of design.md.
- [x] 7.2 Count the `time_range` half with one aggregate by joining the pivot, which repeats a request once per employee attached to it. Join `accounts` and exclude deleted ones, matching `total_employee_on_month` and the `workday` half.
- [x] 7.3 Split `resolveRatiosByAccount()` into `prepareRatioContext($account, $holidays, $settings)` and `resolveRatiosFromContext($context, $date)`. The date classification keeps one implementation. The wrapper was kept at first so the creation-time validation stayed untouched; both controllers now resolve in bulk and call the pair directly, so it was removed, having no callers left.
- [x] 7.4 Add `Account::getHolidaysForAccounts()` and route `getHolidays()` through it: one query for the union of every account's scope, narrowed back per account in memory. Skip the pivot eager-load and the narrowing for a single account so the timesheet calculator pays exactly what it paid before. See Decision 8b.
- [x] 7.5 Move the per-date holiday match into `Holiday::matchByDate()` and have `Account::getHolidayByDate()` call it, so a caller holding a resolved set does not reimplement "first match by descending ratio".
- [x] 7.6 Batch the rest so the cost does not grow with the number of employees: read the pivot rows and the accounts in bulk, eager-load `shift_divisions.shift` so `prepareRatioContext()` issues no query, read the two ratio settings once per company, take the company off the eager-loaded positions rather than through `$account->companyId` which queries again, and group the pivot rows by request once instead of scanning the collection per request.
- [x] 7.7 Report the figure in `Admin/OvertimeRequestController@getSummary`, passing no employee restriction.
- [x] 7.8 Report it in `Employee/OvertimeRequestController@getSummary`.
- [x] 7.11 (Amended: `fix-overtime-manager-scope` restored the narrowing; the whole-roster reading below was tried first and reversed.) Reversal: drop the employee restriction from both of the manager's figures, so they cover every employee a counted request holds. Remove the `$accountIds` parameter from `sumOvertimeDuration()`, which then has no caller passing it, and drop `Account::staffOf()` from `total_employee_on_month`. The `whereNull('accounts.deleted_at')` beside the join stays: `Account` uses `SoftDeletes`, so the clause keeps this half agreeing with the workday half, which resolves its accounts through the model and so passes through the soft-delete scope. The join itself stays too, and its comment now says what it also does — orphan pivot rows survive a hard delete, because the delete path turns foreign key checks off. Settled by the employee-list change, whose roster shows a request's whole set of employees — figures counting a subset would contradict the faces beside them. See Decision 8 of design.md.
- [x] 7.9 Confirm `total_on_month` and `total_employee_on_month` are unaffected: they run off their own `(clone $query)` and gain no join.
- [x] 7.10 Add an `input_mode` filter to the request list, alongside the existing `status` and `company_id` filters in `filterByRequest()`, so a client can show one mode at a time. Document it on the three listing annotations.

## 8. Notifications

- [x] 8.1 Add a variant of the applied-at string in `app/Mail/OvertimeRequestApproved.php` for a request with no time range, stating the date and the amount of overtime workday.
- [x] 8.2 Do the same in `app/Mail/OvertimeRequestCancelled.php`.
- [x] 8.3 Do the same in `app/Listeners/SendOvertimeRequestApprovedNotification.php` and `SendOvertimeRequestCancelledNotification.php`.
- [x] 8.4 Add the new message strings to `resources/lang/*/overtime.php`, alongside the existing `selected_time_less_than_minimum_minute`.

## 9. Language and error codes

- [x] 9.1 Add a message and status code for a `workday` amount below the minimum, distinct from `overtime_selected_time_less_than_minimum_minute` so the client can tell which field failed.
- [x] 9.2 Add a message and status code for a request whose ratios make the minimum check impossible to evaluate.
- [x] 9.3 Tell a ratio that was configured as zero apart from one that was never configured at all. `CompanySetting::getByKey()` does not fall back to the system default once a company id is given, and `holidays.work_ratio` is nullable with no default, so "not set up" reached the client as "is zero" — a different problem needing a different action. `overtime_workday_ratio_not_configured` carries it, resolved through `OvertimeRequest::workdayRatioRefusal()`.
- [x] 9.4 Floor the minimum at one minute, so a company with no `min_minutes_recognized` row does not accept an amount of zero. A company holding the setting is unaffected: `min * r * w` already exceeds a minute.
- [x] 9.5 Accept `HH:MM` only. Seconds were matched by the pattern and then discarded by `Helper::hourCountToMinute()`, so `00:00:45` validated as nothing; neither client sends them.

## 9b. Distinct dates, and naming every refused entry

Prompted by the admin client, which replaces the API's message with its own Vietnamese and so loses the date interpolated into it — see Decision 9 of design.md and `hrm-admin/openspec/changes/add-overtime-workday-input/design.md` Decision 2.

- [x] 9b.1 Refuse a `workday` submission carrying the same date twice, with its own status code `overtime_duplicated_workday_date`. Two entries of one submission share a title and are summed, so a repeated date gains nothing and is a mistake. This does not constrain separate submissions.
- [x] 9b.2 Validate every `workday` entry before creating any of them, moving the checks out of the create loop in `Admin/OvertimeRequestController@store`. The submission is all or nothing, so stopping at the first bad entry costs one round trip per mistake. This also removes a transaction that was opened only to be rolled back.
- [x] 9b.3 Refuse with `entries`, each carrying its `date` and `status_code`, alongside the unchanged `status_code` and `message` of the first failure. Build the response at the call site in the shape `DeactivationGuard::check()` established; do not extend `ResponseTrait::error()`.
- [x] 9b.4 Do the same in `Employee/OvertimeRequestController@store`, collecting every account that failed rather than the first. That endpoint submits one date for many accounts, so an entry is named by `account_id` and `employee_full_name`, and `date` is reported once at the top level because it belongs to the submission.
- [x] 9b.5 Add `overtime.duplicated_workday_date` to the language files, and the `OvertimeRequest::$workdayRefusals` map from status code to language key that both controllers resolve the first failure's message through.
- [x] 9b.6 No `index` field. It was considered and dropped: its only purpose was to tell apart two entries sharing a date, which 9b.1 now forbids.
- [x] 9b.9 Carry the required amount on an entry refused for being below the minimum. The floor is on overtime duration; the amount it corresponds to is `min × r × w`, rounded up to the minute, and differs by date and by employee, so no client can work it out. Put the figure in the message too, replacing wording that named no number at all.
- [x] 9b.10 Compute the ratios once per employee at validation: the admin submission holds one employee across many dates, so prepare its context before the loop; the manager submission holds one date across many employees, so resolve per employee. `reverseWorkdayByAccount()` is removed, having no callers left.
- [ ] 9b.7 Confirm the refusal shape with the admin client before it ships — its task 1.1 holds the same confirmation from the other side. Note for them that `index` is not coming and `entries` is keyed by date.
- [x] 9b.8 Dropped: do not document the refusal shape in OpenAPI. Of the 402 `@OA\Response` blocks under `app/Http/Controllers`, none describes a 400. Documenting one endpoint's error response would be the only such annotation in the repository and would imply the others cannot fail. The contract is specified in the spec instead. Documenting error responses belongs in its own repository-wide change.

## 10. Tests

Hand-test scenarios live in `manual-test.md` beside this file, grouped by screen and written for whoever exercises the feature on dev. The automated coverage below is separate from it.

The suite runs against a migrated and seeded MySQL database, the convention every test in
`tests/` already followed in its docblock. `phpunit.xml` had been forcing an in-memory SQLite
connection that no migration ever ran against, so every test touching a table errored with "no
such table"; the two lines doing that are gone and the connection comes from `.env.testing`.
The overtime tests live in `tests/Feature/Overtime/`, sharing fixtures through
`OvertimeTestCase`. Against the docker-compose dev stack:

```
docker exec -e DB_HOST=db hrm-api-app-1 ./vendor/bin/phpunit --testsuite=Feature
```

`ExampleTest::testBasicTest` fails there and did before this change: it is the Laravel scaffold
test asserting that `/` answers 200, which this API has never done.


- [x] 10.1 A `workday` request credits the entered amount unchanged on an ordinary day, on a day off, and on a public holiday. Done — `OvertimeTimesheetCreditTest`, on all three kinds of day.
- [x] 10.2 The credited amount is unchanged after the overtime ratio setting is altered and the timesheet recalculated.
- [x] 10.3 The credited amount is unchanged after the date is declared a public holiday and the timesheet recalculated.
- [x] 10.4 **No double counting:** a date carrying one `workday` request is credited that amount exactly once. Assert the aggregate that feeds the time-range branch returns zero for that date. This is the highest-severity failure mode in the change — see Risks in design.md.
- [x] 10.5 Both modes on one day sum correctly, in overtime workday and in the reported overtime duration. Done — both the timesheet figures and the month's duration are asserted, so a mode counted twice shows up in whichever reading it reaches.
- [x] 10.6 A date with only `workday` requests is marked `is_recognized_overtime` and its amount appears in the payroll overtime workday total. Done — asserted against the aggregate PayrollCalculator reads, with a date carrying no overtime as the control.
- [x] 10.7 The reported overtime duration for a `workday` request follows a ratio change, and is zero rather than an error when the shift work ratio is zero.
- [x] 10.8 Overlap: a `time_range` request is refused against another `time_range` request; is accepted on a date holding a `workday` request, including when it starts at midnight; and a second `workday` request on one date is accepted.
- [x] 10.9 **List filtering:** filtering the overtime request list by a date range returns `workday` requests. This guards the scope placement of task 5.6.
- [x] 10.10 Minimum duration: a `workday` amount reversing to below the floor is refused; one above is accepted; the same amount is judged differently on an ordinary day and on a holiday.
- [x] 10.11 Annual leave, for a company on `plus_annual_leave_ratio`: a `workday` request credits the entered amount when the shift work ratio is 1, and the entered amount divided by that ratio when it is not. Assert both — see Decision 7 of design.md. Done — both ratios asserted: a shift work ratio of 1 credits the amount entered, a ratio of 0.5 credits twice it.
- [x] 10.12 Regression: an existing `time_range` request produces identical overtime, overtime workday, workday, annual leave and summary figures to before the change. Done — `TimeRangeRegressionTest` writes the pre-change rules out and asserts against them, rather than against a stored baseline.
- [x] 10.12b Summary, counting: a `time_range` request of four hours covering three employees reports twelve hours, one request, three employees. A month with no `workday` requests reports each request's duration once per employee.
- [x] 10.12c Summary, derivation: one figure covers both modes; a `workday` request counts before its date has a timesheet; the derived part follows a ratio change; one request over three employees with differing ratios contributes three separately derived amounts; a request whose ratios forbid the reversal contributes nothing but is still counted among the month's requests and employees.
- [x] 10.12d Summary, scope: a request covering five employees of whom two report to a given manager contributes only those two to that manager's duration and employee count, while the administrator's counts all five; a deleted employee is counted in neither, nor in `total_employee_on_month`. Done — `OvertimeSummaryScopeTest`, on the endpoints rather than the aggregate.
- [x] 10.12e Summary, cost: one `workday` request covering several hundred employees is produced in a query count that does not grow with that number. Assert the count, not the wall clock.
- [x] 10.12f **Holiday resolution is unchanged for one account** — the payroll path. For an account with holidays scoped by position, by department, by company, by `applicable = 'all'`, and for an account holding no position, `getHolidays()` returns the same set in the same order as before, in the same number of queries. Two holidays falling on one date still resolve to the one with the higher `work_ratio`.
- [x] 10.12g Holiday resolution in bulk matches it: across accounts in different departments, a holiday scoped to one department does not leak to an account in another; a `custom` holiday with nothing attached applies to nobody; an account with no position receives only `applicable = 'all'` holidays.
- [x] 10.12h Timesheet regression over a month containing a public holiday: `date_type`, `overtime_ratio`, `overtime_workday`, `workday` and the annual-leave adjustment are identical before and after this change. Done — a week of ordinary days, a weekend and a public holiday, each asserted for `date_type`, `overtime_ratio`, `overtime` and `overtime_workday`.
- [x] 10.13 Distinct dates: a submission repeating a date is refused and creates none of its entries; a submission of three distinct dates creates three requests; the same date submitted twice in separate submissions is accepted and the two amounts sum.
- [x] 10.14 Refusal payload, admin: a four-entry submission with two different failures lists both entries by date, each with its own reason, and creates none of the four.
- [x] 10.15 Refusal payload, manager: a submission of one date for several employees refused for two of them lists both by `account_id` and `employee_full_name`, reports `date` once at the top level, and creates no request for any of them.
- [x] 10.16 Refusal payload, compatibility: `status_code` and `message` carry the first failure on both endpoints, so a client reading only those two fields behaves as before.

## 11. Verification

Ghi chú phát hành nằm ở `release-notes.md` bên cạnh file này. Dòng ngắn cho `CHANGELOG.md` để
sẵn ở cuối file đó, dán vào khi cắt bản phát hành.

- [ ] 11.1 Run the migrations against a copy of real data and confirm every existing overtime request reads as `time_range` with its duration intact.
- [x] 11.2 Confirm the API behaves identically when no client sends the new mode, so the API can be deployed before the client ships.
- [x] 11.3 Record the known limitation in the release notes: an overtime request of either mode only reaches payroll once a timesheet row exists for that account and date, and the `workday` mode is more exposed to this because it exists for days with ragged or missing attendance data.
- [x] 11.4 Release note: the monthly overtime figure on the request screens now counts a request once per employee it covers, where it previously counted it once in total. Companies whose managers create requests covering several employees will see it rise. It is a correction of an under-report, not a regression — see Decision 8 of design.md.
