Skip to content

M2 · Vehicles

D3, D4, D10, D11, D14, D15, D19, D22, D27, D32, D39, D47, D52, D56, D61, D65, D70, D77, D91, D92, D95, D107, D108, D109, D110, D113 (draft).

Conforms to the decisions through D113.

Status: built means its pgTAP tests pass (supabase/tests/database/74_vehicle_list.test.sql). No error keys: every refusal here is hidden rows (zero rows, nothing raised).

Name Kind Status What it gives
public.v_vehicles view, security invoker built One row per car the user may read, inactive cars included (R-VEH-38). Columns: id, organization_id, unit_code, plate_number, pool_id, pool_code, pool_name, rental_company_id, rental_company_name, brand_name, model_id, model_name, year, color, vin, odometer_km, status, supply_status. Filter and page with PostgREST: pool_id, status, supply_status, order unit_code, range and count (R-VEH-39, R-VEH-40). The list adds status=neq.inactive unless the status filter is set (R-VEH-38). rental_company_name is null for a reader without master_data:read, payment:read or vehicle:write (R-VEH-41, R-VEH-74). No company_daily_cost and no plate_is_temporary.
public.find_vehicles(q text) function, security invoker, stable built Rows (id, unit_code, plate_number, pool_id, pool_code, status, supply_status, match_kind, rental_company_name), one per matching car, every match returned. match_kind is unit_code, plate or former_plate. Order: not inactive first, then unit_code, plate, former_plate, then unit_code. Unit code: trimmed, exact match. Plate: whitespace removed, upper-cased. Blank input gives no rows. Another pool's car gives zero rows and no error. A former plate is found only by a vehicle:read holder (R-VEH-32 to R-VEH-37). rental_company_name is last and comes from a left join on rental_companies under the caller, so it is null for a reader without master_data:read or payment:read, exactly as in v_vehicles (R-VEH-46). Call it as supabase.rpc('find_vehicles', { q }).
public.vehicle_plate_history table read built Sheet: vehicle_id=eq.<id>, order valid_to.desc. Plate_number, valid_from, valid_to, changed_by. vehicle:read at the car's pool only (R-VEH-42).
public.vehicle_status_history table read built Sheet: vehicle_id=eq.<id>, order changed_at.desc. from_status, to_status, note, changed_by, changed_at. vehicle:read only (R-VEH-42). Select the columns, never the legacy_ ones.
  • v_vehicles joins the pool, model, brand and rental company names itself, with left joins: a car never drops out when its rental company is hidden (R-MD-12). rental_company_name is empty for a reader without master_data:read or payment:read (admin_driver, admin_fleet, checker); the page shows a dash. It returns inactive cars. Types are in packages/db-types (Views.v_vehicles).
  • find_vehicles returns the columns listed above, not every v_vehicles column: take the car's sheet from v_vehicles by id. PostgREST keeps the function's order for an RPC with no order parameter. There is no row limit of its own: PostgREST's default max-rows applies, which a plate or unit code lookup never reaches. A blank input returns zero rows and no error key; no key exists in this slice.
  • History: vehicle_plate_history (plate_number, valid_from, valid_to, changed_by) and vehicle_status_history (from_status, to_status, note, changed_by, changed_at). Read them as separate selects by vehicle_id (the generated relationships in packages/db-types give an embed from vehicle_plate_history to v_vehicles, and the other way is not needed: two selects by vehicle_id are simpler and keep each history's own policy). changed_by is a profile id only; names are not part of this slice.
  • vehicle_status values: unchecked, returned, not_ready, maintenance, ready, booked, rented, inactive. The database holds no labels; the Indonesian labels belong in apps/web. supply_status values: active, replacing, inactive.
  • Seed (supabase/seed.sql, E2E organization), as fe asked: E2A cars E2E-V01 (B1234E2E, ready, active, rental company E2E Mitra Kendaraan, 2022, Putih, VIN MHKE2E1234567890A, 15200 km), E2E-V02 (now B5678E2E; its former plate B1234E2E is one plate history row; status history maintenance then ready, the newest with the note "back from service"), E2E-V03 and E2E-V04 (both on the listed temporary plate B8888TMP, not B9999TMP, which a pgTAP test counts across organizations), E2E-V05 (B1234E2E too, inactive, supply inactive, so a lookup of B1234E2E gives V01 plate, V02 former_plate, V05 plate last), E2E-0042 (B0006E2E), E2E-42 (B0007E2E), E2E-V08 maintenance (B0008E2E), E2E-V09 unchecked (B0009E2E), E2E-V10 returned (B0010E2E), E2E-V11 supply replacing (B0011E2E), and E2E-P01 to E2E-P25 (B0101P2E to B0125P2E, ready, active) for paging. E2B: no seeded car (E2E-V20 was removed: retiring pool E2B raises master_data.in_use). V01 belongs to E2E Mitra Kendaraan; every other seeded car, E2E-V02 on and E2E-P01 to P25, belongs to TOP, the marked rental company (R-VEH-68). The E2E logins include satpam (tools/db/create-e2e-users.mjs, ROLES), at both pools like every role, so a pool-scoped login still does not exist.

Status: built means its pgTAP tests pass (supabase/tests/database/75_vehicle_create_documents.test.sql). Migration supabase/migrations/20261006003000_vehicle_create_documents.sql. A refusal reaches supabase-js as error.message = the key, error.details = JSON text, error.code P0001 (42501 for vehicle.not_allowed).

Name Kind Status What it gives
public.create_vehicle(home_pool_id, model_id, unit_code, plate_number, year?, color?, vin?, odometer_km?, rental_company_id) rpc, security definer built Adds a car as not_ready and returns its id (R-VEH-47). Plate and VIN are upper-cased with whitespace removed, a blank VIN is null, unit code and color are trimmed. The rental company is required (R-VEH-70, #748); there is no daily cost parameter any more (R-VEH-53). Send rental_company_id by name in the rpc call; the type has it optional only because Postgres defaults it to null, which is refused. Since #746 its checks are app.vehicle_check()'s, which vehicle_batch shares too (under #746 below); the keys and their order are unchanged.
public.add_vehicle_document(vehicle_id, doc_type, expires_on?, tax_due_on?) rpc, security definer built Adds a document with no file and returns its id (R-VEH-48). doc_type: stnk, bpkb, insurance, other; expiry optional for every type. tax_due_on only with stnk, optional there (R-VEH-65, #745).
public.set_vehicle_document_file(document_id, path) rpc, security definer built Sets the document's main path once; the path must be <organization_id>/vehicle_documents/<document_id>/<file> (R-VEH-49).
Storage bucket documents Storage built Upload any number of files to <organization_id>/vehicle_documents/<document_id>/<file> (vehicle:write at the car's pool); list that folder to show them (vehicle:read, within the member's rental companies, R-STO-18). Files are never overwritten or deleted. organization_id is v_vehicles.organization_id.
public.vehicle_documents table read built id, doc_type, expires_on, tax_due_on (#745; null unless stnk), storage_path (null until set), created_at; filter vehicle_id=eq.<id>. vehicle:read at the car's pool, within the member's rental companies (R-VEH-52). No direct insert, update or delete: rows are added by add_vehicle_document and their path set by set_vehicle_document_file (R-VEH-50).
public.vehicle_stnk(vehicle_id) rpc, security invoker, stable built One row (expires_on, state) for a car the caller reads, none otherwise. state: valid, expired or not_on_file, on the pool's today; the latest stnk expiry counts (R-VEH-51).
public.my_permissions() rpc (exists) built The pools where the user may add cars: rows with permission_code = 'vehicle:write' (pool_id, pool_code).
Key Code Detail Raised by
vehicle.field_required P0001 {field}: unit_code, plate_number, home_pool_id, model_id, rental_company_id, doc_type create_vehicle, add_vehicle_document
vehicle.field_invalid P0001 {field}: home_pool_id, model_id, rental_company_id (another organization, or retired), year (1990 to 2100), odometer_km create_vehicle
vehicle.not_allowed 42501 {pool_id} or {vehicle_id} or {document_id} all three writers
vehicle.unit_code_taken P0001 {field: unit_code, value} create_vehicle
vehicle.plate_in_use P0001 {field: plate_number, value} create_vehicle
vehicle.vin_taken P0001 {field: vin, value} create_vehicle
vehicle.not_found P0001 {vehicle_id} add_vehicle_document
vehicle.document_not_found P0001 {document_id} set_vehicle_document_file
vehicle.document_path_invalid P0001 {document_id, path} set_vehicle_document_file
vehicle.document_file_already_set P0001 {document_id} set_vehicle_document_file
vehicle.stnk_expired P0001 {vehicle_id, expires_on} app.set_vehicle_status to ready (R-VEH-25); no UI in this slice

Checks in create_vehicle run in this order: field_required (rental company included), the pool (field_invalid), not_allowed, the rental company of the organization (field_invalid), vehicle.rental_company_not_held, the company active (field_invalid), then model, year, odometer (field_invalid), then unit code, plate, VIN.

Status: built means its pgTAP tests pass (supabase/tests/database/77_car_owner.test.sql). Applies D108. Migrations 20261006000100 to 003000 are edited in place (D11).

Name Kind Status What it gives
vehicles.rental_company_id column built Not null, and of the car's organization (R-VEH-68, R-VEH-69). v_vehicles.rental_company_id is never null.
public.create_vehicle(...) rpc built No company_daily_cost; rental_company_id required, held to the caller's list unless they have the flag (R-VEH-70 to R-VEH-72). Keys in the #463 tables.
public.rental_company_names(organization_id?) rpc, security definer, stable built Rows (id, name, is_active) of the organization's rental companies for a vehicle:write holder at any pool, held to the caller's list (partner-limited) or all with the flag, retired included (R-VEH-74). Use it for the add-car picker: offer rows with is_active, TOP among them; none is preselected. Call supabase.rpc('rental_company_names', { organization_id }).
public.v_vehicles, public.find_vehicles view, rpc built rental_company_name is also filled for a vehicle:write holder, not only master_data:read or payment:read (R-VEH-74); null for other readers.
public.rental_companies.is_operator column built True on the one company marked as the operator's own, TOP (R-MD-84; unique per organization). No function sets or clears it (R-MD-85); a rename keeps it (R-MD-87).
Direct write on vehicles table built Insert and update hold to the member's list; a limited member writing another company's car gets 42501 or no row changed (R-VEH-73).
Key Code Detail Raised by
vehicle.rental_company_not_held 42501 {rental_company_id} create_vehicle (R-VEH-72)
master_data.operator_company_locked P0001 {id} retire_master_data('rental_company', id) on the marked company (R-MD-86)
payout.operator_company P0001 {rental_company_id} insert or update of a payout for the marked company (R-MON-98)

Status: built means its pgTAP tests pass (supabase/tests/database/76_vehicle_photos.test.sql). A refusal reaches supabase-js as on #463.

Name Kind Status What it gives
public.v_vehicle_photos view read, security invoker built The photo each side shows: at most one row per (vehicle_id, side), no row for an empty side. Filter vehicle_id=eq.<id> and sign each row with its own bucket. vehicle_id, organization_id, side (front, back, left, right), source ('v2' or 'v1', a file from v1), id (the photo's or the file from v1's), bucket ('vehicles' or 'inspections'), storage_path, content_type (v1's; null for v2, always JPEG or PNG by R-STO-25), taken_at (v1's; null for v2), created_at. Same rows for all six readers (R-VEH-56, R-VEH-59 to R-VEH-61).
public.add_vehicle_photo(vehicle_id, side) rpc, security definer built Adds a photo with no file and returns its id (R-VEH-54).
public.set_vehicle_photo_file(photo_id, path) rpc, security definer built Sets the photo's path once; the file must already be in bucket vehicles at <organization_id>/vehicle_photos/<photo_id>/<file> (R-VEH-55).
Storage bucket vehicles Storage built Private; image/jpeg and image/png, 10 MB a file (R-STO-25). Upload to <organization_id>/vehicle_photos/<photo_id>/<file> (vehicle:write at the car's pool, within the member's rental companies); read as the row (R-VEH-59). Never overwritten or deleted (R-STO-12). organization_id is v_vehicles.organization_id.
public.vehicle_photos table built Every photo row, shown or not: select only, same six readers. No direct insert, update or delete (R-VEH-57). Read v_vehicle_photos instead.
public.vehicle_photo_side enum built front, back, left, right.
Key Code Detail Raised by
vehicle.not_found P0001 {vehicle_id} add_vehicle_photo
vehicle.not_allowed 42501 {vehicle_id} or {photo_id} both photo functions
vehicle.field_required P0001 {field: side} add_vehicle_photo
vehicle.field_invalid P0001 {field: tax_due_on} add_vehicle_document (R-VEH-65)
vehicle.photo_not_found (new) P0001 {photo_id} set_vehicle_photo_file
vehicle.photo_path_invalid (new) P0001 {photo_id, path} set_vehicle_photo_file
vehicle.photo_file_already_set (new) P0001 {photo_id} set_vehicle_photo_file
vehicle.photo_file_missing (new) P0001 {photo_id, path} set_vehicle_photo_file

Checks run in this order: add_vehicle_photo not_found, not_allowed, field_required; set_vehicle_photo_file photo_not_found, not_allowed, photo_path_invalid, photo_file_already_set, photo_file_missing. A retry reuses the same photo row. If the upload landed but the set failed, call set again, or upload under a new name (files are never overwritten, R-STO-12).

The control of R-VEH-67 shows by public.my_permissions(): rows with permission_code = 'vehicle:write' for the car's pool.

#746 · Adding vehicles in a batch from a CSV file

Section titled “#746 · Adding vehicles in a batch from a CSV file”

Status: built means its pgTAP tests pass (supabase/tests/database/78_vehicle_batch.test.sql). Applies D109. Migration 20261006003000_vehicle_create_documents.sql, edited in place (D11): create_vehicle's checks moved into app.vehicle_check(), which it shares with vehicle_batch, and its own tests (75, 77) pass unchanged. A refusal reaches supabase-js as on #463; for vehicle.batch_refused, error.message is the key and error.details is the JSON text of { refusals: [...] }.

Name Kind Status What it gives
public.vehicle_batch(rows, check_only?) rpc, security definer built Adds many cars, every row or none (R-VEH-77 to R-VEH-83). rows: a JSON array of at most 500 objects { unit_code, plate_number, home_pool_id, rental_company_id, model_id, year, color, vin, odometer_km }, ids and not names, a blank cell as null or left out (R-VEH-76). Call supabase.rpc('vehicle_batch', { rows, check_only }). With check_only true, the default: returns { refusals: [{ row, field, key }] } and writes nothing (R-VEH-80). With check_only false: returns { created: [uuid] }, one id per row in the order of the rows, or raises vehicle.batch_refused and writes nothing (R-VEH-81).
Key Code Detail Raised by
vehicle.batch_refused P0001 { refusals: [{ row, field, key }] }: the list a check returns for the same rows vehicle_batch in save mode
vehicle.batch_too_many P0001 { rows, limit: 500 } vehicle_batch, a check as much as a save, before any row is checked (R-VEH-79)
vehicle.batch_duplicate in the list { row, field, key } on the later row, field unit_code, plate_number or vin (R-VEH-78) vehicle_batch; it is never raised on its own
  • One refusal per row, the first create_vehicle would raise for it, in create_vehicle's order (R-VEH-72); field is the column the refusal's detail names, null for vehicle.not_allowed and vehicle.rental_company_not_held. Every key of R-VEH-47 comes back this way, with R-VEH-70, R-VEH-71 and R-VEH-72.
  • Duplicates in the file (R-VEH-78) are reported on a row that passes every create_vehicle check: its unit code, plate or VIN equals an earlier row's after create_vehicle's normalizing, within one organization, so a member of two organizations may repeat a value across them. An earlier row counts whether or not it is itself refused; no VIN never counts. The list is in row order.
  • Each row is checked with vehicle:write at its own pool (R-VEH-82), so one file may span pools, and a row at a pool the caller may not write at comes back as vehicle.not_allowed with field null.
  • The activity log needs nothing new (R-VEH-83): the cars of a saved batch are audit rows of one transaction, so they share its transaction id and the log lists the batch once (D52, R-AUD-13). A refused save writes none.
  • Not keyed, as create_vehicle isn't: rows that are null or not a JSON array, or an element that isn't an object, fail the call with invalid_parameter_value (22023); a value its column can't read (an id text that isn't a uuid, a year that isn't a whole number) fails the whole call with 22P02. Send the ids as uuid strings and year and odometer_km as JSON numbers. An empty array gives { refusals: [] }, or { created: [] }.
  • In save mode every row is written through create_vehicle, which checks once more: a value taken between the check and the write comes back in the list with its R-VEH-47 key, and nothing is saved.
  • Grants: authenticated, as create_vehicle; anon holds no execute, and the secret key (service_role) keeps execute on vehicle_batch and create_vehicle as on every public function. app.vehicle_check, app.vehicle_input and app.is_refusal live in app and aren't callable from the API.

#464 · Plate change and manual status moves

Section titled “#464 · Plate change and manual status moves”

Status: built means its pgTAP tests pass (supabase/tests/database/79_plate_status.test.sql). Migration supabase/migrations/20261006003200_plate_status.sql. Both functions are security definer, return void, and are granted to authenticated only (anon none). Types: packages/db-types, Functions.change_plate and Functions.move_vehicle_status (to_status is Enums.vehicle_status). A refusal reaches supabase-js as on #463: error.message = the key, error.details = JSON text, error.code P0001 or 42501.

Name Kind Status What it gives
public.change_plate(vehicle_id uuid, plate_number text) rpc, security definer built Changes the car's plate, saved upper case without whitespace (R-VEH-88); the old plate becomes one vehicle_plate_history row (R-VEH-93). No note. Call supabase.rpc('change_plate', { vehicle_id, plate_number }).
public.move_vehicle_status(vehicle_id uuid, to_status vehicle_status, note text default null) rpc, security definer built Retire (any status but booked, rented and inactive, to inactive; vehicle:write), reactivate (inactive to not_ready; vehicle:write), pull (ready to not_ready; vehicle:write or maintenance:write), all at the car's home pool (R-VEH-94 to R-VEH-97). The note, trimmed, blank as null, goes on the status history row (R-VEH-99). Every other move is refused. Call supabase.rpc('move_vehicle_status', { vehicle_id, to_status, note }).
Direct update of vehicles.plate_number trigger guard_plate built Refused for every app user with vehicle.plate_locked (R-VEH-85); other columns still update directly (R-VEH-12).
Key Code Detail Raised by
vehicle.not_found P0001 {vehicle_id} both: no such car, or one the caller can't read (pool read permissions, or a company outside their list)
vehicle.not_allowed 42501 {vehicle_id} change_plate: reads the car, no vehicle:write at its home pool
vehicle.field_required P0001 {field: plate_number} change_plate: empty, spaces only or null
vehicle.inactive (new) P0001 {vehicle_id} change_plate on an inactive car
vehicle.plate_unchanged (new) P0001 {vehicle_id, plate_number} change_plate with the plate the car has, after normalizing
vehicle.plate_in_use P0001 {vehicle_id, plate_number}: the car being changed or reactivated, never the holder change_plate; move_vehicle_status when reactivating
vehicle.status_move_forbidden (new) P0001 {vehicle_id, from_status, to_status} move_vehicle_status: not one of the three moves, or the same status
vehicle.status_forbidden 42501 {vehicle_id} move_vehicle_status: the move's permission is missing at the home pool
vehicle.plate_locked (new) 42501 {vehicle_id} a direct update of plate_number

Checks run in this order and raise the first refusal: change_plate not_found, not_allowed, field_required, inactive, plate_unchanged, plate_in_use (R-VEH-87); move_vehicle_status not_found, status_move_forbidden, status_forbidden, plate_in_use (R-VEH-94).

  • What to offer on the sheet (R-VEH-100, R-VEH-101): getAccess() already gives the permissions per pool: pools[] from my_permissions(), each with id and permissions (a Set of codes). Find the pool whose id is the car's v_vehicles.pool_id (its home pool) and check vehicle:write and maintenance:write there. getCurrentPool() is the switcher's pool, not necessarily the car's, so don't use it for this. Neither knows the member's rental company list, but the sheet only opens for a car the member reads, and the functions still refuse every move.
  • Seed (supabase/seed.sql, E2A, TOP's), no other journey's: E2E-V12 (B0012E2E, ready) to retire and reactivate. A rerun works without a reset, because it is not_ready after the first run and still retirable. E2E-V13 (B0013E2E, ready) to pull: it stays not_ready after the run, so a second run needs pnpm supabase db reset. E2E-V14 (B0014E2E, not_ready) to change the plate of. Change it back at the end of the journey, or a rerun meets vehicle.plate_unchanged. E2E-V15 (B0015E2E, not_ready) holds the plate for the vehicle.plate_in_use journey: change V14 to B0015E2E. No journey may change V15. E2E-V16 (B0016E2E, booked): the sheet offers it no move. E2E-V05 (inactive, B1234E2E, which V01 holds) gives vehicle.plate_in_use on reactivation, if a journey wants it.

Status: built means its pgTAP tests pass (supabase/tests/database/80_insurance_policies.test.sql). Migration supabase/migrations/20261006003300_insurance_policies.sql; the policies and grants of insurance_policies changed in tools/db/gen_rls.py and its generated 20261006001100_rls.sql, edited in place (D11). Rules R-ASR-05, R-ASR-16 to R-ASR-32 (system/rules/insurance.md); R-ASR-33 (search) needs no backend: fe filters v_insurance_expiry through PostgREST. Both functions are security definer, granted to authenticated only (anon none). App users lose direct insert, update and delete on insurance_policies (D3: the premium is money); reads stay direct under R-ASR-04. A refusal reaches supabase-js as on #463: error.message = the key, error.details = JSON text, error.code P0001 or 42501. Types: packages/db-types after pnpm db:types.

Name Kind Status What it gives
public.add_policy(vehicle_id uuid, insurer_id uuid, policy_number text, starts_on date, ends_on date, coverage text default null, premium bigint default null) rpc, security definer built Adds a policy to the car and returns its id (uuid). Needs insurance:write at the car's home pool. policy_number and coverage trimmed, blank coverage as null. premium is whole rupiah, optional, > 0 when given. Overlapping periods are accepted. Call supabase.rpc('add_policy', { vehicle_id, insurer_id, policy_number, starts_on, ends_on, coverage, premium }).
public.change_policy(policy_id uuid, insurer_id uuid, policy_number text, starts_on date, ends_on date, coverage text default null, premium bigint default null) rpc, security definer built Replaces every field but the car: insurer, number, period, coverage and premium. A null coverage or premium clears it, so send the current value to keep it. Returns void. Same checks as add_policy.
public.v_insurance_policies view, security invoker built One row per policy the caller reads (insurance:read at the car's pool, within the member's rental companies, R-ACC-43, R-ACC-44): id, organization_id, vehicle_id, insurer_id, insurer_name, insurer_is_active, policy_number, coverage, starts_on, ends_on, premium, state (active, expiring or expired by its own ends_on, R-ASR-31), days_left (its ends_on minus the home pool's today), is_current (the car's policy with the latest ends_on). For the Polis tab: .eq('vehicle_id', id).order('ends_on', { ascending: false }).
public.v_insurance_expiry view, security invoker built One row per car that isn't inactive, only where the caller holds insurance:read at its home pool, within the member's rental companies (R-ACC-43, R-ACC-44): vehicle_id, organization_id, unit_code, plate_number, pool_id (home pool), pool_code, pool_name, policy_id, insurer_id, insurer_name, policy_number, ends_on (null when none), state (active, expiring, expired, none) and days_left (ends_on minus the home pool's today; negative once expired; null when none). The current policy is the one with the latest ends_on; ends_on is inclusive; the 30-day window is a constant in Postgres. Filter with .eq('state', …), .eq('pool_id', …), sort soonest first with none last with .order('ends_on', { nullsFirst: false }) (R-ASR-30). Paging with .range() and { count: 'exact' } works on the view as on v_vehicles (R-VEH-40). The same row for one car feeds the sheet's tab header: .eq('vehicle_id', id).maybeSingle().
public.insurers table, existing built The picker: id, name, is_active. Readable by every member of the organization (R-MD-52), so insurance:write holders read it. Hide is_active = false; add_policy refuses a retired one anyway.
Key Code Detail Raised by
vehicle.not_found P0001 {vehicle_id} add_policy: no such car, or one the caller can't read
insurance.policy_not_found (new) P0001 {policy_id} change_policy: no such policy, or one the caller can't read
insurance.not_allowed (new) 42501 {vehicle_id}; change_policy adds policy_id both: no insurance:write at the car's home pool
insurance.field_required (new) P0001 {field}: insurer_id, policy_number, starts_on or ends_on both: missing, or blank after trimming
insurance.dates_invalid (new) P0001 {starts_on, ends_on} both: ends_on before starts_on
insurance.premium_invalid (new) P0001 {premium} both: premium given and not above 0
master_data.not_found P0001 {field: insurer_id, id} both: no such insurer, or one of another organization
master_data.retired P0001 {field: insurer_id, id} add_policy, and change_policy when the insurer changes: the insurer is retired
insurance.policy_number_taken (new) P0001 {insurer_id, policy_number} both: the insurer already has this number in the organization (R-ASR-03; the unique constraint stays as the backstop)

A composite foreign key (insurer_id, organization_id) is the backstop for writes outside the functions (23503). Checks run in this order and raise the first refusal: vehicle.not_found or insurance.policy_not_found, insurance.not_allowed, field_required (insurer_id, policy_number, starts_on, ends_on), dates_invalid, premium_invalid, policy_number_taken, master_data.not_found or master_data.retired. A premium that isn't a whole number is a cast error (22P02), not a key. insurance_policies gets the audit_row trigger (R-ASR-23).

#466 · GPS devices, positions and /fleet-monitor

Section titled “#466 · GPS devices, positions and /fleet-monitor”

Status: built: its pgTAP tests pass (supabase/tests/database/81_gps.test.sql). Applies D113 (draft), D15, D32, D39. Rules R-GPS-01 to R-GPS-38 (system/rules/gps.md). A refusal reaches supabase-js as on #463: error.message = the key, error.details = JSON text, error.code P0001 or 42501. Types: packages/db-types after pnpm db:types.

Name Kind Status What it gives
public.v_fleet_monitor view, security invoker built The page's one read. One row per car the user reads (as v_vehicles: vehicle:read or fleet_monitor:read at its home pool, within the member's rental companies), inactive cars included: vehicle_id, organization_id, pool_id, pool_code, unit_code, plate_number, status, gps_device_id and slot (of the active device, null when none), recorded_at, latitude and longitude (float8), speed_kmh, last_seen, is_stale, state, driver_name. state is live, stale, no_data (active device, never reported) or no_device (no active device), computed in Postgres against the organization's gps_stale_minutes (R-GPS-16 to R-GPS-19, R-GPS-31). Hide inactive with .neq('status', 'inactive') unless "show inactive" is on (R-GPS-32). driver_name is the driver of the car's open rental, and null unless the caller holds driver:read at the car's home pool (R-GPS-33, R-ACC-46): the check is in Postgres, so the name is never sent to anyone else. Re-read every 15 s (R-GPS-38).
public.v_vehicle_position view, security invoker built Kept: one row per car with an active device (R-GPS-16, R-GPS-19), now with latitude, longitude, last_seen and is_stale. The page reads v_fleet_monitor instead.
public.v_gps_devices view, security invoker built The sheet's GPS tab: id, vehicle_id, provider, external_id, imei, slot (primary, backup), is_active, installed_on, last_recorded_at (null when it never reported). Filter vehicle_id=eq.<id>, order slot (R-GPS-35). Readers as v_fleet_monitor.
public.link_gps_device(vehicle_id uuid, provider text, external_id text, slot gps_slot) rpc, security definer built Links a device to the car in the slot and returns its id (uuid). Registers a device it hasn't seen, or re-links the unlinked row it has (R-GPS-23 to R-GPS-25). external_id trimmed. Active only when the car has no active device and the slot is primary; a backup starts on standby (R-VEH-23).
public.unlink_gps_device(device_id uuid) rpc, security definer built Takes the device off its car, not active; returns void. Never activates the other device (R-GPS-26).
public.activate_gps_device(device_id uuid) rpc, security definer built Makes the device active and the car's other device standby, in one call; returns void (R-GPS-22).

All three need vehicle:write at the car's home pool, within the member's rental companies (R-GPS-27), and write an audit row (R-GPS-28). They return no row: re-read v_gps_devices after a call. The ingest, the pull and the retention job live in schema app and aren't callable from the API (R-GPS-01, R-GPS-02); gps_pulls is read by no app user (R-GPS-21).

Key Code Detail Raised by
vehicle.not_found P0001 {vehicle_id} link_gps_device: no such car, or one the caller can't read
vehicle.not_allowed 42501 {vehicle_id} all three: no vehicle:write at the car's home pool
gps.device_not_found (new) P0001 {device_id} activate, unlink: no such device, or one the caller can't read
gps.device_not_linked (new) P0001 {device_id} activate, unlink: the device has no car
gps.device_already_active (new) P0001 {device_id} activate
gps.field_required (new, proposed to doc) P0001 {field}: provider, external_id or slot link
gps.unknown_provider (new) P0001 {provider} link, and the ingest
gps.slot_taken (new) P0001 {vehicle_id, slot} link
gps.device_in_use (new) P0001 {provider, external_id}: never the other car's id, which the caller may not read (proposed to doc) link: the device is linked to a car, in any organization (R-GPS-24); backed by the unique index gps_devices_linked_once on (provider, external_id) where vehicle_id is not null

Check order: link vehicle.not_found, vehicle.not_allowed, gps.field_required, gps.unknown_provider, gps.slot_taken, gps.device_in_use; activate and unlink gps.device_not_found, gps.device_not_linked, vehicle.not_allowed, then gps.device_already_active (activate).

Also built: public.set_organization_settings takes a new last parameter gps_stale_minutes int, 1 to 32767; out of range it is refused with settings.out_of_range naming gps_stale_minutes (R-GPS-14, R-GPS-15). The ingest stores speed_kmh null when the provider sends none. Easygo's answer shape and bearer header are assumed until BE-M2-01 confirms them; a provider account is pulled only once its base_url, its Vault key and its organization (gps_providers.organization_id) are set (R-GPS-12, R-GPS-41), so the local stack runs no pull job. Each pull records its organization (gps_pulls.organization_id), and the ingest matches devices only within it (R-GPS-06). app.gps_ingest now takes (provider, organization_id, batch); it is not callable from the API.