Files
api/services/nginx/app/tests/Unit/Cron/CronTaskRegistryTest.php
T
Jeppe Bopenclaw bugfixbugfixbugfix-subagent <[email protected]>
1742033bb7 TRU-70: auto-send invoice on the 3rd business day each month (#402)
## TRU-70: DRIFT 9 — Customer rule "auto-send invoice toggle (3rd
business day each month)"

Adds a per-customer rule that auto-sends the customer's invoice on the
3rd business day of each month. The rule is implemented as a new
customer attribute (`autoSendInvoiceThirdBusinessDay`) that can be
toggled through the existing `POST /customer/attributes` endpoint, plus
a daily cron task that, on the trigger day, enqueues every ready
collected invoice for export via the existing `economic_transfer_queue`.

## Linear

- **TRU-70** (DRIFT 9)

## Changes

- **Customer attribute (TRU-70 / DRIFT 9)**
  - `classes/customer_rule_product_restriction_service.php`
Adds `'autoSendInvoiceThirdBusinessDay'` to `SUPPORTED_ATTRIBUTES` so
the existing customer-attributes route can persist the toggle.

- **3rd-business-day service**
  - `classes/auto_send_invoice_third_business_day_service.php` (new)
- Computes the 3rd business day of any month (weekend-aware, holiday
provider override).
    - `runOnce()` is a no-op on every day except the 3rd business day.
- On the trigger day, scans `customer_attributes` for opted-in customers
and loads their ready `collected_order_invoices` (not booked, not
closed, has at least one order, not deleted).
- Enqueues each via `economic_transfer_queue` and returns a summary
`{triggered, customers, collections_scanned, jobs_enqueued,
skipped_already_queued, errors[]}`.
- Public hooks (`loadEligibleCustomerNumbers`,
`loadReadyInvoiceCollections`) and protected `createTransferQueue()` are
designed for unit-test isolation so no live database is required.

- **Cron task (TRU-70 / DRIFT 9)**
  - `modules/economic/cron/tasks.php`
Registers `'economic.auto_send_invoices_third_business_day'` with a 24h
interval, 15 min timeout, priority 25. Anchored in the economic module
because the actual export goes through `economic_transfer_queue`.
  - `cron/Cron.php`
New `AutoSendInvoicesThirdBusinessDay()` handler. Mirrors the
surrounding cron-task conventions (`warn` + `error_log` breadcrumb on
failure) and only logs a one-liner when the trigger fires.

## Tests

- `tests/Unit/Cron/AutoSendInvoiceThirdBusinessDayTest.php` (new, 16
tests)
- The 3rd-business-day computation (weekday-start, weekend-start,
Saturday, 4th-business-day, holiday skip, holiday forward-shift).
- `thirdBusinessDayOfMonth()` helper for the three reference months used
in the spec (Aug/Sep 2026 and Jul 2026).
  - `runOnce()` no-op path on non-trigger days.
  - `runOnce()` summary on trigger day with zero opted-in customers.
  - `runOnce()` summary with customers and ready collections.
  - `runOnce()` per-collection error recording when enqueue throws.
  - `clearOverrides()` reset.
- The new attribute is in
`customer_rule_product_restriction_service::SUPPORTED_ATTRIBUTES` and
exposes a stable `ATTRIBUTE` constant.
- `tests/Unit/Cron/CronTaskRegistryTest.php`
Updated the discovery assertion from 22 to 23 definitions and added
coverage that the new `'economic.auto_send_invoices_third_business_day'`
task is discovered with the expected schedule and module.

## Backwards compatibility

- The new attribute is additive; existing `customer_attributes` rows are
unaffected. The default customer has no auto-send rule.
- The cron task is registered in the standard task registry; the
existing `cron_worker` (15s poll) handles the trigger without any new
infrastructure.
- The service gracefully no-ops when the transfer queue is unavailable
in unit-test contexts; the production cron task will surface a `warn()`
breadcrumb if e-conomic is unreachable, exactly like the other economic
cron tasks.

## Verification

```
vendor/bin/pest tests/Unit/Cron/ tests/Unit/Customers/
# 43 passed (199 assertions)
```

---------

Co-authored-by: openclaw bugfix <openclaw@copenhagentruckwash.local>
Co-authored-by: bugfix <bugfix@truckwash.local>
Co-authored-by: bugfix-subagent <[email protected]>
2026-08-17 16:42:14 +00:00

87 lines
3.0 KiB
PHP

<?php
use classes\cron_schedule;
use classes\cron_task_registry;
it('discovers module-owned cron task definitions', function (): void {
$registry = new cron_task_registry(app_path('modules'));
$definitions = $registry->definitions();
expect($definitions)->toHaveCount(23);
expect(array_keys($definitions))->toContain(
'system.sync_logs',
'backups.process_jobs',
'backups.prune_retention',
'economic.transfer_queue',
'economic.auto_send_invoices_third_business_day',
'dynamicimages.pre_render',
'weatherapi.preload_department_responses',
'goals.progress_alerts',
'account.process_deletion_requests',
'selfserve.activate_opening_cleaner_relays'
);
expect(array_keys($definitions))->not->toContain('xlvask.autopilot_queue');
$transferQueue = $registry->get('EconomicTransferQueueCron');
expect($transferQueue)->not->toBeNull();
expect($transferQueue->id)->toBe('economic.transfer_queue');
expect($transferQueue->module)->toBe('economic');
expect($transferQueue->schedule)->toBe(['type' => 'interval', 'seconds' => 30]);
$autoSend = $registry->get('AutoSendInvoicesThirdBusinessDay');
expect($autoSend)->not->toBeNull();
expect($autoSend->id)->toBe('economic.auto_send_invoices_third_business_day');
expect($autoSend->module)->toBe('economic');
expect($autoSend->schedule)->toBe(['type' => 'interval', 'seconds' => 86400]);
});
it('keeps every discovered cron task in a module cron folder', function (): void {
$files = glob(app_path('modules/*/cron/tasks.php')) ?: [];
$modules = array_map(
static fn(string $file): string => basename(dirname(dirname($file))),
$files
);
$registry = new cron_task_registry(app_path('modules'));
foreach ($registry->definitions() as $definition) {
expect($modules)->toContain($definition->module);
}
});
it('normalizes and advances interval schedules without tight loops', function (): void {
expect(cron_schedule::normalize(['type' => 'interval', 'seconds' => 60]))
->toBe(['type' => 'interval', 'seconds' => 60]);
$now = strtotime('2026-07-09 12:10:00');
$next = cron_schedule::nextRunAt(
['type' => 'interval', 'seconds' => 300],
'2026-07-09 12:00:00',
$now
);
expect($next)->toBe('2026-07-09 12:15:00');
});
it('keeps minute schedules anchored to intended slots when execution finishes late', function (): void {
$schedule = ['type' => 'interval', 'seconds' => 60];
$first = cron_schedule::nextRunAt(
$schedule,
'2026-07-27 12:00:00',
strtotime('2026-07-27 12:00:47')
);
$second = cron_schedule::nextRunAt(
$schedule,
$first,
strtotime('2026-07-27 12:01:52')
);
expect($first)->toBe('2026-07-27 12:01:00');
expect($second)->toBe('2026-07-27 12:02:00');
});
it('rejects unsafe cron intervals', function (): void {
expect(fn() => cron_schedule::normalize(['type' => 'interval', 'seconds' => 5]))
->toThrow(InvalidArgumentException::class);
});