Files
PHPShop/moneta/class/receipt/Receipt.php
T

112 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace MonetaPhpShop\receipt;
use InvalidArgumentException;
use MonetaPhpShop\Money;
use MonetaPhpShop\protocol\JsonNumber;
/**
* ×åê 54-ÔÇ çàêàçà: ïîêóïàòåëü è ïîçèöèè, ñóììà ïîçèöèé ðàâíà ñóììå îïëàòû äî êîïåéêè.
* Îòäà¸òñÿ â äâóõ ôîðìàõ: `MNT_ATTRIBUTES` XML-îòâåòîâ è îáúåêò `receipt` JSON-îòâåòà Check URL.
*/
final class Receipt
{
/** @var ReceiptClient|null */
private $client;
/** @var array<int, ReceiptItem> */
private $items;
/**
* @param array<int, ReceiptItem> $items
*/
public function __construct(?ReceiptClient $client, array $items)
{
if ($items === []) {
throw new InvalidArgumentException('×åê áåç ïîçèöèé.');
}
$this->client = $client;
$this->items = array_values($items);
}
public function getClient(): ?ReceiptClient
{
return $this->client;
}
/**
* @return array<int, ReceiptItem>
*/
public function getItems(): array
{
return $this->items;
}
public function total(): Money
{
$total = Money::fromMinorUnits(0);
foreach ($this->items as $item) {
$total = $total->add($item->total());
}
return $total;
}
/**
* `MNT_ATTRIBUTES`: `INVENTORY` âñåãäà; `CLIENT`, `CUSTOMER` (email), `PHONE` (áåç `+`) —
* åñëè åñòü êîíòàêò; `SNO` — ïðè ôèñêàëèçàöèè, åñëè ñèñòåìà íàëîãîîáëîæåíèÿ âûáðàíà.
* `DELIVERY` íå ïåðåäà¸òñÿ: äîñòàâêà — ïîçèöèåé `INVENTORY`.
* Áåç ôèñêàëèçàöèè ïîçèöèè óðåçàíû ({@see ReceiptItem::toInventoryPosition()}).
*
* @return array<string, string>
*/
public function toAttributes(bool $fiscalization = true, ?TaxSystem $taxSystem = null): array
{
$attributes = [
'INVENTORY' => JsonNumber::encode(
array_map(static function (ReceiptItem $item) use ($fiscalization): array {
return $item->toInventoryPosition($fiscalization);
}, $this->items),
),
];
$client = ($this->client !== null) ? $this->client->toArray(ReceiptClient::KASSA_PHONE_MAX_LENGTH) : [];
if ($client !== []) {
$attributes['CLIENT'] = JsonNumber::encode([$client]);
if (isset($client['email'])) {
$attributes['CUSTOMER'] = $client['email'];
}
if (isset($client['phone'])) {
$attributes['PHONE'] = ltrim($client['phone'], '+');
}
}
if ($fiscalization && ($taxSystem !== null) && $taxSystem->isPassed()) {
$attributes['SNO'] = $taxSystem->getValue();
}
return $attributes;
}
/**
* Îáúåêò `receipt` JSON-îòâåòà Check URL. Áåç êîíòàêòà — ïóñòîé `client` (`{}`).
*
* @return array<string, mixed>
*/
public function toJsonReceipt(): array
{
$client = $this->client !== null ? $this->client->toArray(ReceiptClient::JSON_PHONE_MAX_LENGTH) : [];
return [
'client' => $client === [] ? new \stdClass() : $client,
'items' => array_map(static function (ReceiptItem $item): array {
return $item->toCheckItem();
}, $this->items),
];
}
}