Skip to content

Commit

Permalink
😉 add tests and readme, do release
Browse files Browse the repository at this point in the history
  • Loading branch information
bethrezen committed Dec 8, 2017
1 parent 5e5a53c commit 0ceba34
Show file tree
Hide file tree
Showing 8 changed files with 159 additions and 12 deletions.
62 changes: 61 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,62 @@
# php-dreamkas
Фискализация чека для Дримкас-Ф на php
Фискализация чека для Дримкас-Ф для PHP 7.2

Для более старых версий PHP придётся править код на предмет типов у функций.

## Установка

```
composer require devgroup/php-dreamkas
```

## Пример кода

```php
<?php
use DevGroup\Dreamkas\Api;
use DevGroup\Dreamkas\CustomerAttributes;
use DevGroup\Dreamkas\exceptions\ValidationException;
use DevGroup\Dreamkas\Payment;
use DevGroup\Dreamkas\Position;
use DevGroup\Dreamkas\Receipt;
use DevGroup\Dreamkas\TaxMode;
use GuzzleHttp\Exception\ClientException;

/***
* 123 - ID кассы
* MODE_MOCK - режим, может быть MODE_MOCK, MODE_PRODUCTION, MODE_MODE_DEBUG
*/
$api = new Api('ACCESS_TOKEN из профиля', 123, Api::MODE_MOCK);

$receipt = new Receipt();
$receipt->taxMode = TaxMode::MODE_SIMPLE;
$receipt->positions[] = new Position([
'name' => 'Билет - тест',
'quantity' => 2,
'price' => 210000, // цена в копейках за 1 шт. или 1 грамм
]);
$receipt->payments[] = new Payment([
'sum' => 420000, // стоимость оплаты по чеку
]);
$receipt->attributes = new CustomerAttributes([
'email' => '[email protected]', // почта покупателя
'phone' => '74996776566', // телефон покупателя
]);

$receipt->calculateSum();


$response = [];
try {
$response = $api->postReceipt($receipt);
} catch (ValidationException $e) {
// Это исключение кидается, когда информация в чеке не правильная
} catch (ClientException $e) {
echo $e->getResponse()->getBody();
// Это исключение кидается, когда при передачи чека в Дрикас произошла ошибка. Лучше отправить чек ещё раз
// Если будут дубли - потом отменяйте через $receipt->type = Receipt::TYPE_REFUND;
}

```

Made by DevGroup.ru - [Создание интернет-магазинов](https://devgroup.ru/services/internet-magazin).
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"description": "Фискализация чека для Дримкас-Ф на php",
"type": "library",
"require": {
"php": "~7.2.0",
"guzzlehttp/guzzle": "~6.3.0"
},
"require-dev": {
Expand Down
9 changes: 3 additions & 6 deletions src/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
namespace DevGroup\Dreamkas;

use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;


/**
* Class Api
Expand All @@ -23,7 +20,7 @@ class Api
/** @var Client */
protected $client;

protected $baseUri = [
protected static $baseUri = [
self::MODE_PRODUCTION => 'https://kabinet.dreamkas.ru/api/',
self::MODE_MOCK => 'https://private-anon-2a1e26f7f7-kabinet.apiary-mock.com/api/',
self::MODE_DEBUG => 'https://private-anon-2a1e26f7f7-kabinet.apiary-proxy.com/api/',
Expand All @@ -43,9 +40,9 @@ public function __construct(string $accessToken, int $deviceId, int $mode = self
$this->createClient();
}

protected function createClient()
protected function createClient(): void
{
$baseUri = $this->baseUri[$this->mode] ?? null;
$baseUri = static::$baseUri[$this->mode] ?? null;
if ($baseUri === null) {
throw new \RuntimeException('Unknown Dreamkas Api mode');
}
Expand Down
6 changes: 3 additions & 3 deletions src/Configurable.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ public function toArray(): array
if ($value === null) {
continue;
}
if (is_array($value)) {
if (\is_array($value)) {
$newValue = [];
foreach ($value as $valueKey => $valueItem) {
if ($valueItem instanceof Configurable) {
if ($valueItem instanceof self) {
$newValue[$valueKey] = $valueItem->toArray();
} else {
$newValue[$valueKey] = $valueItem;
}
}
$value = $newValue;
}
if ($value instanceof Configurable) {
if ($value instanceof self) {
$value = $value->toArray();
}
$result[$key] = $value;
Expand Down
3 changes: 3 additions & 0 deletions src/CustomerAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

use DevGroup\Dreamkas\exceptions\ValidationException;

/**
* Class CustomerAttributes описывает информацию о покупателе, куда ему высылать чек
*/
class CustomerAttributes extends Configurable
{
/** @var string|null */
Expand Down
7 changes: 5 additions & 2 deletions src/Receipt.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ class Receipt extends Configurable
public const TYPE_OUTFLOW = 'OUTFLOW';
public const TYPE_OUTFLOW_REFUND = 'OUTFLOW_REFUND';

// Тип чека
public $type = self::TYPE_SALE;

public $timeout = 300;

// Налоговый режим
public $taxMode;

/** @var Position[] */
Expand All @@ -29,6 +31,7 @@ class Receipt extends Configurable
/** @var CustomerAttributes|array */
public $attributes = [];

// Общая сумма чека
public $total = [
'priceSum' => 0,
];
Expand All @@ -40,7 +43,7 @@ class Receipt extends Configurable
public function toArray(): array
{
$this->calculateSum();
return parent::toArray(); // TODO: Change the autogenerated stub
return parent::toArray();
}

/**
Expand Down Expand Up @@ -75,7 +78,7 @@ public function validate(): bool
throw new ValidationException('No taxMode specified');
}

if (is_array($this->attributes) && \count($this->attributes) === 0) {
if (\is_array($this->attributes) && \count($this->attributes) === 0) {
throw new ValidationException('No customer attributes specified');
}
if ($this->attributes instanceof CustomerAttributes) {
Expand Down
82 changes: 82 additions & 0 deletions tests/ApiTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace DevGroup\Dreamkas\tests;

use DevGroup\Dreamkas\Api;
use DevGroup\Dreamkas\CustomerAttributes;
use DevGroup\Dreamkas\exceptions\ValidationException;
use DevGroup\Dreamkas\Payment;
use DevGroup\Dreamkas\Position;
use DevGroup\Dreamkas\Receipt;
use DevGroup\Dreamkas\TaxMode;
use GuzzleHttp\Exception\ClientException;


/**
* Class ApiTest
*/
class ApiTest extends \PHPUnit_Framework_TestCase
{

public function testJson()
{
$api = new Api('FAKE', 123, Api::MODE_MOCK);
$result = $api->json('GET', 'products');

$this->assertSame([[]], $result);
}

public function testPostReceipt()
{

$api = new Api('FAKE', 123, Api::MODE_MOCK);

$receipt = new Receipt();
$receipt->taxMode = TaxMode::MODE_SIMPLE;
$receipt->positions[] = new Position([
'name' => 'Билет - тест',
'quantity' => 2,
'price' => 210000,
]);
$receipt->payments[] = new Payment([
'sum' => 420000,
]);
$receipt->attributes = new CustomerAttributes([
'email' => '[email protected]',
]);

$receipt->calculateSum();


$response = [];
try {
$response = $api->postReceipt($receipt);
} catch (ValidationException $e) {
$this->assertFalse(true, 'Validation exception: ' . $e->getMessage());
} catch (ClientException $e) {
echo $e->getResponse()->getBody();
$this->assertFalse(true, 'Client exception');
}
$this->assertArrayHasKey('status', $response);
$this->assertArrayHasKey('id', $response);
$this->assertArrayHasKey('createdAt', $response);

//
$receipt->type = Receipt::TYPE_REFUND;
$response = [];
try {
$response = $api->postReceipt($receipt);
} catch (ValidationException $e) {
$this->assertFalse(true, 'Validation exception: ' . $e->getMessage());
} catch (ClientException $e) {
echo $e->getResponse()->getBody();
$this->assertFalse(true, 'Client exception');
}
$this->assertArrayHasKey('status', $response);
$this->assertArrayHasKey('id', $response);
$this->assertArrayHasKey('createdAt', $response);

}


}
1 change: 1 addition & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?php

0 comments on commit 0ceba34

Please sign in to comment.