Files
api/services/nginx/app/tests/Unit/Customers/CustomerInvoiceEmailTest.php
T
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

244 lines
8.4 KiB
PHP

<?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([]);
});