From 4071776ff4001a28780bfbb667ec424df7ea7620 Mon Sep 17 00:00:00 2001 From: DevSviat Date: Fri, 13 Nov 2026 11:05:30 +0200 Subject: [PATCH] =?UTF-8?q?feat:=201.4.0=20=E2=80=94=20=D1=87=D0=B5=D0=BA?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=BA=D1=83=D0=BF=D1=86=D0=B5=D0=B2=D1=96=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D1=82=D0=B5=D0=BB=D0=B5=D1=84=D0=BE=D0=BD=20(Vi?= =?UTF-8?q?ber/SMS)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - налаштування «Куди надсилати чек»: email, телефон, обидва, або телефон лише без email - одне правило для всіх чеків замовлення, включно з післяплатою й поверненням ланцюжка - email у полі emails замість застарілого email - попередження, якщо в кабінеті Checkbox не ввімкнено відправку на телефон --- Backend/Controllers/CheckboxAdmin.php | 20 ++++- Backend/design/html/checkbox_admin.tpl | 19 +++-- Backend/lang/en.php | 7 +- Backend/lang/ru.php | 9 ++- Backend/lang/ua.php | 11 ++- Helpers/CheckboxApiHelper.php | 24 ++++++ Helpers/CheckboxPrepaymentHelper.php | 14 +++- Helpers/CheckboxReceiptDelivery.php | 82 +++++++++++++++++++ Helpers/CheckboxReceiptsHelper.php | 51 +++++++----- Init/Init.php | 2 + Init/module.json | 2 +- README.md | 21 +++++ tests/ReceiptDeliveryTest.php | 107 +++++++++++++++++++++++++ tests/ReceiptIdempotencyTest.php | 62 +++++++++++++- 14 files changed, 389 insertions(+), 42 deletions(-) create mode 100644 Helpers/CheckboxReceiptDelivery.php create mode 100644 tests/ReceiptDeliveryTest.php diff --git a/Backend/Controllers/CheckboxAdmin.php b/Backend/Controllers/CheckboxAdmin.php index 1eacbdc..6d44add 100644 --- a/Backend/Controllers/CheckboxAdmin.php +++ b/Backend/Controllers/CheckboxAdmin.php @@ -12,7 +12,9 @@ use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxChainId; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxHelper; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxPaymentCatalogue; +use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxApiHelper; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxPaymentSources; +use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxReceiptDelivery; use Okay\Modules\Sviat\Checkbox\Init\Init; use Okay\Modules\Sviat\Checkbox\Security\PlainSettingValue; use Okay\Modules\Sviat\Checkbox\Security\RequestOrigin; @@ -23,7 +25,8 @@ class CheckboxAdmin extends IndexAdmin public function fetch( CheckboxHelper $checkboxHelper, CashierShiftsEntity $shiftsEntity, - OrderStatusEntity $orderStatusEntity + OrderStatusEntity $orderStatusEntity, + CheckboxApiHelper $apiHelper ) { // Не просто «був POST», а «прийшла саме ця форма». На сторінці є й чужі // форми з action="" — вихід із адмінки, наприклад, — і будь-яка з них @@ -39,7 +42,7 @@ public function fetch( $this->saveTextSetting('sviat__checkbox__receipt_text'); $this->settings->set('sviat__checkbox__order_status_id', $this->request->post('sviat__checkbox__order_status_id', 'integer')); - $this->settings->set('sviat__checkbox__send_message', $this->request->post('sviat__checkbox__send_message', 'integer')); + $this->settings->set(Init::SEND_MESSAGE, CheckboxReceiptDelivery::mode($this->request->post(Init::SEND_MESSAGE))); $this->saveTextSetting('sviat__checkbox__cashier_login'); $this->saveSecretSetting('sviat__checkbox__cashier_password'); $this->saveSecretSetting('sviat__checkbox__cashier_license_key'); @@ -106,11 +109,20 @@ public function fetch( $this->design->assign('checkboxPasswordIsSet', (string) $this->settings->get('sviat__checkbox__cashier_password') !== ''); $this->design->assign('checkboxLicenseIsSet', (string) $this->settings->get('sviat__checkbox__cashier_license_key') !== ''); $this->design->assign('checkboxReturnUrl', ReturnUrl::safe($this->request->get('return'))); - $this->design->assign('checkboxCashierConfigured', (string) $this->settings->get('sviat__checkbox__cashier_login') !== '' + $cashierConfigured = (string) $this->settings->get('sviat__checkbox__cashier_login') !== '' && (string) $this->settings->get('sviat__checkbox__cashier_password') !== '' - && (string) $this->settings->get('sviat__checkbox__cashier_license_key') !== ''); + && (string) $this->settings->get('sviat__checkbox__cashier_license_key') !== ''; + $this->design->assign('checkboxCashierConfigured', $cashierConfigured); $this->design->assign('checkboxActiveShift', $shiftsEntity->getActiveShift()); + $deliveryMode = CheckboxReceiptDelivery::mode($this->settings->get(Init::SEND_MESSAGE)); + $this->design->assign('checkboxDeliveryMode', $deliveryMode); + // Запит до Checkbox лише тоді, коли від відповіді щось залежить: інакше + // кожне відкриття сторінки входило б касиром у бойовий API. + $this->design->assign('checkboxPhoneDelivery', CheckboxReceiptDelivery::usesPhone($deliveryMode) && $cashierConfigured + ? $apiHelper->phoneDeliveryEnabled() + : null); + $this->response->setContent($this->design->fetch('checkbox_admin.tpl')); } diff --git a/Backend/design/html/checkbox_admin.tpl b/Backend/design/html/checkbox_admin.tpl index 3924649..7b94846 100644 --- a/Backend/design/html/checkbox_admin.tpl +++ b/Backend/design/html/checkbox_admin.tpl @@ -218,14 +218,21 @@
{$btr->sviat__checkbox__message_how_send|escape}
+

{$btr->sviat__checkbox__message_phone_hint|escape}

+ {if $checkboxPhoneDelivery === false} +
+
+
{$btr->sviat__checkbox__message_phone_off|escape}
+
+
+ {/if} diff --git a/Backend/lang/en.php b/Backend/lang/en.php index e4b9780..8ba81e8 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -162,9 +162,14 @@ $lang['sviat__checkbox__type_cash'] = 'Cash'; $lang['sviat__checkbox__type_cashless'] = 'Non-cash payment'; -$lang['sviat__checkbox__message_how_send'] = 'Send receipt via'; +$lang['sviat__checkbox__message_how_send'] = 'Where to send the receipt'; $lang['sviat__checkbox__message_not_send'] = 'Do not send'; $lang['sviat__checkbox__message_email'] = 'Email'; +$lang['sviat__checkbox__message_phone'] = 'Phone (Viber or SMS)'; +$lang['sviat__checkbox__message_email_and_phone'] = 'Email and phone'; +$lang['sviat__checkbox__message_email_else_phone'] = 'Email, or phone if there is no email'; +$lang['sviat__checkbox__message_phone_hint'] = 'Checkbox sends the receipt to Viber and falls back to SMS if it is not delivered. This is a paid service: turn it on and top up the balance in your Checkbox account.'; +$lang['sviat__checkbox__message_phone_off'] = 'Sending receipts to phones is not turned on in your Checkbox account. Until it is, no receipts will go to phones.'; $lang['sviat__checkbox__label_name'] = 'Checkbox label'; $lang['sviat__checkbox__type'] = 'Checkbox payment type'; diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index 78e8bfa..06c691a 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -162,9 +162,14 @@ $lang['sviat__checkbox__type_cash'] = 'Наличные'; $lang['sviat__checkbox__type_cashless'] = 'Безналичный расчёт'; -$lang['sviat__checkbox__message_how_send'] = 'Отправить чек по'; +$lang['sviat__checkbox__message_how_send'] = 'Куда отправлять чек покупателю'; $lang['sviat__checkbox__message_not_send'] = 'Не отправлять'; -$lang['sviat__checkbox__message_email'] = 'По Email'; +$lang['sviat__checkbox__message_email'] = 'На email'; +$lang['sviat__checkbox__message_phone'] = 'На телефон (Viber или SMS)'; +$lang['sviat__checkbox__message_email_and_phone'] = 'На email и на телефон'; +$lang['sviat__checkbox__message_email_else_phone'] = 'На email, а без email — на телефон'; +$lang['sviat__checkbox__message_phone_hint'] = 'На телефон Checkbox отправляет чек в Viber, а если он не дойдёт — SMS. Это платно: отправку включают и пополняют в кабинете Checkbox.'; +$lang['sviat__checkbox__message_phone_off'] = 'В кабинете Checkbox не включена отправка чеков на телефон. Пока её не включить, на телефон чеки не уйдут.'; $lang['sviat__checkbox__label_name'] = 'Название для Checkbox'; $lang['sviat__checkbox__type'] = 'Тип оплаты Checkbox'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index 6fb87b6..e5a35a6 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -163,9 +163,14 @@ $lang['sviat__checkbox__type_cash'] = 'Готівка'; $lang['sviat__checkbox__type_cashless'] = 'Безготівковий розрахунок'; -$lang['sviat__checkbox__message_how_send'] = 'Надіслати чек по'; -$lang['sviat__checkbox__message_not_send'] = 'Не відправляти'; -$lang['sviat__checkbox__message_email'] = 'По Email'; +$lang['sviat__checkbox__message_how_send'] = 'Куди надсилати чек покупцеві'; +$lang['sviat__checkbox__message_not_send'] = 'Не надсилати'; +$lang['sviat__checkbox__message_email'] = 'На email'; +$lang['sviat__checkbox__message_phone'] = 'На телефон (Viber або SMS)'; +$lang['sviat__checkbox__message_email_and_phone'] = 'На email і на телефон'; +$lang['sviat__checkbox__message_email_else_phone'] = 'На email, а без email — на телефон'; +$lang['sviat__checkbox__message_phone_hint'] = 'На телефон Checkbox шле чек у Viber, а якщо він не дійде — SMS. Це платно: відправку вмикають і поповнюють у кабінеті Checkbox.'; +$lang['sviat__checkbox__message_phone_off'] = 'У кабінеті Checkbox не ввімкнено відправку чеків на телефон. Поки її не ввімкнути, на телефон чеки не підуть.'; $lang['sviat__checkbox__label_name'] = 'Назва для Checkbox'; $lang['sviat__checkbox__type'] = 'Тип оплати Checkbox'; diff --git a/Helpers/CheckboxApiHelper.php b/Helpers/CheckboxApiHelper.php index ed60a6b..b023055 100644 --- a/Helpers/CheckboxApiHelper.php +++ b/Helpers/CheckboxApiHelper.php @@ -79,6 +79,30 @@ public function getAccessToken() return $response; } + /** + * Чи ввімкнена в кабінеті Checkbox платна відправка чеків на телефон. Без неї + * Checkbox приймає номер у чеку й нічого не надсилає. + * + * @return bool|null null — не вдалося дізнатися + */ + public function phoneDeliveryEnabled(): ?bool + { + $this->clearErrors(); + if (empty($this->accessToken)) { + $this->getAccessToken(); + if (empty($this->accessToken)) { + return null; + } + } + + $response = $this->makeApiRequest('organization/sms-billing', [], ['method' => 'GET']); + if (!empty($this->errors) || !is_array($response) || !is_bool($response['can_send_sms'] ?? null)) { + return null; + } + + return $response['can_send_sms']; + } + protected function clearErrors(): void { $this->errors = []; diff --git a/Helpers/CheckboxPrepaymentHelper.php b/Helpers/CheckboxPrepaymentHelper.php index 066eb4b..bcd30ef 100644 --- a/Helpers/CheckboxPrepaymentHelper.php +++ b/Helpers/CheckboxPrepaymentHelper.php @@ -61,12 +61,20 @@ public function chainStatus(string $relationId): ?array return is_array($response) && isset($response['pre_payment_status']) ? $response : null; } - /** @return array|string|false */ - public function returnChain(string $relationId, string $cashierName) + /** + * @param array|null $delivery куди надіслати чеки повернення, {@see CheckboxReceiptDelivery} + * @return array|string|false + */ + public function returnChain(string $relationId, string $cashierName, ?array $delivery = null) { + $payload = ['cashier_name' => $cashierName]; + if ($delivery !== null) { + $payload['delivery'] = $delivery; + } + return $this->authorisedRequest( 'prepayment-receipts/' . rawurlencode($relationId) . '/return', - ['cashier_name' => $cashierName], + $payload, 'POST', 'chain not returned' ); diff --git a/Helpers/CheckboxReceiptDelivery.php b/Helpers/CheckboxReceiptDelivery.php new file mode 100644 index 0000000..94a9b16 --- /dev/null +++ b/Helpers/CheckboxReceiptDelivery.php @@ -0,0 +1,82 @@ +, phone?: string}|null null — нікуди не надсилати + */ + public static function payload(int $mode, ?string $email, ?string $phone): ?array + { + $email = self::email($email); + $phone = self::phone($phone); + + $sendEmail = in_array($mode, [self::EMAIL, self::EMAIL_AND_PHONE, self::EMAIL_ELSE_PHONE], true) && $email !== null; + $sendPhone = $phone !== null && match ($mode) { + self::PHONE, self::EMAIL_AND_PHONE => true, + self::EMAIL_ELSE_PHONE => $email === null, + default => false, + }; + + // `emails`, а не одиничне `email`: друге Checkbox позначив застарілим. + $delivery = []; + if ($sendEmail) { + $delivery['emails'] = [$email]; + } + if ($sendPhone) { + $delivery['phone'] = $phone; + } + + return $delivery === [] ? null : $delivery; + } + + /** + * Номер у вигляді 380XXXXXXXXX. Іноземний номер дає null: Checkbox приймає + * лише українські, а `/receipts/{id}/sms` ще й без «+». + */ + public static function phone(?string $raw): ?string + { + $digits = preg_replace('~\D~', '', (string)$raw) ?? ''; + if (preg_match('~^0\d{9}$~', $digits)) { + $digits = '38' . $digits; + } + + return preg_match('~^380\d{9}$~', $digits) ? $digits : null; + } + + private static function email(?string $raw): ?string + { + $email = filter_var(trim((string)$raw), FILTER_VALIDATE_EMAIL); + + return is_string($email) ? $email : null; + } +} diff --git a/Helpers/CheckboxReceiptsHelper.php b/Helpers/CheckboxReceiptsHelper.php index 4389500..cc5db00 100644 --- a/Helpers/CheckboxReceiptsHelper.php +++ b/Helpers/CheckboxReceiptsHelper.php @@ -183,8 +183,8 @@ public function createReceipt(int $orderId, bool $isReturn = false, ?int $receip 'goods' => $context['goods'], 'payments' => $payments, ]; - if ($context['email'] !== null) { - $orderData['delivery'] = ['email' => $context['email']]; + if ($context['delivery'] !== null) { + $orderData['delivery'] = $context['delivery']; } if ($context['footer'] !== '') { $orderData['footer'] = $context['footer']; @@ -623,8 +623,8 @@ private function openChain(int $orderId, int $advanceKopiyky, string $source, ar if ($context['footer'] !== '') { $payload['footer'] = $context['footer']; } - if ($context['email'] !== null) { - $payload['delivery'] = ['email' => $context['email']]; + if ($context['delivery'] !== null) { + $payload['delivery'] = $context['delivery']; } // Рядок-намір ДО виклику: якщо Checkbox створить ланцюжок, а відповідь @@ -907,6 +907,10 @@ private function closeChain(int $orderId, ?int $amountKopiyky, string $source, ? 'cashier_name' => is_array($cashier) && isset($cashier['full_name']) ? (string)$cashier['full_name'] : '', 'payments' => [CheckboxPaymentForm::payment($source, $amount, $label)], ]; + $delivery = $this->orderDelivery($orderId); + if ($delivery !== null) { + $payload['delivery'] = $delivery; + } $response = $this->withShiftRecovery(fn () => $this->prepaymentHelper->addPayment($chain['relation_id'], $payload)); if (!empty($this->errors) || !is_array($response)) { @@ -992,7 +996,8 @@ private function returnChainReceipts(int $orderId) $cashier = $this->shiftsHelper->getCashierInfo(); $cashierName = is_array($cashier) && isset($cashier['full_name']) ? (string)$cashier['full_name'] : ''; - $response = $this->withShiftRecovery(fn () => $this->prepaymentHelper->returnChain($chain['relation_id'], $cashierName)); + $delivery = $this->orderDelivery($orderId); + $response = $this->withShiftRecovery(fn () => $this->prepaymentHelper->returnChain($chain['relation_id'], $cashierName, $delivery)); if (!empty($this->errors)) { return (object)['message' => $this->errors['message'] ?? 'chain return failed']; } @@ -1148,7 +1153,7 @@ private function orderPaymentLabel(int $orderId): ?string * позначки is_return на кожній позиції, і забутий аргумент відправив би * повернення в Checkbox як продаж — мовчки. Хай краще падає. * - * @return array{goods: array, goodsTotal: int, cashierName: string, footer: string, email: string|null}|array{message: string} + * @return array{goods: array, goodsTotal: int, cashierName: string, footer: string, delivery: array|null}|array{message: string} */ private function buildOrderContext(int $orderId, bool $isReturn): array { @@ -1208,27 +1213,35 @@ private function buildOrderContext(int $orderId, bool $isReturn): array ? str_replace('{$order_id}', (string)$orderId, $receiptText) : ''; - // Налаштування «як надсилати чек» діє на всі чеки замовлення, не лише на - // продаж: 0 означає «не надсилати», і чек авансу не має бути винятком. - $email = null; - $sendMessageSetting = $this->settings->get('sviat__checkbox__send_message'); - $sendMessageSetting = is_numeric($sendMessageSetting) ? (int)$sendMessageSetting : 0; - if (in_array($sendMessageSetting, [1, 3, 4], true) && is_string($order->email)) { - $validated = filter_var(trim($order->email), FILTER_VALIDATE_EMAIL); - if ($validated !== false) { - $email = $validated; - } - } - return [ 'goods' => $payload['goods'], 'goodsTotal' => $payload['paymentValue'], 'cashierName' => is_array($cashier) && isset($cashier['full_name']) ? (string)$cashier['full_name'] : '', 'footer' => $footer, - 'email' => $email, + 'delivery' => $this->deliveryFor($order), ]; } + /** + * Куди Checkbox надішле чек. Налаштування діє на всі чеки замовлення: + * аванс, післяплату й повернення теж, інакше «не надсилати» мало б винятки. + */ + private function orderDelivery(int $orderId): ?array + { + $order = $this->entityFactory->get(OrdersEntity::class)->get($orderId); + + return $order ? $this->deliveryFor($order) : null; + } + + private function deliveryFor(object $order): ?array + { + return CheckboxReceiptDelivery::payload( + CheckboxReceiptDelivery::mode($this->settings->get(Init::SEND_MESSAGE)), + is_string($order->email ?? null) ? $order->email : null, + is_string($order->phone ?? null) ? $order->phone : null + ); + } + /** Checkbox наполегливо радить власний UUID чека — він же дає слід у їхніх логах. */ private function uuid4(): string { diff --git a/Init/Init.php b/Init/Init.php index b3b14cc..9b0ae25 100644 --- a/Init/Init.php +++ b/Init/Init.php @@ -51,6 +51,8 @@ class Init extends AbstractInit public const REQUIRE_PAYMENT_METHOD = 'sviat__checkbox__require_payment_method'; + public const SEND_MESSAGE = 'sviat__checkbox__send_message'; + public function install() { $this->setBackendMainController('CheckboxAdmin'); diff --git a/Init/module.json b/Init/module.json index 586d0b2..37e784a 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "1.3.0", + "version": "1.4.0", "moduleName": "Checkbox ПРРО", "vendor": { "email": "devsviat@proton.me", diff --git a/README.md b/README.md index 06ba1d8..392a373 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ - Створення чека повернення. - Перегляд усіх чеків замовлення прямо в адмінці. - Посилання на чек для покупця на сторінці замовлення. +- Чек покупцеві на email або на телефон (Viber, а якщо не дійде — SMS). ### Оплата частинами (передплата) @@ -144,6 +145,26 @@ Опція діє і на нові, і на наявні замовлення. Замовлення з вітрини вона не зачіпає. +### Куди надсилати чек покупцеві + +На вкладці «Чек» оберіть, куди Checkbox надішле чек після фіскалізації: + +- **Не надсилати.** +- **На email.** +- **На телефон (Viber або SMS).** Checkbox шле чек у Viber, а якщо він не дійде — SMS. +- **На email і на телефон.** +- **На email, а без email — на телефон.** Телефон потрібен лише для замовлень без пошти, + тож платних повідомлень менше. + +Налаштування діє на всі чеки замовлення: продаж, повернення, аванс і післяплату. За +замовлення з передплатою на телефон підуть два повідомлення. + +Відправка на телефон платна. Її вмикають і поповнюють у кабінеті Checkbox. Поки її не +ввімкнено, Checkbox приймає номер і нічого не надсилає. Тому, коли вибрано режим із +телефоном, сторінка налаштувань перевіряє це в Checkbox і показує попередження. +Checkbox приймає лише українські номери (+380): покупець з іноземним номером отримає чек +тільки на email, якщо його вказано. + ### Податкові групи 1. Перейдіть в Checkbox ПРРО → Податкові ставки. diff --git a/tests/ReceiptDeliveryTest.php b/tests/ReceiptDeliveryTest.php new file mode 100644 index 0000000..05ae1de --- /dev/null +++ b/tests/ReceiptDeliveryTest.php @@ -0,0 +1,107 @@ + */ + public static function modes(): iterable + { + $email = ['emails' => [self::EMAIL]]; + $phone = ['phone' => '380671234567']; + + yield 'off' => [Delivery::NONE, self::EMAIL, self::PHONE, null]; + yield 'email' => [Delivery::EMAIL, self::EMAIL, self::PHONE, $email]; + yield 'email, order without email' => [Delivery::EMAIL, null, self::PHONE, null]; + yield 'phone' => [Delivery::PHONE, self::EMAIL, self::PHONE, $phone]; + yield 'phone, order without phone' => [Delivery::PHONE, self::EMAIL, null, null]; + yield 'both' => [Delivery::EMAIL_AND_PHONE, self::EMAIL, self::PHONE, $email + $phone]; + yield 'both, only phone known' => [Delivery::EMAIL_AND_PHONE, null, self::PHONE, $phone]; + yield 'email first: has email' => [Delivery::EMAIL_ELSE_PHONE, self::EMAIL, self::PHONE, $email]; + yield 'email first: no email, phone is used' => [Delivery::EMAIL_ELSE_PHONE, null, self::PHONE, $phone]; + yield 'email first: invalid email counts as none' => [Delivery::EMAIL_ELSE_PHONE, 'not-an-email', self::PHONE, $phone]; + yield 'email first: nothing known' => [Delivery::EMAIL_ELSE_PHONE, '', '', null]; + yield 'legacy 5 is not offered and sends nothing' => [5, self::EMAIL, self::PHONE, null]; + } + + #[DataProvider('modes')] + public function testModeDecidesWhereTheReceiptGoes(int $mode, ?string $email, ?string $phone, ?array $expected): void + { + self::assertSame($expected, Delivery::payload($mode, $email, $phone)); + } + + /** @return iterable */ + public static function phones(): iterable + { + yield 'stored E.164' => ['+380671234567', '380671234567']; + yield 'typed with spaces' => ['+38 (067) 123-45-67', '380671234567']; + yield 'local 0XX' => ['0671234567', '380671234567']; + yield 'without plus' => ['380671234567', '380671234567']; + yield 'foreign number: Checkbox delivers only to +380' => ['+48601234567', null]; + yield 'too short' => ['+38067123456', null]; + yield 'empty' => ['', null]; + yield 'null' => [null, null]; + } + + #[DataProvider('phones')] + public function testPhoneIsNormalisedForCheckbox(?string $raw, ?string $expected): void + { + self::assertSame($expected, Delivery::phone($raw)); + } + + public function testEmailIsTrimmedAndValidated(): void + { + self::assertSame(['emails' => [self::EMAIL]], Delivery::payload(Delivery::EMAIL, ' ' . self::EMAIL . ' ', null)); + } + + public function testOnlyListedModesAreAccepted(): void + { + self::assertSame([0, 1, 2, 3, 4], Delivery::MODES); + self::assertSame(Delivery::EMAIL_AND_PHONE, Delivery::mode('3')); + self::assertSame(Delivery::NONE, Delivery::mode('5')); + self::assertSame(Delivery::NONE, Delivery::mode(null)); + self::assertFalse(Delivery::usesPhone(Delivery::EMAIL)); + self::assertTrue(Delivery::usesPhone(Delivery::EMAIL_ELSE_PHONE)); + } + + /** @return iterable */ + public static function billing(): iterable + { + yield 'enabled in Checkbox' => [[], ['can_send_sms' => true, 'billing_enabled' => true, 'balance' => 10], true]; + yield 'not enabled' => [[], ['can_send_sms' => false, 'billing_enabled' => false, 'balance' => 0], false]; + yield 'request failed: unknown, not "off"' => [['message' => 'timed out'], false, null]; + yield 'unexpected body' => [[], ['detail' => 'x'], null]; + } + + /** Без увімкненої послуги Checkbox приймає номер і мовчки нічого не надсилає. */ + #[DataProvider('billing')] + public function testPhoneDeliveryStatusComesFromCheckbox(array $errors, mixed $response, ?bool $expected): void + { + $api = new class ($errors, $response) extends CheckboxApiHelper { + public array $urls = []; + public function __construct(private array $scriptedErrors, private mixed $scripted) { $this->accessToken = 'token'; } + protected function makeApiRequest(string $url, array $params = [], array $requestParams = []) + { + $this->urls[] = ($requestParams['method'] ?? 'GET') . ' ' . $url; + $this->errors = $this->scriptedErrors; + return $this->scripted; + } + protected function logFailure(string $event, array $context = []): void {} + }; + + self::assertSame($expected, $api->phoneDeliveryEnabled()); + self::assertSame(['GET organization/sms-billing'], $api->urls); + } +} diff --git a/tests/ReceiptIdempotencyTest.php b/tests/ReceiptIdempotencyTest.php index b1dea94..8c7d552 100644 --- a/tests/ReceiptIdempotencyTest.php +++ b/tests/ReceiptIdempotencyTest.php @@ -11,6 +11,7 @@ use Okay\Modules\Sviat\Checkbox\Extenders\BackendExtender; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxApiOutcome; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxPrepaymentHelper; +use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxReceiptDelivery; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxReceiptsHelper; use Okay\Modules\Sviat\Checkbox\Helpers\CheckboxShiftsHelper; use PHPUnit\Framework\Attributes\DataProvider; @@ -89,7 +90,9 @@ public function delete($id) { $this->rows = array_values(array_filter($this->row $orders = new class { public array $list = []; + public ?object $order = null; public function find(array $f = []) { return $this->list; } + public function get($id) { return $this->order; } }; $factory = $this->createStub(EntityFactory::class); @@ -120,12 +123,14 @@ public function getCashierInfo() { return ['full_name' => 'Каса']; } $helper = new class ($script, $lockFree) extends CheckboxReceiptsHelper { public array $requests = []; + public array $payloads = []; public array $paidCalls = []; public int $locks = 0; public function __construct(public array $script, public bool $lockFree) {} protected function makeApiRequest(string $url, array $params = [], array $requestParams = []) { $this->requests[] = [$requestParams['method'] ?? 'GET', $url, $params['id'] ?? null]; + $this->payloads[] = $params; [$errors, $response] = array_shift($this->script); $this->errors = $errors; return $response; @@ -147,10 +152,12 @@ public function chainStatus(string $relationId): ?array $response = $this->api->call("prepayment-receipts/$relationId", [], 'GET'); return is_array($response) && isset($response['pre_payment_status']) ? $response : null; } - public function returnChain(string $relationId, string $cashierName) { return $this->api->call("prepayment-receipts/$relationId/return", [], 'POST'); } + public function returnChain(string $relationId, string $cashierName, ?array $delivery = null) { return $this->api->call("prepayment-receipts/$relationId/return", array_filter(['delivery' => $delivery]), 'POST'); } }; + $settingValues = new \ArrayObject(); $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback(fn ($name) => $settingValues[$name] ?? null); Closure::bind(function () use ($factory, $translations, $shifts, $prepayment, $settings) { $this->entityFactory = $factory; @@ -162,7 +169,7 @@ public function returnChain(string $relationId, string $cashierName) { return $t $this->receiptsTableReadable = true; }, $helper, CheckboxReceiptsHelper::class)(); - return (object) ['helper' => $helper, 'entity' => $entity, 'shifts' => $shifts, 'orders' => $orders]; + return (object) ['helper' => $helper, 'entity' => $entity, 'shifts' => $shifts, 'orders' => $orders, 'settings' => $settingValues]; } private function send(object $env, bool $isReturn = false, ?int $rowId = null) @@ -453,7 +460,7 @@ private function callPrivate(object $env, string $name, array $args) private function openChain(object $env) { - $context = ['cashierName' => 'Каса', 'goods' => [], 'footer' => '', 'email' => null, 'goodsTotal' => 30000]; + $context = ['cashierName' => 'Каса', 'goods' => [], 'footer' => '', 'delivery' => null, 'goodsTotal' => 30000]; return $this->callPrivate($env, 'openChain', [22991, 10000, 'cash', $context]); } @@ -549,6 +556,55 @@ public function testRefusalDropsFreshAfterPaymentIntent(string $refusal): void self::assertCount(1, $env->entity->rows); } + private function buyer(object $env, int $mode): void + { + $env->settings['sviat__checkbox__send_message'] = $mode; + $env->orders->order = (object) ['id' => 22991, 'email' => '', 'phone' => '+380671234567']; + } + + /** Чек авансу й так ішов покупцеві; остаточний чек ланцюжка — теж його чек. */ + public function testAfterPaymentReceiptGoesToTheBuyer(): void + { + $env = $this->scripted([$this->chainIsPartlyPaid(), $this->done('final'), [[], ['pre_payment_status' => 'FULL_PAID']]], [$this->chainRow()]); + $this->buyer($env, CheckboxReceiptDelivery::EMAIL_ELSE_PHONE); + + $this->closeChain($env); + + self::assertSame(['POST', 'prepayment-receipts/CHAIN-1'], array_slice($env->helper->requests[1], 0, 2)); + self::assertSame(['phone' => '380671234567'], $env->helper->payloads[1]['delivery'] ?? null); + } + + public function testAfterPaymentHonoursDeliveryOff(): void + { + $env = $this->scripted([$this->chainIsPartlyPaid(), $this->done('final'), [[], ['pre_payment_status' => 'FULL_PAID']]], [$this->chainRow()]); + $this->buyer($env, CheckboxReceiptDelivery::NONE); + + $this->closeChain($env); + + self::assertArrayNotHasKey('delivery', $env->helper->payloads[1]); + } + + public function testChainReturnReceiptsGoToTheBuyer(): void + { + $returned = [[], [['id' => 'ret-1', 'created_at' => '2026-01-01', 'updated_at' => '2026-01-01']]]; + $env = $this->scripted([$returned], [$this->chainRow()]); + $this->buyer($env, CheckboxReceiptDelivery::PHONE); + + $this->callPrivate($env, 'returnChainReceipts', [22991]); + + self::assertSame(['phone' => '380671234567'], $env->helper->payloads[0]['delivery'] ?? null); + } + + public function testAdvanceReceiptCarriesDeliveryFromContext(): void + { + $env = $this->scripted([$this->done('advance')]); + $context = ['cashierName' => 'Каса', 'goods' => [], 'footer' => '', 'delivery' => ['emails' => ['buyer@example.com']], 'goodsTotal' => 30000]; + + $this->callPrivate($env, 'openChain', [22991, 10000, 'cash', $context]); + + self::assertSame(['emails' => ['buyer@example.com']], $env->helper->payloads[0]['delivery'] ?? null); + } + private function failedDocument(array $extra = []): array { return [[], ['id' => 'earlier-uuid', 'status' => 'ERROR', 'created_at' => '2026-01-01', 'updated_at' => '2026-01-01'] + $extra];