Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62f2c80dda | ||
|
|
6f3d7e0f7d | ||
|
|
a8fba73d99 | ||
|
|
669759461d | ||
|
|
38814545c4 | ||
|
|
94c3654240 | ||
|
|
9fa249cc11 |
@@ -240,7 +240,13 @@ class economic_transfer_executor
|
||||
'Queued transfer processed successfully for collected invoice #' . $collected_invoice_id
|
||||
);
|
||||
|
||||
return $collected_order_invoices->asArray();
|
||||
$result = $collected_order_invoices->asArray();
|
||||
$transfer_metrics = $collected_order_invoices->getLastEconomicTransferMetrics();
|
||||
if ($transfer_metrics !== null) {
|
||||
$result['economic_transfer_metrics'] = $transfer_metrics;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -230,6 +230,16 @@ class limited_backoffice_service
|
||||
'limited_backoffice',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<int, true>
|
||||
*/
|
||||
private const PHONE_COUNTRY_CODES = [
|
||||
45 => true,
|
||||
46 => true,
|
||||
47 => true,
|
||||
358 => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
@@ -443,10 +453,15 @@ class limited_backoffice_service
|
||||
$mysqli->begin_transaction();
|
||||
|
||||
try {
|
||||
$priceUpdateAssignments = ['`price` = VALUES(`price`)'];
|
||||
if ($this->tableHasColumn('product_department_prices', 'updated_at')) {
|
||||
$priceUpdateAssignments[] = '`updated_at` = CURRENT_TIMESTAMP';
|
||||
}
|
||||
|
||||
$statement = $mysqli->prepare(
|
||||
'INSERT INTO `product_department_prices` (`department_id`, `product_id`, `price`)
|
||||
VALUES (?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE `price` = VALUES(`price`), `updated_at` = CURRENT_TIMESTAMP'
|
||||
ON DUPLICATE KEY UPDATE ' . implode(', ', $priceUpdateAssignments)
|
||||
);
|
||||
if ($statement === false) {
|
||||
throw new \RuntimeException('Unable to prepare department price update.');
|
||||
@@ -529,7 +544,8 @@ class limited_backoffice_service
|
||||
$roleKey = $this->normalizeRoleKey($payload['role_key'] ?? null);
|
||||
$displayName = $this->normalizeRequiredString($payload['display_name'] ?? null, 'Display name is required.');
|
||||
$password = $this->normalizePassword($payload['password'] ?? null, true);
|
||||
$email = $this->normalizeOptionalString($payload['email'] ?? null);
|
||||
$email = $this->normalizeEmail($payload['email'] ?? null, true);
|
||||
$phone = $this->normalizeOptionalPhonePair($payload);
|
||||
|
||||
$mysqli = $this->mysqli();
|
||||
$mysqli->begin_transaction();
|
||||
@@ -540,13 +556,23 @@ class limited_backoffice_service
|
||||
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
$statement = $mysqli->prepare(
|
||||
'INSERT INTO `users` (`customer_number`, `display_name`, `email`, `password`, `group_id`)
|
||||
VALUES (?, ?, ?, ?, ?)'
|
||||
'INSERT INTO `users`
|
||||
(`customer_number`, `display_name`, `email`, `password`, `group_id`, `phone_country_code`, `phone`)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
if ($statement === false) {
|
||||
throw new \RuntimeException('Unable to prepare employee insert.');
|
||||
}
|
||||
$statement->bind_param('isssi', $customerNumber, $displayName, $email, $passwordHash, $groupId);
|
||||
$statement->bind_param(
|
||||
'isssiii',
|
||||
$customerNumber,
|
||||
$displayName,
|
||||
$email,
|
||||
$passwordHash,
|
||||
$groupId,
|
||||
$phone['phone_country_code'],
|
||||
$phone['phone']
|
||||
);
|
||||
$statement->execute();
|
||||
$employeeId = (int)$mysqli->insert_id;
|
||||
$statement->close();
|
||||
@@ -624,11 +650,12 @@ class limited_backoffice_service
|
||||
? $this->normalizeRequiredString($payload['display_name'], 'Display name is required.')
|
||||
: null;
|
||||
$email = array_key_exists('email', $payload)
|
||||
? $this->normalizeOptionalString($payload['email'])
|
||||
? $this->normalizeEmail($payload['email'], true)
|
||||
: null;
|
||||
$password = array_key_exists('password', $payload)
|
||||
? $this->normalizePassword($payload['password'], false)
|
||||
: null;
|
||||
$phone = $this->normalizeOptionalPhonePair($payload, false);
|
||||
$active = array_key_exists('active', $payload)
|
||||
? (bool)$payload['active']
|
||||
: $this->isEmployeeRowActive($employee);
|
||||
@@ -658,6 +685,10 @@ class limited_backoffice_service
|
||||
if ($password !== null) {
|
||||
$userUpdates['password'] = password_hash($password, PASSWORD_DEFAULT);
|
||||
}
|
||||
if ($phone !== null) {
|
||||
$userUpdates['phone_country_code'] = $phone['phone_country_code'];
|
||||
$userUpdates['phone'] = $phone['phone'];
|
||||
}
|
||||
$usersHaveDeletedAt = $this->tableHasColumn('users', 'deleted_at');
|
||||
if ($active) {
|
||||
$userUpdates['group_id'] = $managedGroupId;
|
||||
@@ -1056,6 +1087,89 @@ class limited_backoffice_service
|
||||
return $value === '' ? null : $value;
|
||||
}
|
||||
|
||||
private function normalizeEmail(mixed $value, bool $required): ?string
|
||||
{
|
||||
$email = $this->normalizeOptionalString($value);
|
||||
if ($email === null) {
|
||||
if ($required) {
|
||||
throw new limited_backoffice_exception('Email is required.', 400);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
||||
throw new limited_backoffice_exception('Email must be a valid email address.', 400);
|
||||
}
|
||||
|
||||
return $email;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
* @return array{phone_country_code:int|null,phone:int|null}|null
|
||||
*/
|
||||
private function normalizeOptionalPhonePair(array $payload, bool $defaultWhenMissing = true): ?array
|
||||
{
|
||||
$hasCountryCode = array_key_exists('phone_country_code', $payload);
|
||||
$hasPhone = array_key_exists('phone', $payload);
|
||||
if (!$hasCountryCode && !$hasPhone) {
|
||||
return $defaultWhenMissing
|
||||
? ['phone_country_code' => null, 'phone' => null]
|
||||
: null;
|
||||
}
|
||||
|
||||
if (!$hasCountryCode || !$hasPhone) {
|
||||
throw new limited_backoffice_exception('Phone country code and phone number must be provided together.', 400);
|
||||
}
|
||||
|
||||
$countryCode = $this->normalizeOptionalDigits($payload['phone_country_code']);
|
||||
$phone = $this->normalizeOptionalDigits($payload['phone']);
|
||||
if ($countryCode === null && $phone === null) {
|
||||
return ['phone_country_code' => null, 'phone' => null];
|
||||
}
|
||||
|
||||
if ($countryCode === null || $phone === null) {
|
||||
throw new limited_backoffice_exception('Phone country code and phone number must be provided together.', 400);
|
||||
}
|
||||
|
||||
if (!isset(self::PHONE_COUNTRY_CODES[$countryCode])) {
|
||||
throw new limited_backoffice_exception('Phone country code is not supported.', 400);
|
||||
}
|
||||
|
||||
$phoneText = (string)$phone;
|
||||
if (!preg_match('/^\d{4,15}$/', $phoneText)) {
|
||||
throw new limited_backoffice_exception('Phone number must be 4-15 digits.', 400);
|
||||
}
|
||||
|
||||
return [
|
||||
'phone_country_code' => $countryCode,
|
||||
'phone' => $phone,
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeOptionalDigits(mixed $value): ?int
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_int($value)) {
|
||||
return $value > 0 ? $value : null;
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$value = trim($value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
if (ctype_digit($value)) {
|
||||
return (int)$value;
|
||||
}
|
||||
}
|
||||
|
||||
throw new limited_backoffice_exception('Phone values must contain digits only.', 400);
|
||||
}
|
||||
|
||||
private function normalizePassword(mixed $value, bool $required): ?string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
@@ -1231,6 +1345,8 @@ class limited_backoffice_service
|
||||
'customer_number' => (int)$row['customer_number'],
|
||||
'display_name' => (string)($row['display_name'] ?? ''),
|
||||
'email' => $row['email'] === null ? null : (string)$row['email'],
|
||||
'phone_country_code' => $row['phone_country_code'] === null ? null : (int)$row['phone_country_code'],
|
||||
'phone' => $row['phone'] === null ? null : (int)$row['phone'],
|
||||
'active' => $active,
|
||||
'role' => $this->rolePayload((string)$row['role_key']),
|
||||
'departments' => $this->departmentSummaries($departmentIds),
|
||||
@@ -1351,7 +1467,7 @@ class limited_backoffice_service
|
||||
$types = '';
|
||||
$values = [];
|
||||
foreach ($fields as $field => $value) {
|
||||
if (!in_array($field, ['display_name', 'email', 'password', 'group_id', 'deleted_at'], true)) {
|
||||
if (!in_array($field, ['display_name', 'email', 'password', 'group_id', 'deleted_at', 'phone_country_code', 'phone'], true)) {
|
||||
continue;
|
||||
}
|
||||
if ($value === null) {
|
||||
|
||||
+33
-5
@@ -61,19 +61,47 @@ class economic_invoices_draft_endpoint
|
||||
* @throws Exception If the request fails
|
||||
*/
|
||||
public function add_order(int $invoiceDraftId, orders_o $order, string $currency = 'DKK'): void
|
||||
{
|
||||
$this->add_orders($invoiceDraftId, [$order], $currency);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add many orders to a draft invoice and flush their lines in batches.
|
||||
*
|
||||
* @param orders_o[] $orders
|
||||
* @return array{order_count:int,orders_with_invoice_lines:int,line_count:int,batch_count:int,batch_sizes:array<int,int>}
|
||||
* @throws Exception If the request fails
|
||||
*/
|
||||
public function add_orders(int $invoiceDraftId, array $orders, string $currency = 'DKK', int $line_batch_size = 500): array
|
||||
{
|
||||
$draftInvoice = (new economic())->getInvoiceDraft($invoiceDraftId, strtoupper($currency), true);
|
||||
// Check if the order includes any items that should be included in the invoice
|
||||
if ($order->getIncludeInInvoiceCount() > 0) {
|
||||
$orders_with_invoice_lines = 0;
|
||||
|
||||
foreach ( $orders as $order ) {
|
||||
if (!$order instanceof orders_o) {
|
||||
throw new Exception('Order payload must contain orders_o instances');
|
||||
}
|
||||
// Check if the order includes any items that should be included in the invoice
|
||||
if ($order->getIncludeInInvoiceCount() <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$orders_with_invoice_lines++;
|
||||
// Add the transaction header (Timestamp, department, etc.)
|
||||
$draftInvoice->addNewTransactionHeader($order);
|
||||
// Add the order lines
|
||||
$draftInvoice->addOrderItemLines($order);
|
||||
// Add an empty line, so the invoice is not empty
|
||||
$draftInvoice->addTextLine('');
|
||||
// Save the draft invoice lines
|
||||
$draftInvoice->addLines();
|
||||
}
|
||||
|
||||
$metrics = $draftInvoice->flushLinesInBatches($line_batch_size);
|
||||
|
||||
return [
|
||||
'order_count' => count($orders),
|
||||
'orders_with_invoice_lines' => $orders_with_invoice_lines,
|
||||
...$metrics,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,4 +179,4 @@ class economic_invoices_draft_endpoint
|
||||
$draft_invoice->addLines();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ use objects\orders_o;
|
||||
|
||||
class economic_invoice_draft
|
||||
{
|
||||
public const DEFAULT_LINE_BATCH_SIZE = 500;
|
||||
|
||||
/**
|
||||
* The Economic draftInvoiceNumber
|
||||
* @var int $draft_invoice_number
|
||||
@@ -110,13 +112,55 @@ class economic_invoice_draft
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the lines to the draft invoice
|
||||
* @return void
|
||||
* Add the lines to the draft invoice.
|
||||
*/
|
||||
public function addLines(): void
|
||||
{
|
||||
$this->flushLinesInBatches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add queued draft lines using chunked requests.
|
||||
*
|
||||
* @return array{line_count:int,batch_count:int,batch_sizes:array<int,int>}
|
||||
*/
|
||||
public function flushLinesInBatches(int $batch_size = self::DEFAULT_LINE_BATCH_SIZE): array
|
||||
{
|
||||
$lines = array_values($this->draft_lines);
|
||||
$line_count = count($lines);
|
||||
if ($line_count === 0) {
|
||||
return [
|
||||
'line_count' => 0,
|
||||
'batch_count' => 0,
|
||||
'batch_sizes' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$batch_size = max(1, $batch_size);
|
||||
$batch_sizes = [];
|
||||
foreach (array_chunk($lines, $batch_size) as $batch) {
|
||||
$this->sendDraftLines($batch);
|
||||
$batch_sizes[] = count($batch);
|
||||
}
|
||||
|
||||
$this->draft_lines = [];
|
||||
|
||||
return [
|
||||
'line_count' => $line_count,
|
||||
'batch_count' => count($batch_sizes),
|
||||
'batch_sizes' => $batch_sizes,
|
||||
];
|
||||
}
|
||||
|
||||
public function pendingLineCount(): int
|
||||
{
|
||||
return count($this->draft_lines);
|
||||
}
|
||||
|
||||
protected function sendDraftLines(array $draft_lines): object
|
||||
{
|
||||
$economic = new economic();
|
||||
$economic->invoices->draft->add_lines($this->draft_invoice_number, $this->draft_lines);
|
||||
return $economic->invoices->draft->add_lines($this->draft_invoice_number, $draft_lines);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -37,6 +37,7 @@ class collected_order_invoices_o extends db
|
||||
public object_property $updated_at;
|
||||
public object_property $closed_at;
|
||||
public int $economic_wash_subscription_user_id = 1857;
|
||||
private ?array $last_economic_transfer_metrics = null;
|
||||
/**
|
||||
* The processor types
|
||||
*
|
||||
@@ -712,6 +713,7 @@ class collected_order_invoices_o extends db
|
||||
*/
|
||||
public function addInvoicesToDraft(bool $skip_check = false): self
|
||||
{
|
||||
$this->last_economic_transfer_metrics = null;
|
||||
// Require the invoice collection to be selected
|
||||
self::requireSelected();
|
||||
// Require the invoice collection to be open
|
||||
@@ -736,10 +738,20 @@ class collected_order_invoices_o extends db
|
||||
usort($orders, function ($a, $b) {
|
||||
return strtotime($a['created_at']) - strtotime($b['created_at']);
|
||||
});
|
||||
// Add the invoices to the invoice draft
|
||||
// Add the invoice lines to the draft in one accumulated batch path.
|
||||
$order_objects = [];
|
||||
foreach ( $orders as $order ) {
|
||||
self::addInvoiceToDraft($order['id'], true, $draft_id, $currency);
|
||||
$order_object = new orders_o();
|
||||
$order_object->select((int)$order['id']);
|
||||
$order_object->requireSelected();
|
||||
$order_objects[] = $order_object;
|
||||
}
|
||||
$metrics = (new economic())->invoices->draft->add_orders($draft_id, $order_objects, $currency);
|
||||
$this->last_economic_transfer_metrics = [
|
||||
'draft_invoice_id' => $draft_id,
|
||||
'currency' => (string)$currency,
|
||||
...$metrics,
|
||||
];
|
||||
// If the customer has the onlyTankCleaning attribute, add the environmental fee & oil fees to the invoice draft
|
||||
self::addEnvironmentalAndOilFeesToDraft($draft_id, $currency);
|
||||
// Object changed
|
||||
@@ -748,6 +760,11 @@ class collected_order_invoices_o extends db
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLastEconomicTransferMetrics(): ?array
|
||||
{
|
||||
return $this->last_economic_transfer_metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the environmental fee & oil fees to the invoice draft, if the customer has the onlyTankCleaning attribute
|
||||
* @param int $draft_id The invoice draft id
|
||||
|
||||
@@ -612,21 +612,46 @@ class orderInvoicesRoute
|
||||
$preview ? 'User previewed splitting collected order invoices by month' : 'User split collected order invoices by order month'
|
||||
);
|
||||
|
||||
$date_from = $db->escape_string($date_range['dateFrom']);
|
||||
$date_to = $db->escape_string($date_range['dateTo']);
|
||||
$sql = "SELECT DISTINCT invoice_collection_id
|
||||
FROM orders
|
||||
WHERE created_at BETWEEN '$date_from' AND '$date_to'
|
||||
AND invoice_collection_id IS NOT NULL
|
||||
AND invoice_collection_id > 0
|
||||
AND deleted_at IS NULL";
|
||||
$query_result = $db->query($sql);
|
||||
$invoice_collection_ids = [];
|
||||
while ($row = $query_result->fetch_assoc()) {
|
||||
$invoice_collection_id = (int)($row['invoice_collection_id'] ?? 0);
|
||||
if ($invoice_collection_id > 0) {
|
||||
if (self::isParametersSet(['invoice_collection_ids'])) {
|
||||
$invoice_collection_ids_raw = self::getParameter('invoice_collection_ids');
|
||||
if (!is_array($invoice_collection_ids_raw)) {
|
||||
$response->error('invoice_collection_ids must be an array', 400);
|
||||
}
|
||||
|
||||
foreach ($invoice_collection_ids_raw as $invoice_collection_id_raw) {
|
||||
if (is_array($invoice_collection_id_raw) || is_object($invoice_collection_id_raw) || !is_numeric($invoice_collection_id_raw)) {
|
||||
$response->error('invoice_collection_ids must contain only positive integer ids', 400);
|
||||
}
|
||||
|
||||
$invoice_collection_id = (int)$invoice_collection_id_raw;
|
||||
if ($invoice_collection_id < 1 || $invoice_collection_id > 999999999) {
|
||||
$response->error('invoice_collection_ids must contain only positive integer ids', 400);
|
||||
}
|
||||
|
||||
$invoice_collection_ids[] = $invoice_collection_id;
|
||||
}
|
||||
|
||||
$invoice_collection_ids = array_values(array_unique($invoice_collection_ids));
|
||||
if (empty($invoice_collection_ids)) {
|
||||
$response->error('invoice_collection_ids must contain at least one id', 400);
|
||||
}
|
||||
} else {
|
||||
$date_from = $db->escape_string($date_range['dateFrom']);
|
||||
$date_to = $db->escape_string($date_range['dateTo']);
|
||||
$sql = "SELECT DISTINCT invoice_collection_id
|
||||
FROM orders
|
||||
WHERE created_at BETWEEN '$date_from' AND '$date_to'
|
||||
AND invoice_collection_id IS NOT NULL
|
||||
AND invoice_collection_id > 0
|
||||
AND deleted_at IS NULL";
|
||||
$query_result = $db->query($sql);
|
||||
while ($row = $query_result->fetch_assoc()) {
|
||||
$invoice_collection_id = (int)($row['invoice_collection_id'] ?? 0);
|
||||
if ($invoice_collection_id > 0) {
|
||||
$invoice_collection_ids[] = $invoice_collection_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$items = [];
|
||||
|
||||
@@ -85,6 +85,65 @@ it('previews monthly split changes without moving orders or creating collections
|
||||
->and(monthly_split_order_collection_id((int)$aprilOrder['id']))->toBe((int)$invoiceCollection['id']);
|
||||
});
|
||||
|
||||
it('previews only explicit monthly split invoice collection ids', function (): void {
|
||||
api_test_covers('POST /collected-invoices/split-by-month', 'preview-scope');
|
||||
|
||||
$customer = api_fixtures()->createUser(['display_name' => 'Scoped Preview Monthly Split Customer']);
|
||||
$department = api_fixtures()->createDepartment();
|
||||
$targetCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
]);
|
||||
$ignoredCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
]);
|
||||
$targetMarchOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $targetCollection['id'],
|
||||
'created_at' => '2096-03-15 10:00:00',
|
||||
]);
|
||||
$targetAprilOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $targetCollection['id'],
|
||||
'created_at' => '2096-04-02 10:00:00',
|
||||
]);
|
||||
$ignoredMarchOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $ignoredCollection['id'],
|
||||
'created_at' => '2096-03-16 10:00:00',
|
||||
]);
|
||||
$ignoredAprilOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $ignoredCollection['id'],
|
||||
'created_at' => '2096-04-03 10:00:00',
|
||||
]);
|
||||
$session = api_fixtures()->createUserSession(['split_collected_invoice']);
|
||||
|
||||
$response = api_client()->post('/collected-invoices/split-by-month', [
|
||||
'dateFrom' => '2096-03-01',
|
||||
'dateTo' => '2096-04-30',
|
||||
'invoice_collection_ids' => [$targetCollection['id']],
|
||||
'preview' => true,
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$payload = $response->data();
|
||||
expect($payload['processed_count'] ?? null)->toBe(1)
|
||||
->and($payload['changed_count'] ?? null)->toBe(1)
|
||||
->and($payload['changed'][0]['invoice_collection_id'] ?? null)->toBe((int)$targetCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$targetMarchOrder['id']))->toBe((int)$targetCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$targetAprilOrder['id']))->toBe((int)$targetCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$ignoredMarchOrder['id']))->toBe((int)$ignoredCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$ignoredAprilOrder['id']))->toBe((int)$ignoredCollection['id']);
|
||||
});
|
||||
|
||||
it('splits a selected March and April collected invoice into monthly collections', function (): void {
|
||||
api_test_covers('POST /collected-invoices/split-by-month', 'happy');
|
||||
|
||||
@@ -139,6 +198,74 @@ it('splits a selected March and April collected invoice into monthly collections
|
||||
}
|
||||
});
|
||||
|
||||
it('splits only explicit monthly split invoice collection ids', function (): void {
|
||||
api_test_covers('POST /collected-invoices/split-by-month', 'scope');
|
||||
|
||||
$customer = api_fixtures()->createUser(['display_name' => 'Scoped Monthly Split Customer']);
|
||||
$department = api_fixtures()->createDepartment();
|
||||
$targetCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
'created_at' => '2096-03-01 00:00:01',
|
||||
]);
|
||||
$ignoredCollection = api_fixtures()->createInvoiceCollection([
|
||||
'customer_number' => $customer['customer_number'],
|
||||
'created_at' => '2096-03-01 00:00:01',
|
||||
]);
|
||||
$targetMarchOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $targetCollection['id'],
|
||||
'created_at' => '2096-03-15 10:00:00',
|
||||
]);
|
||||
$targetAprilOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $targetCollection['id'],
|
||||
'created_at' => '2096-04-02 10:00:00',
|
||||
]);
|
||||
$ignoredMarchOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $ignoredCollection['id'],
|
||||
'created_at' => '2096-03-16 10:00:00',
|
||||
]);
|
||||
$ignoredAprilOrder = api_fixtures()->createOrder([
|
||||
'customer_id' => $customer['customer_number'],
|
||||
'department_id' => $department['id'],
|
||||
'invoice_collection_id' => $ignoredCollection['id'],
|
||||
'created_at' => '2096-04-03 10:00:00',
|
||||
]);
|
||||
$session = api_fixtures()->createUserSession(['split_collected_invoice']);
|
||||
$createdCollectionIds = [];
|
||||
|
||||
try {
|
||||
$response = api_client()->post('/collected-invoices/split-by-month', [
|
||||
'dateFrom' => '2096-03-01',
|
||||
'dateTo' => '2096-04-30',
|
||||
'invoice_collection_ids' => [$targetCollection['id']],
|
||||
], $session['headers']);
|
||||
|
||||
$response
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$payload = $response->data();
|
||||
$createdCollectionIds = (array)($payload['changed'][0]['created_invoice_collection_ids'] ?? []);
|
||||
$aprilCollectionId = (int)($createdCollectionIds[0] ?? 0);
|
||||
|
||||
expect($payload['processed_count'] ?? null)->toBe(1)
|
||||
->and($payload['changed_count'] ?? null)->toBe(1)
|
||||
->and($aprilCollectionId)->toBeGreaterThan(0)
|
||||
->and(monthly_split_order_collection_id((int)$targetMarchOrder['id']))->toBe((int)$targetCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$targetAprilOrder['id']))->toBe($aprilCollectionId)
|
||||
->and(monthly_split_order_collection_id((int)$ignoredMarchOrder['id']))->toBe((int)$ignoredCollection['id'])
|
||||
->and(monthly_split_order_collection_id((int)$ignoredAprilOrder['id']))->toBe((int)$ignoredCollection['id']);
|
||||
} finally {
|
||||
monthly_split_cleanup_collections($createdCollectionIds);
|
||||
}
|
||||
});
|
||||
|
||||
it('sets closed_at to month end when split month has ended', function (): void {
|
||||
api_test_covers('POST /collected-invoices/split-by-month', 'closed-at');
|
||||
|
||||
@@ -345,3 +472,27 @@ it('rejects invalid monthly split date ranges', function (): void {
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false);
|
||||
});
|
||||
|
||||
it('rejects invalid explicit monthly split invoice collection ids', function (): void {
|
||||
api_test_covers('POST /collected-invoices/split-by-month', 'invalid-scope');
|
||||
|
||||
$session = api_fixtures()->createUserSession(['split_collected_invoice']);
|
||||
|
||||
api_client()->post('/collected-invoices/split-by-month', [
|
||||
'dateFrom' => '2096-03-01',
|
||||
'dateTo' => '2096-04-30',
|
||||
'invoice_collection_ids' => ['not-a-number'],
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false);
|
||||
|
||||
api_client()->post('/collected-invoices/split-by-month', [
|
||||
'dateFrom' => '2096-03-01',
|
||||
'dateTo' => '2096-04-30',
|
||||
'invoice_collection_ids' => [],
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false);
|
||||
});
|
||||
|
||||
@@ -85,6 +85,32 @@ function limited_backoffice_without_users_deleted_at(callable $callback): void
|
||||
}
|
||||
}
|
||||
|
||||
function limited_backoffice_without_department_prices_updated_at(callable $callback): void
|
||||
{
|
||||
$db = api_test_runtime()->db();
|
||||
$column = $db->query("SHOW COLUMNS FROM `product_department_prices` LIKE 'updated_at'");
|
||||
if ($column === false) {
|
||||
throw new RuntimeException('Unable to inspect product_department_prices.updated_at test column.');
|
||||
}
|
||||
|
||||
$hadColumn = (int)$column->num_rows > 0;
|
||||
if ($hadColumn) {
|
||||
$db->query('ALTER TABLE `product_department_prices` DROP COLUMN `updated_at`');
|
||||
}
|
||||
|
||||
try {
|
||||
$callback();
|
||||
} finally {
|
||||
if ($hadColumn) {
|
||||
$db->query(
|
||||
'ALTER TABLE `product_department_prices`
|
||||
ADD COLUMN `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
AFTER `created_at`'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('lists and updates explicit prices only for assigned departments', function (): void {
|
||||
api_test_covers('GET /limited-backoffice/departments', 'happy');
|
||||
api_test_covers('GET /limited-backoffice/departments/{departmentId}/prices', 'happy');
|
||||
@@ -148,6 +174,43 @@ it('lists and updates explicit prices only for assigned departments', function (
|
||||
expect(limited_backoffice_price_value((int)$otherDepartment['id'], (int)$product['id']))->toBe(4321);
|
||||
});
|
||||
|
||||
it('updates department prices when the price table has no updated_at column', function (): void {
|
||||
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'schema compatibility');
|
||||
|
||||
$department = api_fixtures()->createDepartment(['name' => 'Limited Prices Legacy Schema']);
|
||||
$category = api_fixtures()->createCategory(['name' => 'Limited Prices Legacy Category']);
|
||||
$products = [
|
||||
api_fixtures()->createProduct(['name' => 'Legacy Price One', 'category' => $category['id']]),
|
||||
api_fixtures()->createProduct(['name' => 'Legacy Price Two', 'category' => $category['id']]),
|
||||
api_fixtures()->createProduct(['name' => 'Legacy Price Three', 'category' => $category['id']]),
|
||||
];
|
||||
api_fixtures()->linkDepartmentCategory((int)$department['id'], (int)$category['id']);
|
||||
|
||||
foreach ($products as $index => $product) {
|
||||
limited_backoffice_price_insert((int)$department['id'], (int)$product['id'], 100 + $index);
|
||||
}
|
||||
|
||||
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||
limited_backoffice_without_department_prices_updated_at(function () use ($department, $products, $session): void {
|
||||
$updated = api_client()->put('/limited-backoffice/departments/' . (int)$department['id'] . '/prices', [
|
||||
'prices' => [
|
||||
['product_id' => (int)$products[0]['id'], 'price' => '999999'],
|
||||
['product_id' => (int)$products[1]['id'], 'price' => '999999'],
|
||||
['product_id' => (int)$products[2]['id'], 'price' => '99999'],
|
||||
],
|
||||
], $session['headers']);
|
||||
|
||||
$updated
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[0]['id']))->toBe(999999);
|
||||
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[1]['id']))->toBe(999999);
|
||||
expect(limited_backoffice_price_value((int)$department['id'], (int)$products[2]['id']))->toBe(99999);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects cross-department price access, body spoofing, and outside products', function (): void {
|
||||
api_test_covers('GET /limited-backoffice/departments/{departmentId}/prices', 'auth');
|
||||
api_test_covers('PUT /limited-backoffice/departments/{departmentId}/prices', 'auth');
|
||||
@@ -337,6 +400,8 @@ it('creates updates lists and deactivates scoped employees without exposing raw
|
||||
$created = api_client()->post('/limited-backoffice/employees', [
|
||||
'display_name' => 'Limited Cashier',
|
||||
'email' => 'limited-cashier@example.test',
|
||||
'phone_country_code' => 45,
|
||||
'phone' => 12345678,
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'cashier',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
@@ -350,6 +415,9 @@ it('creates updates lists and deactivates scoped employees without exposing raw
|
||||
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||
expect($employeeId)->toBeGreaterThan(0);
|
||||
limited_backoffice_cleanup_created_employee($employeeId);
|
||||
expect($created->data()['email'] ?? null)->toBe('limited-cashier@example.test');
|
||||
expect($created->data()['phone_country_code'] ?? null)->toBe(45);
|
||||
expect($created->data()['phone'] ?? null)->toBe(12345678);
|
||||
expect($created->body)->not->toContain('department_access_');
|
||||
expect($created->body)->not->toContain('permissions');
|
||||
|
||||
@@ -368,6 +436,9 @@ it('creates updates lists and deactivates scoped employees without exposing raw
|
||||
|
||||
$updated = api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||
'display_name' => 'Limited Lead',
|
||||
'email' => 'limited-lead@example.test',
|
||||
'phone_country_code' => 358,
|
||||
'phone' => 87654321,
|
||||
'role_key' => 'operations_lead',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
], $session['headers']);
|
||||
@@ -377,11 +448,25 @@ it('creates updates lists and deactivates scoped employees without exposing raw
|
||||
->assertSuccess();
|
||||
|
||||
expect($updated->data()['display_name'] ?? null)->toBe('Limited Lead');
|
||||
expect($updated->data()['email'] ?? null)->toBe('limited-lead@example.test');
|
||||
expect($updated->data()['phone_country_code'] ?? null)->toBe(358);
|
||||
expect($updated->data()['phone'] ?? null)->toBe(87654321);
|
||||
expect($updated->data()['role']['key'] ?? null)->toBe('operations_lead');
|
||||
|
||||
$list = api_client()->get('/limited-backoffice/employees', $session['headers']);
|
||||
$ids = array_column($list->data(), 'id');
|
||||
expect($ids)->toContain($employeeId);
|
||||
$listedEmployee = null;
|
||||
foreach ($list->data() as $employee) {
|
||||
if ((int)($employee['id'] ?? 0) === $employeeId) {
|
||||
$listedEmployee = $employee;
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect($listedEmployee)->not->toBeNull();
|
||||
expect($listedEmployee['email'] ?? null)->toBe('limited-lead@example.test');
|
||||
expect($listedEmployee['phone_country_code'] ?? null)->toBe(358);
|
||||
expect($listedEmployee['phone'] ?? null)->toBe(87654321);
|
||||
expect($list->body)->not->toContain('department_access_');
|
||||
|
||||
$deactivated = api_client()->delete('/limited-backoffice/employees/' . $employeeId, null, $session['headers']);
|
||||
@@ -403,6 +488,34 @@ it('creates updates lists and deactivates scoped employees without exposing raw
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts employees without optional phone details', function (): void {
|
||||
api_test_covers('POST /limited-backoffice/employees', 'happy');
|
||||
|
||||
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee No Phone']);
|
||||
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||
|
||||
$created = api_client()->post('/limited-backoffice/employees', [
|
||||
'display_name' => 'Limited No Phone',
|
||||
'email' => 'limited-no-phone@example.test',
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'viewer',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
], $session['headers']);
|
||||
|
||||
$created
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||
expect($employeeId)->toBeGreaterThan(0);
|
||||
limited_backoffice_cleanup_created_employee($employeeId);
|
||||
expect(array_key_exists('phone_country_code', $created->data()))->toBeTrue();
|
||||
expect(array_key_exists('phone', $created->data()))->toBeTrue();
|
||||
expect($created->data()['phone_country_code'])->toBeNull();
|
||||
expect($created->data()['phone'])->toBeNull();
|
||||
});
|
||||
|
||||
it('rejects employee scopes roles raw permissions self edits superusers and shared groups', function (): void {
|
||||
api_test_covers('POST /limited-backoffice/employees', 'validation');
|
||||
api_test_covers('PUT /limited-backoffice/employees/{employeeId}', 'validation');
|
||||
@@ -413,6 +526,7 @@ it('rejects employee scopes roles raw permissions self edits superusers and shar
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
'display_name' => 'Outside Employee',
|
||||
'email' => 'outside@example.test',
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'cashier',
|
||||
'department_ids' => [(int)$otherDepartment['id']],
|
||||
@@ -424,6 +538,7 @@ it('rejects employee scopes roles raw permissions self edits superusers and shar
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
'display_name' => 'Raw Employee',
|
||||
'email' => 'raw@example.test',
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'cashier',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
@@ -436,6 +551,7 @@ it('rejects employee scopes roles raw permissions self edits superusers and shar
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
'display_name' => 'Unknown Role Employee',
|
||||
'email' => 'unknown-role@example.test',
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'superuser',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
@@ -488,3 +604,88 @@ it('rejects employee scopes roles raw permissions self edits superusers and shar
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Cannot manage shared groups.');
|
||||
});
|
||||
|
||||
it('rejects invalid limited backoffice employee contact details', function (): void {
|
||||
api_test_covers('POST /limited-backoffice/employees', 'validation');
|
||||
api_test_covers('PUT /limited-backoffice/employees/{employeeId}', 'validation');
|
||||
|
||||
$department = api_fixtures()->createDepartment(['name' => 'Limited Employee Contact Validation']);
|
||||
$session = limited_backoffice_manager_session([(int)$department['id']]);
|
||||
$basePayload = [
|
||||
'display_name' => 'Contact Employee',
|
||||
'email' => 'contact@example.test',
|
||||
'password' => 'Secret123!',
|
||||
'role_key' => 'viewer',
|
||||
'department_ids' => [(int)$department['id']],
|
||||
];
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', array_diff_key($basePayload, ['email' => true]), $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Email is required.');
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
...$basePayload,
|
||||
'email' => 'not-an-email',
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Email must be a valid email address.');
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
...$basePayload,
|
||||
'phone_country_code' => 45,
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Phone country code and phone number must be provided together.');
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
...$basePayload,
|
||||
'phone_country_code' => 1,
|
||||
'phone' => 12345678,
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Phone country code is not supported.');
|
||||
|
||||
api_client()->post('/limited-backoffice/employees', [
|
||||
...$basePayload,
|
||||
'phone_country_code' => 45,
|
||||
'phone' => '12ab',
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Phone values must contain digits only.');
|
||||
|
||||
$created = api_client()->post('/limited-backoffice/employees', $basePayload, $session['headers'])
|
||||
->assertStatus(200)
|
||||
->assertEnvelope()
|
||||
->assertSuccess();
|
||||
|
||||
$employeeId = (int)($created->data()['id'] ?? 0);
|
||||
expect($employeeId)->toBeGreaterThan(0);
|
||||
limited_backoffice_cleanup_created_employee($employeeId);
|
||||
|
||||
api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||
'email' => '',
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Email is required.');
|
||||
|
||||
api_client()->put('/limited-backoffice/employees/' . $employeeId, [
|
||||
'phone_country_code' => 45,
|
||||
'phone' => '123',
|
||||
], $session['headers'])
|
||||
->assertStatus(400)
|
||||
->assertEnvelope()
|
||||
->assertSuccess(false)
|
||||
->assertMessage('Phone number must be 4-15 digits.');
|
||||
});
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
it('routes collected invoice draft line uploads through the multi-order batch endpoint', function (): void {
|
||||
$content = file_get_contents(dirname(__DIR__, 3) . '/objects/collected_order_invoices_o.php');
|
||||
|
||||
expect($content)->not->toBeFalse();
|
||||
$content = (string)$content;
|
||||
|
||||
$start = strpos($content, 'public function addInvoicesToDraft');
|
||||
$end = strpos($content, 'public function getLastEconomicTransferMetrics');
|
||||
expect($start)->not->toBeFalse();
|
||||
expect($end)->not->toBeFalse();
|
||||
expect($end)->toBeGreaterThan($start);
|
||||
|
||||
$methodBlock = substr($content, (int)$start, (int)$end - (int)$start);
|
||||
expect($methodBlock)->toContain('$order_objects = [];')
|
||||
->and($methodBlock)->toContain('$metrics = (new economic())->invoices->draft->add_orders($draft_id, $order_objects, $currency);')
|
||||
->and($methodBlock)->toContain('...$metrics')
|
||||
->and($methodBlock)->not->toContain('self::addInvoiceToDraft($order[\'id\'], true, $draft_id, $currency);');
|
||||
});
|
||||
|
||||
it('keeps single-order draft uploads as a wrapper around the batch endpoint', function (): void {
|
||||
$content = file_get_contents(dirname(__DIR__, 3) . '/modules/economic/endpoints/invoices/draft/economic_invoices_draft_endpoint.php');
|
||||
|
||||
expect($content)->not->toBeFalse();
|
||||
$content = (string)$content;
|
||||
|
||||
$singleStart = strpos($content, 'public function add_order');
|
||||
$singleEnd = strpos($content, 'public function add_orders');
|
||||
expect($singleStart)->not->toBeFalse();
|
||||
expect($singleEnd)->not->toBeFalse();
|
||||
expect($singleEnd)->toBeGreaterThan($singleStart);
|
||||
|
||||
$singleBlock = substr($content, (int)$singleStart, (int)$singleEnd - (int)$singleStart);
|
||||
expect($singleBlock)->toContain('$this->add_orders($invoiceDraftId, [$order], $currency);');
|
||||
|
||||
$batchBlock = substr($content, (int)$singleEnd);
|
||||
expect($batchBlock)->toContain('$draftInvoice->flushLinesInBatches($line_batch_size);')
|
||||
->and($batchBlock)->toContain("'orders_with_invoice_lines' => \$orders_with_invoice_lines");
|
||||
});
|
||||
|
||||
it('includes collected invoice batch transfer metrics in queue results when available', function (): void {
|
||||
$content = file_get_contents(dirname(__DIR__, 3) . '/classes/economic_transfer_executor.php');
|
||||
|
||||
expect($content)->not->toBeFalse();
|
||||
$content = (string)$content;
|
||||
|
||||
expect($content)->toContain('$transfer_metrics = $collected_order_invoices->getLastEconomicTransferMetrics();')
|
||||
->and($content)->toContain("\$result['economic_transfer_metrics'] = \$transfer_metrics;");
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
use helpers\economic_invoice_draft;
|
||||
|
||||
if (!class_exists('EconomicInvoiceDraftBatchingProbe')) {
|
||||
class EconomicInvoiceDraftBatchingProbe extends economic_invoice_draft
|
||||
{
|
||||
public array $sentBatches = [];
|
||||
|
||||
protected function sendDraftLines(array $draft_lines): object
|
||||
{
|
||||
$this->sentBatches[] = $draft_lines;
|
||||
return (object)['lines' => $draft_lines];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!class_exists('EconomicInvoiceDraftFailingBatchingProbe')) {
|
||||
class EconomicInvoiceDraftFailingBatchingProbe extends EconomicInvoiceDraftBatchingProbe
|
||||
{
|
||||
public int $failOnBatch = 1;
|
||||
|
||||
protected function sendDraftLines(array $draft_lines): object
|
||||
{
|
||||
if (count($this->sentBatches) + 1 === $this->failOnBatch) {
|
||||
throw new RuntimeException('Simulated e-conomic line batch failure');
|
||||
}
|
||||
|
||||
return parent::sendDraftLines($draft_lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('does not call e-conomic when flushing an empty draft line buffer', function (): void {
|
||||
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||
|
||||
$metrics = $draft->flushLinesInBatches();
|
||||
|
||||
expect($metrics)->toBe([
|
||||
'line_count' => 0,
|
||||
'batch_count' => 0,
|
||||
'batch_sizes' => [],
|
||||
])->and($draft->sentBatches)->toBe([]);
|
||||
});
|
||||
|
||||
it('flushes a small draft line buffer in one request and clears pending lines', function (): void {
|
||||
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||
$draft->addTextLine('line-0');
|
||||
$draft->addTextLine('line-1');
|
||||
$draft->addTextLine('line-2');
|
||||
|
||||
$metrics = $draft->flushLinesInBatches(500);
|
||||
|
||||
expect($metrics)->toBe([
|
||||
'line_count' => 3,
|
||||
'batch_count' => 1,
|
||||
'batch_sizes' => [3],
|
||||
])->and($draft->sentBatches)->toHaveCount(1)
|
||||
->and($draft->sentBatches[0][0]['description'])->toBe('line-0')
|
||||
->and($draft->sentBatches[0][2]['description'])->toBe('line-2')
|
||||
->and($draft->pendingLineCount())->toBe(0);
|
||||
});
|
||||
|
||||
it('chunks large draft line buffers while preserving line order', function (): void {
|
||||
$draft = new EconomicInvoiceDraftBatchingProbe(123, 'DKK', true);
|
||||
for ($i = 0; $i < 1201; $i++) {
|
||||
$draft->addTextLine('line-' . $i);
|
||||
}
|
||||
|
||||
$metrics = $draft->flushLinesInBatches(500);
|
||||
|
||||
expect($metrics)->toBe([
|
||||
'line_count' => 1201,
|
||||
'batch_count' => 3,
|
||||
'batch_sizes' => [500, 500, 201],
|
||||
])->and($draft->sentBatches)->toHaveCount(3)
|
||||
->and($draft->sentBatches[0][0]['description'])->toBe('line-0')
|
||||
->and($draft->sentBatches[1][0]['description'])->toBe('line-500')
|
||||
->and($draft->sentBatches[2][200]['description'])->toBe('line-1200')
|
||||
->and($draft->pendingLineCount())->toBe(0);
|
||||
});
|
||||
|
||||
it('bubbles line batch failures and keeps pending lines available', function (): void {
|
||||
$draft = new EconomicInvoiceDraftFailingBatchingProbe(123, 'DKK', true);
|
||||
$draft->addTextLine('line-0');
|
||||
|
||||
expect(fn () => $draft->flushLinesInBatches(500))
|
||||
->toThrow(RuntimeException::class, 'Simulated e-conomic line batch failure');
|
||||
|
||||
expect($draft->sentBatches)->toBe([])
|
||||
->and($draft->pendingLineCount())->toBe(1);
|
||||
});
|
||||
Reference in New Issue
Block a user