## Context

### The unit chain

Overtime travels through four representations. Confusing any two of them is the main hazard in this change.

```
 overtime_requests.total_time        [minutes of overtime worked]
         │  handleOvertime() — TimesheetCalculator.php:683
         ▼
 timesheets.overtime                 [minutes of overtime worked]
         │  × overtime_ratio × shift.work_ratio
         ▼
 timesheets.overtime_workday         [minutes-of-workday]
         │  ÷ 60 ÷ workday_hours     (Helper::minuteToWorkday)
         ▼
 reported as "OT (Ngày)"             [workday]
```

`workday` is not a time unit. A value in minutes-of-workday becomes a number of workdays by dividing by the company's `workday_hours` setting. `timesheets.overtime_workday` and `payrolls.overtime_workday` are already stored this way; the new column follows them.

### Where the two ratios come from

```
r = timesheets.overtime_ratio    Timesheet::getOvertimeRatio() — Timesheet.php:586
      date_type 'holiday'  → the matching holiday's work_ratio
      date_type 'day_off'  → CompanySetting 'overtime_day_off_ratio'
      otherwise            → CompanySetting 'overtime_ratio'

w = shift.work_ratio             TimesheetCalculator.php:75  ($this->shift->work_ratio ?? 0)
```

Both are known at timesheet-calculation time and only approximable before it: `date_type` is decided inside the calculator from the holiday calendar and the account's applied days (`applyHoliday()` / `applyDayOff()`, TimesheetCalculator.php:317-343), and `w` comes from the shift recorded on the timesheet row, which for a multi-shift employee is not necessarily the primary shift division.

### What consumes the two figures

`timesheets.overtime_workday` is the one that reaches money: `PayrollCalculator.php:265` sums it across timesheets where `is_recognized_overtime = 1`, and `calculateOvertimeWage()` turns that into `overtime_wage`. `calcWorkdayByWorkTime()` also folds it into `workday` when `overtime_option` is `plus_working_time_ratio`.

`timesheets.overtime` has eight readers. Seven are display, filtering or reporting. The eighth is not: when `overtime_option` is `plus_annual_leave_ratio`, `Timesheet::approve()` credits annual leave with `round(overtime × overtime_ratio)` (Timesheet.php:418-431). That one path makes `overtime` load-bearing for a subset of companies.

### Related existing behaviour

`PUT /admin/timesheets/{id}/adjust-overtime` already lets an admin type an overtime figure onto a timesheet. It is not a precedent to build on: it overwrites rather than adds, computes `overtime_workday = overtime_ratio × overtime` without `work_ratio` (disagreeing with the calculator whenever `work_ratio ≠ 1`), is wiped by the next `revert()`, and is no longer exposed in the UI. It is out of scope and tracked separately.

## Goals / Non-Goals

**Goals:**
- Let a manager state a final overtime workday figure for a person on a date, and have payroll credit exactly that figure.
- Keep that figure stable: no later change to a ratio, a shift or a holiday may alter it.
- Leave the time-range path, and everything downstream of it, untouched.
- Keep the conversion between overtime duration and overtime workday in exactly one place.

**Non-Goals:**
- Changing how the time-range mode computes anything.
- Giving the `workday` mode an overlap or ceiling check. See Decision 4.
- Making an overtime request reach payroll without a timesheet row. See Risks.
- Removing or repairing `adjust-overtime`.

## Decisions

### 1. The entered figure is overtime workday, and the ratio is deliberately not applied

A `workday` request stores what the manager typed, in minutes-of-workday, and `handleOvertime()` adds it to `overtime_workday` with no multiplication:

```
overtime_workday = (T × r × w)  +  W
                   └─ time_range ─┘   └ workday: added as-is ┘
```

*Why:* the customer's request is to fix the amount paid. "Credit everyone five hours, never mind the ratio and never mind when they came or left." Any design that routes the figure through `× r` makes the paid amount depend on configuration the manager was explicitly told not to care about.

*What this gives up:* the ratio engine is the mechanism by which overtime policy is expressed and changed centrally. A `workday` request opts out of it. If the company later decides holiday overtime is worth 2.5× instead of 3×, every `time_range` record follows and every `workday` record does not. That is correct for this feature and wrong as a default, which is why the existing mode stays the default and the departure is stated in the proposal.

*A second cost, worth naming to the customer:* the manager now carries the ratio in their head. Entering "five hours of overtime workday" on a public holiday credits five hours, not fifteen. If the manager was thinking in hours worked, they have underpaid by a factor of three and nothing in the system will say so.

*Alternative considered — enter the duration worked instead, and let the ratio apply.* This was the stronger design on every technical axis: one new column, calculator untouched, summary untouched, minimum-duration guard untouched, annual leave untouched, policy kept inside the system. It was rejected because it does not do what was asked: it leaves the paid amount dependent on the ratio, which is the thing the customer wants to escape. Recorded here because if the requirement is ever revisited, this is the design to revisit it toward.

### 2. The request stores the workday figure and never a derived duration

`overtime_requests` holds `total_workday` for a `workday` request and leaves `total_time` at zero. No overtime duration derived from `W` is ever written to the request row.

*Why:* a derived duration is only correct for the `r` and `w` in force when it was computed. Persisting it freezes the display figure, so a date that later becomes a holiday keeps reporting the old number forever. Deriving on demand, inside the calculator, costs nothing because the calculator already holds both ratios.

*A consequence that removes a hazard:* because `total_time` stays zero, `OvertimeRequest::getTotalOvertimeByAccount()` — a bare `sum('total_time')` — cannot pick up a `workday` request, so `W` cannot be counted once as a duration and again as a workday figure. Had the derived duration been stored, forgetting to scope that one aggregate would have doubled every manually entered amount in payroll, silently. The aggregates are still scoped explicitly by mode (Decision 3) rather than relying on the zero.

### 3. Everything a timesheet reports is converted in `handleOvertime()`

```php
T = Σ overtime_requests.total_time      where input_mode = 'time_range'
W = Σ overtime_requests.total_workday   where input_mode = 'workday'

overtime_workday = T × r × w  +  W
overtime         = T  +  (r × w > 0 ? W / (r × w) : 0)
is_recognized_overtime = (T || W) ? 1 : 0
```

`overtime` is derived so that the seven display and reporting readers, and the annual-leave path, keep working without any of them learning about modes.

*Why here:* the repository's existing pattern is that the calculator computes once, writes to the timesheet columns, and every consumer reads the column. Every reader of a timesheet — reports, filters, the annual-leave path — therefore learns nothing about modes.

*The one conversion outside it* is the monthly summary of Decision 8, which cannot read timesheets because it must count a request before one exists. It does not duplicate the rule: both go through `OvertimeRequest::prepareRatioContext()` and `resolveRatiosFromContext()`, which is also what the validation of Decision 6 uses. There is one implementation of the classification and three callers, not three implementations.

*Why `is_recognized_overtime` matters:* `PayrollCalculator.php:265` sums `overtime_workday` only `where('is_recognized_overtime', 1)`. The current guard is `if ($time)`. A day with only `workday` requests has `T = 0`, so without widening that condition the entered amount never reaches payroll at all.

*Implementation constraint — do not read the value back.* Line 686 currently recovers the minute count by reading `$this->timesheet->overtime` back through its accessor, which passes through `Helper::minuteToHourCount()`. That formats `HH:MM:SS` with seconds hard-coded to zero and rounds to whole minutes, and `hourCountToMinute()` then reads only the hour and minute parts. The round trip discards sub-minute precision. Today this is harmless because `T` is always a whole number of minutes from `diffInMinutes()`. Once `overtime` also carries `W / (r × w)`, which is generally fractional, reading it back would corrupt both contributions. `overtime_workday` must be computed from the `$T` and `$W` variables directly.

*Division guard:* `w` defaults to `0` when a shift's `work_ratio` is null (`shifts.work_ratio` is nullable), and both `overtime_ratio` and a holiday's `work_ratio` are permitted to be zero — `Setting.php:166` validates `overtime_ratio` as `min:0`. On PHP 7.4 division by zero yields `INF` with a warning rather than throwing, and `INF` written to a `DECIMAL(8,2)` column either errors mid-batch or silently stores zero. The guard keeps `overtime_workday` exact — it is an addition, never a division — and only the derived display figure is skipped.

### 4. Overlap checking is scoped by mode, and the `workday` mode has none

Overlap checking keeps its current logic and applies only between `time_range` requests.

```
                      │ existing: time_range │ existing: workday
 ─────────────────────┼──────────────────────┼───────────────────
  new: time_range     │  checked (unchanged) │  not checked
  new: workday        │  not checked         │  not checked
```

*Why:* a `workday` request has no time range, so there is nothing to overlap. The customer also wants several on one day, and wants a day to be able to hold both kinds. Everything is summed and the customer validates it themselves.

*Implementation constraint — where the filter goes.* `OvertimeRequest::scopeFilterByRange()` serves two unrelated callers: the three overlap checks, and the date-range filter on the request list (`filterByRequest()`, OvertimeRequest.php:214). Putting the mode condition inside the scope would hide every `workday` request from the list whenever a user filters by date. The condition belongs at the three overlap call sites.

*Why list filtering still works unchanged:* the first branch of `filterByRange` tests `from` alone, and a `workday` request carries `from`. The branches that test `to` simply do not match when `to` is null.

### 5. `from` carries the date for both modes; `to` stays null for `workday`

`OvertimeRequest::filterByDate()` anchors a request to a timesheet with `whereDate('from', $date)`, and `getSummary()` scopes the month with `whereBetween('from', ...)`. Both keep working for the new mode at no cost if `from` holds the date. `to` is already nullable in the schema.

*Consequence, inherited deliberately:* a time-range request that crosses midnight is credited entirely to its `from` date. A `workday` request is credited to the date entered. Both follow the same rule, so no new behaviour is introduced. A manager who wants overtime split across two dates enters two requests.

### 6. The minimum-duration guard is enforced by inverting at validation time, and the result is discarded

`min_minutes_recognized` (default 45) is a floor on overtime *duration*. A `workday` request is validated by deriving `W / (r × w)` with the ratios in force at that moment and refusing the request if the result falls below the floor. The derived value is used for the comparison and thrown away.

*Why not a second setting in workday units:* a constant expressed in minutes-of-workday cannot enforce a floor expressed in minutes of duration, because the exchange rate between them varies by date. A floor of 67 minutes-of-workday is 45 minutes of duration at a ratio of 1.5, 33 at a ratio of 2 and 22 at a ratio of 3. It would let through exactly the short entries it exists to stop. Adding the setting is cheap — `Setting::scopeCompanySetting()` already picks up any key in the `timesheet` group and `UpdateCompanySettings` propagates it to every company — but cheapness is not the problem with it.

*Why validating against point-in-time ratios is acceptable here, when storing a point-in-time figure is not:* validation is inherently a judgement made at submission. Nothing is persisted, so nothing can go stale.

*Cost:* this is the one place outside the calculator that needs `r` and `w`, so it needs its own approximation of `date_type` from `Account::getHolidayByDate()` and `Account::getAppliedDaysByShift()`. It is a second copy of a rule that has been stable since 2023, confined to validation, and wrong only in the direction of accepting or rejecting a borderline entry. It should be extracted into one helper used by both controllers rather than written twice.

### 7. Annual leave conversion is left exactly as it is

For companies whose `overtime_option` is `plus_annual_leave_ratio`, `Timesheet::approve()` credits annual leave with `round(overtime × overtime_ratio)` (Timesheet.php:418-431). Not a line of it changes, and the `workday` mode is carried by the derived `overtime` from Decision 3.

Note that the credit uses the same `timesheets.overtime_ratio` column as the workday calculation — despite the local variable being named `$overtimeToAnnualLeaveRatio`, there is no separate ratio — but unlike the workday calculation it does **not** multiply by `shift.work_ratio`. So across both modes the relationship is uniform:

```
 overtime_workday = overtime × r × w
 annual leave     = overtime × r
                  = overtime_workday ÷ w
```

Substituting the derived duration gives the `workday` mode's contribution to annual leave:

```
 (W / (r × w)) × r  =  W / w         the r cancels
```

Two consequences. The credit is pinned in the same way the payroll figure is — no change to a ratio can move it. And when `shift.work_ratio` is `1`, which is the column default and the normal case, the credit is exactly the amount entered: enter five hours of overtime workday, receive five hours of annual leave.

*The case where they diverge:* on a shift with `work_ratio` of, say, `0.5`, five hours entered credits ten hours of annual leave. This was weighed against pinning the credit to exactly `W`, which would match the "pay exactly this" intent more literally.

*Decision: accept `W / w`.* The relationship `annual leave = overtime_workday ÷ w` already holds for the time-range mode. Breaking it for the new mode alone would put two rules in one table and would require modifying the annual-leave write path, which is the highest-consequence code this change comes near and which it otherwise does not touch at all. The divergence only appears on shifts deliberately configured with a non-unit work ratio — an inconsistency that predates this change and affects the existing mode identically. Correcting it belongs in its own change, applied to both modes together.

### 8. The monthly summary reports one duration, counted per employee, derived from the requests

`getSummary()` keeps a single `total_time_on_month`. A `time_range` request contributes its stored duration; a `workday` request contributes `W / (r × w)`, derived per attached employee from the ratios in force when the summary is read. `OvertimeRequest::sumOvertimeDuration()` holds both halves.

*Why one figure rather than two:* an earlier draft added `total_workday_on_month` beside the existing duration, on the grounds that the two modes measure different things and that folding them together reconstructs the very conversion the mode exists to refuse. That argument holds for a single record — see Decision 2, which is why a request still stores no derived duration — but not for a monthly roll-up, whose question is "how much overtime this month", one quantity. Two tiles make the reader add them, and they cannot be added. Worse, a reader is likely to take the second as the first expressed differently, and so trust a total that is missing a mode.

*Why hours of overtime rather than overtime workday:* the alternative was to report the whole figure in workday units, which would have let a `workday` request contribute exactly the amount typed and pushed the conversion onto the `time_range` side instead. It was rejected on two counts: the tile sits on the overtime **request** screen, where the natural question is how much overtime was approved, not how much it costs — that is the payroll screens' question; and the existing field is labelled as a duration, so the change would have altered the meaning of a live field for no offsetting gain. Both designs leave one mode showing a figure nobody typed; neither is cleaner on that count.

*Why per employee rather than per request:* the old `sum('total_time')` counted a request once however many employees it covered, so a request crediting five people four hours reported four. That under-reports, and it only went unnoticed because requests made through the admin form hold a single employee. It also leaves the `workday` mode nowhere to go: counted per request, it would have to pick one employee's ratios to represent all of them, and there is no non-arbitrary choice. Counting per employee fixes the under-report and removes the dilemma, and makes the three figures of the tile consistent — so many requests, so many employees, so many hours between them.

*A number people may be watching will move.* Any company whose managers create requests covering several employees will see this figure rise. It is a correction, not a regression, but it should be in the release notes.

*Why derived from the requests and not from timesheets:* a timesheet row exists only once attendance for its date has been processed (`TimekeepingRequest::createEmptyTimesheetByDate()`), while the summary spans the whole current month including dates that have not happened. Reading timesheets would make a request approved today for a date later this month count as zero until then — and would regress the `time_range` figure, which counts immediately today. A join against the stored `timesheets.overtime_ratio` and `timesheets.work_ratio` would have cost one query instead of the work below, but carries that same gap.

*The manager's figures count their own employees; the administrator's count every employee.* `filterByManager()` selects any request holding at least one of the manager's own employees, and such a request may cover others besides. Counting all of them was tried and reversed by `fix-overtime-manager-scope`: the manager's figures describe their own team, in agreement with the list's preview and total. The administrator has no manager to scope to.

*Deleted employees are excluded* on both branches, matching `total_employee_on_month`, which has always excluded them.

### 8b. Holidays resolve for many accounts in a fixed number of queries

`Account::getHolidays()` now delegates to `Account::getHolidaysForAccounts()`, which takes any number of accounts, runs one query for the union of their scopes, and narrows that union back to each account in memory. The rule for whether a holiday applies to an account therefore still has one implementation.

*Why this was necessary rather than nice to have:* the summary's worst case is the feature's own headline case. `getApplicableAccountsByRequest()` attaches every employee of a company when a manager names no department, position or employee — "everyone worked late, credit them all five hours". One request can then hold several hundred employees. At the per-account cost that preceded this, each needing a query that walks three pivot tables, a single dashboard tile would have issued five hundred-odd queries and taken seconds. That is not a tail case to watch; it is the scenario the mode was built for.

*What else was batched for the same reason:* the pivot rows and the accounts are read in bulk, `shift_divisions.shift` is eager-loaded so `prepareRatioContext()` touches no query, the two ratio settings are read once per company rather than once per employee, and the company is taken off the eager-loaded positions rather than through `$account->companyId`, which queries for them again. The pairs are grouped by request once instead of the collection being scanned per request. Together these make the summary a fixed cost of roughly eighteen queries whatever the number of employees.

*How the calculator is kept out of it:* a single account's union is by definition its own set, so `getHolidaysForAccounts()` skips both the pivot eager-load and the in-memory narrowing when given one account, and returns the query's result directly. The timesheet calculator's path therefore issues the same two queries it always did and receives the same collection in the same order. An earlier attempt memoised the result on the `Account` instance instead; that was withdrawn because it put a cache in the payroll path to speed up a reporting path, and because a long-lived process — the calculator is bound as a singleton and reuses an account instance across dates — could have served a stale set. A refactor that changes no behaviour is a safer thing to put there than a cache.

### 9. A refused `workday` entry is identified by extra fields on the refusal, built at the call site

The two `workday` refusals return their identifying fields directly in the response body, next to `status_code` and `message`, rather than through `ResponseTrait::error()`.

*Why the fields are needed at all:* the admin client owns the Vietnamese for a recognised `status_code` and renders it from its own catalogue, replacing the API's message wholesale (`hrm-admin`, `openspec/specs/api-error-localization/spec.md`). The date this API interpolates into the message is therefore discarded before the admin sees anything. Since a submission may carry several entries and the whole of it is rolled back on the first failure, a message that says only "an amount is below the minimum" leaves the admin to guess which row to correct.

*Every failure is listed, not the first.* The submission is all or nothing, so an admin shown one failure at a time needs one round trip per mistake — and the failures of a `workday` submission are correlated: if the employee's shift work ratio is zero, every entry fails at once. This follows the rule the repository already states for batch row operations, that a row collects all of its failures rather than only the first (`openspec/specs/employee-excel-import/spec.md:131`). Entries are validated before any is created, which also removes a transaction that was opened only to be rolled back.

*An entry is named by its date, not by a list position.* An earlier draft carried an `index`, on the grounds that a date may appear twice in one submission. Decision 10 forbids that, so the date identifies the entry on its own and the index was dropped. On the manager endpoint the shape is inverted — one date, many employees — so an entry is named by its employee, and the date is reported once at the top level because it belongs to the submission rather than to any entry.

*`status_code` and `message` are untouched.* They describe the first failure, exactly as a single-entry refusal did. Everything new is additive, so the contract the client was already given still holds and nothing had to be renegotiated.

*Why not extend `ResponseTrait::error()`:* a fourth optional parameter would work and stay backward compatible, since none of its 236 call sites passes a third argument. It was rejected because `$statusResponse` sits between, so every caller wanting the payload must pass `400` redundantly, and because the repository already answered this question a different way. `DeactivationGuard::check()` returns a hand-built `response(['status_code', 'message', 'employees'], 400)` and the admin client already consumes that extra field. Following the established precedent keeps one pattern rather than two, and leaves a trait used in 236 places untouched for the sake of four.

*Cost:* the response shape is spelled out at each call site instead of in one helper. With four sites this is cheaper than the indirection; if a fifth appears, extracting a helper in the shape of `DeactivationGuard` is the move, not changing the trait.

*Note on language:* `config/app.php` sets `'locale' => 'en'` as a literal and nothing calls `setLocale`, so `message` is English in every environment. That is accepted here: the message is a fallback for clients with no catalogue, and the client that has one renders its own text from `status_code` plus these fields.

### 10. A submission may not repeat a date

Two entries of one `workday` submission may not carry the same date, and the submission is refused with its own status code when they do.

*Why:* entries of one submission share a title, carry no time of day, and are summed into the same timesheet. Splitting one date across two entries therefore produces two indistinguishable records and conveys nothing that a single entry with the summed amount would not. A repeated date is a mis-click on the "add row" control, not an intention.

*What it does not restrict:* accumulating several `workday` requests on one date through separate submissions, which Decision 4 deliberately permits. The boss who approves more overtime for a day already recorded is doing something meaningful; the boss who types the same date twice in one form is not.

*A simplification it buys:* with dates unique within a submission, a date identifies an entry, so the refusal payload of Decision 9 needs no list index.

*Alternative considered — merge same-date entries silently.* Rejected: it produces a total the admin did not type and hides the mis-click rather than surfacing it.

## Risks / Trade-offs

**The entered amount bypasses the ratio, invisibly to anyone reading a report later** → The departure is deliberate and stated in the proposal. Reports that aggregate overtime workday mix ratio-derived and manually fixed amounts with nothing distinguishing them. Mitigated only by `input_mode` being present on the request record, so the provenance is recoverable; no reporting change is in scope.

**A manager thinking in hours worked underpays by the ratio** → Entering `05:00` credits five hours of overtime workday, not five hours of work at the holiday rate. Mitigated by labelling: the field must read as overtime *workday*, distinct from the duration field in the other mode, which looks identical.

**Double counting if `W` is ever also represented as a duration on the request** → Decision 2 keeps `total_time` at zero for `workday` requests and Decision 3 scopes both aggregates explicitly by mode. If a later change persists a derived duration on the request without scoping `getTotalOvertimeByAccount()`, every manually entered amount doubles in payroll with no error. This is the highest-severity failure mode in the change and needs its own test.

**Scoping `filterByRange` in the wrong place hides records** → Decision 4. The scope is shared with list filtering. A test should cover filtering the request list by a date range and finding a `workday` request in the result.

**Rounding corrupts the time-range contribution** → Decision 3. Computing `overtime_workday` from `$this->timesheet->overtime` instead of from the `$T` variable rounds both contributions to whole minutes through the display format.

**Division by zero when `work_ratio` or the ratio is zero** → Decision 3 for the calculator, Decision 6 for validation. The calculator skips the derived figure and keeps `overtime_workday` exact; validation refuses the request so the manager is told rather than silently credited nothing.

**Annual leave credits `W / w` rather than `W` on a shift whose `work_ratio` is not 1** → Decision 7, accepted. Identical to the entered amount in the normal case (`work_ratio` defaults to `1`), and pinned against ratio changes in every case. The behaviour follows from leaving the annual-leave path untouched, and matches the rule the time-range mode already obeys. Should be asserted in a test rather than assumed, for both `work_ratio = 1` and `work_ratio ≠ 1`.

**An overtime request only reaches payroll once a timesheet row exists** → Pre-existing, not introduced here: `OvertimeRequest::refreshTimesheet()` runs the calculator over timesheets that already exist for that date, and `handleOvertime()` only runs inside a timesheet calculation. Nothing is lost — the request is picked up when attendance for that date is processed — but the credit is deferred, and on a date for which no timesheet is ever created it never lands. The new mode is more exposed to this than the old one, because it exists precisely for days where attendance data is ragged or missing. Recorded as a known limitation; a fix belongs in its own change.

## Migration Plan

1. Add `input_mode` (default `time_range`) and `total_workday` to `overtime_requests`. Existing rows take the default; no backfill is required because `total_time` already holds their duration and `total_workday` is meaningless for them.
2. Deploy. With no client sending the new mode, behaviour is identical: every request is `time_range`, both new aggregates return their existing values, and `W` is always zero.
3. Release the client once the API is live.

Rollback is a column drop. Any `workday` requests created in the meantime would lose their amount, so rollback is only safe before the client ships.

## Open Questions

- **Resolved:** the `workday` mode is offered on the manager-facing endpoints as well as the admin ones. The employee-side `store()` attaches many accounts at once with differing shifts and applied days, so the minimum-duration check of Decision 6 runs for every attached account, and a refusal names the employee it failed for rather than a position in a list (Decision 9).
- Whether a `workday` submission should be allowed to hold several entries at all was reopened and then closed in favour of keeping them. A single-entry mode would have made Decision 9 unnecessary, since one refused entry identifies itself.
