## Context

An employee's organisational placement is held entirely in the `account_position` pivot. There is no `department_id` on accounts: department and company membership are derived by walking `account -> positions -> department -> company`. The read path already assumes a single placement — `Account::getPositionAttribute()` and `Account::getCompanyAttribute()` both take `positions()->first()` — while the write path still validates `positions` as an array and only enforces that all of them belong to one company. In practice every account has exactly one position.

Departments and positions have no status. `DepartmentController@destroy` refuses to delete while any position exists, and `PositionController@destroy` refuses while any account is attached, including accounts of employees who have quit. Because that history must be preserved, a defunct unit can neither be deleted nor retired, and keeps behaving like a live one.

`contract_types` already carries the pattern this change follows: a `tinyInteger is_active` defaulting to `1`.

## Goals / Non-Goals

**Goals:**
- Retire a department or position without deleting it or disturbing historical records.
- Guarantee that a retired unit has no active employees left in it.
- Keep "is this position assignable?" answerable from one place, so the rule cannot drift between call sites.

**Non-Goals:**
- A status on `companies`. Deliberately deferred; see Decision 3.
- A history or audit trail of position changes. See Decision 6.
- Snapshotting `employee_department` / `employee_company` onto contracts. See Risks.
- Changing the one-position-per-account model in either direction. See Decision 4.
- Any bulk operation over employee assignments. Withdrawn; see Decision 5.

## Decisions

### 1. A department's status is written down onto its positions

Deactivating a department writes `is_active = 0` onto every position in it; reactivating writes `1`. A position's own status is then the whole truth about whether it can be assigned, and no caller derives anything.

*Why:* availability has to be readable by clients, not only by queries. Under a derived rule the API returns a position's stored status, which can say `1` while the position is unusable because its department is off. Every consumer — the employee form, the position picker, any list showing a badge — then has to fetch the department and compute the conjunction itself, and several existing payloads (`Account::$relationData`, which selects `positions:id,name,department_id`) do not even carry the fields needed to do it. Pushing the truth into the row removes a class of client-side bugs that no amount of backend correctness would prevent.

*Cost, accepted:* the two reasons a position can be inactive — switched off on its own, or switched off with its department — become indistinguishable once written. Reactivating a department therefore turns on positions that an admin had deliberately turned off earlier. This is mitigated by disclosure rather than by remembering state: a department reports how many of its positions are inactive, so the admin sees the size of the effect before committing. See Decision 1b.

*The invariant this creates:* no position may be active while its department is inactive. Three writes can violate it and each is closed — deactivating a department cascades down, creating a position inside an inactive department is refused, and activating a position inside an inactive department is refused.

*What this trades away:* under the derived rule, consistency was guaranteed by the query and could not drift. It is now guaranteed by write discipline. If a fourth way to set a position's status is ever added and does not honour the invariant, the data goes quietly wrong in a way the old design was immune to. The three enforcement points are the price of a single readable field.

*Alternative considered:* keep the derived rule and expose a computed `is_available` alongside the stored `is_active`. Rejected because it leaves two status fields on the same object, and a client that reads the wrong one is wrong in a way that looks right.

### 1b. Reactivation discloses its blast radius

A department reports a count of its inactive positions, so the admin is told how many positions reactivating it will switch back on.

*Why:* Decision 1 makes reactivation coarse. Rather than refusing to reactivate, or inventing a memory of prior state, the system states the consequence and lets the admin decide. A count is enough for that judgement and costs one field.

### 2. One scope owns the availability rule

Availability is asked through a single Eloquent scope on `Position`. Under Decision 1 that scope is now a single column test, but the indirection stays: callers ask `available()` rather than testing `is_active` directly, so the definition remains in one place.

*Why:* there are at least five write paths that assign positions plus several listing endpoints. A condition copy-pasted across them will drift. Concentrating it also means a future company tier is one edit — see Decision 3. This indirection is what made reversing Decision 1 cheap: the definition changed, its four call sites did not.

### 3. No company status now, and the same cascade would extend to it

`companies` gets no `is_active` in this change. Because Decision 2 confines the rule to one scope, adding a third tier later is an edit to that scope rather than to every consumer:

```
available(P)  ==  P.is_active AND D.is_active            <- now
available(P)  ==  P.is_active AND D.is_active AND C.is_active   <- later, same place
```

*Note after Decision 1:* a company tier would extend by the same mechanism — deactivating a company would cascade through its departments to their positions — rather than by adding a third term to a derived condition.

*Why defer:* the requested scope is departments and positions. A company tier changes what "retiring a company" means operationally (every department beneath it, every employee moved or quit) and deserves its own proposal.

### 4. One position per account is a given

Every account holds exactly one position, and therefore one department and one company. Department membership is read through it — `Account::getPositionAttribute()` and `Account::getCompanyAttribute()` both take `positions()->first()`.

*Why it matters here:* the deactivation guard asks "does this unit still have an active employee?", which is only a well-posed question because placement is singular. With concurrent placements the guard would have to decide whether an employee counted against every unit they sit in.

*Caveat:* this is a convention, not a constraint. `positions` is validated as `array` with no size limit and the pivot has no uniqueness on `account_id`. Nothing in this change writes to the pivot, so the convention breaking would skew the guard's count rather than destroy data.

### 5. Withdrawn: bulk transfer of employees

An operation to move a whole department's employees to one target position was planned and built, then withdrawn at the product's request because the front end does not use it. The routes, controller actions and their API documentation are removed.

*What this leaves:* the deactivation guard stands, but there is no bulk remedy for it. An admin facing a department with active employees must reassign them one at a time through the existing employee update operation, or mark them as having quit. For a large department that is substantial manual work, and it is the accepted cost of not carrying an endpoint nobody calls.

*What it does not change:* moving a single employee between companies keeps its existing path, `EmployeeController@changeCompany`, with its own permission and `company_mode` requirements. Decision 8 still applies to it.

### 6. No audit log

Employee reassignments are not recorded anywhere beyond the resulting pivot state.

*Why:* the repository's existing log machinery for this is not alive. `EmployeeSettingLog` is only ever deleted, never written — its writes were meant to flow through the `SalaryChanges` event, which is registered with an empty listener array and broadcasts to a placeholder channel. `EmployeeTypeLog` is annotated for removal. The only working pattern is `AccountPayslipItemLog`, which exists because payroll genuinely reads historical values; nothing comparable reads position history. A log that nothing consumes is cost without benefit.

*Consequence, accepted:* after a reassignment there is no record of which department an employee previously belonged to.

### 7. Import rejects unavailable positions with a distinct reason, and unavailable positions stop competing

Two coupled behaviours in employee Excel import:

- Unavailable positions are excluded from the candidate set during resolution. A name that matches one retired and one live position resolves to the live one rather than failing as ambiguous.
- When exclusion is what emptied the candidate set — the name would have matched, but every match was unavailable — the row is reported as unavailable rather than as not found.

*Why:* excluding alone would tell an admin a position does not exist when they can plainly see it; rejecting alone would leave retired duplicates poisoning name resolution forever. Together, retiring a position both removes it from consideration and produces an accurate message when it was the only thing that matched.

### 8. The `changeCompany` leader defect is fixed here

`EmployeeController@changeCompany` decides whether to clear leader references by comparing the employee's current company against `Company::find($positionIds[0])` — a lookup of the `companies` table keyed by a *position* id. The comparison is therefore meaningless: usually it yields a non-match and the cleanup runs unnecessarily, but when a position id happens to coincide with the employee's current company id the cleanup is skipped and a leader reference is left dangling across companies. Introduced 2023-12-18 in `7208b861b` and shipped in v1.22.3.

*Why fix it in this change:* it was found while tracing how employees leave a department being retired, which is the problem this change exists to solve, and it silently weakens the only cleanup guarding against cross-company leader references. The intended value is reachable via the existing `Position::getCompany()`.

### 9. Reactivation is a separate gate from assignment

Returning an employee to `active` is checked on its own, not by the assignment rule alone.

*Why:* the assignment rule answers "may this position be set?" and deliberately exempts the position an employee already holds, so that an employee sitting in a retired unit can still have their record corrected. Reactivation asks a different question — "may this unit gain a working employee?" — and the exemption is exactly what makes it unsafe. An employee who quit keeps their assignment when their department is retired, as the deactivation guard counts only `active` employees; flipping them back to `active` therefore repopulates a retired department without any position ever being assigned. Two call sites reach this: `EmployeeController@update`, where a body carrying only `status` never triggers the assignment rule because no `positions` are present, and `EmployeeController@updateStatus`, which validates nothing but `status`.

*Consequence:* on the reactivation path the "already holds it" exemption does not apply. Resubmitting the same unavailable position is refused, so the only way through is a position that is genuinely available.

*Alternative considered:* let `updateStatus` accept an optional `positions` so the problem can be fixed in place. Rejected to keep that endpoint's shape as it is; the refusal directs the admin to the employee update operation, which already takes both status and positions in one request.

*Alternative considered:* auto-move the employee to a fallback position on reactivation. Rejected — silently choosing someone's department is worse than refusing and asking.

### 10. Status rides on the normal update, not a dedicated action

`is_active` is part of the department and position update payload. There is no separate deactivate or reactivate action.

*Why:* the status of a unit is edited on the same form as its name, description and leader. With a dedicated action the front end has to issue two requests to save one form, and the pair is not atomic — the status change can succeed while the information save fails, leaving a department retired with its edits lost. One request removes the failure mode entirely.

*Where the guard runs:* the active-employee precondition is unchanged in substance. It moves into the update action, runs only when the request would turn an active record inactive, and returns the same `status_code` and `employees[]` payload, so the front end's handling of a blocked deactivation is unaffected. Reactivation stays ungated.

*Consequence:* the guard now has two callers' worth of context to serve — departments and positions — so it is extracted into one place rather than duplicated, consistent with Decision 2's reasoning about a rule that must not drift.

*Alternative considered:* keep the dedicated actions and have the front end orchestrate the two requests. Rejected: it pushes atomicity onto the client for no gain, and the dedicated actions carried the same authorisation as update, so they were never a separate permission boundary.

## Risks / Trade-offs

**A department cannot be retired while an active employee remains, and there is no bulk way to empty it** → With bulk transfer withdrawn (Decision 5), an admin must reassign each employee through the existing employee update operation, or mark them as having quit. Retiring a large department is therefore proportionally laborious. Accepted: the guard is what makes the status trustworthy, and the product does not want the endpoint that would have softened it.

**Reassigning an employee loses the record of their previous department** → Accepted under Decision 6: the pivot is overwritten and nothing logs what it held. This is pre-existing behaviour of the employee update operation, not introduced here.

**Re-rendering a contract after an employee is reassigned shows the new department** → `Field::$defaultKeyByCodes` resolves `employee_department` and `employee_company` live through the pivot, while `employee_position` already reads the `employees.contract_position` snapshot. A signed contract's rendered `preview` and static PDF are frozen and are not touched by a reassignment; they are only re-rendered if someone subsequently edits that contract through `ContractController@updateByAccount`, which does not refuse signed contracts. This is pre-existing behaviour, reachable today by editing a single employee, and is accepted as-is rather than addressed here.

**Consistency now depends on write discipline rather than on the query** → Decision 1 closes the three writes that can leave a position active inside an inactive department. A fourth path added later that sets a position's status without honouring the invariant would corrupt availability silently, where the derived rule could not. Mitigated by routing availability through one scope (Decision 2) and by keeping status writes in the controllers' update actions rather than spread across helpers.

**Reactivating a department switches on positions an admin had deliberately switched off** → Inherent to Decision 1; the two reasons a position is inactive are not distinguishable once written down. Mitigated by disclosure, not by memory: the department reports its inactive-position count so the admin sees the size of the effect first. See Decision 1b.

**The one-position-per-account model is a convention, not a constraint** → Nothing in the schema or the API enforces it. Nothing in this change writes to the pivot, so a violation would skew the deactivation guard's count of active employees rather than destroy data — a unit could be reported as blocked by an employee whose other placement is elsewhere. See Decision 4.

## Migration Plan

1. Add `is_active` to `departments` and `positions`, `tinyInteger` default `1`, matching `contract_types`. Existing rows are active, so behaviour is unchanged at deploy.
2. Ship the derived scope and the validation rule. With everything active, no assignment is refused.
3. Ship `is_active` on the department and position update operation, guarded.
4. Front end surfaces status and filtering on the department and position forms.

Rollback: the feature is inert while every row is active. Reverting the application code leaves two unused columns; dropping them is safe if no row has been deactivated.
