# LegacyApp module

Bridge between this system and the legacy CodeIgniter application's database
(`vessel_discharge`). The legacy tables are read over a second, read-only database
connection, mapped into the current schema and written here once - with a ledger
that ties every imported row back to its source.

Other legacy domains (fuel pumps, lorries, storage tanks ...) will follow the same
shape: a `Legacy<Domain>` repository, mapper and import service under
`app/Services/Legacy<Domain>/`, a controller, and a ledger table. VTV is the first.

## Connection

`config/database.php` defines `legacy_db`, driven by these environment variables:

```
LEGACY_DB_HOST=127.0.0.1
LEGACY_DB_PORT=3306
LEGACY_DB_DATABASE=vessel_discharge
LEGACY_DB_USERNAME=root
LEGACY_DB_PASSWORD=
```

`backend/.env` is git-ignored, so add these lines by hand on every machine.
The connection is `strict => false` (the legacy data carries zero dates) and every
legacy Eloquent model extends `Models\Legacy\LegacyModel`, which throws on any
save or delete: nothing is ever written back to the old database.

## Turning fetching off (General Settings > Legacy System)

One switch, `legacy_app_settings.fetch_enabled` (on by default), edited by administrators
at `GET|PUT /api/portal/legacy/settings` (`{fetchEnabled}`). Turned off, nothing reads
the legacy database again; everything already copied stays in this system's tables and
keeps working (copied open bills simply stop being refreshed).

`Support\LegacyFetch` holds the switch (cached; flushed on save) and is enforced twice:

- **Every entry point** asks `LegacyFetch::enabled()` first and behaves as if the legacy
  system had nothing: Search Bill / Search Payment, Certificates, stickers, the VTV plate
  check and Instrument Search (VTV and SBL), bill refreshes, the customer picker, the
  `legacy:*` sync commands. Import results carry status `disabled`, which screens ignore.
- **Every legacy read** goes through `LegacyModel::getConnectionName()` or
  `LegacyFetch::connection()`, which throw `LegacyFetchDisabledException` (never logged)
  while off - so a new path that forgets to ask still cannot reach the old database.

New legacy code must read through a `LegacyModel` subclass or `LegacyFetch::connection()`,
never `DB::connection('legacy_db')` directly.

## Legacy VTV - how the old tables hang together

```
vehicle_tanks (data_id, id = VTV_xxx, hash)        one row per yearly registration
  +-- compartments.vehicle_id  = vehicle_tanks.id    one row per reading (litres @ mm)
  +-- chart_number.vehicleId   = vehicle_tanks.id
calibrated_tanks (data_id, id = VTV_xxx_<suffix>)   written when the registration was billed
  +-- original_id              = vehicle_tanks.data_id
  +-- bill_items.BillItemRef   = calibrated_tanks.id
        +-- wma_bill.BillId    = bill_items.BillId
customers.hash = vehicle_tanks.hash = calibrated_tanks.hash
```

Two traps in the data, both handled in `LegacyVtvRepository` /
`Support\LegacyCompartmentBatches`:

- **Every yearly verification is a new `vehicle_tanks` row** with its own id. The
  "last verification" is the newest non-deleted `calibrated_tanks` snapshot for the
  plate, and the compartments and chart number are read from *that snapshot's*
  registration (by `original_id`, or by the id prefix of the snapshot id, provided
  the plates match). A snapshot is never paired with a registration by plate alone.
- **Re-saving a compartment appended a new batch of rows** instead of replacing the
  old ones. Only the batch with the newest `created_at` per compartment is carried
  over; identical (litres, mm) pairs within it are kept once.

## Readiness checks

A legacy vehicle is written into this system only when every check passes.
Otherwise the response says which are missing (`missing` / `missingReasons`).

| Check | Meaning |
| --- | --- |
| `isInVehicleTanks` | a registration row exists |
| `isInCalibratedTanks` | a non-deleted billed snapshot exists |
| `hasCompartments` | at least one compartment carries readings |
| `hasChartNumber` | a chart number was issued to the registration |
| `isBilled` | a bill line exists whose bill was not cancelled |
| `hasCustomer` | an owner is known (legacy customer row, or the bill's payer) |
| `hasUniqueLegacyId` | no registration of a different plate shares the legacy id |

Non-blocking oddities (fewer charted compartments than declared, an unpaid bill,
prefix-matched registration) are returned as `warnings`.

Legacy ids (VTV_xxx, VTV_xxx_suffix, customer hashes) are never shown to users: they
live only in `legacy_source_id` and on the ledger. Migration
`2026_09_21_000400_replace_legacy_ids_on_imported_vtv_rows` renumbers rows imported
before this rule.

## Dates and the "copied from legacy" flag

Every row written by the importer is dated by the legacy system, not by the import:
`vehicles`, `vehicle_verifications` and `vehicle_ownerships` are created at the legacy
registration's `created_at` and last updated at the billed snapshot's; compartments
and readings at the batch they were saved; the archive row at the snapshot; a created
customer (and its address) at the legacy customer's `registered_at`. Only the ledger's
`imported_at` says when the copy was made.

Every copied row also carries two columns (migration
`2026_09_21_000200_add_legacy_import_flags_to_vtv_and_customer_tables`):

| Column | Meaning |
| --- | --- |
| `imported_from_legacy` | `1` when the row was copied from the legacy database |
| `legacy_source_id` | the legacy row it came from: `vehicle_tanks.id`, `calibrated_tanks.id` or `customers.hash` |

on `vehicles`, `vehicle_verifications`, `verified_vehicle_tanks`, `compartments`,
`vehicle_ownerships` and `customers`. They are not mass-assignable; only the importer
writes them (through `forceFill`).

## What gets written

| Current table | From |
| --- | --- |
| `customers` + `customer_addresses` | legacy `customers` (matched by ledger, then TIN, then phone + name; created otherwise) |
| `vehicles` | registration / snapshot; `vehicle_id` is a new-system code (V-XXXXXXXXXX) |
| `vehicle_ownerships` | owner above, dated at the legacy verification date |
| `vehicle_verifications` | snapshot: activity, dates, inspection results, capacity, fine, remarks (+ an "Imported from the legacy system" note); stage `complete` |
| `compartments` + `compartment_measurements` | newest batch per compartment |
| `verified_vehicle_tanks` | `verification_number` issued in the new-system format (VT + legacy billing date + random), `control_number` = legacy bill control number, `chart_number` = legacy chart number |
| `legacy_vtv_imports` | the ledger: every legacy id, the bill and its payment state, counts, a JSON snapshot of the rows read |
| `legacy_customer_imports` | legacy customer hash -> customer here, and how it was matched |

Deliberately **not** written:

- `wma_bill` / `bill_items` - the legacy bill stays in the legacy system. Mirroring it
  would put legacy money into this system's revenue reports and rollups.
  `LegacyVtvSettlementService` answers the VTV wizard's "was this paid?" from the
  ledger instead, so a paid legacy chart can be reused on re-verification.
- `vehicle_calibration_charts` - the register of chart numbers *this* system has
  issued. A legacy sequence in it would move the next number issued. The legacy chart
  number is carried on `verified_vehicle_tanks.chart_number` and the ledger.

### Unpaid legacy bills

When the plate check finds an unpaid verification whose bill was raised in the legacy
system, the reply carries `billSource: legacy` and `legacyBillId`, and the wizard labels
it "Legacy Bill". "View Bill" calls the usual `get-bill-by-control/{controlNo}`, which
falls back to `LegacyBillService` when the control number is not in `wma_bill` and
returns the legacy bill (with its items) in the same preview shape - read live, never
copied. Every settlement of a legacy-imported verification first refreshes the ledger's
payment state from the legacy `wma_bill` (`legacy_bill_checked_at` records when), so a
bill paid in the legacy system clears the alert on the next plate check. If the legacy
database is down, the last known state is used.

The legacy schema has no tank type; imports default to petroleum
(`legacyapp.vtv.default_tank_type`).

## Legacy customers in the customer picker

The shared customer picker (`CustomerRegistration.jsx`) searches the register and,
alongside it, the legacy `customers` table (`GET /api/portal/legacy/customers/search`,
by name or phone in local or international form). Legacy rows are marked "Legacy"
and carry no `customer_uuid`; choosing one calls
`POST /api/portal/legacy/customers/import {hash}`, which writes the customer into
`customers` + `customer_addresses` under the current schema (dated by the legacy
`registered_at`, flagged `imported_from_legacy`, location ids resolved when the names
match the Tanzania hierarchy) - or links the hash to the customer it already is here
(matched by TIN, then phone + name) - and returns the register row to select. A legacy
customer already brought over is not offered by the legacy search again.

## Legacy Sand & Ballast Lorries (Instrument Search)

Instrument Search (`activity=sbl&search_type=plate`) asks the legacy system about a plate
it finds nothing for, through `LegacySbl\LegacySblImportService`, and copies the lorry's
last verification over - the same shape as the VTV import (repository, mapper, record with
readiness checks, ledger `legacy_sbl_imports`), all in one transaction.

```
lorries (data_id, id = SBLxxx, hash)            one row per registration
  +-- lorry_trailers.vehicleId = lorries.id       appended when a trailer was added
verified_lorries (data_id, id = SBLxxx)         written when it was billed - SAME id
  +-- original_id              = lorries.data_id
  +-- bill_items.BillItemRef   = verified_lorries.id
```

The billed snapshot carries every detail of the verification, so the registration row is
not required (locally most are missing). A trailer plate resolves to the lorry it is
registered with. The trailer on the imported verification is the newest one registered
under the lorry id no later than the billing; `capacity` is the total, `mainCapacity` the
lorry's share, and the legacy `height` is the body length.

| Check | Meaning |
| --- | --- |
| `isInVerifiedLorries` | a non-deleted billed snapshot exists |
| `isBilled` | a bill line exists whose bill was not cancelled |
| `hasCustomer` | an owner is known (legacy customer row, or the bill's payer) |
| `hasUniqueLegacyId` | no snapshot of a different plate shares the legacy id |

Written: `lorries`, `lorry_ownerships`, `lorry_verifications` (stage `complete`),
`verified_lorries` (verification number in this system's `LV` format, dated by the legacy
billing), and the bill with its lines, payments and stickers (`LegacyBillCopier`), the
lorry's line re-pointed from `SBLxxx` to the verification number. All carry
`imported_from_legacy` / `legacy_source_id`. The verifying officer is linked through
`LegacyOfficers` (email), else left empty. A still-open copied bill is refreshed from the
legacy database each time the lorry's details or history are read. A plate already on a
lorry here (soft-deleted included) is never imported.

`SandAndBallastLorries` has no `module.json`, so `migrate` does not discover its
migrations on a fresh database. Migration `2026_09_21_000800` therefore skips lorry tables
that do not exist yet and can be run again once they do; `LegacySblImportTest` builds them
from the module's own migrations.

## Legacy certificates of correctness and conformity

The legacy app wrote a row to `correctness_certificate` / `conformity_certificate` the
first time a control number was searched on its Certificates screen. The Certificates
screen here (`GET /api/portal/certificates?type=...&control_number=...`) does the same
lookup in the legacy system when it holds no certificate of that type for a whole control
number, through `LegacyCertificates\LegacyCertificateImporter`:

1. The bill behind the control number is copied first (`LegacyBillImporter`), so the
   certificate is tied to its bill (`bill_uuid`) and a cancelled bill voids it.
2. A certificate the legacy system issued is copied once (`LegacyCertificateCopier`) with
   its **own number, public id and issue date** - flagged `imported_from_legacy`, legacy
   row id in `legacy_source_id` (unique per type), shown with a Legacy badge.
3. A paid legacy bill the legacy system never issued a certificate for gets one here, as
   the search would have issued it there: numbered in this system's sequence, dated
   today, not flagged.

A bill raised here is never looked up. Partial control numbers never go to the legacy DB.

| Legacy column | Here |
| --- | --- |
| `certificateNumber`, `certificateId`, `createdAt` | `certificate_number`, `certificate_id` (when free), `issued_at` |
| `region` | `collection_center` (same center numbers) |
| `officer` (`users.unique_id`) | `officer_uuid` - the user here with the same email (legacy `auth_identities`), else null; the legacy name in `officer_name`, which the rendered certificate falls back to |
| `activity` / `activities` | `gfs_code` (the first code; `activities` is JSON, a bare code or a comma list) |
| correctness `items` | `items`; `trade` from the bill's line tasks |
| conformity `products` (`product_details.id`) | `items` as "commodity, quantity, unit"; hashes the legacy screen could not resolve either fall back to the bill's line names |

Legacy numbers are sequential per center like the ones here and both started at 000001,
so the same number can exist in both systems. The number index is scoped by the
generated `number_scope` column (`''` here, the legacy id on a copy), and
`CertificateNumberGenerator` ignores copied rows - a copy never moves the next number.

## Endpoints (`routes/portal.php`, `/api/portal/legacy`)

| Method | Path | Permission (or super-admin) | Does |
| --- | --- | --- | --- |
| GET | `/status` | view-legacy-records, import-legacy-records, createVehicle | is the legacy DB reachable |
| GET | `/customers/search?q=` | any signed-in user | legacy customers not yet brought over |
| POST | `/customers/import` `{hash}` | any signed-in user | write (or link) the legacy customer and return it as a register row |
| GET | `/vtv/lookup?plate=` | view-legacy-records, import-legacy-records, createVehicle | preview + checks, nothing written |
| POST | `/vtv/import` `{plate, attachToExisting?}` | import-legacy-records, createVehicle | import if every check passes |
| GET | `/vtv/imports?q=` | view-legacy-records, import-legacy-records | the ledger |

**Instrument Search** (`GET /api/portal/instrument-search?activity=vtv&search_type=plate`)
asks the legacy system when a plate is unknown here, imports it when every check
passes, and then returns it like any other result - with `vehicle.importedFromLegacy`,
`vehicle.legacySourceId` and `billing.legacy` set, a `legacy` object describing what
happened, and `history` entries flagged `importedFromLegacy`. A legacy bill has no
print preview here (`billPreview` is null): the bill lives in the legacy system.

The VTV plate check (`GET /api/portal/vtv/check-plate`) calls the importer itself
when a plate is unknown here, and returns a `legacy` object saying what happened:
`imported` / `already_imported` (the plate check then continues against the
recovered vehicle), `blocked` with `missing`, `plate_mismatch`, or `not_found`.
The legacy DB being down never breaks the plate check.

Two further rules keep the two systems consistent:

- **A vehicle registered here but never billed** (added in the wizard, no archive
  row) and not yet given its legacy history has the legacy verification attached to
  it on the next plate check (`attachToExisting`), so the chart it left the old
  system with is the "previous chart" the wizard offers to copy. A vehicle with a
  billed history here is never touched.
- **A legacy registration already imported under a different plate** (the legacy
  row was re-plated after the import) is reported as `plate_mismatch` and nothing
  is written: the same physical vehicle must not exist here twice, and the fix is a
  plate amendment on the vehicle already on file.

## Staff accounts

`php artisan legacy:import-users [--dry-run]` copies the legacy staff accounts
(CodeIgniter Shield: `users`, `auth_identities`, `auth_groups_users`) into `users`:

- first/last name, phone number and collection center (legacy `users.collection_center`
  uses the same center numbers as `collection_centers.center_number` here);
- the login email (`auth_identities.secret`, type `email_password`), lower-cased. An
  account that already exists here under that email is recorded as `linked` and never
  changed;
- roles through `legacyapp.users.role_map`. Groups with no counterpart (headofsection,
  surveillance) and the administrative ones (admin, superadmin) get no role - the
  command lists them so an admin can assign roles by hand;
- the password is not carried over: every new account starts on
  `legacyapp.users.default_password` (`LEGACY_USERS_DEFAULT_PASSWORD`, default
  `Tanzania$255`) and its owner changes it from their profile;
- status follows legacy `users.active`.

Soft-deleted legacy users, rows without a valid email or name, and unknown collection
centers are skipped and listed. The `legacy_user_imports` ledger makes re-runs safe.

`php artisan legacy:import-user-phones <file.csv> [--dry-run] [-v]` then fills in phone
numbers from a CSV with `Email` and `Phone Number` columns, matched by email
(case-insensitive). Rows without a phone number are skipped, so a number is never
blanked out; `-v` lists every change.

## Tests

- `tests/Unit` - batch selection, readiness rule, column mapping (no database).
- `tests/Feature` - real MySQL (`mysql_testing`); the legacy tables are built in the
  same testing database under the `legacy_` prefix, which `legacy_db` is pointed at.
