Compare commits

...
Author SHA1 Message Date
OpenClaw 96ec0c2411 fix(economic): sanitize user-input fields to prevent 400 errors
E-conomic API returns HTTP 400 when text-line descriptions contain certain
characters. The most common case is '/' in the order reference field,
which causes the entire draft-invoice export to fail.

This change adds a single sanitizer class (economic_export_sanitizer) that
handles all user-input fields flowing into e-conomic:

  - sanitizeTextLine() — for plain text lines (reference, notes, po, reg_*, etc.)
  - sanitizeProductNumber() — for product identifiers
  - sanitizeProductDescription() — for product-line descriptions
  - sanitizeForEconApi() — catch-all

Sanitization rules:
  - '/' is replaced with '-' (the reported 400 trigger)
  - Control characters (\x00-\x1F except \t and \n) are stripped
  - Tab and newline characters collapse to a single space
  - Whitespace is normalized and trimmed
  - Lengths capped (text 250, product 50, description 500) with '...' suffix

Applied to all vulnerable fields in economic_invoice_draft.php:
  - order.po
  - order.reference (PRIMARY FIX for the reported issue)
  - order.notes
  - order.reg_1/2/3
  - order_item.reference
  - order_item.notes
  - product.description
  - product.productNumber
  - department_name

Test coverage:
  - 31 unit tests with 45 assertions
  - All edge cases (null, empty, control chars, multibyte, very long)
  - Lint and test suite both pass

Refs: TRU-189, TRU-190, TRU-191, TRU-192, TRU-193, TRU-194, TRU-196
2026-08-17 10:13:46 +00:00
935b2d58ce fix(api): remove broken Coolify cron-worker auto-deploy (#389)
## Summary

The Coolify-based auto-deployment of a separate `cron` worker app after
every API deploy was never reliable. This PR removes the ~800 lines of
dead auto-deploy logic from `release_manager.php` while keeping the
underlying cron mechanism (`cron_worker.php`, `cron_scheduler.php`, the
docker-compose `cron-worker` service) intact.

## Changes

- **`release_manager.php`** (-818 lines)
- Removed 19 private methods: `deployCronWorker*`, `cronWorker*`,
`cronWorkerAutoprovision*`, etc.
- Removed 3 constants: `CRON_WORKER_APP`, `CRON_WORKER_START_COMMAND`,
`CRON_WORKER_DESIRED_COUNT`
- Kept `cronWorkerStatus()` but rewrote as a direct DB query (no Coolify
dependency)
- **`tests/Unit/ReleaseManager/ReleaseManagerTest.php`** (-208 lines,
removed 9 cron-worker tests)
- **`tests/Unit/Cron/CronWorkerWiringTest.php`** (rewritten — now
asserts removed wiring is GONE)
- **`docs/CRON_PLAN.md`** (new — comprehensive plan)

## What replaced the broken auto-deploy

- The cron worker runs as part of the main API docker-compose stack (the
`cron-worker` service is unchanged)
- New verification cron `1bb56ba8-2f3e-4bea-baa2-39801ea88ea8` runs
`/workspace/scripts/verify-api-cron.py` every 5 min
- Alerts to Slack #ai-daily (`C0AM3E43249`) if no fresh heartbeat in 10+
min

## Test results

- 4/4 cron tests pass
- 54/54 ReleaseManager tests pass
- Full Unit suite: **1279 passed** (same 7 pre-existing failures on
master, unchanged)
- `php -l` passes on all modified files

## Plan

See `docs/CRON_PLAN.md` for the full audit, plan, and acceptance
criteria.

🤖 Generated with [OpenClaw](https://docs.openclaw.ai)

---------

Co-authored-by: bugfix <bugfix@truckwash.local>
Co-authored-by: openhands <openhands@all-hands.dev>
2026-08-17 10:16:03 +02:00
Jeppe Bandbugfix 4c6b60c9f2 fix(api): self-healing schema bootstrap on every request (TRU-77 follow-up) (#387)
## Summary

Makes the database **self-healing** — every request auto-runs all
`*_schema_bootstrap::ensureSchema()` after `$db->connect()`. This
catches the "merged-to-master-but-migration-never-applied-to-prod"
failure mode that just bit us with TRU-77 (`invoice_email` column).

## Why

PR #383 added a pre-deploy schema step to `deploy.yml`. Correct, but
requires GitHub secrets (`DEPLOY_SSH_KEY`, `DEPLOY_USER`,
`SMOKE_BASE_URL`) that aren't set on the `api` repo yet. Until those
secrets exist, the pre-deploy step is skipped and migrations never reach
production. Result: API still references `invoice_email` but the column
doesn't exist → `Unknown column 'invoice_email' in 'SELECT'`.

## Fix

- New class `classes/schema_bootstrap_runtime.php`:
  - Auto-discovers all `*_schema_bootstrap.php` files in `classes/`
  - Calls `ensureSchema()` on each
  - Memoized per PHP process (`private static bool $ran = false`)
  - One failure does not block others (logged, not thrown)
- New hook in `services/nginx/app/index.php` right after
`$db->connect()`:
  ```php
  try {
      \classes\schema_bootstrap_runtime::runAll();
  } catch (Throwable $e) {
error_log('[schema-bootstrap] runtime::runAll() failed: ' .
$e->getMessage());
  }
  ```
- New test: `tests/Unit/SchemaBootstrapRuntimeTest.php` (3 cases)

## Safety

Each existing `*_schema_bootstrap` is **additive + idempotent**:
- `SHOW COLUMNS` check before any `ALTER`
- `ALTER TABLE ADD COLUMN` only if missing
- Per-class `private static bool $initialized = false` short-circuit
- Errors logged but never break the request

So: first request after deploy adds missing columns. Every subsequent
request hits the in-process `$ran` short-circuit (~microseconds). The
new column then exists, the API works, error goes away.

## Test plan

1. Wait for CI (PHP unit + integration)
2. Merge to master
3. Production auto-deploys (or manual re-deploy if secrets not set)
4. Hit the failing endpoint — first request will auto-migrate, response
should be 200
5. Verify with `GET /api/admin/schema-check` that all columns are
present

## Rollback

If anything goes wrong, revert the merge commit. The runtime class only
auto-discovers files matching `*_schema_bootstrap.php`; removing it
reverts the system to the pre-deploy-step-only behavior.

---

**Closes** the TRU-77 follow-up: the "Unknown column 'invoice_email' in
'SELECT'" error should never recur, because the code now self-heals
regardless of whether the deploy pre-deploy step ran.

---------

Co-authored-by: bugfix <bugfix@truckwash.local>
2026-08-16 23:00:03 +02:00
18092b271e feat(api): schema health check + pre-deploy migration runner (fixes TRU-77 production error) (#383)
## Problem

Production was returning:
```json
{"success":false,"data":{"message":"Internal server error: Unknown column 'invoice_email' in 'SELECT'"}}
```
when authenticating as a superuser. The migration that adds
`users.invoice_email` was merged to master in api#381 but never applied
to the production database.

## Fix

- New `GET /api/admin/schema-check` endpoint — returns 503 with explicit
list of missing columns if any are absent (instead of a generic 500)
- `scripts/run-schema-bootstraps.php` — auto-discovers and runs every
`*_schema_bootstrap` class on the live database (additive, idempotent)
- `scripts/schema-health-check.php` — CLI tool for the same check, used
by deploy pipelines
- New Pest contract test `SchemaHealthCheckTest` — verifies the test DB
has every required users column and the schema-check endpoint works
- `deploy.yml`: pre-deploy step runs the bootstrap runner, smoke test
also runs the schema check, Slack alert on failure

## What this prevents

- Future migrations being merged without being applied to production
- Silent failures (generic 500) when a column is missing
- Repeated manual investigation of the same root cause

Refs: TRU-77 (the original bug), api#381 (the original PR)

---------

Co-authored-by: Jeppe B <jeppe@copenhagentruckwash.io>
Co-authored-by: bugfix-subagent <bugfix-subagent@truckwash.local>
Co-authored-by: OpenClaw Bugfix Agent <bugfix@openclaw.local>
2026-08-16 22:30:03 +02:00
Jeppe Bandbugfix 76ad696691 docs: mark pen-test plan as CANCELLED (TRU-80, no budget approved) (#386)
## Summary

Marks the pen-test plan document as **CANCELLED** per Jeppe's
instruction 2026-08-16 20:00 UTC.

External pen-test engagement is **not** happening at this time (no
budget approved). The plan document is kept as a planning artefact for
future reference, but explicitly bannered as CANCELLED so future agents
and engineers do not assume this is an active project.

## Changes

- Added  CANCELLED banner to the top of
`documentation/security/pen-test-plan.md`
- Banner includes: status, reason, meaning, owner, and how to re-open in
the future
- Original content preserved below the banner (296 lines → 304 lines
with banner)

## Context

- TRU-80 (Linear): remains in **Done** state (planning artefact
complete, execution not authorised)
- Qodana Cloud: remains active (no workflow changes)
- GitHub Dependabot + secret scanning: remain active (free tier)
- This PR supersedes PR #385 (which was rolled back because it also
removed Qodana by mistake)

## Checklist

- [x] No external vendor will be engaged
- [x] No workflow changes
- [x] No secret removals
- [x] Original plan content preserved

---------

Co-authored-by: bugfix <bugfix@truckwash.local>
2026-08-16 22:20:03 +02:00
Jeppe Bandbugfix 80dca6b5f0 docs(security): white-hat pen test plan + engagement scope (TRU-80) (#384)
## Summary

TRU-80 (DRIFT 19): white-hat penetration testing of the platform —
action
required was to *plan and schedule* the engagement and define scope and
budget. This PR delivers the planning artefact.

## What this PR adds

- `documentation/security/pen-test-plan.md` — full engagement plan:
  - **Scope (in):** API (116 route files + Stripe / Limble / Scanner /
    Edge Gateway / Bird / Self-Serve Studio modules), pleno-vue web SPA,
    Capacitor iOS/Android mobile, infra & cross-cutting (TLS, headers,
    subdomains).
  - **Out of scope:** third-party SaaS internals (Stripe, Economic,
    Shelly, Limble, WP), OT/physical, DoS, social engineering,
    transitive-dep audit.
  - **Methodology:** OWASP ASVS L2 (stretch L3 on auth + payment), WSTG,
    MASVS, 8 phases over ~12 vendor-days.
  - **Rules of engagement**, deliverables, daily standup channel,
    re-test terms.
- **Budget:** 180 000 – 220 000 DKK + 25 000 retainer (mid-tier vendor),
    with boutique and Big-4 tiers for comparison. Total envelope with
    contingency ≈ 230 000 DKK.
  - **Schedule:** vendor RFP late Aug, engagement week 39 (2026-09-22),
    final report mid-Oct, re-test mid-Nov 2026.
  - **Pre-engagement hardening checklist** for engineering to land in
    parallel (HSTS, CSP, cookies, CSRF, webhook signature verification,
    rate-limits, SCA in CI, Capacitor WebView hardening, secrets audit).
    Doubles as re-test acceptance criteria.
  - **Open questions** for management (budget cap, contract owner,
    language, retainer approval, scope trim).
- `documentation/security/README.md` — index for future security
    artefacts. Per convention, raw pen-test reports stay out of the
    public repo; only planning docs and re-test acceptance letters are
    committed.

## Why a docs PR, not code

TRU-80 is a planning task (DRIFT 19), not a code defect. The deliverable
is the engagement plan itself so management can sign off on budget and
timeline. Once approved, the actual engagement will be a separate SOW
with the selected vendor.

## Test plan

- [x] Plan reviewed against the issue description
  (Plan + schedule + scope + budget).
- [x] Branch name follows `fix/tru-80-<short-slug>` convention.
- [x] Commit message references TRU-80.
- [ ] Management sign-off on §6 budget and §6.3 schedule.
- [ ] Vendor RFP and selection (separate Linear sub-tasks to be opened
      off this plan).

## Linear

- Closes TRU-80 (planning deliverable for DRIFT 19).
- After merge, follow-up issues will be opened for: vendor RFP, vendor
  selection, contract / NDA, pre-engagement hardening checklist items
  (§7 of the plan).

Refs: https://linear.app/truck-wash-aps/issue/TRU-80

Co-authored-by: bugfix <bugfix@truckwash.local>
2026-08-16 21:46:03 +02:00
7c4acc636c fix(api): post new-booking Slack notifications only for pickups (TRU-106) (#378)
## Summary

SENERE 14 / **TRU-106**: only PICKUP bookings should post a new-booking
notification to the department Slack channel. Drop-off bookings
(pickup_bool = 0) are now silently filtered out. SMS and email delivery
paths are unaffected.

## Change

Minimal, non-refactor:

- New `classes\slack::send_new_booking_notification(...)` that wraps
`format_new_booking` + `send_webhook_message` and short-circuits when
`pickup_bool === false`. Returns bool (sent vs. filtered).
- Two call sites in `objects/bookings_o.php` (`addOrUpdate` +
`notifyNewBooking`) updated to use the new wrapper. Same arguments, no
other behavior changes.
- Other Slack notification types (customer registration, internal
department goal progress, unfulfilled bookings) are deliberately
untouched.

## Tests

New Pest test `tests/Unit/Slack/SlackNewBookingPickupFilterTest.php`:

- pickup -> notification sent (one webhook call, message contains the
booking id)
- drop-off -> no notification, no log entry
- no webhook configured -> no notification
- webhook URL never appears in log payload

PHP isn't installed in this sandbox; the test was code-reviewed against
the existing `SlackCustomerRegistrationWebhookTest` pattern (subclass +
it()/expect()). Please run `./vendor/bin/phpunit
tests/Unit/Slack/SlackNewBookingPickupFilterTest.php` on CI / locally to
confirm.

## Risk

Low. Adds an early-return filter inside a new method; existing call
sites already pass pickup_bool as a boolean. No DB schema change, no new
dependency, no config file change.

Closes TRU-106

---------

Co-authored-by: backend-subagent <agent@openclaw.local>
Co-authored-by: Jeppe B <jeppe@copenhagentruckwash.io>
Co-authored-by: OpenClaw Bugfix <bugfix@openclaw.local>
Co-authored-by: Truck Wash Bugfix Bot <bugfix@truckwash.local>
2026-08-16 21:09:10 +02:00
Jeppe B 34df80530c feat(api): product merging infrastructure for SF (TRU-94) (#379)
Auto-merged by cron with review-gate (trivial change, no critical path).
2026-08-16 20:45:10 +02:00
3d0a8eeae7 feat(api): add optional invoice_email field for customers (TRU-77) (#381)
## Summary

Adds an optional `invoice_email` (Danish: *faktura email*) field to
customers, so e-conomic can deliver invoices to a dedicated accounting
mailbox instead of the customer's primary email.

Linear: **TRU-77** (DRIFT 16)

## Changes

- **Migration** (additive, via existing schema_bootstrap pattern)
- New `customer_invoice_email_schema_bootstrap` adds the `invoice_email
VARCHAR(255) NULL` column to `users` after `wash_certificate_email`.
Idempotent — skips when the column already exists.

- **Domain object — `objects/users_o.php`**
  - New `invoice_email` object property.
- `getInvoiceEmail()` returns the dedicated address or falls back to the
primary `email`.
- `getInvoiceEmailOverride()` returns only the explicit override (no
fallback).
- `setInvoiceEmail($email)` validates and writes the value; `null`/empty
clears it.
- `add($customer_number, $password, $role, ?$invoice_email = null)` now
accepts the optional field and persists it.
- The user payload output now exposes `invoice_email` and
`invoice_email_fallback`.

- **API — `routes/usersRoute.php`**
- `POST /users` accepts an optional `invoice_email`, validated before
insert.
- `PUT /users` accepts `invoice_email` (including null/empty to clear)
on existing users.

- **Customer mass import — `classes/customer_mass_import_service.php`**
  - Payload now accepts `invoice_email`.
- `normalizeInvoiceEmail()` rejects malformed addresses before any
e-conomic call.
- `resolveInvoiceEmail()` / `resolveCreateEmail()` route the e-conomic
customer email to the dedicated address when set, otherwise the primary
`email` (with the existing `jb@truckwash.dk` fallback when neither is
provided).
  - `syncLocalCustomer()` persists `invoice_email` on the local user.
  - `import()` result now includes the resolved `invoice_email`.

- **Tests — `tests/Unit/Customers/CustomerInvoiceEmailTest.php` (new)**
  - Schema bootstrap adds the column when missing.
  - Schema bootstrap is a no-op when the column already exists.
  - Schema bootstrap skips when the `users` table is not present.
  - e-conomic customer email is set to `invoice_email` when provided.
- e-conomic customer email falls back to `email` when `invoice_email` is
omitted.
  - Invalid `invoice_email` is rejected before any e-conomic call.

## Backwards compatibility

- The column is nullable; existing rows are unaffected.
- The `add()` signature is additive (new optional parameter with default
`null`).
- The route payloads ignore `invoice_email` unless supplied, so no
client change is required.

## Linear

- TRU-77 (DRIFT 16: "Add 'faktura email' field to customer creation
form")

---------

Co-authored-by: Jeppe B <jeppe@copenhagentruckwash.io>
Co-authored-by: OpenClaw Bugfix Bot <openclaw-bot@truckwash.dk>
Co-authored-by: bugfix sub-agent <bugfix@openclaw.local>
2026-08-16 18:58:05 +02:00
Jeppe BOpenClaw Backend AgentJeppe Bjeppemaxclaw[bot] <bot@jeppemaxclaw.local>Bugfix Subagent
60222a7d91 fix(api): clarify user-invoice PUT validation so customers can invoice (TRU-128) (#382)
## Summary

Fixes **TRU-128** ("Jeg kan ikke fakturere") — a customer in
#afdelingsansvarlige could not invoice because the customer-facing
invoice PUT endpoint returned a misleading 400 error.

## Root cause

`PUT /collected-invoices` in
`services/nginx/app/routes/userInvoicesRoute.php` had two related bugs:

1. **Misleading error message** — the 'both fields missing' guard
errored with
   `'Missing required parameters: po_number, closed_at'`, which reads as
   if BOTH fields are required. The actual condition (`&&`) only fires
   when neither is set, so only one is required. Customers who tried
   different combinations kept getting the same error and concluded the
   system was broken.

2. **Inconsistent `closed_at` clearing** — the 'forbidden closed_at for
   non-superusers' guard fired for ANY present `closed_at` key,
   including `null` and `""`. That blocked customers from CLEARING a
   previously-set `closed_at`, even though the handler further down
   already nulls the field when it receives an empty value.

## Fix

- Reword the missing-fields error to state the actual contract:
  *"At least one of po_number or closed_at must be provided"*.
- Narrow the forbidden guard to *non-empty* `closed_at`, so customers
  can still pass `null` / `""` to clear a previously-set value.
  The clear-on-null/empty logic further down in the handler is unchanged
  — the guard now matches it.

## Test

`tests/Unit/Invoicing/UserCollectedInvoiceUpdateRouteValidationTest.php`
- Locks in the new error message.
- Locks in the new `$closed_at_is_non_empty` guard shape with the
  `if (self::isParametersSet(['closed_at'])) { ... }` pre-check.
- Locks in the regression: the previous 'any present closed_at -> 403'
  pattern is explicitly asserted to be absent.

## Files changed

- `services/nginx/app/routes/userInvoicesRoute.php`
-
`services/nginx/app/tests/Unit/Invoicing/UserCollectedInvoiceUpdateRouteValidationTest.php`

## Refs

- TRU-128
- Slack: #afdelingsansvarlige (kunde-rapport)

---------

Co-authored-by: OpenClaw Backend Agent <agent@openclaw.ai>
Co-authored-by: Jeppe B <jeppe@copenhagentruckwash.io>
Co-authored-by: jeppemaxclaw[bot] <bot@jeppemaxclaw.local>
Co-authored-by: Bugfix Subagent <bugfix-subagent@openclaw.local>
2026-08-16 18:20:03 +02:00
78b11d0b79 fix(api): route invoices to correct Economic account per-customer (TRU-18) (#380)
## Summary

Fixes **TRU-18 / AUT-14** — `truckwash.io` invoices were being routed to
the wrong Economic (EC) account for some users.

## Root cause

`getUserByCustomerNumber()` in `services/nginx/app/objects/users_o.php`
trusted the **inverse Redis cache** (`customer_number → user_id`)
without verifying that the user it loaded actually owned the requested
EC customer_number in the local DB.

When that cache went stale — e.g. after a `customer_number` re-mapping
on a code path that did not clear the inverse-cache entry —
`getUserByCustomerNumber()` would silently return a **different user**
whose current `customer_number` no longer matched the one the caller
asked for. Downstream invoice export code (`getCustomerEcocomicData()` →
`$customer_economic->customer_number` →
`economic_invoice_draft->setCustomerNumber(...)`) then used that wrong
user's current EC customer_number, and the draft invoice was created
against the **wrong Economic account**.

Because this only manifests when the inverse cache is stale, it surfaces
as "some users" — exactly the symptom reported.

## Fix

Minimal change in `getUserByCustomerNumber()`:

1. After the Redis fast-path loads a user, read the actual
`customer_number` from the DB via `getObjectProperties()`.
2. **Verify** that it equals the requested `$customer_number`.
3. If not, the inverse cache is stale: clear it
(`clear_user_id_from_customer_number`) and re-fetch via the recursive
call, which now falls through to the authoritative `SELECT id FROM users
WHERE customer_number = ?` DB query.

The DB path was always correct (it filters by exact `customer_number`);
the bug was exclusively in the unchecked Redis fast-path.

## Regression test

`tests/Unit/Users/GetUserByCustomerNumberStaleCacheTest.php` — wiring
tests that assert the verification + cache-clear + recursive re-fetch
are present, plus that the DB lookup path is the source of truth.
Prevents the regression from reappearing silently.

## Test run

PHP is unavailable in the sandbox, so the new test has not been executed
locally. It is a pure wiring test (string assertions on the source file)
and will be verified by CI on PR open.

## Out of scope

- No change to `openclaw.json`, deployment config, or any other config
files.
- Auto-merge is intentionally **not** enabled — leaving that to the
existing auto-merge cron.
- Existing tests untouched.

## Linear

- TRU-18 will be moved to "In Review" with the PR URL in a follow-up
comment.

🤖 Generated with [MaxClaw](https://maxclaw.ai)

---------

Co-authored-by: TRU-18 backend bot <bot@truckwash.dev>
Co-authored-by: Jeppe B <jeppe@copenhagentruckwash.io>
2026-08-16 16:04:03 +02:00
Jeppe B 55ddabb0ee test(api): lock program-registry contract for TRU-19 (#377)
The api does NOT expose a /programs endpoint by design — program names ("FF Uvs", "10min", "SF", etc.) live on the wash bay hardware itself, not in the api.

This test locks that architecture so any future /programs endpoint must be explicitly added and documented, and so the machine-types endpoint remains reachable as the api-side closest equivalent.

Three assertions:
1. No /programs endpoint exists in any route file (or per-module route file)
2. /department/selfserve/machine-types is wired with the list permission and returns the success() envelope
3. /modules/self-serve/lane/relay/machine_program_picker/{status,set,enable} endpoints exist

Refs TRU-19
2026-08-16 13:00:21 +02:00
16048e2ce3 chore(release): merge develop into master — XL Vask flag text fix + edge-broker health (Aug 15 2026) (#376)
Brings all of the develop branch's commits into master.

## What this contains

The 2 commits on develop that landed during the XL Vask integration
dispatch:

- **PR #373** (TRU-6 / AUT-2) — feat(edge-broker): expose lastActivityAt
on /api/health (AUT-2/TRU-6)
- **PR #375** (TRU-49 / AUT-49) — fix(api): include wash_id in
xlvask_missing_order_link flag text (AUT-49/TRU-49)

## Why

The XL Vask integration dispatch via the OpenSymphony orchestrator
(MiniMax M3) produced 2 api-side fixes:
- **PR #373** — adds `lastActivityAt` to the api health endpoint so
operators can see if the edge-broker has processed any requests
recently.
- **PR #375** — the actual root-cause fix for the user-reported symptom
"XL Vask-registreringen er hverken ignoreret eller knyttet til en ordre
i den valgte periode doesn't show the wash". The bug was in
`messageParts()` for the `xlvask_missing_order_link` arm — the link text
was hard-coded to 'XL Vask wash' instead of using the actual wash_id.
This PR makes the link identify the wash it points to.

## Verification

Both source PRs passed:
- Required CI (PHP unit, PHP integration, PHP api, PHP legacy, edge
broker, edge agent, edge gateway backend)
- The api ruleset allows squash merges

## Notes

- The pleno-vue repo has its own equivalent develop→master PR (#312)
with the 9 UI fixes (component, i18n, and a Playwright E2E).

---------

Co-authored-by: Jeppe <jeppe@copenhagentruckwash.io>
Co-authored-by: openhands <openhands@all-hands.dev>
2026-08-16 09:08:03 +02:00
43 changed files with 3273 additions and 1158 deletions
+167
View File
@@ -0,0 +1,167 @@
name: Deploy to Hetzner (staging)
on:
push:
branches: [master]
workflow_dispatch:
inputs:
reason:
description: 'Reason for manual deploy'
required: false
default: 'manual'
concurrency:
group: deploy-${{ github.repository }}
cancel-in-progress: false
env:
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
jobs:
test-and-deploy:
name: CI + Deploy
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Show commit info
run: |
echo "Repo: ${{ github.repository }}"
echo "Branch: ${{ github.ref }}"
echo "Commit: ${{ github.sha }}"
echo "Actor: ${{ github.actor }}"
# === CI (phpunit / vitest) runs here via repo's existing CI config ===
# (Most of our repos already have a "Required CI" check; this section
# would invoke that. If your repo doesn't have a CI workflow, the
# required-check on the branch will block this workflow's deploy step.)
- name: Setup SSH
uses: webfactory/ssh-agent@v0.9.0
with:
ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}
- name: Add host key
run: |
mkdir -p ~/.ssh
ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts 2>/dev/null
- name: Pre-deploy snapshot
id: pre
run: |
ssh "$DEPLOY_USER@$DEPLOY_HOST" '
set -e
cd /opt/${{ github.event.repository.name }}
git rev-parse HEAD > /tmp/last_deploy_sha
echo "PRE_SHA=$(cat /tmp/last_deploy_sha)"
echo "pre_sha=$(cat /tmp/last_deploy_sha)" >> $GITHUB_OUTPUT
'
- name: Deploy
id: deploy
run: |
ssh "$DEPLOY_USER@$DEPLOY_HOST" '
set -e
cd /opt/${{ github.event.repository.name }}
git fetch origin master
git reset --hard origin/master
# PHP repos: composer install + clear cache
if [ -f composer.json ]; then
composer install --no-dev --optimize-autoloader --no-interaction
php artisan cache:clear || true
php artisan config:cache || true
# Restart php-fpm if used
sudo systemctl reload php8.2-fpm || true
fi
# Node repos: npm ci + build
if [ -f package.json ]; then
npm ci --ignore-scripts
npm run build
# Restart node service
sudo systemctl reload pleno-vue || sudo systemctl reload nginx || true
fi
# Restart generic services
sudo systemctl reload nginx || true
echo "Deploy complete: $(git rev-parse --short HEAD)"
'
- name: Pre-deploy schema check (run all *_schema_bootstrap)
id: pre_schema
run: |
echo "Running schema bootstraps against the live database…"
# Idempotent — adds missing columns, never drops anything.
# Catches the "Unknown column 'invoice_email' in 'SELECT'"
# production failure mode (TRU-77) where migrations were
# merged to master but never applied to the live DB.
php scripts/run-schema-bootstraps.php
echo "Schema bootstraps complete."
- name: Alert Slack if schema-check fails (pre-deploy)
if: failure()
run: |
php scripts/schema-health-check.php > /tmp/schema.json 2>&1 || true
msg=$(jq -r '"Schema health FAILED on '$SMOKE_BASE_URL'\nMissing: " + (.missing | join(", "))' /tmp/schema.json 2>/dev/null || echo "Schema check produced no JSON")
curl -sS -X POST -H "Authorization: Bearer $SLACK_BOT_TOKEN" \
-H "Content-Type: application/json; charset=utf-8" \
https://slack.com/api/chat.postMessage \
-d "{\"channel\":\"$AI_DAILY_CHANNEL\",\"text\":\":rotating_light: *${{ github.event.repository.name }} — schema health FAIL\n${msg}\"}"
- name: Smoke test
id: smoke
continue-on-error: true
run: |
chmod +x scripts/smoke-test.sh
./scripts/smoke-test.sh
# Also hit the new admin schema-check endpoint to verify
# no required columns are missing.
echo "::group::Schema health check"
php scripts/schema-health-check.php | tee /tmp/schema-report.json
if [ "$(jq -r .ok /tmp/schema-report.json)" != "true" ]; then
echo "::error::Schema health check FAILED — missing columns:"
jq -r '.missing[]' /tmp/schema-report.json | sed 's/^/ • /'
exit 1
fi
echo "Schema health check OK."
- name: Auto-rollback on smoke failure
if: steps.smoke.outcome == 'failure'
run: |
echo "::error::Smoke test failed — rolling back to ${{ steps.pre.outputs.pre_sha }}"
ssh "$DEPLOY_USER@$DEPLOY_HOST" '
set -e
cd /opt/${{ github.event.repository.name }}
git reset --hard ${{ steps.pre.outputs.pre_sha }}
if [ -f composer.json ]; then
composer install --no-dev --optimize-autoloader --no-interaction
sudo systemctl reload php8.2-fpm || true
fi
if [ -f package.json ]; then
npm ci --ignore-scripts
npm run build
sudo systemctl reload nginx || true
fi
'
- name: Post Slack status
if: always()
uses: slackapi/slack-github-action@v1.27.0
with:
channel-id: ${{ secrets.AI_DAILY_CHANNEL }}
payload: |
{
"text": "${{ job.status == 'success' && '✅' || '❌' }} Deploy *${{ github.repository }}@${{ github.sha[0:7] }}* — ${{ job.status }}\n${{ steps.smoke.outcome == 'failure' && '⚠️ Auto-rolled back' || '✓ Smoke test passed' }}"
}
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
- name: Update Linear issue
if: success() && steps.deploy.outcome == 'success'
run: |
# Find Linear issues in this commit's history and post a comment
# (uses GitHub's auto-link: if PR body contains "TRU-123" it auto-links)
# We skip this here; the OpenClaw cron `f26dfd83` handles Linear updates.
echo "Deploy notification will be picked up by OpenClaw cron."
+115
View File
@@ -0,0 +1,115 @@
# Plan: Remove broken Coolify cron-worker deployment; add reliable 5-min cron
## Audit findings
The "Coolify cron worker flow" is a **dual-deployment mechanism** that:
- Tries to auto-deploy a **separate Coolify "cron" application** every time the API is deployed
- That separate app runs `php index.php run cron-worker` as a long-running process
- Tracks worker heartbeats in a `cron_worker_state` table
The "auto-deploy" part is implemented in `release_manager.php` (~300 lines of
`cronWorker*` methods: `deployCronWorker*`, `cronWorkerAutoprovision*`,
`cronWorkerTarget*`, etc.) and is **broken** because the Coolify API endpoints
for creating a new application for the cron worker are not stable/reliable in
our setup.
Meanwhile, the **actual cron mechanism** (`cron_worker.php`, `cron_scheduler.php`,
`cron_task_registry.php`, and the 20+ scheduled tasks in `modules/*/cron/tasks.php`)
is sound. The Docker compose files already define a `cron-worker` service
that runs the long-running process. The auto-deploy logic is just trying to
maintain a separate Coolify app for the same purpose — and failing.
## The plan
### 1. Remove the broken auto-deploy logic
Delete or no-op the following from `release_manager.php`:
- `cronWorkerStatus()`
- `deployCronWorker()`
- `deployCronWorkerForApiTarget()`
- `deployCronWorkerAfterApiDeployment()`
- `cronWorkerAutoprovisionEnabled()`
- `cronWorkerAutoprovisionRequired()`
- `cronWorkerTarget*()` (5 methods)
- `cronWorkerSummary()`, `cronWorkerHealth()`, `cronWorkerDeploymentReadiness()`
- `cronWorkerMergeIssues()`, `cronWorkerIssue()`
- `cronWorkerDeploymentAgeSeconds()`, `cronWorkerProviderStatus()`
- `cronWorkerDeployContext()`
- `createCronWorkerDeploymentRecord()`, `cronWorkerDeployments()`
- `cronWorkerChannels()`, `cronWorkersForTarget()`
- `cronWorkerSourceFromCronTarget()`
- Constants: `CRON_WORKER_APP`, `CRON_WORKER_START_COMMAND`, `CRON_WORKER_DESIRED_COUNT`, `CRON_WORKER_HEARTBEAT_GRACE_SECONDS`
- The `$result['cron_worker'] = ...` call after API deployment
Keep:
- `cron_worker.php` class (the actual worker)
- `cron_scheduler.php`, `cron_schedule.php`, `cron_task_registry.php`
- `cron_schema_bootstrap.php` and the `cron_worker_state` table
- All 20+ scheduled tasks in `modules/*/cron/tasks.php`
- The `cron-worker` service in `docker-compose*.yml`
- The `cron-worker` case in `cli.php`
### 2. Remove the corresponding tests
- `tests/Unit/Cron/CronWorkerWiringTest.php` — delete or rewrite (only assert things that still exist)
- `tests/Unit/ReleaseManager/ReleaseManagerTest.php` — remove the `cron_worker_*` test cases (~150 lines)
- `tests/Smoke/boolean_normalization_smoke.php` — remove cron_worker reference
### 3. Add a reliable 5-min cron mechanism
Two-layer approach:
1. **Long-running `cron-worker` Docker service** (already in compose) — handles
tasks that need to run frequently (60s intervals, etc.). Started automatically
with the rest of the stack.
2. **System cron / health-check loop** — verifies the cron-worker is alive every
5 min. If no fresh heartbeat in 10 min, alert.
This replaces the broken auto-deploy with a simple, observable contract.
### 4. Add a verification harness
`/workspace/scripts/verify-api-cron.py`:
- Hits the API's `cronWorkerStatus` endpoint
- Reads `cron_worker_state` rows via the public route (or a new `/api/admin/cron-status` endpoint)
- If no fresh heartbeat in 10 min, post to #ai-daily
- Run every 5 min via a new cron job
### 5. Update documentation
- `inventory/self-serve-inventory.md` — remove coolify-cron-worker references
- `openapi.yaml` — remove `cron_worker_status` route documentation
- `routes/cronRoute.php` — remove the coolify-cron-worker endpoints
## Acceptance criteria
- [ ] `release_manager.php` no longer contains `deployCronWorker`, `cronWorkerAutoprovision*`, `cronWorkerTarget*`, `CRON_WORKER_APP`
- [ ] No tests reference removed methods
- [ ] `docker-compose.yml` still has a `cron-worker` service (unchanged)
- [ ] `cronWorkerStatus` route returns 200 with `{"workers":[],"issues":[]}` or similar (not 500)
- [ ] A new cron job runs `verify-api-cron.py` every 5 min
- [ ] Verify script posts to #ai-daily if no heartbeat in 10 min
- [ ] PR created, tests pass, merge
## Risk
- **Removing `deployCronWorker*` could break live deployments** if someone is
actively using the API endpoint to deploy a cron worker. Mitigation: keep the
HTTP route returning a friendly "removed" message instead of deleting it.
- **Removing `cronWorkerStatus()` from the release_manager endpoint** could
break dashboards. Mitigation: replace the route handler with a direct query
to `cron_worker_state` so the response shape is preserved.
## Steps
1. Create a feature branch `fix/remove-coolify-cron-worker`
2. Edit `release_manager.php`: remove the broken methods, replace `cronWorkerStatus` with a direct query
3. Edit `tests/Unit/ReleaseManager/ReleaseManagerTest.php`: remove cron_worker tests
4. Edit `tests/Unit/Cron/CronWorkerWiringTest.php`: drop assertions on removed wiring
5. Edit `routes/cronRoute.php`: keep the status endpoint but call the new direct query
6. Edit `cli.php`: no change needed (cron-worker case still works)
7. Edit `docker-compose*.yml`: no change needed (cron-worker service unchanged)
8. Create `/workspace/scripts/verify-api-cron.py` for the verification harness
9. Add a new cron job `5 * * * *` Europe/Copenhagen that runs `verify-api-cron.py`
10. Add a new endpoint `GET /api/admin/cron-status` that returns the cron state JSON
11. Run the test suite locally
12. Push branch, create PR, get user review
+16
View File
@@ -0,0 +1,16 @@
# Security documentation
This folder holds security-related planning, post-mortems, and pen-test
artefacts for the Truck Wash ApS platform.
| Doc | Purpose | Status |
| --- | --- | --- |
| [`pen-test-plan.md`](./pen-test-plan.md) | TRU-80: scope, methodology, schedule and budget for the next white-hat pen test. | Draft v1, awaiting management sign-off. |
Conventions:
- Pen-test reports and any raw findings live in date-stamped subfolders
(e.g. `2026-q4-pentest/`) and are **never** committed to the public
repository — only the planning docs and re-test acceptance letters are.
- All security work is tracked under the Linear project
*UI Library & Pen Testing*.
+304
View File
@@ -0,0 +1,304 @@
# White-Hat Penetration Test — Plan & Engagement (TRU-80)
> ## ⛔ CANCELLED — DO NOT EXECUTE
> **Status:** Cancelled 2026-08-16 by Jeppe Bundgaard
> **Reason:** No budget approved at this time. The platform continues to rely on free, in-house tools (Qodana Cloud static analysis, GitHub Dependabot, GitHub secret scanning, weekly dependency digests).
> **What this means:** No external pen-test firm is being engaged. This document is kept as a planning artifact for future reference. If/when a budget is approved, re-open TRU-80 and execute per the scope below.
> **Owner:** Jeppe Bundgaard (jeppe@copenhagentruckwash.io)
>
> ---
**Linear:** [TRU-80 — DRIFT 19: White hat pen test (security review)](https://linear.app/truck-wash-aps/issue/TRU-80/drift-19-white-hat-pen-test-security-review)
**Project:** UI Library & Pen Testing
**Priority:** Medium
**Status (this doc):** Draft v1 — ready for engineering + management review
**Author:** bugfix sub-agent (TRU-80)
**Date:** 2026-08-16
---
## 1. Purpose
Define the scope, methodology, deliverables, scheduling, and budget envelope for an
independent white-hat penetration test of the Truck Wash ApS platform. The engagement
is intended to validate the security posture of the customer- and operator-facing
production stack before further public rollout and ahead of any major commercial
expansion (e.g. additional self-serve sites, additional payment integrations).
This document is the planning artefact for TRU-80. It does **not** itself perform
or simulate a pen test — it specifies the engagement so that an external vendor can
be selected and contracted.
---
## 2. Scope (in)
The following systems are **in scope** for the engagement. Coverage is **production
stack only** (no staging is exposed for pen-test unless explicitly noted).
### 2.1 API (PHP / NGINX, `copenhagentruckwash/api`)
- All HTTP(S) routes under `services/nginx/app/routes/` (≈116 route files) and
`services/nginx/app/modules/*/routes/` (multiple modules incl. Stripe, Limble,
Scanner, Self-Serve Studio, Edge Gateway, Bird Control Plane, etc.).
- Authentication / session endpoints, including:
- `usersRoute.php`, `userSecurityRoute.php`, `superuserSecurityRoute.php`,
`subusersRoute.php`, `limitedBackofficeRoute.php`
- `limitedBackofficeLoginGrantService.php` and the backoffice grant flow
- Authorization model: role-based access (customer / sub-user / backoffice /
superuser) and per-customer data isolation.
- Customer & invoice routes: `customerNotes`, `customerDefaultDepartmentRoute`,
`customerCodeDepartmentRoute`, wash certificate, vehicle plate lookup,
collected-invoices, order routes.
- Payment integration: Stripe module (`moduleStripeRoute.php`).
- Economic ERP integration (`economic_endpoint_t.php` trait) — read-only
token handling, invoice push.
- Edge gateway / IoT surface: `moduleEdgeGatewayRoute.php`, `edgegateway.php`,
`shelly.php`, `gateway_shelly_transport.php`, `birdControlPlaneRoute.php`.
- File / media endpoints: `file_server.php` (auth-gated downloads, S3 / local).
- Rate limiting, CORS, CSRF, JWT / session cookie handling, and the underlying
Redis trait (`redis_t.php`).
- WordPress trait / integration (`wordpress_api_object_t.php`) — only as far as
our code consumes it; the upstream WP instance is **out of scope** unless
hosted by us.
- Container/infrastructure: `Dockerfile`, `Dockerfile.coolify-api`, NGINX
config (`nginx.conf`, `apache-ssl.conf`), `docker-compose.prod.yml`,
`coolify` deploy config. Black-box reachable attack surface only.
### 2.2 Pleno-Vue (Vue 3 + Capacitor, `copenhagentruckwash/pleno-vue`)
- Web SPA (`app/`, `index.html`, `dist/`) reachable at the production hostname.
- Mobile builds for Android (`android/`, `build.gradle`, `fastlane/`) and iOS
(`ios/`) packaged via Capacitor (`capacitor.config.ts`).
- API client and token storage in the SPA (where tokens live, at-rest
protection, refresh flow).
- Build-time secrets, env handling (`env.d.ts`, `manifest-checksum.txt`,
`Gemfile` if used for asset signing), the public OpenAPI spec committed at
the root (`openapi.yaml`).
- Capacitor deep-link / universal-link / custom-scheme handling
(`capacitor.config.ts`).
### 2.3 Infrastructure & cross-cutting (in)
- TLS configuration (cert chain, HSTS, cipher suites) on the production
public host.
- HTTP security headers (CSP, X-Frame-Options, Referrer-Policy,
Permissions-Policy, X-Content-Type-Options).
- Subdomain / wildcard exposure (`*.truckwash.dk` style).
- Email & SMS notification paths only as far as they can be abused for
spoofing / phishing of our users (we control the From domain).
### 2.4 Out of scope (explicitly)
- Upstream SaaS providers' own infrastructure: Stripe, Economic, WordPress.com,
Shelly cloud, Limble, Mailgun, etc. We will only test the **integration**,
not the third party itself.
- Internal office LAN, employee laptops, MDT, and physical site hardware
(gate controllers, scanners) — these are covered by a separate physical /
OT scope and **out of scope** for this IT pen test.
- Denial-of-service / load testing.
- Social engineering of Truck Wash staff.
- Source-code review of `node_modules` / vendor dependencies (the engagement
will use SCA tooling to flag known CVEs, but not audit transitive deps).
- Any production data exfiltration — the vendor will be given sanitised or
test accounts and synthetic data only.
---
## 3. Methodology
Industry-standard, manual-led engagement with tooling support. Recommended
methodology base: **OWASP ASVS** level 2 (with a stretch goal of level 3 on
auth + payment) and **OWASP WSTG** for the web/API surface. Mobile builds will
use **OWASP MASVS** as the checklist.
Phases (estimated total: 12 working days of vendor effort, see §6):
1. **Scoping & recon (1 day)**
- Confirm target list, accounts, and rules of engagement.
- Passive recon (DNS, cert transparency, subdomains, public OpenAPI spec).
- Active recon limited to non-destructive fingerprinting.
2. **API pen test (3 days)**
- AuthN/AuthZ boundary testing on every route group in §2.1.
- IDOR / BOLA testing on customer-scoped resources (invoices, plates,
wash certificates, sub-users, customer notes).
- Input validation: SQLi, command injection, SSRF, XXE, path traversal,
deserialisation, header injection.
- Business-logic abuse: free-wash flow, refund / credit flow, coupon /
discount stacking, sub-user privilege escalation.
- Webhook signature validation (Stripe, Edge Gateway, Shelly).
3. **Web SPA pen test (2 days)**
- XSS (reflected, stored, DOM-based) including Vue template injection.
- Token storage, leakage via 3rd-party scripts, postMessage abuse.
- Open-redirect / OAuth misconfig in any SSO flow.
- CSP / SRI effectiveness.
4. **Mobile (Capacitor) review (2 days)**
- Static analysis of the built APK / IPA (Capacitor WebView).
- Insecure WebView settings (`allowFileAccess`, `MixedContentMode`,
custom-scheme handlers).
- Local storage of tokens, biometric bypass if implemented.
- Deep-link / universal-link hijack attempts.
5. **Infrastructure & config (1.5 days)**
- TLS, headers, cookie flags, HSTS preload eligibility.
- NGINX hardening review (based on provided config snapshots).
- Docker / coolify surface only as externally reachable.
6. **SCA / dependency check (0.5 day)**
- `composer.json` and `package.json` SCA scan.
- High-severity known-CVE report only; no deep audit.
7. **Exploitation & PoC (1 day)**
- Build proofs-of-concept for any Critical / High findings.
8. **Reporting & re-test (1 day)**
- Draft report → vendor walkthrough → final report.
- Re-test of fixed findings is scoped separately (see §6).
---
## 4. Rules of engagement (RoE)
- **Window:** business hours Europe/Copenhagen by default; out-of-hours
exploitation only with prior written approval per critical finding.
- **Contact channel:** shared Signal thread + email; vendor given a Slack
guest account in a dedicated `#sec-pentest-2026Q4` channel.
- **Stop conditions:** any finding that risks data loss, payment integrity,
or production gate operation → immediate stop + phone call to on-call.
- **Data handling:** vendor may only use synthetic / test data. No
exfiltration of real customer PII. All artifacts returned or destroyed at
end of engagement (TBD in contract).
- **Coverage of third parties:** the vendor will not test Stripe / Economic
/ Shelly / Limble directly; if a third-party vulnerability is suspected,
we follow responsible-disclosure to the vendor ourselves.
---
## 5. Deliverables
1. **Kick-off doc** (this plan, signed off by both parties).
2. **Daily standup notes** in `#sec-pentest-2026Q4` (one paragraph + new
findings list).
3. **Mid-engagement check-in** at end of phase 3 — informal review of any
Critical / High so we can start patching in parallel.
4. **Final report (PDF + JSON)** including:
- Executive summary, risk heatmap, business-impact narrative.
- Each finding: title, CVSS v3.1, affected asset, steps to reproduce,
screenshots / Burp session, recommended fix, references.
- SCA dependency report as an appendix.
5. **Re-test letter** (separate SOW, see §6).
6. **Knowledge transfer**: 60-min session for engineering on the top 5
findings.
---
## 6. Budget & scheduling
### 6.1 Indicative effort
| Phase | Days | Notes |
| --- | --- | --- |
| 1. Scoping & recon | 1.0 | joint with us |
| 2. API pen test | 3.0 | |
| 3. Web SPA | 2.0 | |
| 4. Mobile (Capacitor) | 2.0 | |
| 5. Infra & config | 1.5 | |
| 6. SCA | 0.5 | tooling-led |
| 7. Exploitation / PoC | 1.0 | |
| 8. Reporting | 1.0 | incl. 1 review round |
| **Total** | **12.0 days** | |
### 6.2 Indicative cost (DKK, ex. VAT)
Pricing varies significantly with vendor. Three realistic budget tiers for
procurement:
| Tier | Daily rate (DKK) | Total (12 d) | Notes |
| --- | --- | --- | --- |
| Boutique / Nordic boutique (e.g. Danish / Swedish) | 12 000 16 000 | **144 000 192 000** | Best fit for our stack size, Danish-language reporting available. |
| Mid-tier international (e.g. NCC, Securix, Pentest People) | 15 000 22 000 | **180 000 264 000** | More brand name, more bureaucracy, stronger report templates. |
| Top-tier / Big-4 style | 25 000 40 000 | **300 000 480 000** | Overkill for current footprint; revisit at Series-A. |
**Recommended envelope: 180 000 220 000 DKK** (mid-tier, 12 days) plus a
**re-test retainer of ~25 000 DKK** (1 day, scheduled 30 days after final
report).
Add ~5 000 DKK contingency for incident-response hours if a Critical is
found mid-engagement.
### 6.3 Schedule (proposed)
- **2026-08-25** — this plan reviewed and signed off by management.
- **2026-08-26 → 2026-09-08** — vendor RFP: shortlist 3 vendors, request
proposals, evaluate.
- **2026-09-09 → 2026-09-15** — contract + NDA + RoE finalisation.
- **2026-09-22 (week 39)** — engagement kick-off.
- **2026-09-22 → 2026-10-07** — on-site / remote testing (2.5 calendar
weeks, vendor working in parallel with their normal cadence).
- **2026-10-08** — draft report.
- **2026-10-15** — final report + walkthrough.
- **2026-11-15** — re-test (retainer).
All dates are **provisional** until a vendor is selected.
### 6.4 Vendor shortlist (candidates to approach)
We will request proposals from at least 3 of the following (final shortlist
to be confirmed with management):
1. **Securix** (DK) — boutique, OWASP ASVS-aligned, good fit for our size.
2. **Pentest People** (UK / EU) — mid-tier, mobile capability.
3. **NCC Group / nCC / NowSecure** (international) — heavier, good brand
for enterprise due-diligence.
4. **Curity** (SE) — strong API / OAuth expertise, fits our auth model.
5. **Deutsche Cyber AG / similar Nordic boutique** — fallback.
Procurement will evaluate on: relevant references (Logistics / IoT / payment),
ASVS/MASVS familiarity, daily rate, lead time, report quality, re-test terms.
---
## 7. Pre-engagement hardening checklist (for engineering, run in parallel)
We should land these before the vendor starts — they reduce noise and let
the vendor focus on real issues:
- [ ] HSTS preload submitted; `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload`
- [ ] CSP `default-src 'self'` baseline, no `unsafe-inline`; report-only first
- [ ] All cookies `Secure; HttpOnly; SameSite=Lax` (or `Strict` for backoffice)
- [ ] CSRF token on every state-changing route; verified for Stripe / Edge
Gateway webhooks
- [ ] Webhook signature verification on Stripe, Shelly, Edge Gateway
- [ ] Rate-limit on auth, password reset, and OTP endpoints
- [ ] Sub-user privilege model re-verified against `subusersRoute.php`
- [ ] File-server (`file_server.php`) path-traversal tests in CI
- [ ] SCA in CI: `composer audit` and `npm audit --omit=dev` blocking
high+ vulns
- [ ] Mobile: `allowFileAccess=false`, mixed content disabled, JS interfaces
removed
- [ ] Secrets: no production keys in repo (`git log -S` audit)
This list is also the basis for re-test acceptance criteria.
---
## 8. Open questions for management
1. Confirm total budget cap (recommend ≤ 220 000 DKK + 25 000 retainer).
2. Confirm legal/procurement owner and contract template.
3. Confirm whether to require a Danish-language final report (recommended).
4. Confirm re-test budget is approved up-front, or per-finding.
5. Confirm we are comfortable with the 12-day estimate, or want a lighter
6-day "API + SPA only" first pass.
---
## 9. References
- OWASP ASVS 4.0 — https://owasp.org/www-project-application-security-verification-standard/
- OWASP WSTG — https://owasp.org/www-project-web-security-testing-guide/
- OWASP MASVS — https://mas.owasp.org/MASVS/
- OWASP API Security Top 10 (2023) — https://owasp.org/API-Security/editions/2023/
- Linear project: *UI Library & Pen Testing* (`acc087b4-b8ce-40c4-bbca-077fd93513a4`)
---
*This document is a planning artefact, not the test itself. Once approved, a
separate SOW will be drafted with the selected vendor and linked from this
issue.*
+1
View File
@@ -7,4 +7,5 @@
<!-- AUTO-GENERATED, DO NOT EDIT -->
<p>Comprehensive API reference generated from the repository root <code>openapi.yaml</code>.</p>
<p>The edge broker's <code>/api/health</code> response additionally exposes a <code>lastActivityAt</code> field (ISO 8601 timestamp). It reports the most recent successful HTTP request handled by the broker container and defaults to the container's start time when no request has been processed yet.</p>
</topic>
@@ -405,6 +405,10 @@ def render_api_reference_topic() -> str:
' title="API Reference" id="API-Reference">\n'
f"\n <!-- {AUTOGEN_NOTE} -->\n"
" <p>Comprehensive API reference generated from the repository root <code>openapi.yaml</code>.</p>\n"
" <p>The edge broker's <code>/api/health</code> response additionally exposes a "
"<code>lastActivityAt</code> field (ISO 8601 timestamp). It reports the most recent "
"successful HTTP request handled by the broker container and defaults to the container's "
"start time when no request has been processed yet.</p>\n"
"</topic>\n"
)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env php
<?php
/**
* Pre-deploy schema bootstrap runner.
*
* Loads and runs every `*_schema_bootstrap` class so the production
* database has all the columns the current code expects. Each
* bootstrap is additive and idempotent — safe to run on every deploy.
*
* Run via:
* php scripts/run-schema-bootstraps.php
*
* Used in .github/workflows/deploy.yml as a pre-deploy step.
*
* When you add a new *_schema_bootstrap class, you don't need to
* edit this file — the runner auto-discovers any class whose name
* ends in `_schema_bootstrap`.
*/
namespace scripts;
// Load the app entry point so $db is wired up the same way as in
// normal request handling.
$index = __DIR__ . '/../services/nginx/app/index.php';
if (!file_exists($index)) {
fwrite(STDERR, "Cannot find app entry point at {$index}\n");
exit(2);
}
require_once $index;
$classesDir = __DIR__ . '/../services/nginx/app/classes';
$bootstraps = glob($classesDir . '/*_schema_bootstrap.php');
if (!$bootstraps) {
fwrite(STDERR, "No *_schema_bootstrap.php files found in {$classesDir}\n");
exit(0);
}
$ran = 0;
$skipped = 0;
foreach ($bootstraps as $file) {
require_once $file;
$base = basename($file, '.php');
$class = "classes\\{$base}";
if (!class_exists($class)) {
fwrite(STDERR, " [skip] {$base}: class not found\n");
$skipped++;
continue;
}
if (!method_exists($class, 'ensureSchema')) {
fwrite(STDERR, " [skip] {$base}: no ensureSchema() method\n");
$skipped++;
continue;
}
try {
$class::ensureSchema();
echo " [ok] {$base}\n";
$ran++;
} catch (\Throwable $e) {
fwrite(STDERR, " [FAIL] {$base}: " . $e->getMessage() . "\n");
exit(1);
}
}
echo "Schema bootstraps complete: {$ran} ran, {$skipped} skipped.\n";
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env php
<?php
/**
* Schema health check — verifies all required DB columns exist.
*
* Run via:
* GET /api/admin/schema-check (returns JSON report)
* php scripts/schema-health-check.php (CLI, exits 0/1)
*
* Lists the columns that the code expects to find in each critical
* table. If a column is missing, the response is 503 (HTTP) or
* exit code 1 (CLI) — clearly distinct from a generic 500.
*
* Add to the list when introducing a new optional column.
*/
namespace scripts;
require_once __DIR__ . '/../services/nginx/app/classes/customer_invoice_email_schema_bootstrap.php';
use classes\customer_invoice_email_schema_bootstrap;
const SCHEMA_REQUIREMENTS = [
'users' => [
'invoice_email', // TRU-77 (added 2026-08-16)
'wash_certificate_email',
'email',
'customer_number',
],
'invoices' => [
'po_number',
'closed_at',
'customer_number',
],
'bookings' => [
'id',
'customer_number',
'department',
],
];
function check_schema(): array
{
global $db;
$report = [
'ok' => true,
'missing' => [],
'tables_checked' => 0,
'columns_checked' => 0,
'timestamp' => date('c'),
];
if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
$report['ok'] = false;
$report['error'] = 'no_db_connection';
return $report;
}
// First: run the schema bootstrap (additive, idempotent) so we
// give the DB a chance to self-heal.
if (class_exists(customer_invoice_email_schema_bootstrap::class)) {
customer_invoice_email_schema_bootstrap::ensureSchema();
}
foreach (SCHEMA_REQUIREMENTS as $table => $columns) {
$report['tables_checked']++;
// Confirm the table itself exists
$tableSafe = str_replace('`', '', $table);
$result = $db->query("SHOW TABLES LIKE '{$tableSafe}'");
if (!$result || (int)$result->num_rows === 0) {
$report['ok'] = false;
$report['missing'][] = "table `{$table}` does not exist";
continue;
}
foreach ($columns as $column) {
$report['columns_checked']++;
$colSafe = str_replace("'", '', $column);
$r = $db->query("SHOW COLUMNS FROM `{$tableSafe}` LIKE '{$colSafe}'");
if (!$r || (int)$r->num_rows === 0) {
$report['ok'] = false;
$report['missing'][] = "{$table}.{$column}";
}
}
}
return $report;
}
// CLI mode
if (PHP_SAPI === 'cli') {
$report = check_schema();
echo json_encode($report, JSON_PRETTY_PRINT) . "\n";
exit($report['ok'] ? 0 : 1);
}
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Generic smoke test for any deployed app.
#
# Usage: ./scripts/smoke-test.sh [base_url]
# Default: https://staging.truckwash.io
#
# Required env vars (set by GitHub Action):
# SMOKE_BASE_URL - base URL to test (default: https://staging.truckwash.io)
#
# Optional env vars:
# SMOKE_TOKEN - bearer token for authenticated checks
# SMOKE_TIMEOUT - curl timeout in seconds (default: 10)
#
# Exits 0 on all-pass, 1 on any failure.
set -euo pipefail
BASE_URL="${SMOKE_BASE_URL:-${1:-https://staging.truckwash.io}}"
TIMEOUT="${SMOKE_TIMEOUT:-10}"
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
FAIL=0
check() {
local name="$1"
local url="$2"
local expected="${3:-200}"
local method="${4:-GET}"
local status
status=$(curl -s -o /dev/null -w "%{http_code}" -X "$method" --max-time "$TIMEOUT" "$url" || echo "000")
if [[ "$status" =~ ^($expected)$ ]] || [[ "$expected" == "2xx" && "$status" =~ ^2 ]]; then
echo -e " ${GREEN}${NC} $name ($status) — $url"
else
echo -e " ${RED}${NC} $name (expected $expected, got $status) — $url"
FAIL=1
fi
}
echo "Smoke test against $BASE_URL"
echo " (timeout ${TIMEOUT}s per check)"
echo
# === Health endpoints (universal) ===
check "health check" "$BASE_URL/healthz" "2xx"
check "ping" "$BASE_URL/api/ping" "2xx"
# === Authentication (should NOT 500) ===
check "login page" "$BASE_URL/login" "2xx"
# === Public endpoints (api repo) ===
check "customer list (public schema)" "$BASE_URL/api/customer" "2xx"
check "kundeoprettelse form" "$BASE_URL/kundeoprettelse" "2xx"
# === Public endpoints (pleno-vue) ===
check "self-serve program picker" "$BASE_URL/self-serve/program" "2xx"
check "vehicle step" "$BASE_URL/self-serve/vehicle" "2xx"
# === Custom 404 should not 500 ===
check "404 page" "$BASE_URL/this-route-does-not-exist" "404"
# === Optional authenticated check ===
if [ -n "${SMOKE_TOKEN:-}" ]; then
check "auth check" "$BASE_URL/api/me" "2xx"
fi
echo
if [ "$FAIL" -eq 0 ]; then
echo -e "${GREEN}✓ All smoke tests passed${NC}"
exit 0
else
echo -e "${RED}✗ Some smoke tests failed${NC}"
exit 1
fi
+8
View File
@@ -189,6 +189,8 @@ export function createBrokerServer(options = {}) {
const browserStreamSessions = new Map();
const gatewayStreamSessions = new Map();
const inflightGatewaySyncs = new Map();
const containerStartedAt = currentTimestamp();
let lastActivityAt = containerStartedAt;
const managerRequest = async (path, body = {}, method = "POST") => {
if (!managerUrl) {
@@ -480,6 +482,7 @@ export function createBrokerServer(options = {}) {
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
lastActivityAt = currentTimestamp();
if (req.method === "GET" && url.pathname === "/api/health") {
jsonResponse(res, 200, {
ok: true,
@@ -488,6 +491,7 @@ export function createBrokerServer(options = {}) {
manager_url_configured: Boolean(managerUrl),
shared_secret_configured: Boolean(sharedSecret),
agents_connected: agents.size,
lastActivityAt,
});
return;
}
@@ -1083,6 +1087,10 @@ export function createBrokerServer(options = {}) {
pendingCommands,
managerUrl,
authMode,
containerStartedAt,
get lastActivityAt() {
return lastActivityAt;
},
},
};
}
+39
View File
@@ -219,6 +219,10 @@ test("broker exposes health and shared-secret diagnostics", async () => {
assert.equal(healthJson.auth_mode, "manager");
assert.equal(healthJson.manager_url_configured, true);
assert.equal(healthJson.shared_secret_configured, true);
assert.equal(typeof healthJson.lastActivityAt, "string");
assert.match(healthJson.lastActivityAt, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
assert.ok(healthJson.lastActivityAt >= broker.state.containerStartedAt);
assert.equal(healthJson.lastActivityAt, broker.state.lastActivityAt);
const invalidSecretResponse = await fetch(`http://127.0.0.1:${port}/api/diagnostics/shared-secret`, {
method: "POST",
@@ -247,6 +251,41 @@ test("broker exposes health and shared-secret diagnostics", async () => {
await broker.close();
});
test("broker updates lastActivityAt after each successful request", async () => {
const broker = createBrokerServer({ authMode: "manager", sharedSecret: "secret", managerUrl: "http://manager.test" });
const address = await broker.listen(0);
const port = address.port;
assert.equal(broker.state.lastActivityAt, broker.state.containerStartedAt);
const firstResponse = await fetch(`http://127.0.0.1:${port}/api/health`);
const firstJson = await firstResponse.json();
const firstActivityAt = broker.state.lastActivityAt;
assert.equal(typeof firstJson.lastActivityAt, "string");
assert.equal(firstJson.lastActivityAt, firstActivityAt);
assert.ok(firstActivityAt >= broker.state.containerStartedAt);
await new Promise((resolve) => setTimeout(resolve, 5));
await fetch(`http://127.0.0.1:${port}/api/diagnostics/shared-secret`, {
method: "POST",
headers: {
"x-edge-broker-secret": "secret",
},
});
assert.notEqual(broker.state.lastActivityAt, firstActivityAt);
assert.ok(broker.state.lastActivityAt > firstActivityAt);
const secondResponse = await fetch(`http://127.0.0.1:${port}/api/health`);
const secondJson = await secondResponse.json();
assert.equal(secondJson.lastActivityAt, broker.state.lastActivityAt);
await broker.close();
});
test("broker bridges browser shell sessions through the connected agent", async () => {
const closedSessions = [];
const broker = createBrokerServer({
@@ -0,0 +1,93 @@
<?php
namespace classes;
/**
* Ensures additive schema for the customer `invoice_email` field
* (TRU-77 / DRIFT 16). The field is optional and stores an
* e-mail address that should receive the customer's invoices
* separately from the customer's primary `email`.
*/
class customer_invoice_email_schema_bootstrap
{
private static bool $initialized = false;
private const TABLE = 'users';
private const COLUMN = 'invoice_email';
public static function ensureSchema(): void
{
if (self::$initialized) {
return;
}
global $db;
if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
return;
}
self::ensureUsersTable($db);
self::ensureInvoiceEmailColumn($db);
self::$initialized = true;
}
private static function ensureUsersTable(object $db): void
{
$db->query(
"CREATE TABLE IF NOT EXISTS users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_number INT NOT NULL,
display_name VARCHAR(255) NULL,
email VARCHAR(255) NULL,
phone_country_code INT NULL,
phone BIGINT NULL,
password VARCHAR(255) NULL,
group_id INT NOT NULL DEFAULT 0,
xlvask_customer_id VARCHAR(255) NULL,
sms_notifications_enabled TINYINT(1) NOT NULL DEFAULT 0,
email_notifications_enabled TINYINT(1) NOT NULL DEFAULT 0,
wash_certificate_email VARCHAR(255) NULL,
invoice_email VARCHAR(255) NULL,
two_factor_enabled TINYINT(1) NOT NULL DEFAULT 0,
two_factor_secret VARCHAR(255) NULL,
created_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
KEY idx_users_customer_number (customer_number),
KEY idx_users_group_id (group_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
);
}
private static function ensureInvoiceEmailColumn(object $db): void
{
if (!self::tableExists($db, self::TABLE)) {
return;
}
if (self::columnExists($db, self::TABLE, self::COLUMN)) {
return;
}
$safeTable = str_replace('`', '', self::TABLE);
$db->query(
"ALTER TABLE `{$safeTable}`
ADD COLUMN " . self::COLUMN . " VARCHAR(255) NULL
AFTER wash_certificate_email"
);
}
private static function tableExists(object $db, string $table): bool
{
$safeTable = str_replace('`', '', $table);
$result = $db->query("SHOW TABLES LIKE '{$safeTable}'");
return $result && (int)$result->num_rows > 0;
}
private static function columnExists(object $db, string $table, string $column): bool
{
$safeTable = str_replace('`', '', $table);
$safeColumn = str_replace("'", '', $column);
$result = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
return $result && (int)$result->num_rows > 0;
}
}
@@ -14,6 +14,10 @@ class customer_mass_import_service
*/
public function import(array $payload): array
{
// TRU-77 / DRIFT 16: ensure the invoice_email column exists before we
// attempt to populate it on a local customer.
customer_invoice_email_schema_bootstrap::ensureSchema();
$normalized = $this->normalizePayload($payload);
$this->assertValidNormalizedPayload($normalized);
@@ -62,9 +66,15 @@ class customer_mass_import_service
}
$normalized['name'] = $this->resolveCreateName($normalized);
$normalized['email'] = $this->resolveCreateEmail($normalized, $warnings);
// TRU-77 / DRIFT 16: resolve the e-conomic delivery address into a
// local variable instead of overwriting $normalized['email']. The
// primary customer email must remain intact for the result payload
// and for downstream local-customer sync; the create call needs the
// dedicated invoice address (or the primary as a fallback) on its
// own.
$createEmail = $this->resolveCreateEmail($normalized, $warnings);
$createResponse = $this->createEconomicCustomer($normalized);
$createResponse = $this->createEconomicCustomer($normalized, $createEmail);
$createdCustomerNumber = $this->extractEconomicCustomerNumber($createResponse);
if ($createdCustomerNumber !== $customerNumber) {
@@ -111,6 +121,7 @@ class customer_mass_import_service
'cvr' => $this->normalizeDigitString($payload['cvr'] ?? null),
'name' => $this->normalizeText($payload['name'] ?? $payload['company_name'] ?? null),
'email' => $this->normalizeEmail($payload['email'] ?? null),
'invoice_email' => $this->normalizeInvoiceEmail($payload['invoice_email'] ?? null),
'ean' => $this->normalizeDigitString($payload['ean'] ?? null),
];
}
@@ -193,6 +204,42 @@ class customer_mass_import_service
return $email;
}
/**
* Normalize the optional dedicated invoice email (TRU-77 / DRIFT 16).
* Empty/whitespace values collapse to null. An explicit non-empty value
* must be a syntactically valid email address; an invalid value is
* rejected to keep invoices from being routed to a malformed address.
*/
protected function normalizeInvoiceEmail(mixed $value): ?string
{
$email = $this->normalizeText($value);
if ($email === null) {
return null;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \RuntimeException('Invalid invoice email address.', 400);
}
return $email;
}
/**
* Resolve the e-mail address that e-conomic should use to deliver
* invoices for the customer (TRU-77 / DRIFT 16). Prefers the dedicated
* `invoice_email` when provided, falling back to the customer's primary
* `email`.
*/
protected function resolveInvoiceEmail(array $normalized, array &$warnings): string
{
if (!empty($normalized['invoice_email'])) {
return (string)$normalized['invoice_email'];
}
if (!empty($normalized['email'])) {
return (string)$normalized['email'];
}
$warnings[] = 'No invoice email was provided, defaulted to jb@truckwash.dk for the new e-conomic customer.';
return 'jb@truckwash.dk';
}
protected function resolveCreateName(array $normalized): string
{
if ($normalized['name'] !== null) {
@@ -209,12 +256,9 @@ class customer_mass_import_service
protected function resolveCreateEmail(array $normalized, array &$warnings): string
{
if ($normalized['email'] !== null) {
return $normalized['email'];
}
$warnings[] = 'No email was provided, defaulted to jb@truckwash.dk for the new e-conomic customer.';
return 'jb@truckwash.dk';
// TRU-77 / DRIFT 16: invoices must be routed to the dedicated
// invoice_email when provided, otherwise to the customer's email.
return $this->resolveInvoiceEmail($normalized, $warnings);
}
protected function searchEconomicCustomersByCvr(string $cvr): array
@@ -229,7 +273,7 @@ class customer_mass_import_service
return is_array($response) ? $response : [];
}
protected function createEconomicCustomer(array $normalized): object
protected function createEconomicCustomer(array $normalized, string $createEmail): object
{
$payload = [
'customerNumber' => (int)$normalized['customer_number'],
@@ -241,7 +285,10 @@ class customer_mass_import_service
'paymentTermsNumber' => 12,
],
'name' => (string)$normalized['name'],
'email' => (string)$normalized['email'],
// TRU-77 / DRIFT 16: the dedicated invoice_email (or the
// primary email as a fallback) is passed in explicitly so the
// caller's $normalized['email'] is never mutated here.
'email' => $createEmail,
'phone' => (int)$normalized['phone'],
'telephoneAndFaxNumber' => (string)$normalized['phone'],
'mobilePhone' => (string)$normalized['phone'],
@@ -396,6 +443,7 @@ class customer_mass_import_service
'cvr' => (string)$normalized['cvr'],
'name' => $customerName,
'email' => $normalized['email'],
'invoice_email' => $normalized['invoice_email'] ?? null,
'ean' => $normalized['ean'],
'action' => $action,
'message' => $message,
@@ -416,6 +464,7 @@ class customer_mass_import_service
$name = $normalized['name'] ?? null;
$email = $normalized['email'] ?? null;
$invoice_email = $normalized['invoice_email'] ?? null;
$phone = $normalized['phone'] ?? null;
$displayName = trim((string)($customer->display_name->value() ?? ''));
@@ -431,6 +480,16 @@ class customer_mass_import_service
}
}
// TRU-77 / DRIFT 16: persist the dedicated invoice email override
// when provided so invoice routing survives subsequent local edits.
if ($invoice_email !== null && $customer->getInvoiceEmailOverride() === null) {
try {
$customer->setInvoiceEmail($invoice_email);
} catch (\Throwable $throwable) {
$warnings[] = 'Unable to update local invoice email: ' . $throwable->getMessage();
}
}
if ($phone !== null && empty($customer->phone->value())) {
try {
$customer->setPhoneNumber((int)$phone);
@@ -0,0 +1,111 @@
<?php
namespace classes;
/**
* Sanitizes user-input fields that are sent to the e-conomic API.
*
* Background: e-conomic returns 400 errors when description fields contain
* certain characters. The known issue is "/" in the order reference field
* (TRU-188), but we sanitize defensively for all such cases.
*
* - sanitizeTextLine(): for plain text lines (reference, notes, po, etc.)
* - sanitizeProductNumber(): for product identifiers
* - sanitizeProductDescription(): for product-line descriptions
* - sanitizeForEconApi(): catch-all for arbitrary user input
*/
class economic_export_sanitizer
{
/** E-conomic soft limit for a single description line. */
public const TEXT_LINE_MAX_LENGTH = 250;
/** E-conomic soft limit for a product description. */
public const PRODUCT_DESCRIPTION_MAX_LENGTH = 500;
/** E-conomic soft limit for a product number. */
public const PRODUCT_NUMBER_MAX_LENGTH = 50;
/** Characters that are illegal in product numbers on most e-conomic setups. */
private const PRODUCT_NUMBER_FORBIDDEN = ['/', '\\', ':', '*', '?', '"', '<', '>', '|', "\0"];
/**
* Sanitize a value for use in a single-line text description.
*
* Transformations (in order):
* 1. Replaces "/" with "-" (the reported 400 trigger)
* 2. Strips control characters (\x00-\x1F) except \t and \n
* 3. Replaces tab with single space
* 4. Collapses newlines into spaces (text lines are single-line)
* 5. Collapses runs of spaces to a single space
* 6. Trims leading/trailing whitespace
* 7. Truncates to $maxLength with "..." suffix if needed
*/
public static function sanitizeTextLine(mixed $value, int $maxLength = self::TEXT_LINE_MAX_LENGTH): string
{
if ($value === null) {
return '';
}
$text = (string)$value;
if ($text === '') {
return '';
}
// 1. Strip control characters except \t and \n
$text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $text);
// 2. Replace tab with single space
$text = str_replace("\t", ' ', $text);
// 3. Collapse newlines to single space (text lines are single-line)
$text = preg_replace('/[\r\n]+/u', ' ', $text);
// 4. Replace forward slashes (the reported 400 trigger)
$text = str_replace('/', '-', $text);
// 5. Collapse runs of spaces
$text = preg_replace('/\s+/u', ' ', $text);
// 6. Trim
$text = trim($text);
// 7. Truncate with ellipsis if too long
if ($maxLength > 3 && mb_strlen($text) > $maxLength) {
$text = mb_substr($text, 0, $maxLength - 3) . '...';
} elseif (mb_strlen($text) > $maxLength) {
$text = mb_substr($text, 0, $maxLength);
}
return $text;
}
/**
* Sanitize a product number/identifier.
*
* Removes characters that are illegal in product numbers on most
* e-conomic setups (filesystem-unsafe + path separators).
*/
public static function sanitizeProductNumber(mixed $value): string
{
if ($value === null) {
return '';
}
$text = (string)$value;
if ($text === '') {
return '';
}
$text = str_replace(self::PRODUCT_NUMBER_FORBIDDEN, '', $text);
$text = preg_replace('/[\x00-\x1F\x7F]/u', '', $text);
$text = trim($text);
if (mb_strlen($text) > self::PRODUCT_NUMBER_MAX_LENGTH) {
$text = mb_substr($text, 0, self::PRODUCT_NUMBER_MAX_LENGTH);
}
return $text;
}
/**
* Sanitize a longer product description.
*/
public static function sanitizeProductDescription(mixed $value): string
{
return self::sanitizeTextLine($value, self::PRODUCT_DESCRIPTION_MAX_LENGTH);
}
/**
* Catch-all sanitizer for any user-input value going to e-conomic.
* Defaults to text-line rules.
*/
public static function sanitizeForEconApi(mixed $value): string
{
return self::sanitizeTextLine($value);
}
}
@@ -1495,6 +1495,7 @@ class invoice_period_flag_service
{
$product = (string)($params['product'] ?? 'Item');
$expectedProduct = (string)($params['expected_product'] ?? 'expected product');
$washId = (string)($params['wash_id'] ?? '');
return match ($definitionKey) {
'price_mismatch' => "{$product} product price differs from expected.",
'customer_rule_restrict_addon_services' => "{$product} violates restricted addon services.",
@@ -1514,7 +1515,9 @@ class invoice_period_flag_service
'duplicate_vehicle_subscription_charge_same_month' => "Duplicate vehicle subscription charges exist in the same month.",
'vehicle_subscription_type_mismatch' => "{$product} does not match the vehicle subscription type {$expectedProduct}.",
'historical_primary_product_mismatch' => "{$product} differs from the registration number's usual product {$expectedProduct}.",
'xlvask_missing_order_link' => "XL Vask wash is neither ignored nor linked to an order in the selected period.",
'xlvask_missing_order_link' => $washId === ''
? 'XL Vask wash is neither ignored nor linked to an order in the selected period.'
: "XL Vask wash {$washId} is neither ignored nor linked to an order in the selected period.",
default => "Automatically detected invoice-period issue.",
};
}
@@ -1541,7 +1544,8 @@ class invoice_period_flag_service
['type' => 'text', 'text' => ' is attached without a wash certificate item.'],
],
'xlvask_missing_order_link' => [
['type' => 'xlvask_usage_log', 'text' => 'XL Vask wash'],
['type' => 'text', 'text' => 'XL Vask wash '],
['type' => 'xlvask_usage_log', 'text' => (string)($params['wash_id'] ?? '')],
['type' => 'text', 'text' => ' is neither ignored nor linked to an order in the selected period.'],
],
default => [],
@@ -33,6 +33,31 @@ class products_schema_bootstrap
);
}
if (!self::columnExists($db, 'products', 'merged_into_product_id')) {
$db->query(
"ALTER TABLE products
ADD COLUMN merged_into_product_id INT NULL DEFAULT NULL
AFTER max_quantity_per_order,
ADD KEY idx_products_merged_into (merged_into_product_id)"
);
}
if (!self::tableExists($db, 'product_merges')) {
$db->query(
"CREATE TABLE IF NOT EXISTS product_merges (
id INT AUTO_INCREMENT PRIMARY KEY,
source_product_id INT NOT NULL,
target_product_id INT NOT NULL,
merged_by_user_id INT NULL,
reason VARCHAR(500) NULL,
merged_at DATETIME NOT NULL,
KEY idx_product_merges_source (source_product_id),
KEY idx_product_merges_target (target_product_id),
UNIQUE KEY uq_product_merges_source (source_product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
);
}
self::$initialized = true;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,82 @@
<?php
namespace classes;
/**
* Self-healing schema bootstrap.
*
* Runs every `*_schema_bootstrap::ensureSchema()` on app start so the
* production database always has the columns the current code expects.
* This catches the "merged-to-master-but-never-applied-to-prod" failure
* mode (e.g. TRU-77 invoice_email) where the deploy pipeline pre-deploy
* step didn't run (missing GitHub secrets, network glitch, etc.).
*
* Each bootstrap is **additive + idempotent**:
* - SHOW COLUMNS check before any ALTER
* - ALTER TABLE ADD COLUMN only if missing
* - Once `ensureSchema()` has been called once for a class, the static
* `$initialized` flag short-circuits subsequent calls
*
* The discovery + run loop itself is memoized per PHP process via
* `self::$ran`, so the cost after the first request is a single
* `class_exists` check (~microseconds).
*
* Errors in a single bootstrap are logged but never throw — a broken
* migration must not 500 every request. A future /api/admin/schema-check
* call will surface the failure.
*/
class schema_bootstrap_runtime
{
/** @var bool Memoization for the discovery+run loop */
private static bool $ran = false;
/** @var string[] Class names that already failed this process (don't retry) */
private static array $failed = [];
public static function runAll(): void
{
if (self::$ran) {
return;
}
self::$ran = true;
$classesDir = __DIR__;
$bootstraps = glob($classesDir . DIRECTORY_SEPARATOR . '*_schema_bootstrap.php');
if (!$bootstraps) {
return;
}
foreach ($bootstraps as $file) {
$base = basename($file, '.php');
$class = "classes\\{$base}";
if (in_array($class, self::$failed, true)) {
continue;
}
try {
if (!class_exists($class)) {
require_once $file;
}
if (!class_exists($class)) {
continue;
}
if (!method_exists($class, 'ensureSchema')) {
continue;
}
$class::ensureSchema();
} catch (\Throwable $e) {
self::$failed[] = $class;
error_log(sprintf(
'[schema-bootstrap] %s failed: %s',
$base,
$e->getMessage()
));
// Intentionally do not throw — a broken migration must
// not 500 every request. The next /api/admin/schema-check
// call (or the next deploy's pre-deploy step) will
// surface the failure.
}
}
}
}
+65 -3
View File
@@ -33,17 +33,17 @@ class slack implements notification_i
public function send_department_booking_notification(int $department_id, $message): self
{
// Get the departments webhook
$webhook = self::get_department_webhook($department_id);
$webhook = static::get_department_webhook($department_id);
// Check if the webhook is empty
if (empty($webhook)) {
throw new \Exception('Department webhook is empty');
}
// Send the notification to the department
self::add_log(self::send_webhook_message($message, $webhook));
self::add_log(static::send_webhook_message($message, $webhook));
return $this;
}
private function get_department_webhook(int $department_id): string|null
protected function get_department_webhook(int $department_id): string|null
{
// Check if the department webhook is cached
$webhook = redis->get_department_webhook($department_id);
@@ -134,6 +134,68 @@ class slack implements notification_i
. "Status: $status";
}
/**
* Send a new-booking notification to the department's Slack webhook.
*
* Filter: only PICKUP bookings trigger a Slack notification. Drop-off
* bookings (pickup_bool === false) are intentionally silenced per
* Mikkel's SENERE 14 / TRU-106 request — drop-offs are noise in the
* channel. Other delivery channels (SMS, email) are unaffected.
*
* Returns true if a Slack message was sent, false if it was filtered
* out (drop-off) or the department has no Slack webhook configured.
*
* @throws \Exception If the department lookup or webhook send fails.
*/
public function send_new_booking_notification(
$id,
$customer_number,
string $wash_type,
string $contact_email,
string $reference_number,
string $regNrTraekker,
string $regNrTrailer,
string $washCertificateEmail,
string $date,
int $department,
bool $pickup_bool,
string $notes,
string $washCertificateStatus,
string $washCertificateUrl,
string $status
): bool {
// TRU-106: drop-off bookings must not post to Slack.
if (!$pickup_bool) {
return false;
}
$webhook = static::get_department_webhook($department);
if (empty($webhook)) {
return false;
}
$message = static::format_new_booking(
$id,
$customer_number,
$wash_type,
$contact_email,
$reference_number,
$regNrTraekker,
$regNrTrailer,
$washCertificateEmail,
$date,
$department,
$pickup_bool,
$notes,
$washCertificateStatus,
$washCertificateUrl,
$status
);
self::add_log(static::send_webhook_message($message, $webhook));
return true;
}
public function send_message(string $string, ?string $module = null): void
{
global $SLACK_DEFAULT_WEBHOOK;
+12
View File
@@ -213,6 +213,18 @@ try {
$response->error($e->getMessage(), 500);
}
// Self-healing schema bootstrap. Runs every *_schema_bootstrap::ensureSchema()
// once per process. Each is additive + idempotent (SHOW COLUMNS check before
// any ALTER), so this is safe on every request. Catches the
// "merged-to-master-but-migration-never-applied" failure mode (e.g. TRU-77
// invoice_email) even when the deploy pipeline pre-deploy step is skipped
// (missing GitHub secrets, network glitch, manual deploy, etc.).
try {
\classes\schema_bootstrap_runtime::runAll();
} catch (Throwable $e) {
error_log('[schema-bootstrap] runtime::runAll() failed: ' . $e->getMessage());
}
try {
release_manager::initializeRequestContext();
$releaseIngressPath = (string)(parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH) ?: '');
@@ -185,45 +185,55 @@ class economic_invoice_draft
$department_name = (new departments_o())->getDepartmentName((int)$order->department_id->value());
// Parse the date of the transaction.
$parsed_date = date('d/m/Y H:i', strtotime($order->created_at->value()));
// Sanitize the department name (could contain "/" or other chars)
$department_name = \classes\economic_export_sanitizer::sanitizeTextLine($department_name, 100);
// Add the text line to the draft invoice
self::addTextLine("[ " . $parsed_date . ' ' . $department_name . ' #' . $order->id . " ]");
// If there's a PO number, add it to the invoice
if ($order->po->value() !== '') {
self::addTextLine('PO: ' . $order->po->value());
self::addTextLine('PO: ' . \classes\economic_export_sanitizer::sanitizeTextLine($order->po->value()));
}
// If there's a reference, add it to the invoice
if ($order->reference->value() !== '') {
$reference_value = $order->reference->value();
if ($reference_value !== '') {
self::addTextLine('Reference:');
// Sanitize the whole reference (handles "/" → "-" per TRU-188)
$reference_sanitized = \classes\economic_export_sanitizer::sanitizeTextLine($reference_value);
// Add "# " in the beginning of each line (If there's more than one line, otherwise we just add the prefix once)
if (str_contains($order->reference->value(), "\n")) {
foreach ( explode("\n", $order->reference->value()) as $line ) {
if (str_contains($reference_sanitized, "\n")) {
foreach ( explode("\n", $reference_sanitized) as $line ) {
self::addTextLine('# ' . $line);
}
} else {
self::addTextLine('# ' . $order->reference->value());
self::addTextLine('# ' . $reference_sanitized);
}
}
// Add the registration numbers (if any)
$line_reg = '';
if ($order->reg_1->value() !== '')
$line_reg .= 'Reg 1: ' . strtoupper($order->reg_1->value());
if ($order->reg_2->value() !== '')
$line_reg .= ', Reg 2: ' . strtoupper($order->reg_2->value());
if ($order->reg_3->value() !== '')
$line_reg .= ', Reg 3: ' . strtoupper($order->reg_3->value());
if ($order->reg_1->value() !== '') {
$line_reg .= 'Reg 1: ' . strtoupper(\classes\economic_export_sanitizer::sanitizeTextLine($order->reg_1->value(), 50));
}
if ($order->reg_2->value() !== '') {
$line_reg .= ', Reg 2: ' . strtoupper(\classes\economic_export_sanitizer::sanitizeTextLine($order->reg_2->value(), 50));
}
if ($order->reg_3->value() !== '') {
$line_reg .= ', Reg 3: ' . strtoupper(\classes\economic_export_sanitizer::sanitizeTextLine($order->reg_3->value(), 50));
}
// Add the line to the invoice (If there's any registration numbers)
if ($line_reg !== '')
self::addTextLine($line_reg);
// If there's a note, add it to the invoice
if ($order->notes->value() !== '') {
$notes_value = $order->notes->value();
if ($notes_value !== '') {
self::addTextLine('Notat:');
// Add "# " in the beginning of each line (If there's more than one line, otherwise we just add the prefix once)
if (str_contains($order->notes->value(), "\n")) {
foreach ( explode("\n", $order->notes->value()) as $line ) {
// Sanitize notes (could contain "/", newlines, special chars)
$notes_sanitized = \classes\economic_export_sanitizer::sanitizeTextLine($notes_value);
if (str_contains($notes_sanitized, "\n")) {
foreach ( explode("\n", $notes_sanitized) as $line ) {
self::addTextLine('# ' . $line);
}
} else {
self::addTextLine('# ' . $order->notes->value());
self::addTextLine('# ' . $notes_sanitized);
}
}
}
@@ -341,26 +351,28 @@ class economic_invoice_draft
// If there's a reference, add it to the line
if ($order_item['reference'] !== '') {
self::addTextLine('Reference:');
// Add "# " in the beginning of each line (If there's more than one line, otherwise we just add the prefix once)
if (str_contains($order_item['reference'], "\n")) {
foreach ( explode("\n", $order_item['reference']) as $line ) {
// Sanitize the reference (handles "/" → "-" per TRU-188)
$item_reference_sanitized = \classes\economic_export_sanitizer::sanitizeTextLine($order_item['reference']);
if (str_contains($item_reference_sanitized, "\n")) {
foreach ( explode("\n", $item_reference_sanitized) as $line ) {
self::addTextLine('# ' . $line);
}
} else {
self::addTextLine('# ' . $order_item['reference']);
self::addTextLine('# ' . $item_reference_sanitized);
}
}
// If there's a note, add it to the line
if (!empty($order_item['notes'])) {
self::addTextLine('Notat:');
// Add "# " in the beginning of each line (If there's more than one line, otherwise we just add the prefix once)
if (str_contains($order_item['notes'], "\n")) {
foreach ( explode("\n", $order_item['notes']) as $line ) {
// Sanitize notes (could contain "/", newlines, special chars)
$item_notes_sanitized = \classes\economic_export_sanitizer::sanitizeTextLine($order_item['notes']);
if (str_contains($item_notes_sanitized, "\n")) {
foreach ( explode("\n", $item_notes_sanitized) as $line ) {
self::addTextLine('# ' . $line);
}
} else {
self::addTextLine('# ' . $order_item['notes']);
self::addTextLine('# ' . $item_notes_sanitized);
}
}
@@ -470,6 +482,9 @@ class economic_invoice_draft
*/
public function addProductLine(string $productNumber, string $description, float $quantity, float $unitNetPrice, int $economic_department_id, int $dimension, float $discountPercentage = 0): void
{
// Sanitize product identifier and description (defense in depth — also done at addLines())
$productNumber = \classes\economic_export_sanitizer::sanitizeProductNumber($productNumber);
$description = \classes\economic_export_sanitizer::sanitizeProductDescription($description);
// We then add a 0 in front of the product number to make sure it's the right one, made by FlexPOS.
// Add a line to the invoice
$line = [
+10 -6
View File
@@ -205,10 +205,12 @@ class bookings_o extends db
$sql = "SELECT * FROM $this->table WHERE id = $id";
$result = $db->query($sql);
if ($db->num_rows($result) === 0) {
// Send a department webhook if the booking is new
// Send a department webhook if the booking is new.
// TRU-106: send_new_booking_notification() filters out drop-offs
// (pickup_bool = 0) so only pickup bookings post to Slack.
$slack = new slack();
try {
$slack->send_department_booking_notification($department, $slack->format_new_booking(
$slack->send_new_booking_notification(
$id,
$customer_number,
$wash_type,
@@ -219,12 +221,12 @@ class bookings_o extends db
$washCertificateEmail,
$date,
$department,
$pickup_bool,
(bool)$pickup_bool,
$notes,
$washCertificateStatus,
$washCertificateUrl,
$status
));
);
} catch (Exception $e) {
// Log the error
$logs = new logs_o();
@@ -313,11 +315,13 @@ class bookings_o extends db
!$deliverSlack // Only send email if slack is not available
);
// Check if the department has a slack webhook
// TRU-106: send_new_booking_notification() filters out drop-offs
// (pickup_bool = false) so only pickup bookings post to Slack.
if ($deliverSlack) {
// Send a notification to the department
$slack = new slack();
try {
$slack->send_department_booking_notification($department->id, $slack->format_new_booking(
$slack->send_new_booking_notification(
$this->id,
$customer_array['customer_number'],
self::formatWashTypeFromServices(json_decode($this->data->value(), true)),
@@ -333,7 +337,7 @@ class bookings_o extends db
$this->washCertificateStatus->value(),
$this->washCertificateUrl->value(),
$this->status->value()
));
);
} catch (Exception $e) {
// Previously this bare call would crash the entire
// notifyNewBooking() flow if Slack returned non-2xx, so
+132
View File
@@ -84,6 +84,12 @@ class products_o extends db
* @var object_property $max_quantity_per_order
*/
public object_property $max_quantity_per_order;
/**
* If non-null, this product has been merged into the product with the given id.
* All read paths should resolve to the target product (see resolveActiveProductId()).
* @var object_property $merged_into_product_id
*/
public object_property $merged_into_product_id;
/**
* The timestamp of when the object was created
* @var object_property
@@ -134,6 +140,7 @@ class products_o extends db
$this->display_in_booking_form = new object_property($this->table, $this->id, 'display_in_booking_form', 'bool', false);
$this->order_priority = new object_property($this->table, $this->id, 'order_priority', 'int', false);
$this->max_quantity_per_order = new object_property($this->table, $this->id, 'max_quantity_per_order', 'int', false);
$this->merged_into_product_id = new object_property($this->table, $this->id, 'merged_into_product_id', 'int', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'string', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'string', false);
}
@@ -227,6 +234,7 @@ class products_o extends db
'display_in_booking_form' => (bool)$this->display_in_booking_form->value(),
'order_priority' => (int)$this->order_priority->value(),
'max_quantity_per_order' => $this->max_quantity_per_order->value() === null ? null : (int)$this->max_quantity_per_order->value(),
'merged_into_product_id' => $this->merged_into_product_id->value() === null ? null : (int)$this->merged_into_product_id->value(),
'created_at' => (string)$this->created_at->value(),
'updated_at' => (string)$this->updated_at->value(),
];
@@ -370,4 +378,128 @@ class products_o extends db
self::requireSelected();
return $this->id === 41;
}
/**
* Returns the product id that should be used for new orders and pricing.
* If this product has been merged into another (merged_into_product_id is set),
* the target id is returned. The merge chain is followed transitively with a
* safety cap to avoid infinite loops.
*/
public function resolveActiveProductId(): int
{
self::requireSelected();
products_schema_bootstrap::ensureTables();
$currentId = (int)$this->id;
$visited = [$currentId => true];
$maxHops = 16;
for ($i = 0; $i < $maxHops; $i++) {
$next = self::fetchMergedInto($currentId);
if ($next === null) {
return $currentId;
}
if (isset($visited[$next])) {
// Cycle detected: stop at the current node rather than spinning.
return $currentId;
}
$visited[$next] = true;
$currentId = $next;
}
return $currentId;
}
/**
* Static helper: given a product id, return the product id it is merged into,
* or null if it is not merged. Performs a single hop (no chain following).
*/
public static function fetchMergedInto(int $productId): ?int
{
global $db;
if (!isset($db) || $productId <= 0) {
return null;
}
$productId = (int)$db->escape_string((string)$productId);
$result = $db->query("SELECT merged_into_product_id FROM products WHERE id = {$productId}");
if ($result === false || !is_object($result) || (int)$result->num_rows === 0) {
return null;
}
$row = $db->fetch_assoc($result);
$merged = $row['merged_into_product_id'] ?? null;
if ($merged === null || $merged === '' || (int)$merged === 0) {
return null;
}
return (int)$merged;
}
/**
* Merge this product into another. The source product keeps its id (and therefore
* its historical order_items references), but reads and new orders will resolve to
* the target product. An audit row is written to product_merges.
*
* Throws \RuntimeException on validation failure.
*/
public function mergeInto(int $targetProductId, ?int $mergedByUserId = null, ?string $reason = null): void
{
self::requireSelected();
products_schema_bootstrap::ensureTables();
global $db, $response;
$sourceId = (int)$this->id;
if ($sourceId === $targetProductId) {
throw new \RuntimeException('Cannot merge a product into itself');
}
if ($targetProductId <= 0) {
throw new \RuntimeException('Invalid target product id');
}
// Target must exist
$targetCheck = $db->query("SELECT id FROM products WHERE id = " . (int)$targetProductId);
if ($targetCheck === false || !is_object($targetCheck) || (int)$targetCheck->num_rows === 0) {
throw new \RuntimeException('Target product does not exist');
}
// Source must not already be merged
$existing = self::fetchMergedInto($sourceId);
if ($existing !== null) {
throw new \RuntimeException("Source product {$sourceId} is already merged into product {$existing}");
}
// Target must not itself be a source (no chains during creation; chain
// resolution is supported at read time, but creating a chain here keeps
// the audit table unambiguous).
$targetIsSource = $db->query("SELECT id FROM products WHERE id = " . (int)$targetProductId . " AND merged_into_product_id IS NOT NULL");
if ($targetIsSource !== false && is_object($targetIsSource) && (int)$targetIsSource->num_rows > 0) {
throw new \RuntimeException('Target product is itself merged into another product; cannot chain merges during creation');
}
$sourceIdEsc = (int)$db->escape_string((string)$sourceId);
$targetIdEsc = (int)$db->escape_string((string)$targetProductId);
$mergedBy = $mergedByUserId === null ? 'NULL' : (string)(int)$mergedByUserId;
$reasonSql = $reason === null ? 'NULL' : "'" . $db->escape_string(mb_substr($reason, 0, 500)) . "'";
$now = date('Y-m-d H:i:s');
$db->query("START TRANSACTION");
try {
$updateSql = "UPDATE products SET merged_into_product_id = {$targetIdEsc} WHERE id = {$sourceIdEsc}";
if (!$db->query($updateSql)) {
throw new \RuntimeException('Failed to update products.merged_into_product_id');
}
$insertSql = "INSERT INTO product_merges (source_product_id, target_product_id, merged_by_user_id, reason, merged_at) VALUES ({$sourceIdEsc}, {$targetIdEsc}, {$mergedBy}, {$reasonSql}, '{$now}')";
if (!$db->query($insertSql)) {
throw new \RuntimeException('Failed to insert product_merges audit row');
}
$db->query("COMMIT");
} catch (\RuntimeException $e) {
$db->query("ROLLBACK");
throw $e;
}
// Refresh local object state
$this->getObjectProperties();
}
}
+88 -1
View File
@@ -44,6 +44,7 @@ class users_o extends db
public object_property $sms_notifications_enabled;
public object_property $email_notifications_enabled;
public object_property $wash_certificate_email; // Optional
public object_property $invoice_email; // Optional - TRU-77 / DRIFT 16
protected array $wash_subscription_transactions;
public object_property $two_factor_secret;
public object_property $two_factor_enabled;
@@ -123,6 +124,7 @@ class users_o extends db
$this->sms_notifications_enabled = new object_property($this->table, $this->id, 'sms_notifications_enabled', 'bool', false);
$this->email_notifications_enabled = new object_property($this->table, $this->id, 'email_notifications_enabled', 'bool', false);
$this->wash_certificate_email = new object_property($this->table, $this->id, 'wash_certificate_email', 'string', false);
$this->invoice_email = new object_property($this->table, $this->id, 'invoice_email', 'string', false);
$this->two_factor_secret = new object_property($this->table, $this->id, 'two_factor_secret', 'string', false);
$this->two_factor_enabled = new object_property($this->table, $this->id, 'two_factor_enabled', 'bool', false);
}
@@ -234,15 +236,27 @@ class users_o extends db
}
public function add(string $customer_number, mixed $password, int $role = 0): void
public function add(string $customer_number, mixed $password, int $role = 0, ?string $invoice_email = null): void
{
global $db;
// Ensure the invoice_email column exists (TRU-77 / DRIFT 16)
\classes\customer_invoice_email_schema_bootstrap::ensureSchema();
// Avoid SQL injection
$customer_number = $db->escape_string($customer_number);
$role = $db->escape_string($role);
// Hash the password
$password = password_hash($password, PASSWORD_DEFAULT);
$password = $db->escape_string($password);
$invoice_email_value = null;
if ($invoice_email !== null) {
$trimmed = trim($invoice_email);
if ($trimmed !== '') {
if (!filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Invalid invoice email address');
}
$invoice_email_value = $db->escape_string($trimmed);
}
}
// Create a new record in the database
$sql = "INSERT INTO $this->table (customer_number, password, group_id) VALUES ('$customer_number', '$password', $role)";
$db->query($sql);
@@ -256,6 +270,11 @@ class users_o extends db
// Set the values of the object properties
$this->getObjectProperties();
if ($invoice_email_value !== null) {
$this->invoice_email->set($invoice_email_value);
}
// Set the default attributes
//$this->addAttribute('invoiceAllOrdersIndividually');
$this->addAttribute('restrictTankCleaning');
@@ -389,6 +408,19 @@ class users_o extends db
if ($user_id !== null) {
$this->id = (int)$user_id;
$this->getObjectProperties();
// BUG FIX (TRU-18 / AUT-14): Verify the loaded user actually owns the
// requested EC customer_number. If the inverse Redis cache
// (customer_number -> user_id) is stale — e.g. because a user's
// customer_number was re-mapped via a code path that did not clear
// this cache — getObjectProperties() will have loaded the user's
// CURRENT customer_number from the DB, which may differ from the
// one we asked for. Without this check, downstream invoice code
// (getCustomerEcocomicData, setCustomerNumber) would use the
// stale user and route the invoice to the wrong EC account.
if ((int)$this->customer_number->value() !== $customer_number) {
self::redisCache()?->clear_user_id_from_customer_number($customer_number);
return $this->getUserByCustomerNumber($customer_number);
}
return $this;
}
@@ -428,6 +460,8 @@ class users_o extends db
'number' => $phone,
],
'email' => $this->email->value(),
'invoice_email' => $this->getInvoiceEmailOverride(),
'invoice_email_fallback' => $this->email->value(),
'notifications' => [
'sms_notifications_enabled' => (bool)$this->sms_notifications_enabled->value(),
'email_notifications_enabled' => (bool)$this->email_notifications_enabled->value(),
@@ -1564,6 +1598,59 @@ class users_o extends db
$this->email->set($email);
}
/**
* Get the optional invoice email for the user.
* Returns the dedicated invoice email when set, otherwise falls back to
* the user's primary email. This is the address e-conomic uses to send
* invoices for the customer (TRU-77 / DRIFT 16).
*/
public function getInvoiceEmail(): string|null
{
self::requireSelected();
$invoice = $this->invoice_email->value();
if ($invoice !== null && trim((string)$invoice) !== '') {
return (string)$invoice;
}
$primary = $this->email->value();
if ($primary !== null && trim((string)$primary) !== '') {
return (string)$primary;
}
return null;
}
/**
* Get the explicit invoice email override, if any. Unlike
* {@see getInvoiceEmail()} this does not fall back to the primary email.
*/
public function getInvoiceEmailOverride(): string|null
{
self::requireSelected();
$invoice = $this->invoice_email->value();
if ($invoice === null) {
return null;
}
$trimmed = trim((string)$invoice);
return $trimmed === '' ? null : $trimmed;
}
/**
* Set the optional invoice email for the user. Pass null/empty to clear.
* @throws Exception If the email address is invalid
*/
public function setInvoiceEmail(string|null $email): void
{
self::requireSelected();
if ($email === null || trim($email) === '') {
$this->invoice_email->set(null);
return;
}
$trimmed = trim($email);
if (!filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Invalid invoice email address');
}
$this->invoice_email->set($trimmed);
}
public function isCustomerBarred(int $customer_number): bool
{
if ($customer_number === 0) {
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace routes;
use classes\authentication;
use classes\response;
use classes\customer_invoice_email_schema_bootstrap;
use traits\route_t;
/**
* Admin / ops endpoints. Currently exposes the schema health check.
*
* The schema health check verifies that all required DB columns exist
* for the routes the code references. If a column is missing (e.g. a
* migration wasn't run on production), the endpoint returns 503 with
* a clear list of missing columns — much more useful than a generic
* 500 with "Unknown column" hidden in the stack trace.
*/
class adminRoute
{
use route_t;
public function run(): void
{
// Schema health check — used by deploy pipelines, monitoring,
// and the cron job. Anonymous (no auth) so it can be hit
// before user login; returns only structural info, no data.
$this->get('/admin/schema-check', function () {
global /** @var response $response */ $response;
// Self-heal: run all schema bootstraps first
if (class_exists(customer_invoice_email_schema_bootstrap::class)) {
try {
customer_invoice_email_schema_bootstrap::ensureSchema();
} catch (\Throwable $e) {
// Bootstrap may fail in environments where $db is
// not yet wired up; report and continue with check
}
}
$report = $this->runSchemaCheck();
$response->setStatus($report['ok'] ? 200 : 503);
$response->setBody(json_encode($report, JSON_PRETTY_PRINT));
});
}
/**
* Returns ['ok' => bool, 'missing' => array, ...].
* If ok=false, the deploy should be blocked.
*/
private function runSchemaCheck(): array
{
global $db;
$report = [
'ok' => true,
'missing' => [],
'tables_checked' => 0,
'columns_checked' => 0,
'timestamp' => date('c'),
'note' => 'If "missing" is non-empty, the migration that adds these columns was not run on the database.',
];
if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
$report['ok'] = false;
$report['error'] = 'no_db_connection';
return $report;
}
$requirements = [
'users' => [
'invoice_email', // TRU-77 (added 2026-08-16, was missing on production)
'wash_certificate_email',
'email',
'customer_number',
],
'invoices' => [
'po_number',
'closed_at',
'customer_number',
],
'bookings' => [
'id',
'customer_number',
'department',
],
];
foreach ($requirements as $table => $columns) {
$report['tables_checked']++;
$tableSafe = str_replace('`', '', $table);
$result = $db->query("SHOW TABLES LIKE '{$tableSafe}'");
if (!$result || (int)$result->num_rows === 0) {
$report['ok'] = false;
$report['missing'][] = "table `{$table}` does not exist";
continue;
}
foreach ($columns as $column) {
$report['columns_checked']++;
$colSafe = str_replace("'", '', $column);
$r = $db->query("SHOW COLUMNS FROM `{$tableSafe}` LIKE '{$colSafe}'");
if (!$r || (int)$r->num_rows === 0) {
$report['ok'] = false;
$report['missing'][] = "{$table}.{$column}";
}
}
}
return $report;
}
}
@@ -88,6 +88,18 @@ class productsRoute
return $parsed;
}
private function routePositiveInt(string $name): int
{
global $response;
$raw = $this->fromRoute($name);
if (!is_string($raw) || !preg_match('/^[1-9][0-9]*$/', $raw)) {
$response->error('Invalid route parameter', 400);
}
return (int)$raw;
}
private function isNullLikeOptionalParameter(mixed $value): bool
{
if ($value === null) {
@@ -548,5 +560,55 @@ class productsRoute
'edit_product' => 'Edit a product'
]
);
// POST /products/:id/merge — merge a product into another.
// Body: { target_id: int, reason?: string }
// The source product is preserved (so historical order_items references remain valid),
// but is marked as merged in the products table. Reads and new orders should follow
// merged_into_product_id to the target. An audit row is written to product_merges.
$this->post('/products/{id}/merge', function () {
global $response;
$this->requirePermission('edit_product');
$user = (new authentication())->get_user();
if (!$user) {
(new logs_o())->add('products', 'global', 1, 0, 'MERGE_PRODUCT', 'No user found, or invalid session');
$response->error('Invalid session', 400);
}
$sourceId = $this->routePositiveInt('id');
$targetId = (int)($response->getRequestParameter('target_id') ?? 0);
if ($targetId <= 0) {
$response->error('target_id is required and must be a positive integer', 400);
}
$reason = $response->getRequestParameter('reason');
if ($reason !== null && !is_string($reason)) {
$response->error('reason must be a string', 400);
}
$source = (new products_o())->select($sourceId);
if (!$source->exists()) {
$response->error('Source product not found', 404);
}
try {
$source->mergeInto($targetId, (int)$user->id, $reason);
} catch (\RuntimeException $e) {
(new logs_o())->add('products', 'global', 3, (int)$user->id, 'MERGE_PRODUCT_FAILED', "source={$sourceId} target={$targetId} error=" . $e->getMessage());
$response->error($e->getMessage(), 400);
}
(new logs_o())->add('products', 'global', 1, (int)$user->id, 'MERGE_PRODUCT', "source={$sourceId} target={$targetId}");
$response->success([
'message' => 'Product merged successfully',
'source_product_id' => $sourceId,
'target_product_id' => $targetId,
'merged_into_product_id' => (int)$source->merged_into_product_id->value(),
]);
},
[
'edit_product' => 'Merge a product into another (preserves historical order references; new orders resolve to the target).'
]
);
}
}
@@ -62,9 +62,21 @@ class userInvoicesRoute
self::requireSameLength($id, self::getParameter('id'));
$is_superuser = $this->hasPermission('superuser');
if (!self::isParametersSet(['po_number']) && !self::isParametersSet(['closed_at'])) {
$response->error('Missing required parameters: po_number, closed_at', 400);
// At least one of po_number or closed_at must be provided. The
// previous message said "Missing required parameters:
// po_number, closed_at" which read as if BOTH were required
// and confused customers trying to invoice (TRU-128).
$response->error('At least one of po_number or closed_at must be provided', 400);
}
if (self::isParametersSet(['closed_at']) && !$is_superuser) {
// Only superusers may set a non-empty closed_at. Customers are
// still allowed to pass an empty/null closed_at to CLEAR a
// previously set value (the field is then set to null below).
$closed_at_is_non_empty = false;
if (self::isParametersSet(['closed_at'])) {
$raw_closed_at = self::getParameter('closed_at');
$closed_at_is_non_empty = ($raw_closed_at !== null && $raw_closed_at !== '');
}
if ($closed_at_is_non_empty && !$is_superuser) {
$response->error('Forbidden: only superusers can update closed_at', 403);
}
// Make sure optional fields are valid
+28 -1
View File
@@ -119,8 +119,19 @@ class usersRoute
if ($role !== 0) {
$this->requirePermission('edit_user_role');
}
// TRU-77 / DRIFT 16: optional dedicated invoice email
$invoice_email = null;
if (isset($data['invoice_email']) && $data['invoice_email'] !== null && $data['invoice_email'] !== '') {
$candidate = trim((string)$data['invoice_email']);
if ($candidate !== '') {
if (!filter_var($candidate, FILTER_VALIDATE_EMAIL)) {
$response->error('Invalid invoice email address', 400);
}
$invoice_email = $candidate;
}
}
// Add the user
(new users_o())->add($data['customer_number'], $data['password'], $role);
(new users_o())->add($data['customer_number'], $data['password'], $role, $invoice_email);
// Log the incident
(new logs_o())->add('users', 'global', 1, $user->id, 'ADD_USER', 'Successfully added a user');
// Return a success message
@@ -193,6 +204,22 @@ class usersRoute
}
// Edit the user
(new users_o())->edit((int)$data['id'], (string)$data['customer_number'], $data['role'], $data['password'], $data['display_name']);
// TRU-77 / DRIFT 16: allow updating the dedicated invoice email
if (array_key_exists('invoice_email', $data)) {
$raw = $data['invoice_email'];
if ($raw === null || $raw === '' || $raw === 'null') {
$targetUser->setInvoiceEmail(null);
} else {
$candidate = trim((string)$raw);
if ($candidate === '') {
$targetUser->setInvoiceEmail(null);
} elseif (!filter_var($candidate, FILTER_VALIDATE_EMAIL)) {
$response->error('Invalid invoice email address', 400);
} else {
$targetUser->setInvoiceEmail($candidate);
}
}
}
// Log the incident
(new logs_o())->add('users', 'global', 1, $user->id, 'EDIT_USER', 'Successfully edited a user with ID: ' . $data['id']);
// Return a success message
@@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
use objects\products_o;
usesApiSuite();
/**
* Tests for TRU-94: product merging infrastructure.
*
* Verifies that:
* - Merging product A into B preserves historical order_items references (FK still points at A)
* - The source product's merged_into_product_id is set, and resolveActiveProductId() follows it
* - An audit row is written to product_merges
* - Price changes to the target (B) are what new orders will see (since reads resolve to the target)
* - The API endpoint POST /products/{id}/merge behaves as expected and validates inputs
* - The schema is additive and idempotent (running the bootstrap twice is safe)
*/
it('adds merged_into_product_id to products and product_merges table is idempotent', function (): void {
api_test_covers('schema', 'product-merges');
// Calling ensureTables on a clean test DB should be a no-op (column/table already exist
// from earlier schema runs in the same suite, or it should add them without error).
\classes\products_schema_bootstrap::ensureTables();
\classes\products_schema_bootstrap::ensureTables();
$db = api_test_runtime()->db();
$col = $db->query("SHOW COLUMNS FROM `products` LIKE 'merged_into_product_id'");
expect($col)->not->toBeFalse();
expect((int)$col->num_rows)->toBe(1);
$tbl = $db->query("SHOW TABLES LIKE 'product_merges'");
expect($tbl)->not->toBeFalse();
expect((int)$tbl->num_rows)->toBe(1);
});
it('resolveActiveProductId follows merged_into_product_id', function (): void {
$source = api_fixtures()->createProduct([
'name' => 'SF Source (Lastbil)',
'price' => 100,
]);
$target = api_fixtures()->createProduct([
'name' => 'SF Target (Lastbil)',
'price' => 150,
]);
$sourceObj = (new products_o())->select((int)$source['id']);
expect($sourceObj->exists())->toBeTrue();
expect($sourceObj->resolveActiveProductId())->toBe((int)$source['id']);
// No chain yet, and target is unchanged
$targetObj = (new products_o())->select((int)$target['id']);
expect($targetObj->resolveActiveProductId())->toBe((int)$target['id']);
// Perform the merge
$sourceObj->mergeInto((int)$target['id'], null, 'TRU-94 test merge');
expect((int)$sourceObj->merged_into_product_id->value())->toBe((int)$target['id']);
expect($sourceObj->resolveActiveProductId())->toBe((int)$target['id']);
// Reload from DB to confirm persistence
$reloaded = (new products_o())->select((int)$source['id']);
expect($reloaded->resolveActiveProductId())->toBe((int)$target['id']);
expect((int)$reloaded->merged_into_product_id->value())->toBe((int)$target['id']);
});
it('mergeInto preserves historical order_items references and writes an audit row', function (): void {
$source = api_fixtures()->createProduct([
'name' => 'Legacy SF',
'price' => 200,
]);
$target = api_fixtures()->createProduct([
'name' => 'New SF',
'price' => 250,
]);
// Create a historical order and order_item that points at the source.
$user = api_fixtures()->createUser(['name' => 'Merge Test User']);
$cashier = api_fixtures()->createUser(['name' => 'Merge Test Cashier']);
$department = api_fixtures()->createDepartment();
$order = api_fixtures()->createOrder([
'customer_id' => (int)$user['id'],
'department_id' => (int)$department['id'],
]);
$item = api_fixtures()->createOrderItem([
'order_id' => (int)$order['id'],
'product_id' => (int)$source['id'],
'cashier_id' => (int)$cashier['id'],
'price' => 200,
'quantity' => 1,
]);
expect((int)$item['product_id'])->toBe((int)$source['id']);
// Merge source into target
(new products_o())->select((int)$source['id'])->mergeInto((int)$target['id'], null, 'TRU-94 historical preservation');
// Historical order_items.product_id MUST still point at the source.
// (This is the whole point of the merge: we don't rewrite history.)
$db = api_test_runtime()->db();
$row = $db->query("SELECT product_id FROM order_items WHERE id = " . (int)$item['id'])->fetch_array();
expect((int)$row['product_id'])->toBe((int)$source['id']);
// Audit row exists
$audit = $db->query("SELECT * FROM product_merges WHERE source_product_id = " . (int)$source['id'])->fetch_array();
expect($audit)->not->toBeNull();
expect((int)$audit['source_product_id'])->toBe((int)$source['id']);
expect((int)$audit['target_product_id'])->toBe((int)$target['id']);
expect($audit['reason'])->toBe('TRU-94 historical preservation');
});
it('price change on the target is what new orders see (resolution goes to target)', function (): void {
$source = api_fixtures()->createProduct(['name' => 'SF Pre-Merge', 'price' => 100]);
$target = api_fixtures()->createProduct(['name' => 'SF Post-Merge', 'price' => 100]);
(new products_o())->select((int)$source['id'])->mergeInto((int)$target['id']);
// Simulate a price change on the target (the only product new orders can be placed against)
$targetObj = (new products_o())->select((int)$target['id']);
$targetObj->price->set(175);
// The source still resolves to the target, and a fresh read of the target shows the new price
$resolvedId = (new products_o())->select((int)$source['id'])->resolveActiveProductId();
expect($resolvedId)->toBe((int)$target['id']);
$reloaded = (new products_o())->select($resolvedId);
expect((int)$reloaded->price->value())->toBe(175);
});
it('POST /products/{id}/merge requires edit_product permission', function (): void {
$source = api_fixtures()->createProduct(['name' => 'Perm Source']);
$target = api_fixtures()->createProduct(['name' => 'Perm Target']);
// IMPORTANT: do NOT pass ['group_id' => 1] here. group_id 1 is a
// hardcoded superuser/admin in objects\users_o::hasPermission() and
// bypasses the groups_permissions check entirely, so the route would
// 200 instead of 403. createUserSession([], []) creates a fresh empty
// group (id > 1) with no permissions, which is what this test needs.
$session = api_fixtures()->createUserSession([], []);
$response = api_client()->post(
'/products/' . (int)$source['id'] . '/merge',
['target_id' => (int)$target['id']],
$session['headers']
);
$response
->assertStatus(403)
->assertEnvelope()
->assertSuccess(false);
});
it('POST /products/{id}/merge succeeds with edit_product permission', function (): void {
$source = api_fixtures()->createProduct(['name' => 'API Merge Source']);
$target = api_fixtures()->createProduct(['name' => 'API Merge Target']);
$session = api_fixtures()->createUserSession(['edit_product'], ['group_id' => 1]);
$response = api_client()->post(
'/products/' . (int)$source['id'] . '/merge',
['target_id' => (int)$target['id'], 'reason' => 'SENERE 2 — TRU-94'],
$session['headers']
);
$response
->assertStatus(200)
->assertEnvelope()
->assertSuccess();
expect($response->data())
->toBeArray()
->toHaveKey('source_product_id', (int)$source['id'])
->toHaveKey('target_product_id', (int)$target['id'])
->toHaveKey('merged_into_product_id', (int)$target['id']);
});
it('POST /products/{id}/merge rejects self-merge', function (): void {
$product = api_fixtures()->createProduct(['name' => 'Self Merge']);
$session = api_fixtures()->createUserSession(['edit_product'], ['group_id' => 1]);
$response = api_client()->post(
'/products/' . (int)$product['id'] . '/merge',
['target_id' => (int)$product['id']],
$session['headers']
);
$response
->assertStatus(400)
->assertEnvelope()
->assertSuccess(false);
});
it('POST /products/{id}/merge rejects double-merge', function (): void {
$a = api_fixtures()->createProduct(['name' => 'A']);
$b = api_fixtures()->createProduct(['name' => 'B']);
$c = api_fixtures()->createProduct(['name' => 'C']);
$session = api_fixtures()->createUserSession(['edit_product'], ['group_id' => 1]);
// First merge succeeds
$first = api_client()->post(
'/products/' . (int)$a['id'] . '/merge',
['target_id' => (int)$b['id']],
$session['headers']
);
$first->assertStatus(200)->assertEnvelope()->assertSuccess();
// Second merge of A into C should fail because A is already merged
$second = api_client()->post(
'/products/' . (int)$a['id'] . '/merge',
['target_id' => (int)$c['id']],
$session['headers']
);
$second
->assertStatus(400)
->assertEnvelope()
->assertSuccess(false);
});
@@ -58,6 +58,7 @@ CREATE TABLE IF NOT EXISTS `users` (
`sms_notifications_enabled` TINYINT(1) NOT NULL DEFAULT 0,
`email_notifications_enabled` TINYINT(1) NOT NULL DEFAULT 0,
`wash_certificate_email` VARCHAR(255) NULL,
`invoice_email` VARCHAR(255) NULL,
`two_factor_enabled` TINYINT(1) NOT NULL DEFAULT 0,
`two_factor_secret` VARCHAR(255) NULL,
`created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
@@ -175,6 +175,11 @@ final class ApiTestRuntime
);
$this->db->set_charset('utf8mb4');
// Expose $GLOBALS['db'] as a classes\db wrapper around the same connection
// so that legacy object code (e.g. products_o::exists / products_o::mergeInto)
// that relies on `global $db` works inside the API test runtime.
$this->bindGlobalLegacyDb($this->db, $dbConfig);
$redisConfig = $this->readRedisConfig();
if ($redisConfig !== null) {
$parameters = [
@@ -204,6 +209,42 @@ final class ApiTestRuntime
$this->bootstrapped = true;
}
/**
* Bind $GLOBALS['db'] to a classes\db wrapper around the active mysqli connection.
*
* The API test runtime speaks to the database through a raw mysqli handle
* (see db() above). However, a lot of the production object layer
* (e.g. objects\products_o::exists, objects\products_o::mergeInto,
* traits\db_object_t) uses `global $db;` and then calls methods on it.
*
* This wrapper re-uses the same underlying mysqli connection so that
* fixtures written via $this->db are visible to the legacy object layer
* and vice versa, without opening a second connection.
*/
private function bindGlobalLegacyDb(mysqli $connection, array $dbConfig): void
{
if (!class_exists(\classes\db::class)) {
// Legacy wrapper not available; tests that don't need it will still pass.
return;
}
if (!isset($GLOBALS['db']) || !$GLOBALS['db'] instanceof \classes\db) {
$legacyDb = new \classes\db([
'host' => (string)$dbConfig['host'],
'user' => (string)$dbConfig['user'],
'password' => (string)$dbConfig['password'],
'database' => (string)$dbConfig['database'],
'port' => (int)$dbConfig['port'],
'ssl_mode' => (string)($dbConfig['ssl_mode'] ?? 'DISABLED'),
]);
$GLOBALS['db'] = $legacyDb;
}
// Share the runtime mysqli handle so reads/writes stay consistent
// with the rest of the API test runtime.
$GLOBALS['db']->conn = $connection;
}
private function bootstrapSchemaIfRequested(): void
{
if ($this->schemaBootstrapped) {
@@ -1,9 +1,14 @@
<?php
// Test that the cron mechanism is properly wired. The Coolify auto-deploy logic
// was removed from release_manager.php 2026-08-17, so this test no longer asserts
// anything about cron worker deployment. The actual cron mechanism
// (cron_worker.php, cron_scheduler.php, cli.php, cronRoute.php) is unchanged.
$cronAppRoot = dirname(__DIR__, 3);
require_once $cronAppRoot . '/classes/cron_worker.php';
it('wires cron workers through schema, CLI, scheduler, and superuser routes', function (): void {
it('wires cron workers through schema, scheduler, CLI, and routes', function (): void {
$appRoot = dirname(__DIR__, 3);
$repoRoot = getenv('PLENO_REPO_ROOT_FOR_TESTS') ?: dirname($appRoot, 3);
$schema = file_get_contents($appRoot . '/classes/cron_schema_bootstrap.php');
@@ -11,12 +16,6 @@ it('wires cron workers through schema, CLI, scheduler, and superuser routes', fu
$scheduler = file_get_contents($appRoot . '/classes/cron_scheduler.php');
$cli = file_get_contents($appRoot . '/cli.php');
$route = file_get_contents($appRoot . '/routes/cronRoute.php');
$manager = file_get_contents($appRoot . '/classes/release_manager.php');
$composeFiles = [
$repoRoot . '/docker-compose.yml',
$repoRoot . '/docker-compose.example.yml',
$repoRoot . '/docker-compose.prod.standalone.yml',
];
expect($schema)->toContain('CREATE TABLE IF NOT EXISTS cron_worker_state');
expect($schema)->toContain('last_heartbeat_at');
@@ -47,29 +46,24 @@ it('wires cron workers through schema, CLI, scheduler, and superuser routes', fu
expect($cli)->toContain('new \\classes\\cron_worker()');
expect($route)->toContain('/superuser/cron/workers');
expect($route)->toContain('/superuser/cron/workers/deploy');
expect($route)->toContain('$response->success($result, 202)');
expect($route)->toContain('queueTaskRun(');
expect($route)->toContain('$response->success($run, 202)');
expect($route)->toContain('superuser_cron_view');
expect($route)->toContain('superuser_cron_manage');
expect($route)->toContain('superuser_coolify_manage');
});
expect($manager)->toContain("private const CRON_WORKER_APP = 'cron'");
expect($manager)->toContain("private const CRON_WORKER_START_COMMAND = 'php index.php run cron-worker'");
expect($manager)->toContain('deployCronWorkerAfterApiDeployment');
expect($manager)->toContain('deployment_kind = \'cron_worker\'');
expect($manager)->toContain('createCronWorkerDeploymentRecord');
expect($manager)->toContain('waiting_for_heartbeat');
expect($manager)->toContain('cronWorkerAutoprovisionRequired');
expect($manager)->toContain('cron_worker_autoprovision_disabled');
expect($manager)->toContain('cron_worker_deploy_failed');
expect($manager)->toContain('auto_deploy = 0');
it('starts the cron-worker service via the docker-compose entrypoint', function (): void {
$appRoot = dirname(__DIR__, 3);
$repoRoot = getenv('PLENO_REPO_ROOT_FOR_TESTS') ?: dirname($appRoot, 3);
$composeFiles = [
$repoRoot . '/docker-compose.yml',
$repoRoot . '/docker-compose.example.yml',
$repoRoot . '/docker-compose.prod.standalone.yml',
];
foreach ($composeFiles as $composeFile) {
$compose = file_get_contents($composeFile);
expect(str_contains($compose, 'command: ["php", "index.php", "run", "cron-worker"]'))->toBeTrue();
expect(str_contains($compose, 'while true; do php index.php run cron; sleep 60; done'))->toBeFalse();
}
});
@@ -104,3 +98,18 @@ it('reports consecutive scheduler loops as once-per-minute execution proof', fun
$result = $publicWorker->invoke($worker, $row);
expect($result['minute_cadence']['verified'])->toBeFalse();
});
it('exposes a cron status endpoint that no longer references Coolify auto-deploy', function (): void {
$appRoot = dirname(__DIR__, 3);
$manager = file_get_contents($appRoot . '/classes/release_manager.php');
// The Coolify auto-deploy constants and methods must be gone
expect($manager)->not->toContain("private const CRON_WORKER_APP = 'cron'");
expect($manager)->not->toContain("private const CRON_WORKER_START_COMMAND = 'php index.php run cron-worker'");
expect($manager)->not->toContain('function deployCronWorker');
expect($manager)->not->toContain('function deployCronWorkerAfterApiDeployment');
expect($manager)->not->toContain('function cronWorkerAutoprovision');
expect($manager)->not->toContain('function cronWorkerHealth');
// The cronWorkerStatus method should still exist as a thin DB wrapper
expect($manager)->toContain('public function cronWorkerStatus');
expect($manager)->toContain("'coolify_auto_deploy_enabled' => false");
});
@@ -0,0 +1,243 @@
<?php
use classes\customer_invoice_email_schema_bootstrap;
use classes\customer_mass_import_service;
if (!class_exists('CustomerInvoiceEmailSchemaResultStub')) {
final class CustomerInvoiceEmailSchemaResultStub
{
public int $num_rows = 0;
/** @var list<array<string, mixed>> */
private array $rows;
/** @param list<array<string, mixed>> $rows */
public function __construct(array $rows = [])
{
$this->rows = array_values($rows);
$this->num_rows = count($this->rows);
}
/** @return array<string, mixed>|null */
public function fetch_assoc(): ?array
{
return array_shift($this->rows) ?? null;
}
}
}
if (!class_exists('CustomerInvoiceEmailSchemaDbStub')) {
final class CustomerInvoiceEmailSchemaDbStub
{
public bool $hasUsersTable = true;
public bool $hasInvoiceEmailColumn = false;
/** @var list<string> */
public array $queries = [];
public function query(string $sql): CustomerInvoiceEmailSchemaResultStub
{
$this->queries[] = $sql;
if (str_contains($sql, "SHOW TABLES LIKE 'users'")) {
return $this->hasUsersTable
? new CustomerInvoiceEmailSchemaResultStub([['Tables_in_db' => 'users']])
: new CustomerInvoiceEmailSchemaResultStub();
}
if (str_contains($sql, "SHOW COLUMNS FROM `users` LIKE 'invoice_email'")) {
return $this->hasInvoiceEmailColumn
? new CustomerInvoiceEmailSchemaResultStub([['Field' => 'invoice_email']])
: new CustomerInvoiceEmailSchemaResultStub();
}
return new CustomerInvoiceEmailSchemaResultStub();
}
}
}
it('adds the invoice_email column to the users table when the column is missing', function (): void {
$db = new CustomerInvoiceEmailSchemaDbStub();
$db->hasUsersTable = true;
$db->hasInvoiceEmailColumn = false;
$GLOBALS['db'] = $db;
try {
customer_invoice_email_schema_bootstrap::ensureSchema();
} finally {
unset($GLOBALS['db']);
}
expect($db->queries)->toContain('ALTER TABLE `users`
ADD COLUMN invoice_email VARCHAR(255) NULL
AFTER wash_certificate_email');
});
it('does not re-add the invoice_email column when it already exists', function (): void {
$db = new CustomerInvoiceEmailSchemaDbStub();
$db->hasUsersTable = true;
$db->hasInvoiceEmailColumn = true;
$GLOBALS['db'] = $db;
try {
customer_invoice_email_schema_bootstrap::ensureSchema();
} finally {
unset($GLOBALS['db']);
}
$alterStatements = array_values(array_filter(
$db->queries,
static fn(string $query): bool => str_contains($query, 'ALTER TABLE')
));
expect($alterStatements)->toBe([]);
});
it('skips column add when the users table does not exist yet', function (): void {
$db = new CustomerInvoiceEmailSchemaDbStub();
$db->hasUsersTable = false;
$db->hasInvoiceEmailColumn = false;
$GLOBALS['db'] = $db;
try {
customer_invoice_email_schema_bootstrap::ensureSchema();
} finally {
unset($GLOBALS['db']);
}
$alterStatements = array_values(array_filter(
$db->queries,
static fn(string $query): bool => str_contains($query, 'ALTER TABLE')
));
expect($alterStatements)->toBe([]);
});
// --- customer mass import service invoice_email routing (TRU-77) ---
if (!class_exists('CustomerInvoiceEmailMassImportProbe')) {
final class CustomerInvoiceEmailMassImportProbe extends customer_mass_import_service
{
public array $economicSearchResults = [];
public array $createCalls = [];
public array $bootstrapCalls = [];
public ?object $bootstrapUser = null;
public ?object $createResponse = null;
public string $companyName = 'Probe Company';
protected function searchEconomicCustomersByCvr(string $cvr): array
{
return $this->economicSearchResults;
}
protected function createEconomicCustomer(array $normalized, string $createEmail): object
{
// The production service no longer mutates $normalized['email'];
// the create call uses the dedicated invoice_email (or the
// primary as a fallback) that import() resolves for it. Mirror
// that here so the recorded payload reflects what is sent to
// e-conomic.
$payload = $normalized;
$payload['email'] = $createEmail;
$this->createCalls[] = $payload;
return $this->createResponse ?? (object)[
'customerNumber' => (int)$normalized['customer_number'],
];
}
protected function bootstrapLocalCustomerOrFail(int $customerNumber): object
{
$this->bootstrapCalls[] = $customerNumber;
if ($this->bootstrapUser === null) {
throw new RuntimeException('Customer was created in e-conomic but could not be imported locally.', 500);
}
return $this->bootstrapUser;
}
protected function fetchCompanyNameByCvr(string $cvr): string
{
return $this->companyName;
}
protected function syncLocalCustomer(object $customer, array $normalized, array &$warnings): void
{
// No-op for the routing assertions; tests focus on payload + create call.
}
// Override the DB lookup so the unit test does not need a real
// (or stubbed) mysqli connection. The TRU-77 routing tests treat
// the import as a "new customer" flow, so we hard-code the
// "does not exist locally" answer.
protected function localCustomerNumberExists(int $customerNumber): bool
{
return false;
}
protected function loadLocalCustomerByNumber(int $customerNumber): ?object
{
return null;
}
}
}
it('routes the e-conomic customer email to the dedicated invoice_email when provided', function (): void {
$service = new CustomerInvoiceEmailMassImportProbe();
$service->bootstrapUser = new class {
public int $id = 5001;
public function exists(): bool { return true; }
public function hasPassword(): bool { return false; }
};
$service->createResponse = (object)['customerNumber' => 22725567];
$result = $service->import([
'cvr' => '29424764',
'name' => 'TGP TRANSPORT APS',
'email' => 'primary@example.com',
'invoice_email' => 'faktura@example.com',
'phone' => '22725567',
]);
expect($service->createCalls)->toHaveCount(1);
expect($service->createCalls[0]['email'])->toBe('faktura@example.com');
expect($result['email'])->toBe('primary@example.com');
expect($result['invoice_email'])->toBe('faktura@example.com');
});
it('falls back to the primary email when no dedicated invoice_email is provided', function (): void {
$service = new CustomerInvoiceEmailMassImportProbe();
$service->bootstrapUser = new class {
public int $id = 5002;
public function exists(): bool { return true; }
public function hasPassword(): bool { return false; }
};
$service->createResponse = (object)['customerNumber' => 22725567];
$result = $service->import([
'cvr' => '29424764',
'name' => 'TGP TRANSPORT APS',
'email' => 'primary@example.com',
'phone' => '22725567',
]);
expect($service->createCalls)->toHaveCount(1);
expect($service->createCalls[0]['email'])->toBe('primary@example.com');
expect($result['invoice_email'])->toBeNull();
});
it('rejects an invalid dedicated invoice_email before contacting e-conomic', function (): void {
$service = new CustomerInvoiceEmailMassImportProbe();
$service->bootstrapUser = new class {
public int $id = 5003;
public function exists(): bool { return true; }
public function hasPassword(): bool { return false; }
};
$call = static fn() => $service->import([
'cvr' => '29424764',
'name' => 'TGP TRANSPORT APS',
'email' => 'primary@example.com',
'invoice_email' => 'not-an-email',
'phone' => '22725567',
]);
expect($call)->toThrow(RuntimeException::class, 'Invalid invoice email address.');
expect($service->createCalls)->toBe([]);
});
@@ -49,9 +49,16 @@ if (!class_exists('CustomerMassImportServiceProbe')) {
return $this->economicSearchResults;
}
protected function createEconomicCustomer(array $normalized): object
protected function createEconomicCustomer(array $normalized, string $createEmail): object
{
$this->createCalls[] = $normalized;
// TRU-77 / DRIFT 16: the production service no longer mutates
// $normalized['email'] before calling createEconomicCustomer —
// the dedicated invoice_email (or the primary as a fallback) is
// resolved by import() and passed in as $createEmail. Mirror that
// here so the recorded payload reflects what is sent to e-conomic.
$payload = $normalized;
$payload['email'] = $createEmail;
$this->createCalls[] = $payload;
return $this->createResponse ?? (object)[
'customerNumber' => (int)$normalized['customer_number'],
];
@@ -0,0 +1,224 @@
<?php
namespace tests\Unit\Economic;
use classes\economic_export_sanitizer;
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../../classes/economic_export_sanitizer.php';
class EconomicExportSanitizerTest extends TestCase
{
// ========================================================================
// sanitizeTextLine
// ========================================================================
public function testSlashIsReplacedWithDash(): void
{
$this->assertSame('ABC-123-XYZ', economic_export_sanitizer::sanitizeTextLine('ABC/123/XYZ'));
$this->assertSame('Order 1 - 2 - 3', economic_export_sanitizer::sanitizeTextLine('Order 1 / 2 / 3'));
$this->assertSame('-leading and trailing-', economic_export_sanitizer::sanitizeTextLine('/leading and trailing/'));
}
public function testControlCharactersAreStripped(): void
{
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine("hel\x00lo"));
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine("hel\x01lo"));
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine("hel\x1Flo"));
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine("hel\x7F\x7Flo"));
}
public function testTabIsReplacedWithSpace(): void
{
$this->assertSame('a b c', economic_export_sanitizer::sanitizeTextLine("a\tb\tc"));
}
public function testNewlinesCollapsedToSpace(): void
{
$this->assertSame('line1 line2 line3', economic_export_sanitizer::sanitizeTextLine("line1\nline2\nline3"));
$this->assertSame('line1 line2', economic_export_sanitizer::sanitizeTextLine("line1\r\nline2"));
$this->assertSame('line1 line2', economic_export_sanitizer::sanitizeTextLine("line1\n\n\nline2"));
}
public function testMultipleSpacesCollapsed(): void
{
$this->assertSame('a b c', economic_export_sanitizer::sanitizeTextLine('a b c'));
}
public function testTrimsLeadingAndTrailingWhitespace(): void
{
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine(' hello '));
$this->assertSame('hello', economic_export_sanitizer::sanitizeTextLine("\n\thello\n\t"));
}
public function testTruncatesAtMaxLengthWithEllipsis(): void
{
$text = str_repeat('a', 300);
$result = economic_export_sanitizer::sanitizeTextLine($text, 250);
$this->assertSame(250, mb_strlen($result));
$this->assertStringEndsWith('...', $result);
}
public function testTruncatesAtMaxLengthWithoutEllipsisWhenTooShort(): void
{
// When maxLength is 3, no room for ellipsis
$text = str_repeat('a', 100);
$result = economic_export_sanitizer::sanitizeTextLine($text, 3);
$this->assertSame(3, mb_strlen($result));
$this->assertSame('aaa', $result);
}
public function testDoesNotTruncateWhenShorterThanMaxLength(): void
{
$this->assertSame('short text', economic_export_sanitizer::sanitizeTextLine('short text', 250));
}
public function testNullReturnsEmptyString(): void
{
$this->assertSame('', economic_export_sanitizer::sanitizeTextLine(null));
}
public function testEmptyReturnsEmptyString(): void
{
$this->assertSame('', economic_export_sanitizer::sanitizeTextLine(''));
}
public function testWhitespaceOnlyReturnsEmptyString(): void
{
$this->assertSame('', economic_export_sanitizer::sanitizeTextLine(" \t\n "));
}
public function testWhitespaceOnlyWithSlashesReturnsEmptyString(): void
{
// After all transformations, "///" becomes "---"
// After trim of whitespace-only, " / " becomes "" (since / is replaced but space was there)
// Actually let's see: " / " -> " " stays; " - " -> "-"; then trim -> "-"
// So it doesn't become empty in this case. Let me re-test:
$result = economic_export_sanitizer::sanitizeTextLine(' / ');
$this->assertSame('-', $result);
}
public function testHandlesMultibyteChars(): void
{
$this->assertSame('æøå', economic_export_sanitizer::sanitizeTextLine('æøå'));
$this->assertSame('中文', economic_export_sanitizer::sanitizeTextLine('中文'));
$this->assertSame('🚗 car', economic_export_sanitizer::sanitizeTextLine('🚗 car'));
}
public function testTruncationRespectsMultibyteBoundaries(): void
{
$text = str_repeat('æ', 300);
$result = economic_export_sanitizer::sanitizeTextLine($text, 10);
$this->assertSame(10, mb_strlen($result));
$this->assertStringEndsWith('...', $result);
}
public function testHtmlTagsAreNotStripped(): void
{
// We don't strip HTML — that's a different concern (XSS). We just sanitize for e-conomic.
// The "/" in </b> gets replaced with "-" (per the rules).
$this->assertSame('<b>notags<-b>', economic_export_sanitizer::sanitizeTextLine('<b>notags</b>'));
}
public function testSlashesInTheMiddleOfValueAreReplaced(): void
{
$this->assertSame('foo-bar-baz', economic_export_sanitizer::sanitizeTextLine('foo/bar/baz'));
}
public function testMultipleProblemCharsCombined(): void
{
$input = "AB/\nC\t\rD\x00E ";
$result = economic_export_sanitizer::sanitizeTextLine($input);
// After: strip control -> "AB/\nC\tDE ", tab->space -> "AB/\nC DE ",
// newline->space -> "AB/ C DE ", slash->dash -> "AB- C DE ",
// collapse spaces -> "AB- C DE ", trim -> "AB- C DE"
$this->assertSame('AB- C DE', $result);
}
public function testIntegerIsConvertedToString(): void
{
$this->assertSame('42', economic_export_sanitizer::sanitizeTextLine(42));
}
public function testFloatIsConvertedToString(): void
{
$this->assertSame('3.14', economic_export_sanitizer::sanitizeTextLine(3.14));
}
// ========================================================================
// sanitizeProductNumber
// ========================================================================
public function testProductNumberRemovesPathSeparators(): void
{
$this->assertSame('ABCDEF', economic_export_sanitizer::sanitizeProductNumber('ABC/DEF'));
$this->assertSame('ABCDEF', economic_export_sanitizer::sanitizeProductNumber('ABC\\DEF'));
}
public function testProductNumberRemovesForbiddenChars(): void
{
$input = "PROD:01?*<>|\"";
$result = economic_export_sanitizer::sanitizeProductNumber($input);
$this->assertSame('PROD01', $result);
}
public function testProductNumberTruncatesAt50Chars(): void
{
$text = str_repeat('a', 100);
$result = economic_export_sanitizer::sanitizeProductNumber($text);
$this->assertSame(50, mb_strlen($result));
}
public function testProductNumberTrimsWhitespace(): void
{
$this->assertSame('PROD01', economic_export_sanitizer::sanitizeProductNumber(' PROD01 '));
}
public function testProductNumberStripsControlChars(): void
{
$this->assertSame('PROD01', economic_export_sanitizer::sanitizeProductNumber("PROD\x0001"));
}
public function testProductNumberNullReturnsEmpty(): void
{
$this->assertSame('', economic_export_sanitizer::sanitizeProductNumber(null));
}
public function testProductNumberAllForbiddenReturnsEmpty(): void
{
$this->assertSame('', economic_export_sanitizer::sanitizeProductNumber('///\\\\::'));
}
public function testProductNumberKeepsDotsAndDashes(): void
{
$this->assertSame('PROD-01.0', economic_export_sanitizer::sanitizeProductNumber('PROD-01.0'));
}
// ========================================================================
// sanitizeProductDescription
// ========================================================================
public function testProductDescriptionTruncatesAt500(): void
{
$text = str_repeat('a', 1000);
$result = economic_export_sanitizer::sanitizeProductDescription($text);
$this->assertSame(500, mb_strlen($result));
}
public function testProductDescriptionReplacesSlashes(): void
{
$this->assertSame('foo-bar-baz', economic_export_sanitizer::sanitizeProductDescription('foo/bar/baz'));
}
// ========================================================================
// sanitizeForEconApi
// ========================================================================
public function testSanitizeForEconApiIsAliasForTextLine(): void
{
$this->assertSame(
economic_export_sanitizer::sanitizeTextLine('foo/bar'),
economic_export_sanitizer::sanitizeForEconApi('foo/bar')
);
}
}
@@ -167,7 +167,8 @@ it('builds interactive message parts for order and wash certificate warnings', f
['type' => 'text', 'text' => ' is present without a wash certificate.'],
]);
expect($xlVaskFlag['message_parts'])->toBe([
['type' => 'xlvask_usage_log', 'text' => 'XL Vask wash'],
['type' => 'text', 'text' => 'XL Vask wash '],
['type' => 'xlvask_usage_log', 'text' => 'wash-55'],
['type' => 'text', 'text' => ' is neither ignored nor linked to an order in the selected period.'],
]);
});
@@ -9,8 +9,12 @@ it('requires id and at least one mutable field for PUT /collected-invoices in us
expect($content)->toContain("self::requireParameters(['id']);");
expect($content)->toContain("\$is_superuser = \$this->hasPermission('superuser');");
expect($content)->toContain("if (!self::isParametersSet(['po_number']) && !self::isParametersSet(['closed_at'])) {");
expect($content)->toContain("\$response->error('Missing required parameters: po_number, closed_at', 400);");
expect($content)->toContain("if (self::isParametersSet(['closed_at']) && !\$is_superuser) {");
// TRU-128: The previous error message ("Missing required parameters:
// po_number, closed_at") read as if BOTH were required and confused
// customers trying to invoice. We now state the actual contract: at
// least one must be provided.
expect($content)->toContain("\$response->error('At least one of po_number or closed_at must be provided', 400);");
expect($content)->toContain("if (\$closed_at_is_non_empty && !\$is_superuser) {");
expect($content)->toContain("\$response->error('Forbidden: only superusers can update closed_at', 403);");
expect($content)->toContain("if ((int)\$invoice->customer_number->value() !== (int)\$user->customer_number->value() && !\$is_superuser) {");
});
@@ -28,3 +32,24 @@ it('supports independent po_number and closed_at updates for PUT /collected-invo
expect($content)->toContain("self::requireDateFormat((string)\$closed_at, self::FORMAT_DATE());");
expect($content)->toContain("\$invoice->closed_at->set(\$closed_at === null || \$closed_at === '' ? null : date('Y-m-d 23:59:59', strtotime((string)\$closed_at . ' 00:00:01')));");
});
it('locks in the TRU-128 bug fix: customers can clear closed_at with null/empty string', function (): void {
// TRU-128 / "Jeg kan ikke fakturere": a non-superuser could not pass
// closed_at at all (even null/empty) because isParametersSet() returns
// true for any present key. The route returned 403 Forbidden and the
// customer could not clear a previously-set closed_at either. The fix
// narrows the forbidden check to *non-empty* closed_at values, matching
// the existing clear-on-null/empty logic further down in the handler.
$routeFile = app_path('routes/userInvoicesRoute.php');
$content = file_get_contents($routeFile);
expect($content)->not->toBeFalse();
// The "present + non-empty" check must precede the 403 guard, so
// clearing closed_at (passing null or "") for a non-superuser is allowed.
expect($content)->toMatch(
'/\$closed_at_is_non_empty\s*=\s*false;\s*if\s*\(self::isParametersSet\(\[\'closed_at\'\]\)\)\s*\{[^}]*\$closed_at_is_non_empty\s*=\s*\(\$raw_closed_at\s*!==\s*null\s*&&\s*\$raw_closed_at\s*!==\s*\'\'\);[^}]*\}\s*if\s*\(\$closed_at_is_non_empty\s*&&\s*!\$is_superuser\)\s*\{[^}]*Forbidden:\s*only\s*superusers/s'
);
// The previous shape of the guard (which would always fire for any
// present closed_at, including null) must no longer be present.
expect($content)->not->toContain("if (self::isParametersSet(['closed_at']) && !\$is_superuser) {");
});
@@ -411,214 +411,6 @@ it('uses the self-contained Coolify API Dockerfile for API applications', functi
expect($payload)->not->toHaveKey('is_static');
});
it('creates private Coolify application payloads for cron workers', function (): void {
$manager = new release_manager();
$payloadMethod = new ReflectionMethod(release_manager::class, 'releaseCoolifyApplicationPayload');
$payload = $payloadMethod->invoke($manager, [
'channel_slug' => 'internal',
'app' => 'cron',
'repository' => 'copenhagentruckwash/api',
'branch' => 'master',
'auto_deploy' => 0,
], [
'coolify_service_name' => 'release-internal-cron-worker',
'coolify_project_uuid' => 'project-internal',
'coolify_github_app_uuid' => 'github-app-copenhagentruckwash-github',
'coolify_build_pack' => 'dockerfile',
'coolify_deploy_now' => true,
'coolify_start_command' => 'php index.php run cron-worker',
], [
'default_environment_name' => 'production',
'default_server_uuid' => 'server-node3',
]);
expect($payload['name'])->toBe('release-internal-cron-worker');
expect($payload['build_pack'])->toBe('dockerfile');
expect($payload['ports_exposes'])->toBe('80');
expect($payload['dockerfile_location'])->toBe('/Dockerfile.coolify-api');
expect($payload['start_command'])->toBe('php index.php run cron-worker');
expect($payload['is_auto_deploy_enabled'])->toBeFalse();
expect($payload)->not->toHaveKey('domains');
expect($payload)->not->toHaveKey('is_force_https_enabled');
});
it('derives cron worker deployment context from the API target without public routing', function (): void {
$manager = new release_manager();
$contextMethod = new ReflectionMethod(release_manager::class, 'cronWorkerDeployContext');
$context = $contextMethod->invoke($manager, [
'id' => 17,
'channel_id' => 3,
'channel_slug' => 'internal',
'deploy_context_json' => json_encode([
'coolify_project_uuid' => 'project-internal',
'coolify_environment_name' => 'production',
'coolify_github_app_uuid' => 'github-app-copenhagentruckwash-github',
'coolify_public_url' => 'https://api-v2.truckwash.io',
'manual_endpoint_host' => 'manual.example.test',
]),
], null, '5555555555555555555555555555555555555555', 41);
expect($context['coolify_auto_create'])->toBeTrue();
expect($context['coolify_resource_type'])->toBe('application');
expect($context['coolify_build_pack'])->toBe('dockerfile');
expect($context['coolify_dockerfile_location'])->toBe('/Dockerfile.coolify-api');
expect($context['coolify_start_command'])->toBe('php index.php run cron-worker');
expect($context['coolify_is_auto_deploy_enabled'])->toBeFalse();
expect($context['coolify_enable_ssl'])->toBeFalse();
expect($context['coolify_service_name'])->toBe('release-internal-cron-worker');
expect($context['coolify_git_commit_sha'])->toBe('5555555555555555555555555555555555555555');
expect($context['coolify_env']['CRON_WORKER_RELEASE_CHANNEL_ID'])->toBe('3');
expect($context['coolify_env']['CRON_WORKER_RELEASE_TARGET_ID'])->toBe('41');
expect($context['coolify_env']['CRON_WORKER_SOURCE'])->toBe('coolify_worker');
expect($context)->not->toHaveKey('coolify_public_url');
expect($context)->not->toHaveKey('manual_endpoint_host');
});
it('requires Coolify cron worker autoprovisioning for API deployments by default', function (): void {
$manager = new release_manager();
$enabledMethod = new ReflectionMethod(release_manager::class, 'cronWorkerAutoprovisionEnabled');
$requiredMethod = new ReflectionMethod(release_manager::class, 'cronWorkerAutoprovisionRequired');
expect($enabledMethod->invoke($manager, ['deploy_context_json' => null]))->toBeTrue();
expect($requiredMethod->invoke($manager, ['deploy_context_json' => null]))->toBeTrue();
$optionalTarget = [
'deploy_context_json' => json_encode([
'cron_worker_autoprovision_required' => false,
]),
];
expect($enabledMethod->invoke($manager, $optionalTarget))->toBeTrue();
expect($requiredMethod->invoke($manager, $optionalTarget))->toBeFalse();
$disabledTarget = [
'deploy_context_json' => json_encode([
'cron_worker_autoprovision' => false,
]),
];
expect($enabledMethod->invoke($manager, $disabledTarget))->toBeFalse();
expect($requiredMethod->invoke($manager, $disabledTarget))->toBeFalse();
$managerSource = file_get_contents(app_path('classes/release_manager.php'));
expect($managerSource)->toContain('Cron worker deployment is required for API deployments');
});
it('classifies cron worker deployment and heartbeat lifecycle states', function (): void {
$manager = new release_manager();
$healthMethod = new ReflectionMethod(release_manager::class, 'cronWorkerHealth');
expect($healthMethod->invoke($manager, null, null, [], ['running' => 0, 'stale' => 0, 'failed' => 0], null)['state'])
->toBe('needs_deploy');
expect($healthMethod->invoke($manager, ['id' => 4], null, [], ['running' => 0, 'stale' => 0, 'failed' => 0], null)['state'])
->toBe('needs_deploy');
expect($healthMethod->invoke($manager, ['id' => 4], ['id' => 9], [], ['running' => 0, 'stale' => 0, 'failed' => 0], [
'status' => 'deploying',
'created_at' => date('Y-m-d H:i:s'),
])['state'])->toBe('deploying');
expect($healthMethod->invoke($manager, ['id' => 4], ['id' => 9], [], ['running' => 0, 'stale' => 0, 'failed' => 0], [
'status' => 'deployed',
'completed_at' => date('Y-m-d H:i:s'),
])['state'])->toBe('waiting_for_heartbeat');
expect($healthMethod->invoke($manager, ['id' => 4], ['id' => 9], [
['status' => 'running', 'stale' => false],
], ['running' => 1, 'stale' => 0, 'failed' => 0], [
'status' => 'deployed',
])['state'])->toBe('healthy');
expect($healthMethod->invoke($manager, ['id' => 4], ['id' => 9], [], ['running' => 0, 'stale' => 0, 'failed' => 0], [
'status' => 'deployed',
'completed_at' => '2020-01-01 00:00:00',
])['state'])->toBe('failed');
});
it('extracts Coolify cron deployment operation identifiers from provider payloads', function (): void {
$manager = new release_manager();
$operationMethod = new ReflectionMethod(release_manager::class, 'coolifyDeploymentOperationId');
expect($operationMethod->invoke($manager, ['deployment' => ['deployment_uuid' => 'deployment-123']]))
->toBe('deployment-123');
expect($operationMethod->invoke($manager, ['data' => ['uuid' => 'operation-456']]))
->toBe('operation-456');
expect($operationMethod->invoke($manager, ['message' => 'queued']))
->toBeNull();
});
it('detects missing Coolify cron worker resources from provider errors', function (): void {
$method = new ReflectionMethod(release_manager::class, 'coolifyResourceMissing');
expect($method->invoke(null, new RuntimeException('Coolify API request failed: HTTP 404')))->toBeTrue();
expect($method->invoke(null, new RuntimeException('Application not found')))->toBeTrue();
expect($method->invoke(null, new RuntimeException('Coolify API request failed: HTTP 401')))->toBeFalse();
});
it('classifies missing Coolify cron worker resources as repairable', function (): void {
$manager = new release_manager();
$readiness = new ReflectionMethod(release_manager::class, 'cronWorkerDeploymentReadiness');
$result = $readiness->invoke($manager, [
'id' => 17,
'app' => 'api',
'coolify_instance_id' => 3,
'repository' => 'copenhagentruckwash/api',
], [
'id' => 71,
'app' => 'cron',
'coolify_instance_id' => 3,
'coolify_service_uuid' => 'missing-cron-worker',
'repository' => 'copenhagentruckwash/api',
'branch' => 'master',
], [
'configured' => true,
'missing' => true,
]);
expect($result['action'])->toBe('repair');
expect($result['can_deploy'])->toBeTrue();
expect(array_column($result['issues'], 'code'))->toContain('missing_coolify_worker_resource');
});
it('repairs from an existing cron target when the API target is absent', function (): void {
$manager = new release_manager();
$readiness = new ReflectionMethod(release_manager::class, 'cronWorkerDeploymentReadiness');
$result = $readiness->invoke($manager, null, [
'id' => 71,
'app' => 'cron',
'coolify_instance_id' => 3,
'coolify_service_uuid' => 'missing-cron-worker',
'repository' => 'copenhagentruckwash/api',
'branch' => 'master',
], [
'configured' => true,
'missing' => true,
]);
expect($result['action'])->toBe('repair');
expect($result['can_deploy'])->toBeTrue();
expect(array_column($result['issues'], 'code'))->toContain('repairable_cron_target');
});
it('blocks cron worker deployment without an API target or deployable cron context', function (): void {
$manager = new release_manager();
$readiness = new ReflectionMethod(release_manager::class, 'cronWorkerDeploymentReadiness');
$result = $readiness->invoke($manager, null, [
'id' => 71,
'app' => 'cron',
'coolify_instance_id' => null,
'coolify_service_uuid' => 'missing-cron-worker',
'repository' => '',
'branch' => 'master',
], [
'configured' => true,
'missing' => true,
]);
expect($result['action'])->toBe('blocked');
expect($result['can_deploy'])->toBeFalse();
expect(array_column($result['issues'], 'code'))->toContain('missing_api_target');
});
it('builds explicit Coolify application route labels for release API targets', function (): void {
$manager = new release_manager();
$payloadMethod = new ReflectionMethod(release_manager::class, 'releaseCoolifyApplicationRoutePayload');
@@ -0,0 +1,51 @@
<?php
namespace tests\Unit;
use classes\schema_bootstrap_runtime;
use PHPUnit\Framework\TestCase;
/**
* Verifies the self-healing schema bootstrap runtime:
* 1. Discovers and calls every *_schema_bootstrap::ensureSchema() in classes/
* 2. Is idempotent (does not re-run within the same process)
* 3. Does not throw if a bootstrap throws (logs and moves on)
*
* The actual DB-touching work is exercised in production; here we
* stub the global $db so the columnExists() check inside each
* ensureSchema() can be observed.
*/
class SchemaBootstrapRuntimeTest extends TestCase
{
public function testRunAllDiscoversAndInvokesEachBootstrap(): void
{
$classesDir = __DIR__ . '/../../classes';
$bootstraps = glob($classesDir . '/*_schema_bootstrap.php');
$this->assertNotEmpty($bootstraps, 'No *_schema_bootstrap.php files found in classes/');
// Ensure no real $db is required: each ensureSchema() in the
// existing classes guards with `if (!isset($db) ...) { return; }`
// so they are no-ops without one. We just verify the runtime
// doesn't throw.
schema_bootstrap_runtime::runAll();
$this->assertTrue(true); // no exception
}
public function testRunAllIsIdempotent(): void
{
// First call already happened in test 1; calling again must
// short-circuit and not throw.
schema_bootstrap_runtime::runAll();
schema_bootstrap_runtime::runAll();
$this->assertTrue(true);
}
public function testNoOpWhenNoBootstrapsExist(): void
{
// Reflection: ensure runAll() is robust even if a different
// classes dir somehow had no bootstraps. We just call it
// again — it should be a no-op due to the static $ran flag.
schema_bootstrap_runtime::runAll();
$this->assertTrue(true);
}
}
@@ -0,0 +1,220 @@
<?php
/**
* Contract test: every column that the code expects to find in the
* `users` table must exist. Catches the production failure mode
* where a migration was added to code but never run on the database
* (e.g. "Unknown column 'invoice_email' in 'SELECT'" — TRU-77).
*
* This test runs against the test database (configured in
* phpunit.xml / Pest configuration). It does NOT run against
* production — that's covered by the `/admin/schema-check` HTTP
* endpoint in `adminRoute.php` which the deploy pipeline hits.
*/
app_require('classes/customer_invoice_email_schema_bootstrap.php');
use classes\customer_invoice_email_schema_bootstrap;
const REQUIRED_USERS_COLUMNS = [
// TRU-77 (added 2026-08-16) — the column that was missing in
// production after the migration was merged to master.
'invoice_email',
// Older required columns that the code references.
'wash_certificate_email',
'email',
'customer_number',
'phone_country_code',
'phone',
'group_id',
'created_at',
];
/**
* The unit test bootstrap does not create a $db global. This contract
* test is unique in that it needs a real database to verify schema
* state, so wire one up here using the same CONFIG_DB_* env vars the
* rest of the CI suite exports. If the database is unavailable, the
* tests below will fail with a clear "no_db_connection" error.
*/
schema_health_check_test_wire_db();
function schema_health_check_test_wire_db(): void
{
if (isset($GLOBALS['db']) && is_object($GLOBALS['db'])) {
return;
}
if (!class_exists('mysqli')) {
return;
}
$host = (string)(getenv('CONFIG_DB_HOST') ?: 'mysql-debug');
$user = (string)(getenv('CONFIG_DB_USER') ?: 'root');
$password = (string)(getenv('CONFIG_DB_PASSWORD') ?: 'debug_root_password');
$database = (string)(getenv('CONFIG_DB_DATABASE') ?: 'nnks_db_debug');
$port = (int)(getenv('CONFIG_DB_PORT') ?: 3306);
try {
mysqli_report(MYSQLI_REPORT_OFF);
$conn = new mysqli($host, $user, $password, $database, $port);
if ($conn->connect_errno) {
return;
}
$conn->set_charset('utf8mb4');
} catch (\Throwable $e) {
return;
}
$GLOBALS['db'] = new class($conn) {
private mysqli $conn;
public function __construct(mysqli $conn)
{
$this->conn = $conn;
}
public function query(string $sql)
{
return $this->conn->query($sql);
}
public function fetch_assoc($result)
{
return $result ? $result->fetch_assoc() : null;
}
public function close(): void
{
try {
$this->conn->close();
} catch (\Throwable) {
}
}
};
}
/**
* The unit suite starts with a freshly-dropped `nnks_db_debug` database
* (see run_ci_suite::reset_ci_state). The schema bootstrap only owns
* the `users` table; `invoices` and `bookings` are managed by other
* migrations that don't run in the unit suite. Create the bare-minimum
* schema that adminRoute::runSchemaCheck needs so the third test can
* verify the "all columns exist" happy path.
*/
function schema_health_check_test_ensure_aux_tables(): void
{
global $db;
if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
return;
}
$create = function (string $table, string $createSql, array $requiredColumns) use ($db): void {
$r = $db->query("SHOW TABLES LIKE '{$table}'");
if (!$r || (int)$r->num_rows === 0) {
$db->query($createSql);
return;
}
foreach ($requiredColumns as $column => $definition) {
$r = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
if (!$r || (int)$r->num_rows === 0) {
$db->query("ALTER TABLE `{$table}` ADD COLUMN `{$column}` {$definition}");
}
}
};
$create('invoices', "CREATE TABLE `invoices` (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_number INT NOT NULL DEFAULT 0,
po_number VARCHAR(64) NULL,
closed_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", [
'po_number' => 'VARCHAR(64) NULL',
'closed_at' => 'DATETIME NULL',
'customer_number' => 'INT NOT NULL DEFAULT 0',
]);
$create('bookings', "CREATE TABLE `bookings` (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_number INT NOT NULL DEFAULT 0,
department INT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", [
'customer_number' => 'INT NOT NULL DEFAULT 0',
'department' => 'INT NULL',
]);
}
beforeEach(function () {
// Force a fresh real DB connection. Earlier unit tests in the
// same process may have left $GLOBALS['db'] as a Mockery mock,
// which would cause the schema bootstrap below to silently no-op
// and leave the `users` table uncreated. The wiring helper
// short-circuits when a $db is already set, so we unset first.
unset($GLOBALS['db']);
schema_health_check_test_wire_db();
if (class_exists(customer_invoice_email_schema_bootstrap::class)) {
// Reset the bootstrap's static `$initialized` cache. A
// previous test (possibly against a mock $db) may have set
// it to true, which would cause ensureSchema() to skip
// creating the `users` table on our real connection.
$bootstrapRef = new ReflectionClass(customer_invoice_email_schema_bootstrap::class);
$initProp = $bootstrapRef->getProperty('initialized');
$initProp->setAccessible(true);
$initProp->setValue(null, false);
// Self-heal: run the schema bootstrap so the test DB has all
// the columns the contract requires. The bootstrap is additive
// and idempotent — safe to run on every test.
customer_invoice_email_schema_bootstrap::ensureSchema();
}
schema_health_check_test_ensure_aux_tables();
});
it('users table has every required column the code references', function () {
global $db;
expect($db)->toBeObject();
expect(method_exists($db, 'query'))->toBeTrue();
$missing = [];
foreach (REQUIRED_USERS_COLUMNS as $column) {
$safeColumn = str_replace("'", '', $column);
$result = $db->query("SHOW COLUMNS FROM `users` LIKE '{$safeColumn}'");
if (!$result || (int)$result->num_rows === 0) {
$missing[] = $column;
}
}
expect($missing)->toBe(
[],
"users table is missing required columns: " . implode(', ', $missing)
. ". Did the migration run? See customer_invoice_email_schema_bootstrap."
);
});
it('invoice_email column accepts a normal email address', function () {
global $db;
// Insert a throwaway user with an invoice_email, read it back.
// If the column doesn't exist or the type is wrong, this fails.
$email = 'test-invoice-' . uniqid() . '@example.com';
$customerNumber = 99900000 + random_int(1, 99999);
$db->query("INSERT INTO `users` (customer_number, display_name, email, invoice_email) VALUES ({$customerNumber}, 'Contract Test', '{$email}', 'invoice@example.com')");
$result = $db->query("SELECT invoice_email FROM `users` WHERE customer_number = {$customerNumber}");
expect($result)->toBeObject();
$row = $result->fetch_assoc();
expect($row['invoice_email'] ?? null)->toBe('invoice@example.com');
// Cleanup
$db->query("DELETE FROM `users` WHERE customer_number = {$customerNumber}");
});
it('admin schema-check endpoint reports ok=true when all columns exist', function () {
$admin = new \routes\adminRoute();
$reflection = new ReflectionClass($admin);
$method = $reflection->getMethod('runSchemaCheck');
$method->setAccessible(true);
$report = $method->invoke($admin);
expect($report['ok'])->toBeTrue(
'schema check failed: ' . json_encode($report['missing'] ?? [])
);
expect($report['columns_checked'])->toBeGreaterThan(0);
});
@@ -0,0 +1,97 @@
<?php
/**
* Program-registry contract tests for TRU-19.
*
* Locks the architecture decision that the api does NOT expose a /programs
* endpoint that returns user-facing program names ("FF Uvs", "10min", "SF",
* etc.). Those names live on the wash bay hardware itself, not in the api.
*
* The api exposes MACHINE TYPES (e.g. "Mafa 5", "Washtec") via
* /department/selfserve/machine-types and PROGRAM PICKER relay control
* via /modules/self-serve/lane/relay/machine_program_picker/{status,set,enable,...}.
*
* The dashboard (pleno-vue) renders a numeric button registry (0-11) that
* maps to the physical programs on the wash bay. If a /programs endpoint
* ever appears in the api by accident, this test will fail and force the
* author to either (a) document the new endpoint and update this test, or
* (b) remove the spurious endpoint.
*
* Also locks the /department/selfserve/machine-types endpoint as a
* reachable, list-returning smoke target — this is the closest thing to
* a /programs endpoint that the api offers, and it should remain stable.
*/
it('does not expose a /programs endpoint (program names live on the wash bay)', function (): void {
$routesDir = app_path('routes');
$moduleRoutesDirs = glob(app_path('modules') . '/*/routes') ?: [];
$routeFiles = array_merge(
glob($routesDir . '/*.php') ?: [],
// Collect per-module route files
array_merge(...array_map(static fn($dir) => glob($dir . '/*.php') ?: [], $moduleRoutesDirs))
);
expect($routeFiles)->not->toBeEmpty('Expected to find at least one route file');
foreach ($routeFiles as $file) {
$source = file_get_contents($file);
expect($source)->not->toBeFalse("Failed to read route file: {$file}");
// Check for any route that would expose a /programs-style endpoint.
// The regex matches a $this->get(...) or $this->post(...) call with a
// /programs URI segment. We use word boundaries to avoid false
// positives on /modules/self-serve/lane/relay/machine_program_picker/*.
$matches = preg_match_all(
'/\$this->(?:get|post|put|delete|patch)\s*\(\s*[\'"]\/[^\'"]*\/programs[\'"]/',
$source,
$ignored
);
expect($matches)->toBe(
0,
"Found a /programs endpoint in {$file}. Program names live on the wash bay hardware — "
. 'the api should not expose them. If you intentionally want to add one, update this test '
. 'and document the new endpoint in docs/.'
);
}
});
it('exposes /department/selfserve/machine-types as the api-side program-adjacent endpoint', function (): void {
$machineTypesRoute = file_get_contents(app_path('routes/departmentSelfserveMachineTypesRoute.php'));
expect($machineTypesRoute)->not->toBeFalse();
expect($machineTypesRoute)->toContain('/department/selfserve/machine-types');
expect($machineTypesRoute)->toContain("'list_department_selfserve_machine_types'");
// The route must call $response->success(...) which is the standard
// "200 OK with JSON body" envelope. The contract is: a GET to this
// endpoint returns a JSON list of machine types.
expect($machineTypesRoute)->toContain('$response->success(');
// The route must enforce the list_* permission so unauthorized callers
// cannot enumerate machine types.
expect($machineTypesRoute)->toContain("requirePermission('list_department_selfserve_machine_types')");
});
it('exposes /modules/self-serve/lane/relay/machine_program_picker/* for program picker relay control', function (): void {
$selfServeRoute = file_get_contents(app_path('routes/moduleSelfServeRoute.php'));
expect($selfServeRoute)->not->toBeFalse();
// The program picker relay endpoints must exist. Pest's toContain does
// not accept a custom failure message, so we collect failures into a
// single assert at the end with a list of missing endpoints.
$expectedEndpoints = [
'/modules/self-serve/lane/relay/machine_program_picker/status',
'/modules/self-serve/lane/relay/machine_program_picker/set',
'/modules/self-serve/lane/relay/machine_program_picker/enable',
];
$missing = array_values(array_filter(
$expectedEndpoints,
static fn(string $endpoint): bool => !str_contains($selfServeRoute, $endpoint)
));
expect($missing)->toBe(
[],
'Missing program picker relay endpoints: ' . implode(', ', $missing)
);
});
@@ -0,0 +1,157 @@
<?php
app_require('classes/slack.php');
use classes\slack;
/**
* Fake slack subclass that captures webhook messages without doing I/O.
* Overrides get_department_webhook() so we don't touch redis/db.
*/
final class SlackNewBookingPickupFilterFake extends slack
{
public array $messages = [];
public string $webhook = 'https://hooks.slack.test/services/TRU-106-pickup-filter';
public ?string $webhookOverride = null; // null => use $this->webhook, '' => empty, etc.
public string $sendResult = 'Message sent successfully. Response: ok';
public function __construct()
{
// Skip parent config loading for unit isolation.
}
protected function get_department_webhook(int $department_id): string
{
return $this->webhookOverride ?? $this->webhook;
}
public function send_webhook_message(string $message, string $webhook): string
{
$this->messages[] = [
'message' => $message,
'webhook' => $webhook,
];
return $this->sendResult;
}
/**
* Stub format_new_booking so unit tests don't need a live redis/db
* (the real implementation calls departments_o::getDepartmentName,
* which dereferences the global `redis` object that is not loaded
* in the unit test bootstrap).
*/
public function format_new_booking(
$id,
$customer_number,
string $wash_type,
string $contact_email,
string $reference_number,
string $regNrTraekker,
string $regNrTrailer,
string $washCertificateEmail,
string $date,
int $department,
$pickup_bool,
string $notes,
string $washCertificateStatus,
string $washCertificateUrl,
string $status
): string {
$pickupLabel = $pickup_bool ? '1' : '0';
return "*Ny booking oprettet* ( ID: {$id} )\n"
. "Kunde: ({$customer_number})\n"
. "Type: {$wash_type}\n"
. "Reference nummer: {$reference_number}\n"
. "RegNr Traekker: {$regNrTraekker}\n"
. "RegNr Trailer: {$regNrTrailer}\n"
. "Dato: {$date}\n"
. "Hentning: {$pickupLabel}\n"
. "Noter: {$notes}";
}
}
/**
* Sample booking data used by all the tests below.
*/
function tru106_sample_booking(): array
{
return [
'id' => 4242,
'customer_number' => 1001,
'wash_type' => 'Standard wash',
'contact_email' => 'dispatcher@example.com',
'reference_number' => 'REF-001',
'regNrTraekker' => 'AB12345',
'regNrTrailer' => 'CD67890',
'washCertificateEmail' => '',
'date' => '2026-08-16 09:00:00',
'department' => 4,
'notes' => 'No notes',
'washCertificateStatus' => '',
'washCertificateUrl' => '',
'status' => 'pending',
];
}
function tru106_call_send_new_booking_notification(slack $slack, array $b, bool $pickup): bool
{
return $slack->send_new_booking_notification(
$b['id'],
$b['customer_number'],
$b['wash_type'],
$b['contact_email'],
$b['reference_number'],
$b['regNrTraekker'],
$b['regNrTrailer'],
$b['washCertificateEmail'],
$b['date'],
$b['department'],
$pickup,
$b['notes'],
$b['washCertificateStatus'],
$b['washCertificateUrl'],
$b['status']
);
}
it('posts a Slack notification when the new booking is a pickup (TRU-106)', function (): void {
$slack = new SlackNewBookingPickupFilterFake();
$sent = tru106_call_send_new_booking_notification($slack, tru106_sample_booking(), true);
expect($sent)->toBeTrue()
->and($slack->messages)->toHaveCount(1)
->and($slack->messages[0]['webhook'])->toBe('https://hooks.slack.test/services/TRU-106-pickup-filter')
->and($slack->messages[0]['message'])->toContain('Ny booking oprettet')
->and($slack->messages[0]['message'])->toContain('ID: 4242')
->and($slack->messages[0]['message'])->toContain('Kunde:')
->and(json_encode($slack->get_log(), JSON_UNESCAPED_SLASHES))->toContain('sent successfully');
});
it('does NOT post a Slack notification when the new booking is a drop-off (TRU-106)', function (): void {
$slack = new SlackNewBookingPickupFilterFake();
$sent = tru106_call_send_new_booking_notification($slack, tru106_sample_booking(), false);
expect($sent)->toBeFalse()
->and($slack->messages)->toBe([])
->and($slack->get_log())->toBe([]);
});
it('does NOT post a Slack notification when the department has no webhook configured (TRU-106)', function (): void {
$slack = new SlackNewBookingPickupFilterFake();
$slack->webhookOverride = '';
$sent = tru106_call_send_new_booking_notification($slack, tru106_sample_booking(), true);
expect($sent)->toBeFalse()
->and($slack->messages)->toBe([])
->and($slack->get_log())->toBe([]);
});
it('does not leak the webhook URL into the log payload for a pickup (TRU-106)', function (): void {
$slack = new SlackNewBookingPickupFilterFake();
tru106_call_send_new_booking_notification($slack, tru106_sample_booking(), true);
$logDump = json_encode($slack->get_log(), JSON_UNESCAPED_SLASHES);
expect($logDump)->not->toContain('hooks.slack.test')
->and($logDump)->toContain('sent successfully');
});
@@ -0,0 +1,59 @@
<?php
/*
* Regression test for TRU-18 / AUT-14:
* "api — truckwash.io invoices route to wrong EC account; some users"
*
* Root cause: getUserByCustomerNumber() in objects/users_o.php trusted the
* inverse Redis cache (customer_number -> user_id) without verifying that the
* user it loaded actually owns the requested EC customer_number in the local
* DB. When that cache went stale (e.g. after a customer_number re-mapping on
* a code path that did not clear the inverse cache), getUserByCustomerNumber()
* would return the wrong user. Downstream invoice code (getCustomerEcocomicData,
* setCustomerNumber) would then use that wrong user's current customer_number
* and route the draft invoice to the wrong Economic account.
*
* The fix verifies the loaded user owns the requested customer_number after
* the Redis fast-path, clears the stale cache entry, and re-fetches when the
* fast-path returned a user whose actual customer_number does not match.
*/
it('revalidates loaded user against requested customer_number after Redis fast-path (TRU-18)', function (): void {
$usersFile = app_path('objects/users_o.php');
$content = file_get_contents($usersFile);
expect($content)->not->toBeFalse();
// The fast-path (Redis cache hit) must verify the loaded user actually
// owns the requested EC customer_number before returning.
expect($content)->toContain('// BUG FIX (TRU-18 / AUT-14)');
expect($content)->toContain('getUserByCustomerNumber(int $customer_number)');
expect($content)->toContain('self::redisCache()?->get_user_id_from_customer_number($customer_number)');
expect($content)->toContain('$this->getObjectProperties();');
expect($content)->toContain('if ((int)$this->customer_number->value() !== $customer_number) {');
expect($content)->toContain('self::redisCache()?->clear_user_id_from_customer_number($customer_number);');
expect($content)->toContain('return $this->getUserByCustomerNumber($customer_number);');
});
it('keeps the DB lookup path as the source of truth when the Redis cache is empty or stale', function (): void {
$usersFile = app_path('objects/users_o.php');
$content = file_get_contents($usersFile);
expect($content)->not->toBeFalse();
// After clearing the stale cache, the recursive call must fall through to
// the DB query path which selects by exact customer_number match.
expect($content)->toContain('SELECT id FROM $this->table WHERE customer_number = \'$customer_number\'');
});
it('does not use the requested customer_number for any unrelated lookup in the invoice export flow', function (): void {
// Sanity check: the invoice export flow must go through getCustomerByOrderId
// -> getUserByCustomerNumber, so the TRU-18 fix above is the choke point.
$ordersFile = app_path('objects/orders_o.php');
$content = file_get_contents($ordersFile);
expect($content)->not->toBeFalse();
expect($content)->toContain('public function getCustomerByOrderId(?string $order_id): users_o');
expect($content)->toContain("SELECT customer_id FROM orders WHERE id = \$order_id");
expect($content)->toContain('return (new users_o())->getUserByCustomerNumber($row[\'customer_id\']);');
});