# Random

# 📘 Random Pool Selection Engine

This document defines the technical and functional logic of the **Random Pool Selection** engine (`RandomPoolServiceImp`), covered by the `RandomPoolServiceImpTest` suite. Its goal is audit transparency: every number shown before a run can be traced back to a concrete rule below.

> **Last reviewed:** 2026-12-01 — includes the Secondary Organization rule change (double random allowed).

---

## 1. Pool Universe (who can be selected)

A random always runs for the **organization selected in the session**, but its pool spans **every organization that shares the same `Group Random`** value. The pool is built in this order:

1. **Active DOT employees** (`type = DOT`, `enabled = true`) whose primary organization belongs to the group.
2. **Rescued inactive employees**, according to the `RANDOM_POOL_INCLUDE_INACTIVE_EMPLOYEE` parameter (see §3).
3. **Secondary organization employees**: active DOT employees whose *secondary* organization belongs to the group (see §2).

Each person enters the pool **once**. If someone is already in the pool by step 1 or 2, step 3 does not add them again.

The same eligibility service (`IPersonEligibilityService`) feeds the **Distribution List**, **Preview** and **Run**, so the list on screen and the pool used by the engine always contain the same people.

---

## 2. Secondary Organization Rule

> ⚠️ **Rule changed (2026-12-01).** The previous rule ("an employee is excluded from their primary organization if they have an active pool record in their secondary organization") **no longer applies** and was removed from the engine.

**Current rule: double random is allowed.**

- An employee with a secondary organization stays in the pool of **both** organizations: the primary and the secondary one.
- They can be selected in **both randoms independently**, even if one of them is still NEW or RUNNING. There is no check that blocks a person from being in two active randoms; this is intended.
- An employee can have **only one** secondary organization.
- Only **active** employees enter through a secondary organization (inactive rescue does not apply to secondary org).
- When a person enters by secondary organization, the engine uses the **secondary organization's `TypeFormGroupRandom`** (Solo Drug / Solo Alcohol / ALL) to decide whether they are eligible for Drug, Alcohol or both — not the one of their primary organization.
- In the summary, they are counted in the **2nd ORG** column under the **secondary organization's** row.

**Business context:** used when the same employer has sub-companies per DOT mode (e.g., FMCSA + PHMSA). Before running a random, the admin can temporarily set a secondary organization on the employees that must be covered, and remove it afterwards. Because randoms often stay open for months while data is completed, overlaps between randoms are expected.

> DOT multi-agency guidance generally suggests one pool per employee. Allowing double random was reviewed and **accepted as a business decision**.

**Where it shows in the UI:**

- **Distribution List → "Pool Source" column:** badge `Secondary org · Primary: <primary org name>` for people who entered by secondary organization. Empty for everyone else.
- **Activation headers** (HUB popovers, services panel, Employee forms modal): show `· Random from: <org>` when the random that activated the test belongs to a different organization than the employee's form record.
- **HUB:** changing *Organization (Reg Mode)* or *Secondary Organization* asks for confirmation (showing old → new value), because it changes which random pools the employee enters. The organizations offered as secondary are limited by the `SHOW_SECONDARY_ORGANIZATION` parameter.

---

## 3. Inactive Rescue Parameter

Parameter: `RANDOM_POOL_INCLUDE_INACTIVE_EMPLOYEE` (global, configured in the database).

<table style="width: 100%; border-collapse: collapse; margin-top: 10px;"><thead><tr style="background-color: #f1f5f9;"><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Value</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Behavior</th></tr></thead><tbody><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Empty / not configured</td><td style="border: 1px solid #cbd5e1; padding: 10px;">No inactive employee is rescued.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>true</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">All inactive DOT employees of the group are rescued.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>{COLUMN_CODE;VALUE}</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">Only employees whose custom column matches that value are rescued. Example: <code>{EE_STATUS;L}</code> (Leave of Absence).</td></tr></tbody></table>

Inactive employees that are **not** rescued are reported in the **IGNORED** column.

---

## 4. Audit Transparency Structure (Preview)

The Preview shows one row per organization with 6 columns, each with a **D|A (Drug | Alcohol)** breakdown:

<table id="bkmrk-column-functional-de" style="width: 100%; border-collapse: collapse; margin-top: 10px;"><thead><tr style="background-color: #f1f5f9;"><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Column</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Functional Definition</th></tr></thead><tbody><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**ELIGIBLE (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Active DOT employees counted under their primary organization (any organization of the Group Random), filtered by the organization's type (Solo Drug, Solo Alcohol or ALL). Excludes rescued inactives and secondary-org entries.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**INACTIVE (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Inactive employees rescued by <code>RANDOM&#95;POOL&#95;INCLUDE&#95;INACTIVE&#95;EMPLOYEE</code> (§3).</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**2nd ORG (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Employees who entered the pool because this organization is their secondary organization. Counted under the secondary organization's row, using its type (§2).</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**IGNORED (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Inactive employees in the database who were NOT rescued. Informational only; they are not part of the pool.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**C/O (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">**Carry-Over:** tests marked CARRY_OVER in the organization's most recent previous random (by start date), whatever its status (§6). Counted under the employee's current primary organization.</td></tr><tr style="background-color: #f8fafc; font-weight: bold;"><td style="border: 1px solid #cbd5e1; padding: 10px;">**TARGET (D|A)**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Per organization: <code>ceil((Eligible + Inactive + 2nd Org) × %)</code> + Carry-Over. Carry-Over is added only if the organization's pool for that test is greater than 0. In fixed-quantity mode, see §8.</td></tr></tbody></table>

After a real **Run**, the results modal shows per organization: **ONLY DRUG**, **ONLY ALC**, **BOTH** and **TOTAL** selected.

---

## 5. Selection Logic

- **Percentage or fixed quantity:** the admin chooses either a percentage (0–100) or a fixed number of employees for Drug and for Alcohol.
- **Draw scope:** the draw is done **once for the whole Group Random pool**, separately for Drug and for Alcohol. Each draw only considers people whose organization type allows that test (`ALL` or the matching Solo type).
- **Rounding:** percentage draws use `Math.ceil` (round up). A fixed quantity larger than the pool is capped at the pool size.
- **Randomness:** the pool is shuffled with `SecureRandom` (cryptographic-grade). Only counts are logged (`RANDOM_SELECTION universe=… requested=… selected=…`), never the list of people.
- **Group Respect:** if an organization is Solo Drug, its Alcohol columns always show **0|0** (and vice versa).
- **Preview vs. Run:** both use the same engine and the same pool rules, so the **counts and targets** match as long as the data does not change between them. The **people selected are not the same**: Preview is a simulation and every draw is random. Preview does not save anything.
- **Other random forms:** besides Drug and Alcohol, any other form linked to the Random Pool test type in the company is activated for every person selected by the draw.

---

## 6. Carry-Over

**Automatic (on Run):** the engine takes the organization's **most recent previous random** (ordered by start date, **any status**, including CANCELED) and adds every test marked **CARRY_OVER** in it to the new random.

- Carry-over is **additive**: if a person is selected in the new draw **and** has a carry-over, they get **two** tests (one from the draw, one from the carry-over with a reference to the original record).
- The carry-over keeps the employee type recorded on the original test, even if the employee's type has changed since.
- Carry-overs for forms other than Drug/Alcohol (e.g., Medical) are also carried.

**Manual Pull Carry-Over:** from an existing random, the admin can pull carry-overs from another random of the same organization.

- Target random must be **NEW** or **RUNNING**. Source random must be **FINISHED** or **RUNNING**.
- A read-only preview lists the people and forms that will be pulled before confirming.
- Carry-overs already pulled (into this random or any other) are skipped. If nothing is left, the user gets an informational message instead of an error.
- Both randoms must belong to the organization selected in the session; otherwise the system answers "not found".

---

## 7. Data Integrity & Constraints

- **One record per person per random (Double-Dip Protection):** a person selected for both Drug and Alcohol gets a single `RandomPoolPerson` record, and is counted as **BOTH** in the summary. Each test (form) still gets its own record.
- **Full pool snapshot:** people in the pool who were not selected are also saved in the random with `included = false`, so the random keeps evidence of the full universe it was drawn from.
- **Run parameters saved for audit:** drug value, alcohol value and whether it was a percentage are stored on the random.
- **Name:** `RNDMPL-<ORG CODE>-<MMMdd>-<YYYY>`.
- **Atomic run:** the run is transactional; if any step fails, nothing is saved.

---

## 8. Known Limitations

- **TARGET vs. actual selection:** TARGET is calculated per organization, while the draw runs over the whole group. With several organizations in the group, the sum of per-organization `ceil` values can be slightly higher than the number actually drawn.
- **Fixed-quantity mode:** each organization's TARGET shows the full fixed quantity, but the draw takes that quantity once for the whole group.
- **Inactive rescue parameter is global**, not per organization.
- **Migration mode does not validate person IDs** against the company or organization: the caller must make sure every ID belongs to the organization being migrated (§11).
- **Migration mode summary counters** (ELIGIBLE, INACTIVE, 2nd ORG, TARGET) are not meaningful: they mix the provided distribution list with the regular pool rules. Use the ONLY DRUG / ONLY ALC / BOTH results instead.

---

## 9. Lifecycle

<table style="width: 100%; border-collapse: collapse; margin-top: 10px;"><thead><tr style="background-color: #f1f5f9;"><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Status</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Meaning</th></tr></thead><tbody><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**NEW**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Created by a Run.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**RUNNING**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Tests in progress.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**FINISHED**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Closed with the Finish button. Only allowed when every selected employee has completed their test.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">**CANCELED**</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Any non-finished random can be canceled; its incomplete tests are canceled too.</td></tr></tbody></table>

---

## 10. Validations

The process stops with a controlled error (no data saved) if:

<table style="width: 100%; border-collapse: collapse; margin-top: 10px;"><thead><tr style="background-color: #f1f5f9;"><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">When</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Condition</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">HTTP</th></tr></thead><tbody><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Preview / Run</td><td style="border: 1px solid #cbd5e1; padding: 10px;">No stakeholder (service provider) assigned to the Random Pool test type for the organization. Checked first.</td><td style="border: 1px solid #cbd5e1; padding: 10px;">409</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Preview / Run</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Percentage mode with a Drug or Alcohol value outside 0–100.</td><td style="border: 1px solid #cbd5e1; padding: 10px;">400</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Preview / Run</td><td style="border: 1px solid #cbd5e1; padding: 10px;">The pool (Active + Rescued Inactive + 2nd Org) is empty.</td><td style="border: 1px solid #cbd5e1; padding: 10px;">409</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Finish</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Some selected employees have not completed their test.</td><td style="border: 1px solid #cbd5e1; padding: 10px;">409</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Pull Carry-Over</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Target random not NEW/RUNNING, or source random not FINISHED/RUNNING.</td><td style="border: 1px solid #cbd5e1; padding: 10px;">409</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;">Run</td><td style="border: 1px solid #cbd5e1; padding: 10px;">Failure activating tests for the selected employees (whole run is rolled back).</td><td style="border: 1px solid #cbd5e1; padding: 10px;">500</td></tr></tbody></table>

---

## 11. Migration Mode (historical load)

Migration mode loads into Nexus33 a random that **was already drawn outside the system** (e.g., historical randoms from before onboarding). It does **not** perform a draw: it records exactly the people provided.

> **Not available in the UI.** It is triggered only through the Run endpoint with `migration = true`, by the development/support team.

**Input (Run request):**

<table style="width: 100%; border-collapse: collapse; margin-top: 10px;"><thead><tr style="background-color: #f1f5f9;"><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Field</th><th style="border: 1px solid #cbd5e1; padding: 10px; text-align: left;">Meaning</th></tr></thead><tbody><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>migration</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>true</code> to enable the mode.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>distributionListIds</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">Comma-separated person IDs: the full universe of the historical random. Replaces the calculated pool.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>drugIds</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">Comma-separated person IDs selected for Drug.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>alcoholIds</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">Comma-separated person IDs selected for Alcohol.</td></tr><tr><td style="border: 1px solid #cbd5e1; padding: 10px;"><code>startDate</code> / <code>finishDate</code></td><td style="border: 1px solid #cbd5e1; padding: 10px;">Historical dates of the random. <code>startDate</code> is also used as the tests' activation date and in the random's name.</td></tr></tbody></table>

**Behavior:**

- Drug and Alcohol selections are taken **exactly** from `drugIds` / `alcoholIds`: no shuffle, no percentage, no `TypeFormGroupRandom` filter.
- People in `distributionListIds` who are not in either list are saved with `included = false`, the same as a normal run.
- The standard validations still apply: a stakeholder must be assigned, the regular pool must not be empty, and, if `percentage = true`, the values must be between 0 and 100.
- Carry-over from the organization's previous random is still added (§6).
- The random is created as **NEW**, the same as a normal run, and its tests are activated and notified the same way.