# Recras Analytics Guide

Lean reference for writing ClickHouse SQL against the flattened export of a Recras instance (a
booking/activity management system for leisure companies: bookings of packages and products,
customers, invoices, payments, staff planning). Pair this with `DESCRIBE <table>` for the exact
column list; this guide covers what is **not** obvious from the schema.

The tables are regenerated from a read-only mirror of the Recras API (`bin/console analytics:export`,
every four hours, after the mirror has synced). They are snapshots: every row carries `synced_at` (last time the
source record was seen) and `deleted_at` (set when the record disappeared from Recras).

## Tables

### `flattened_bookings` — one row per booking

- **Booking** columns: `id`, `reference` (customer-facing, like `47-2`), `date` (booking date),
  `status`, `status_updated_at`, `package_name` (name shown to the customer), `package_id`,
  `persons` (group size), `online_booking` (made through online booking), `status_expiry_date`
  (option/reservation expiry), `particulars` (internal remarks), `should_invoice`,
  `invoiced_amount`, `created_at`.
- **Cost header** (`cost_*`): `cost_total_incl_vat` is the booking value including VAT as calculated
  by Recras, `cost_company_id` the company that invoices, `cost_payment_term` in days.
- **Customer** (`customer_*`): the contact the booking belongs to (`customer_id` = `flattened_contacts.id`),
  with `customer_type` (free-text category configured per company, e.g. "Bedrijf", "Familie"),
  address fields and `customer_contact_type` (always `klant` for bookings).
- **Main contact person** (`main_contact_*`): the primary person of the customer.
- **Company** (`company_*`): the invoicing company (a Recras instance can run several companies).
- **Package catalogue** (`package_catalog_*`): the package definition if it still exists.
- **Booking lines** (`line_*`): the activities/products on the booking: `line_count`,
  `first_line_begin_at`/`last_line_end_at` (actual activity window), `line_quantity_total`,
  `line_product_count`, `line_product_names`, `line_location_names` (comma separated).
- **Cost lines**: `cost_item_count`, `cost_items_amount` = Σ quantity × unit price of item lines
  (excluding VAT, before discounts); prefer `cost_total_incl_vat` for the booking value.
- **Invoices and payments**: `invoice_count`, `invoice_total_incl_vat`, `invoice_statuses` (comma
  separated set), `first_invoice_date`, `last_invoice_date`, `payment_count`, `paid_total`,
  `last_payment_at`, `outstanding_amount` = invoiced − paid (NULL when nothing invoiced).
- **Staff**: `shift_count`, `shift_hours`, `shift_staff_names`, `shift_qualification_names` (shifts explicitly linked to the
  booking in Recras) and `covering_shift_count`, `covering_skipper_names` (confirmed shifts, resp. skipper shifts, on the same
  location overlapping any of the booking's lines — vessel shifts are rarely linked, so use `covering_skipper_names IS NULL`
  for "trip without a skipper"). Shift-level detail lives in `flattened_shifts`.
- **Contact moments**: `contact_moment_count`, `last_contact_moment_at` (e-mails/notes linked to this booking).

### `flattened_contacts` — one row per contact

`contact_type` is `klant` (customer), `leverancier` (supplier), `personeel` (staff) or `overig`. The same person often exists
twice: once as `personeel` and once as `klant` (staff who also book). `twin_contact_id`/`twin_contact_type` point to the other
row and `twin_match` says how it was linked: `email` (the staff e-mail equals the customer's main contact-person e-mail) or
`name` (only one contact of the other type has the same display name; ambiguous names stay unlinked). `person_key` is the
normalised display name. Staff rows carry `email`, `phone`, `first_name`, `last_name`, `plannable`, `deactivated_at`.
Columns: contact fields (`display_name`, address, `country_code`, `province_code`, `customer_type`,
`department`, `vat_number`, `company_id` + `company_name`), the main contact person
(`main_contact_*`, `contact_person_count`), and aggregates:

- as customer: `booking_count`, `booking_confirmed_count` (status definitief/gaande/voltooid),
  `booking_cancelled_count`, `first_booking_date`, `last_booking_date`, `booking_persons_total`,
  `booking_cost_total_incl_vat`, `invoice_count`, `invoice_total_incl_vat`, `last_invoice_date`,
  `payment_count`, `paid_total`, `last_payment_at`, `outstanding_amount`;
- communication: `contact_moment_count`, `first_contact_moment_at`, `last_contact_moment_at`;
- as staff member: `shift_count`, `recorded_hours_count`, `recorded_hours_total` (hours worked, breaks deducted).

### `flattened_contact_moments` — one row per contact moment

A contact moment is an e-mail sent from Recras or a note logged on a contact: `moment_type`
(e.g. `mail`), `subject`, `message` (HTML, can be long; `message_length` is its size), `message_text` (the same as readable
plain text — prefer it for reading or searching), `contact_type` of the contact (`personeel` for staff mails),
`is_planning_mail` + `planning_change_count` (the daily planning digests, exploded in `flattened_staff_planning_notifications`),
`to_customer`, `sticky`, `created_at`, `staff_id`/`staff_name` (NULL for automatic mails),
`booking_id` with `booking_*` columns when the moment is linked to a booking, and `contact_*` /
`person_*` columns for the contact and contact person.

### `flattened_shifts` — one row per staff shift (dienst)

A shift is one staff member planned for one time slot. Columns: `id`, `status`, `begin_at`/`end_at` (UTC),
`date` and `weekday` (**local Europe/Amsterdam calendar day** of the start — use these for "who worked on day X"),
`planned_minutes`/`planned_hours`, `internal_reference`, `remark` (visible in the planning), `note` (planning department),
`staff_id`/`staff_name`/`staff_company_id` (`staff_id` = `flattened_contacts.id` of a `personeel` contact),
`qualification_id`/`qualification_name` (the **role**: Schipper = skipper, Dagco = day coordinator, Runner, Kade host,
Grillmeister, Cocktail Bartender, Quizmaster, Histo host; see `recras_qualifications`), `task_qualification_names`,
`location_id`/`location_name` (the **vessel or place**: Sloep, OG, Borrelpraam, Satoshi, Borrelkade, ...),
`booking_*` (the booking the shift serves, same meaning as in `flattened_bookings`), `booking_line_id` + `line_*`
(the booking line/product of the shift's first task), `task_count`/`task_descriptions`/`task_begin_at`/`task_end_at`,
and recorded hours: `recorded_count`, `recorded_begin_at`/`recorded_end_at`, `recorded_break_minutes`,
`recorded_minutes`/`recorded_hours` (worked time **after** deducting breaks), `recorded_notes`,
`hours_difference` (= recorded − planned hours, NULL when nothing was recorded).

- Role, location and booking are taken from the shift itself or, when the shift does not carry them, from its first task;
  shifts planned from a booking line usually have them on the task.
- Shift `status`: `bevestigd` (confirmed), `concept` (draft), `gevraagd` (requested from the staff member),
  `geannuleerd` (cancelled), `geweigerd` (declined). Count `bevestigd` as worked/planned; for "actually worked" prefer
  `recorded_count > 0`.
- About a third of the shifts have a booking; the rest are general shifts (bar, quay, office). Roughly 40 % have a role.
- **Recras keeps no modification history for shifts** (only `created_at`, `created_by`, `updated_by`, `is_generated`). What a
  staff member was *told* is in the daily planning mails: `last_notified_at`, `last_notified_change_type`,
  `last_notified_begin_at`/`last_notified_end_at`, `last_notified_status` come from the newest mail line that matches the shift
  (`notification_match` = `exact` when staff, begin and end match; `date` when the staff member had only one shift that day),
  `notification_in_sync` = 1 when the last communicated times equal the current times, 0 when the shift was moved after the
  last mail (mails go out once a day at 07:02 local with the previous day's changes), NULL when never mailed.
- `covered_booking_count`, `covered_booking_ids`, `covered_booking_references`, `covered_package_names`, `covered_persons_total`:
  the trips this shift covers, **derived** as bookings (option or confirmed) with a line on the same location whose window
  overlaps the shift. Skipper shifts on vessels are rarely linked to a booking in Recras, so use these instead of `booking_id`
  for "which trips did this skipper sail".
- `staff_id` is the id of the `personeel` row in `flattened_contacts`; `staff_customer_contact_id` is the same person's
  `klant` row when it could be linked by e-mail (see `flattened_contacts.twin_*`).

### `flattened_staff_planning_notifications` — one row per shift line in a planning mail

Recras mails each staff member a daily digest "Wijzigingen in de personeelsplanning" (07:02 local) listing the shifts that were
added, changed or cancelled the day before. This table is the **communicated history** of shifts: `contact_moment_id`,
`staff_id`/`staff_name`, `sent_at` (UTC), `change_type` (`new`, `changed`, `cancelled`), `shift_date` (local day as printed),
`begin_at`/`end_at` (UTC), `previous_begin_at`/`previous_end_at` (for changes: the times before, from "was 18:00"),
`status` (as printed, lower-cased; NULL for cancelled), `matched_shift_id` + `matched_shift_status`/`_begin_at`/`_end_at`
(the current shift it refers to), `match` (`exact` | `date` | NULL — see the rule above; staff can have overlapping shifts,
so anything looser would be guesswork), `position` (order within the mail).

- A shift that was moved twice between two mails shows only the net change; a move after the last mail is invisible here but
  shows as `notification_in_sync = 0` on `flattened_shifts`.
- The parsed text of every mail is also in `flattened_contact_moments.message_text` (`is_planning_mail = 1`).


## Always-apply filters

- `deleted_at IS NULL` on every table unless you explicitly analyse removed records.
- Exclude cancelled bookings for revenue/volume questions: `status <> 'geannuleerd'`. Information
  requests (`informatie`, `interesse`) and options (`optie`) are not confirmed business; the
  confirmed statuses are `reservering`, `definitief`, `gaande` (ongoing) and `voltooid` (completed).
  State which statuses you included.
- Staff contacts (`contact_type = 'personeel'`) and suppliers are not customers: filter
  `contact_type = 'klant'` for customer analyses.

## Enums and conventions

- Booking `status`: `informatie`, `interesse`, `optie`, `pending_online`, `reservering`, `definitief`,
  `gaande`, `voltooid`, `geannuleerd` (Dutch; information, interest, option, pending online payment,
  reservation, confirmed, ongoing, completed, cancelled).
- Invoice statuses in `invoice_statuses`: `concept` (draft), `verzonden` (sent, unpaid),
  `deels_betaald` (partially paid), `betaald` (paid).
- All `DateTime` columns are UTC; `date` columns are calendar dates as Recras shows them.
- Amounts are in the instance currency (EUR); `*_incl_vat` includes VAT.
- Text is Dutch (package names, customer types, subjects).
- Count columns are `UInt32` and never NULL; sums/dates over empty sets are NULL.

## Gotchas

- `cost_items_amount` excludes VAT and discounts; `cost_total_incl_vat` is the authoritative booking value.
- `invoice_total_incl_vat` can exceed the booking value when invoices were credited and re-issued;
  check `invoice_statuses` and `outstanding_amount`.
- `booking_id` on contact moments is only known for about half of the moments (mails sent from a
  booking); customer-level communication is better analysed through `contact_id`.
- Bookings and invoices without a known customer row (deleted contacts) have NULL `customer_*` columns.
- Row counts: thousands of bookings/contacts/shifts, tens of thousands of contact moments. Queries are
  capped at 500 rows and 30 seconds; aggregate instead of listing.

## Example questions

- Revenue per month: `SELECT toStartOfMonth(date) AS month, sum(cost_total_incl_vat) FROM flattened_bookings WHERE deleted_at IS NULL AND status IN ('definitief','gaande','voltooid') GROUP BY month ORDER BY month`
- Top customers: `SELECT display_name, booking_count, invoice_total_incl_vat FROM flattened_contacts WHERE deleted_at IS NULL AND contact_type = 'klant' ORDER BY invoice_total_incl_vat DESC LIMIT 20`
- Outstanding invoices per customer: `SELECT display_name, outstanding_amount FROM flattened_contacts WHERE outstanding_amount > 0 ORDER BY outstanding_amount DESC`
- Who worked yesterday, in which role and where: `SELECT staff_name, qualification_name, location_name, begin_at, end_at, recorded_hours FROM flattened_shifts WHERE deleted_at IS NULL AND status = 'bevestigd' AND date = yesterday() ORDER BY begin_at`
- Skipper per trip: `SELECT booking_reference, booking_date, staff_name FROM flattened_shifts WHERE deleted_at IS NULL AND qualification_name = 'Schipper' AND booking_id IS NOT NULL ORDER BY booking_date DESC LIMIT 50`
- Confirmed bookings in the next 14 days without a skipper: `SELECT reference, date, package_name, persons, line_location_names FROM flattened_bookings WHERE deleted_at IS NULL AND status IN ('reservering','definitief') AND date BETWEEN today() AND today() + 14 AND covering_skipper_names IS NULL ORDER BY date`
- What a staff member was told about a day versus the current plan: `SELECT staff_name, change_type, sent_at, begin_at, end_at, previous_begin_at, previous_end_at, matched_shift_id, matched_shift_begin_at, matched_shift_end_at, match FROM flattened_staff_planning_notifications WHERE staff_id = 4277 AND shift_date = '2026-10-17' ORDER BY sent_at`
- Shifts moved after the last mail: `SELECT staff_name, date, begin_at, end_at, last_notified_begin_at, last_notified_end_at, last_notified_at FROM flattened_shifts WHERE deleted_at IS NULL AND status = 'bevestigd' AND notification_in_sync = 0 AND date >= today() - 7 ORDER BY date`
- Trips a skipper sailed: `SELECT date, location_name, covered_booking_references, covered_persons_total FROM flattened_shifts WHERE staff_name = 'Timo Heijnen' AND qualification_name = 'Schipper' AND deleted_at IS NULL AND status = 'bevestigd' ORDER BY date DESC LIMIT 30`
- One person across contact types: `SELECT id, contact_type, display_name, twin_contact_id, twin_match FROM flattened_contacts WHERE person_key = 'tess schroor' AND deleted_at IS NULL`
- Staff hours per vessel per month: `SELECT toStartOfMonth(date) AS month, location_name, sum(recorded_hours) AS worked, sum(planned_hours) AS planned FROM flattened_shifts WHERE deleted_at IS NULL AND status = 'bevestigd' GROUP BY month, location_name ORDER BY month, worked DESC`
- Planned vs recorded per person: `SELECT staff_name, count() AS shifts, sum(planned_hours) AS planned, sum(recorded_hours) AS recorded, avg(hours_difference) AS avg_difference FROM flattened_shifts WHERE deleted_at IS NULL AND status = 'bevestigd' AND date >= today() - 90 GROUP BY staff_name ORDER BY recorded DESC`
- Communication load per staff member: `SELECT staff_name, count() FROM flattened_contact_moments WHERE created_at >= now() - INTERVAL 90 DAY GROUP BY staff_name ORDER BY count() DESC`
