Compare commits

...

4 Commits

Author SHA1 Message Date
703c5178f5 Минорные апдейты зависимостей 2021-12-08 16:11:39 +08:00
fdc64954f9 Третья итерация Receipt
- просчёт ставок секи в `setVats()`
- просчёт суммы чека в `setItems()`
- геттеры `getItems()` и `getVats()` возвращают пустую коллекцию, если в чеке они отсутствуют
- фикс `vats => supplier_info` в `jsonSerialize()`
- тесты поставщика, ставок, расчёта ставок и суммы чека
2021-12-08 16:01:25 +08:00
793549aaac Entity теперь имплементирует Arrayable и ArrayAccess для совместимости с иммутабельными методами коллекций 2021-12-08 15:56:07 +08:00
b57acf8b05 EntityCollection помечен для переделки 2021-12-08 15:50:06 +08:00
7 changed files with 245 additions and 79 deletions

View File

@ -32,8 +32,8 @@
}
],
"support": {
"rss": "https://t.me/atolonline_php",
"chat": "https://t.me/+Rky7ia68fctjZmUy",
"rss": "https://github.com/anthonyaxenov/atol-online/discussions/categories/announcements",
"chat": "https://github.com/anthonyaxenov/atol-online/discussions",
"source": "https://github.com/anthonyaxenov/atol-online",
"issues": "https://github.com/anthonyaxenov/atol-online/issues",
"docs": "https://github.com/anthonyaxenov/atol-online/blob/master/docs/readme.md"

64
composer.lock generated
View File

@ -68,16 +68,16 @@
},
{
"name": "guzzlehttp/guzzle",
"version": "7.4.0",
"version": "7.4.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "868b3571a039f0ebc11ac8f344f4080babe2cb94"
"reference": "ee0a041b1760e6a53d2a39c8c34115adc2af2c79"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/868b3571a039f0ebc11ac8f344f4080babe2cb94",
"reference": "868b3571a039f0ebc11ac8f344f4080babe2cb94",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/ee0a041b1760e6a53d2a39c8c34115adc2af2c79",
"reference": "ee0a041b1760e6a53d2a39c8c34115adc2af2c79",
"shasum": ""
},
"require": {
@ -86,7 +86,7 @@
"guzzlehttp/psr7": "^1.8.3 || ^2.1",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2"
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
@ -172,7 +172,7 @@
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.4.0"
"source": "https://github.com/guzzle/guzzle/tree/7.4.1"
},
"funding": [
{
@ -188,7 +188,7 @@
"type": "tidelift"
}
],
"time": "2021-10-18T09:52:00+00:00"
"time": "2021-12-06T18:43:05+00:00"
},
{
"name": "guzzlehttp/promises",
@ -391,16 +391,16 @@
},
{
"name": "illuminate/collections",
"version": "v8.74.0",
"version": "v8.75.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/collections.git",
"reference": "f292b77824b42cd28decc7327e7c2e24c3806371"
"reference": "5a018387352afa2af30fd2be0a78c31e93295720"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/collections/zipball/f292b77824b42cd28decc7327e7c2e24c3806371",
"reference": "f292b77824b42cd28decc7327e7c2e24c3806371",
"url": "https://api.github.com/repos/illuminate/collections/zipball/5a018387352afa2af30fd2be0a78c31e93295720",
"reference": "5a018387352afa2af30fd2be0a78c31e93295720",
"shasum": ""
},
"require": {
@ -441,20 +441,20 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2021-11-30T14:29:03+00:00"
"time": "2021-12-07T14:48:29+00:00"
},
{
"name": "illuminate/contracts",
"version": "v8.74.0",
"version": "v8.75.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/contracts.git",
"reference": "b0886ec05a63b204634d64d0b39d5b78a7c06f81"
"reference": "b07755f7c456cf587dfbfd6f0854f9f7c1a34b2f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/contracts/zipball/b0886ec05a63b204634d64d0b39d5b78a7c06f81",
"reference": "b0886ec05a63b204634d64d0b39d5b78a7c06f81",
"url": "https://api.github.com/repos/illuminate/contracts/zipball/b07755f7c456cf587dfbfd6f0854f9f7c1a34b2f",
"reference": "b07755f7c456cf587dfbfd6f0854f9f7c1a34b2f",
"shasum": ""
},
"require": {
@ -489,11 +489,11 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2021-11-17T15:04:30+00:00"
"time": "2021-12-07T08:18:44+00:00"
},
{
"name": "illuminate/macroable",
"version": "v8.74.0",
"version": "v8.75.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/macroable.git",
@ -1171,25 +1171,25 @@
},
{
"name": "symfony/deprecation-contracts",
"version": "v2.5.0",
"version": "v3.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "6f981ee24cf69ee7ce9736146d1c57c2780598a8"
"reference": "c726b64c1ccfe2896cb7df2e1331c357ad1c8ced"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/6f981ee24cf69ee7ce9736146d1c57c2780598a8",
"reference": "6f981ee24cf69ee7ce9736146d1c57c2780598a8",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/c726b64c1ccfe2896cb7df2e1331c357ad1c8ced",
"reference": "c726b64c1ccfe2896cb7df2e1331c357ad1c8ced",
"shasum": ""
},
"require": {
"php": ">=7.1"
"php": ">=8.0.2"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "2.5-dev"
"dev-main": "3.0-dev"
},
"thanks": {
"name": "symfony/contracts",
@ -1218,7 +1218,7 @@
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.0"
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.0.0"
},
"funding": [
{
@ -1234,7 +1234,7 @@
"type": "tidelift"
}
],
"time": "2021-07-12T14:48:14+00:00"
"time": "2021-11-01T23:48:49+00:00"
},
{
"name": "symfony/polyfill-ctype",
@ -2002,16 +2002,16 @@
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.9",
"version": "9.2.10",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "f301eb1453c9e7a1bc912ee8b0ea9db22c60223b"
"reference": "d5850aaf931743067f4bfc1ae4cbd06468400687"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f301eb1453c9e7a1bc912ee8b0ea9db22c60223b",
"reference": "f301eb1453c9e7a1bc912ee8b0ea9db22c60223b",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/d5850aaf931743067f4bfc1ae4cbd06468400687",
"reference": "d5850aaf931743067f4bfc1ae4cbd06468400687",
"shasum": ""
},
"require": {
@ -2067,7 +2067,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.9"
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.10"
},
"funding": [
{
@ -2075,7 +2075,7 @@
"type": "github"
}
],
"time": "2021-11-19T15:21:02+00:00"
"time": "2021-12-05T09:12:13+00:00"
},
{
"name": "phpunit/php-file-iterator",

View File

@ -27,6 +27,8 @@ abstract class EntityCollection extends Collection
public function __construct($items = [])
{
$this->checkCount($items);
//TODO следует переделать EntityCollection в обёртку над Collection,
// ибо ломает методы Collection, которые return new static
$this->checkItemsClasses($items);
parent::__construct($items);
}
@ -85,6 +87,7 @@ abstract class EntityCollection extends Collection
*/
public function checkCount(array $items = []): void
{
//TODO проверять пустоту?
if (count($items) > static::MAX_COUNT || $this->count() === static::MAX_COUNT) {
throw new (static::EXCEPTION_CLASS)(static::MAX_COUNT);
}

View File

@ -11,14 +11,29 @@ declare(strict_types = 1);
namespace AtolOnline\Entities;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use JsonSerializable;
use Stringable;
/**
* Абстрактное описание любой сущности, представляемой как json
*/
abstract class Entity implements JsonSerializable, Stringable
abstract class Entity implements JsonSerializable, Stringable, Arrayable, ArrayAccess
{
/**
* @inheritDoc
*/
abstract public function jsonSerialize(): array;
/**
* @inheritDoc
*/
public function toArray()
{
return $this->jsonSerialize();
}
/**
* Возвращает строковое представление json-структуры объекта
*
@ -26,6 +41,42 @@ abstract class Entity implements JsonSerializable, Stringable
*/
public function __toString()
{
return json_encode($this->jsonSerialize(), JSON_UNESCAPED_UNICODE);
return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
}
/**
* @inheritDoc
*/
public function offsetExists(mixed $offset): bool
{
return isset($this->toArray()[$offset]);
}
/**
* @inheritDoc
*/
public function offsetGet(mixed $offset): mixed
{
return $this->toArray()[$offset];
}
/**
* @inheritDoc
*/
public function offsetSet(mixed $offset, mixed $value)
{
throw new \BadMethodCallException(
'Объект ' . static::class . ' нельзя изменять как массив. Следует использовать сеттеры.'
);
}
/**
* @inheritDoc
*/
public function offsetUnset(mixed $offset): void
{
throw new \BadMethodCallException(
'Объект ' . static::class . ' нельзя изменять как массив. Следует использовать сеттеры.'
);
}
}

View File

@ -196,7 +196,7 @@ class Receipt extends Entity
*/
public function getItems(): Items
{
return $this->items;
return $this->items ?? new Items();
}
/**
@ -207,6 +207,7 @@ class Receipt extends Entity
* @return Receipt
* @throws EmptyItemsException
* @throws InvalidEntityInCollectionException
* @throws Exception
*/
public function setItems(Items $items): self
{
@ -215,6 +216,8 @@ class Receipt extends Entity
}
$items->checkItemsClasses();
$this->items = $items;
$this->getItems()->each(fn ($item) => $this->total += $item->getSum());
$this->total = round($this->total, 2);
return $this;
}
@ -251,7 +254,7 @@ class Receipt extends Entity
*/
public function getVats(): ?Vats
{
return $this->vats;
return $this->vats ?? new Vats();
}
/**
@ -260,6 +263,7 @@ class Receipt extends Entity
* @param Vats|null $vats
* @return Receipt
* @throws EmptyVatsException
* @throws Exception
*/
public function setVats(?Vats $vats): self
{
@ -267,6 +271,8 @@ class Receipt extends Entity
throw new EmptyVatsException();
}
$this->vats = $vats;
/** @var Vat $vat */
$this->getVats()->each(fn ($vat) => $vat->setSum($this->getTotal()));
return $this;
}
@ -280,18 +286,6 @@ class Receipt extends Entity
return $this->total;
}
/**
* Устанавливает полную сумму чека
*
* @param float $total
* @return Receipt
*/
public function setTotal(float $total): self
{
$this->total = $total;
return $this;
}
/**
* Возвращает установленного кассира
*
@ -387,28 +381,11 @@ class Receipt extends Entity
'payments' => $this->getPayments(),
];
$this->getAgentInfo()?->jsonSerialize() && $json['agent_info'] = $this->getAgentInfo();
$this->getSupplier()?->jsonSerialize() && $json['vats'] = $this->getVats();
$this->getSupplier()?->jsonSerialize() && $json['supplier_info'] = $this->getSupplier();
$this->getVats()?->jsonSerialize() && $json['vats'] = $this->getVats();
!is_null($this->getAddCheckProps()) && $json['additional_check_props'] = $this->getAddCheckProps();
!is_null($this->getCashier()) && $json['cashier'] = $this->getCashier();
$this->getAddUserProps()?->jsonSerialize() && $json['additional_user_props'] = $this->getAddUserProps();
return $json;
}
///**
// * Пересчитывает, сохраняет и возвращает итоговую сумму чека по всем позициям (включая НДС). Тег ФФД - 1020.
// *
// * @return float
// * @throws Exception
// */
//public function calcTotal(): float
//{
// $sum = 0;
// $this->clearVats();
// foreach ($this->items->get() as $item) {
// $sum += $item->calcSum();
// $this->addVat(new Vat($item->getVat()->getType(), $item->getSum()));
// }
// return $this->total = round($sum, 2);
//}
}

View File

@ -16,8 +16,7 @@ use AtolOnline\Exceptions\InvalidEnumValueException;
use AtolOnline\Helpers;
use JetBrains\PhpStorm\{
ArrayShape,
Pure
};
Pure};
/**
* Класс, описывающий ставку НДС
@ -97,7 +96,7 @@ final class Vat extends Entity
}
/**
* Возвращает sdрасчитанный итоговый размер ставки НДС в рублях
* Возвращает расчитанный итоговый размер ставки НДС в рублях
*
* @return float
* @see https://nalog-nalog.ru/nds/nalogovaya_baza_nds/kak-schitat-nds-pravilno-vychislyaem-20-ot-summy-primer-algoritm/

View File

@ -12,6 +12,7 @@ namespace AtolOnline\Tests\Entities;
use AtolOnline\{
Collections\Items,
Collections\Payments,
Collections\Vats,
Entities\AgentInfo,
Entities\Client,
Entities\Company,
@ -20,6 +21,8 @@ use AtolOnline\{
Entities\PayingAgent,
Entities\Receipt,
Entities\ReceivePaymentsOperator,
Entities\Supplier,
Entities\Vat,
Enums\AgentTypes,
Enums\SnoTypes,
Tests\BasicTestCase};
@ -27,6 +30,7 @@ use AtolOnline\Exceptions\{
EmptyItemNameException,
EmptyItemsException,
EmptyPaymentsException,
EmptyVatsException,
InvalidEntityInCollectionException,
InvalidEnumValueException,
InvalidInnLengthException,
@ -35,6 +39,7 @@ use AtolOnline\Exceptions\{
NegativeItemQuantityException,
NegativePaymentSumException,
TooHighItemPriceException,
TooHighItemSumException,
TooHighPaymentSumException,
TooLongItemNameException,
TooLongPayingAgentOperationException,
@ -76,8 +81,9 @@ class ReceiptTest extends BasicTestCase
*/
public function testConstructor(): void
{
$receipt = $this->validReceipt();
$receipt = $this->newReceipt();
$this->assertIsAtolable($receipt);
$receipt->getItems();
}
/**
@ -104,7 +110,7 @@ class ReceiptTest extends BasicTestCase
* @throws TooLongPayingAgentOperationException
* @throws Exception
*/
public function testSetAgentInfo(): void
public function testAgentInfo(): void
{
$agent_info = new AgentInfo(
AgentTypes::ANOTHER,
@ -112,9 +118,42 @@ class ReceiptTest extends BasicTestCase
new ReceivePaymentsOperator(['+79519999999']),
new MoneyTransferOperator('MTO Name', '9876543210', 'London', ['+79517777777']),
);
$receipt = $this->validReceipt()->setAgentInfo($agent_info);
$receipt = $this->newReceipt()->setAgentInfo($agent_info);
$this->assertArrayHasKey('agent_info', $receipt->jsonSerialize());
$this->assertEquals($receipt->getAgentInfo(), $receipt->jsonSerialize()['agent_info']);
$this->assertArrayNotHasKey('agent_info', $receipt->setAgentInfo(null)->jsonSerialize());
}
/**
* Тестирует установку данных поставщика
*
* @return void
* @covers \AtolOnline\Entities\Receipt::setSupplier
* @covers \AtolOnline\Entities\Receipt::getSupplier
* @covers \AtolOnline\Entities\Receipt::jsonSerialize
* @throws EmptyItemNameException
* @throws EmptyItemsException
* @throws EmptyPaymentsException
* @throws InvalidEntityInCollectionException
* @throws InvalidEnumValueException
* @throws InvalidInnLengthException
* @throws InvalidPhoneException
* @throws NegativeItemPriceException
* @throws NegativeItemQuantityException
* @throws NegativePaymentSumException
* @throws TooHighItemPriceException
* @throws TooHighPaymentSumException
* @throws TooLongItemNameException
* @throws TooManyException
* @throws Exception
*/
public function testSupplier(): void
{
$supplier = new Supplier('some name', '+fasd3\qe3fs_=nac99013928czc', ['+122997365456']);
$receipt = $this->newReceipt()->setSupplier($supplier);
$this->assertArrayHasKey('supplier_info', $receipt->jsonSerialize());
$this->assertEquals($receipt->getSupplier(), $receipt->jsonSerialize()['supplier_info']);
$this->assertArrayNotHasKey('supplier_info', $receipt->setSupplier(null)->jsonSerialize());
}
/**
@ -122,7 +161,7 @@ class ReceiptTest extends BasicTestCase
*
* @return void
* @covers \AtolOnline\Entities\Receipt
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Entities\Receipt::setItems
* @covers \AtolOnline\Collections\Items::checkCount
* @covers \AtolOnline\Exceptions\EmptyItemsException
* @throws InvalidEnumValueException
@ -147,7 +186,7 @@ class ReceiptTest extends BasicTestCase
*
* @return void
* @covers \AtolOnline\Entities\Receipt
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Entities\Receipt::setItems
* @covers \AtolOnline\Collections\Items::checkItemsClasses
* @covers \AtolOnline\Collections\Items::checkItemClass
* @covers \AtolOnline\Exceptions\InvalidEntityInCollectionException
@ -204,7 +243,7 @@ class ReceiptTest extends BasicTestCase
*
* @return void
* @covers \AtolOnline\Entities\Receipt
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Entities\Receipt::setPayments
* @covers \AtolOnline\Collections\Items::checkItemsClasses
* @covers \AtolOnline\Collections\Items::checkItemClass
* @covers \AtolOnline\Exceptions\InvalidEntityInCollectionException
@ -230,6 +269,103 @@ class ReceiptTest extends BasicTestCase
);
}
/**
* Тестирует выброс исключения при передаче пустой коллекции ставок НДС
*
* @return void
* @covers \AtolOnline\Entities\Receipt
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Collections\Vats::checkCount
* @covers \AtolOnline\Exceptions\EmptyVatsException
* @throws EmptyItemNameException
* @throws EmptyItemsException
* @throws EmptyPaymentsException
* @throws EmptyVatsException
* @throws InvalidEntityInCollectionException
* @throws InvalidEnumValueException
* @throws NegativeItemPriceException
* @throws NegativeItemQuantityException
* @throws NegativePaymentSumException
* @throws TooHighItemPriceException
* @throws TooHighPaymentSumException
* @throws TooLongItemNameException
* @throws TooManyException
*/
public function testEmptyVatsException(): void
{
$this->expectException(EmptyVatsException::class);
$this->newReceipt()->setVats(new Vats([]));
}
/**
* Тестирует выброс исключения при передаче коллекции ставок НДС с некорректным содержимым
*
* @return void
* @covers \AtolOnline\Entities\Receipt
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Collections\Vats::checkItemsClasses
* @covers \AtolOnline\Collections\Vats::checkItemClass
* @covers \AtolOnline\Exceptions\InvalidEntityInCollectionException
* @throws EmptyItemNameException
* @throws EmptyItemsException
* @throws EmptyPaymentsException
* @throws EmptyVatsException
* @throws InvalidEntityInCollectionException
* @throws InvalidEnumValueException
* @throws NegativeItemPriceException
* @throws NegativeItemQuantityException
* @throws NegativePaymentSumException
* @throws TooHighItemPriceException
* @throws TooHighPaymentSumException
* @throws TooLongItemNameException
* @throws TooManyException
*/
public function testInvalidVatInCollectionException(): void
{
$this->expectException(InvalidEntityInCollectionException::class);
$this->expectErrorMessage('Коллекция AtolOnline\Collections\Vats должна содержать объекты AtolOnline\Entities\Vat');
$this->newReceipt()->setVats(new Vats(['qwerty']));
}
/**
* Тестирует просчёт общей суммы чека и ставок НДС
*
* @covers \AtolOnline\Entities\Receipt::setVats
* @covers \AtolOnline\Entities\Receipt::getVats
* @covers \AtolOnline\Entities\Receipt::getTotal
* @throws TooHighItemPriceException
* @throws NegativeItemPriceException
* @throws EmptyPaymentsException
* @throws InvalidEntityInCollectionException
* @throws InvalidEnumValueException
* @throws TooHighItemSumException
* @throws NegativePaymentSumException
* @throws TooHighPaymentSumException
* @throws EmptyItemsException
* @throws EmptyItemNameException
* @throws TooManyException
* @throws NegativeItemQuantityException
* @throws TooLongItemNameException
* @throws Exception
*/
public function testCalculations(): void
{
$items_total = 0;
$receipt = $this->newReceipt();
//TODO при $receipt->getItems()->pluck('sum') стреляет InvalidEntityInCollectionException
// см. примечания в конструкторе EntityCollection
$receipt->getItems()->each(function ($item) use (&$items_total) {
/** @var Item $item */
return $items_total += $item->getSum();
});
$this->assertEquals($items_total, $receipt->getTotal());
/** @var Vat $vat */
$receipt->setVats(new Vats($this->generateVatObjects(2)))->getVats()
->each(fn ($vat) => $this->assertEquals($items_total, $vat->getSum()));
}
/**
* Возвращает валидный тестовый объект чека
*
@ -247,12 +383,12 @@ class ReceiptTest extends BasicTestCase
* @throws TooLongItemNameException
* @throws TooManyException
*/
protected function validReceipt(): Receipt
protected function newReceipt(): Receipt
{
return new Receipt(
new Client('John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', '+fasd3\qe3fs_=nac99013928czc'),
new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'),
new Items($this->generateItemObjects()),
new Items($this->generateItemObjects(2)),
new Payments($this->generatePaymentObjects())
);
}