forked from hiqdev/php-billing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBillingContext.php
496 lines (429 loc) · 15.8 KB
/
BillingContext.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<?php
/**
* PHP Billing Library
*
* @link https://github.com/hiqdev/php-billing
* @package php-billing
* @license BSD-3-Clause
* @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/)
*/
namespace hiqdev\php\billing\tests\behat\bootstrap;
use Behat\Gherkin\Node\TableNode;
use BehatExpectException\ExpectException;
use DateTimeImmutable;
use hiqdev\php\billing\bill\BillInterface;
use hiqdev\php\billing\charge\ChargeInterface;
use PHPUnit\Framework\Assert;
class BillingContext extends BaseContext
{
use ExpectException {
mayFail as protected;
shouldFail as protected;
assertCaughtExceptionMatches as protected;
}
protected $saleTime;
protected $bill;
protected $charges = [];
/**
* @Given reseller :reseller
*/
public function reseller($reseller)
{
$this->builder->buildReseller($reseller);
}
/**
* @Given customer :customer
*/
public function customer($customer)
{
$this->builder->buildCustomer($customer);
}
/**
* @Given manager :manager
*/
public function manager($manager)
{
$this->builder->buildManager($manager);
}
/**
* @Given /^(\S+ )?(\S+) tariff plan (\S+)/
*/
public function plan($prefix, $type, $plan)
{
$prefix = strtr($prefix, ' ', '_');
$grouping = $prefix === 'grouping_';
$type = $grouping ? $type : $prefix.$type;
$this->builder->buildPlan($plan, $type, $grouping);
}
protected function fullPrice(array $data)
{
if (!empty($data['price'])) {
$data['rate'] = $data['price'];
}
$this->builder->buildPrice($data);
}
/**
* @Given /price for (\S+) is +(\S+) (\S+) per (\S+) for target (.+)$/
*/
public function priceWithTarget($type, $price, $currency, $unit, $target)
{
return $this->fullPrice(compact('type', 'price', 'currency', 'unit', 'target'));
}
/**
* @Given /price for (\S+) is +(\S+) (\S+) per (\S+) prepaid (\S+)$/
*/
public function priceWithPrepaid($type, $price, $currency, $unit, $prepaid)
{
return $this->fullPrice(compact('type', 'price', 'currency', 'unit', 'prepaid'));
}
/**
* @Given /price for (\S+) is +(\S+) (\S+) per (\S+) prepaid (\S+) for target (\S+)$/
*/
public function priceWithPrepaidAndTarget($type, $price, $currency, $unit, $prepaid, $target)
{
return $this->fullPrice(compact('type', 'price', 'currency', 'unit', 'prepaid', 'target'));
}
/**
* @Given /price for (\S+) is +(\S+) (\S+) per (\S+)$/
*/
public function price($type, $price, $currency, $unit)
{
return $this->fullPrice(compact('type', 'price', 'currency', 'unit'));
}
/**
* @Given /price for (\S+) is +(\S+) (\S+) per 1 (\S+) and (\S+) (\S+) per 2 (\S+) for target (\S+)/
*/
public function enumPrice($type, $price, $currency, $unit, $price2, $currency2, $unit2, $target)
{
$sums = [1 => $price, 2 => $price2];
return $this->fullPrice(compact('type', 'sums', 'currency', 'unit', 'target'));
}
/**
* @Given /^remove and recreate tariff plan (\S+)/
*/
public function recreatePlan($plan)
{
$this->builder->recreatePlan($plan);
}
/**
* @Given /sale target (\S+) by plan (\S+) at (\S+)/
*/
public function sale($target, $plan, $time): void
{
$this->saleTime = $this->prepareTime($time);
$this->builder->buildSale($target, $plan, $this->saleTime);
}
/**
* @When /^sale close is requested for target "([^"]*)" at "([^"]*)", assuming current time is "([^"]*)"$/
*/
public function saleClose(string $target, string $time, ?string $wallTime)
{
throw new PendingException();
}
/**
* @Then /^target "([^"]*)" has exactly (\d+) sale for customer$/
*/
public function targetHasExactlyNSaleForCustomer(string $target, string $count)
{
// TODO: implement
// $sales = $this->builder->findSales(['target-name' => $target]);
Assert::assertCount($count, $sales);
}
/**
* @Given /purchase target (\S+) by plan (\S+) at (\S+)$/
*/
public function purchaseTarget(string $target, string $plan, string $time): void
{
$time = $this->prepareTime($time);
$this->builder->buildPurchase($target, $plan, $time);
}
/**
* @Given /^purchase target "([^"]*)" by plan "([^"]*)" at "([^"]*)" with the following initial uses:$/
*/
public function purchaseTargetWithInitialUses(string $target, string $plan, string $time, TableNode $usesTable): void
{
$time = $this->prepareTime($time);
$uses = array_map(static function (array $row) {
return [
'type' => $row['type'],
'unit' => $row['unit'],
'amount' => $row['amount'],
];
}, $usesTable->getColumnsHash());
$this->mayFail(
fn() => $this->builder->buildPurchase($target, $plan, $time, $uses)
);
}
/**
* @Given /resource consumption for (\S+) is +(\S+) (\S+) for target (\S+) at (.+)$/
*/
public function setConsumption(string $type, int $amount, string $unit, string $target, string $time): void
{
$time = $this->prepareTime($time);
$this->builder->setConsumption($type, $amount, $unit, $target, $time);
}
/**
* @Given /recalculate autotariff for target (\S+)( +at (\S+))?$/
*/
public function recalculateAutoTariff(string $target, string $time = null): void
{
$this->builder->clientSetAutoTariff($target, $time);
}
/**
* @Given /perform billing at (\S+)/
*/
public function performBilling(string $time): void
{
$this->builder->performBilling($this->prepareTime($time));
}
/**
* @Given /action for (\S+) is +(\S+) (\S+) +for target (.+?)( +at (\S+))?$/
*/
public function setAction(string $type, int $amount, string $unit, string $target, string $at = null, string $time = null): void
{
$time = $this->prepareTime($time);
$this->builder->setAction($type, $amount, $unit, $target, $time);
}
/**
* @Given /perform calculation( at (\S+))?/
*/
public function performCalculation(string $at = null, string $time = null): array
{
$this->charges = $this->builder->performCalculation($this->prepareTime($time));
return $this->charges;
}
/**
* @Given /bill +for (\S+) is +(\S+) (\S+) per (\S+) (\S+) for target (.+?)( +at (.+))?$/
*/
public function billWithTime($type, $sum, $currency, $quantity, $unit, $target, $at = null, $time = null)
{
$this->builder->flushEntitiesCacheByType('bill');
$quantity = $this->prepareQuantity($quantity);
$sum = $this->prepareSum($sum, $quantity);
$time = $this->prepareTime($time);
$bill = $this->findBill([
'type' => $type,
'target' => $target,
'sum' => "$sum $currency",
'quantity' => "$quantity $unit",
'time' => $time,
]);
Assert::assertSame($type, $bill->getType()->getName(), "Bill type mismatch: expected $type, got {$bill->getType()->getName()}");
Assert::assertSame($target, $bill->getTarget()->getFullName(), "Bill target mismatch: expected $target, got {$bill->getTarget()->getFullName()}");
Assert::assertEquals(bcmul($sum, 100), $bill->getSum()->getAmount(), "Bill sum mismatch: expected $sum, got {$bill->getSum()->getAmount()}");
Assert::assertSame($currency, $bill->getSum()->getCurrency()->getCode(), "Bill currency mismatch: expected $currency, got {$bill->getSum()->getCurrency()->getCode()}");
Assert::assertEquals((float)$quantity, (float)$bill->getQuantity()->getQuantity(), "Bill quantity mismatch: expected $quantity, got {$bill->getQuantity()->getQuantity()}");
Assert::assertEquals(strtolower($unit), strtolower($bill->getQuantity()->getUnit()->getName()), "Bill unit mismatch: expected $unit, got {$bill->getQuantity()->getUnit()->getName()}");
if ($time) {
Assert::assertEquals(new DateTimeImmutable($time), $bill->getTime(), "Bill time mismatch: expected $time, got {$bill->getTime()->format(DATE_ATOM)}");
}
}
public function findBill(array $params): BillInterface
{
$bills = $this->builder->findBills($params);
$this->bill = reset($bills);
$this->charges = $this->bill->getCharges();
return $this->bill;
}
/**
* @Given /bills number is (\d+) for (\S+) for target (.+?)( +at (\S+))?$/
*/
public function billsNumberWithTime($number, $type, $target, $at = null, $time = null)
{
$count = count($this->builder->findBills(array_filter([
'type' => $type,
'target' => $target,
'time' => $this->prepareTime($time),
])));
Assert::assertEquals($number, $count);
}
/**
* @Given /charges number is (\d+)/
*/
public function chargesNumber($number)
{
Assert::assertEquals($number, count($this->charges));
}
/**
* @Given /charge for (\S+) is +(\S+) (\S+) per (\S+) (\S+)$/
*/
public function charge($type, $amount, $currency, $quantity, $unit)
{
$this->chargeWithTarget($type, $amount, $currency, $quantity, $unit, null);
}
/**
* @Given /charge for (\S+) is +(\S+) (\S+) per +(\S+) (\S+) +for target (.+?)( +at (\S+))?$/
*/
public function chargeWithTarget($type, $amount, $currency, $quantity, $unit, $target, $at = null, $time = null)
{
$quantity = $this->prepareQuantity($quantity);
$amount = $this->prepareSum($amount, $quantity);
$charge = $this->findCharge($type, $target);
Assert::assertNotNull($charge);
Assert::assertSame($type, $charge->getType()->getName());
Assert::assertSame($target, $charge->getTarget()->getFullName());
Assert::assertEquals(bcmul($amount, 100), (int)$charge->getSum()->getAmount());
Assert::assertSame($currency, $charge->getSum()->getCurrency()->getCode());
Assert::assertEquals((float)$quantity, (float)$charge->getUsage()->getQuantity());
Assert::assertEquals(strtolower($unit), strtolower($charge->getUsage()->getUnit()->getName()));
}
public function findCharge($type, $target): ?ChargeInterface
{
foreach ($this->charges as $charge) {
if ($charge->getType()->getName() !== $type) {
continue;
}
if ($charge->getTarget()->getFullName() !== $target) {
continue;
}
return $charge;
}
return null;
}
public function getNextCharge(): ChargeInterface
{
$charge = current($this->charges);
next($this->charges);
return $charge;
}
/**
* @return string|false|null
*/
protected function prepareTime(string $time = null)
{
if ($time === null) {
return null;
}
if ($time === 'midnight second day of this month') {
return date('Y-m-02');
}
if (strncmp($time, 'pY', 1) === 0) {
return date(substr($time, 1), strtotime('-1 year'));
}
if (str_contains($time, 'pm')) {
$time = str_replace('pm', 'm', $time);
$time = date($time, strtotime('-1 month'));
}
if (strncmp($time, 'Y', 1) === 0) {
return date($time);
}
return $time;
}
private function prepareQuantity($quantity)
{
if ($quantity[0] === 's') {
return $this->getSaleQuantity();
}
return $quantity;
}
private function prepareSum($sum, $quantity)
{
if ($sum[0] === 's') {
$sum = round(substr($sum, 1) * $quantity*100)/100;
}
return $sum;
}
public function getSaleQuantity()
{
return $this->days2quantity(new DateTimeImmutable($this->saleTime));
}
private function days2quantity(DateTimeImmutable $from)
{
$till = new DateTimeImmutable('first day of next month midnight');
$diff = $from->diff($till);
if ($diff->m) {
return 1;
}
return $diff->d/date('t');
}
/**
* @When /^tariff plan change is requested for target "([^"]*)" to plan "([^"]*)" at "([^"]*)"$/
*/
public function tariffPlanChangeIsRequestedForTarget(string $target, string $planName, string $date)
{
$this->mayFail(fn () => $this->builder->targetChangePlan($target, $planName, $this->prepareTime($date)));
}
/**
* @When /^tariff plan change is requested for target "([^"]*)" to plan "([^"]*)" at "([^"]*)", assuming current time is "([^"]*)"$/
*/
public function tariffPlanChangeIsRequestedForTargetAtSpecificTime(string $target, string $planName, string $date, ?string $wallTime = null)
{
$this->mayFail(fn () => $this->builder->targetChangePlan($target, $planName, $this->prepareTime($date), $this->prepareTime($wallTime)));
}
/**
* @Then /^target "([^"]*)" is sold to customer by plan "([^"]*)" since "([^"]*)"(?: till "([^"]*)")?$/
*/
public function targetIsSoldToCustomerByPlanSinceTill(string $target, string $planName, string $saleDate, ?string $saleCloseDate = null)
{
$sales = $this->builder->findHistoricalSales([
'target' => $target,
]);
$saleDateTime = new DateTimeImmutable('@' . strtotime($saleDate));
$saleCloseDateTime = new DateTimeImmutable('@' . ($saleCloseDate ? strtotime($saleCloseDate) : time()));
foreach ($sales as $sale) {
/** @noinspection PhpBooleanCanBeSimplifiedInspection */
$saleExists = true
&& str_contains($sale->getPlan()->getName(), $planName)
&& $sale->getTime()->format(DATE_ATOM) === $saleDateTime->format(DATE_ATOM)
&& (
($saleCloseDate === null && $sale->getCloseTime() === null)
||
($saleCloseDate !== null && $sale->getCloseTime()->format(DATE_ATOM) === $saleCloseDateTime->format(DATE_ATOM))
);
if ($saleExists) {
return;
}
}
Assert::fail('Requested sale does not exist');
}
/**
* @Then /^target "([^"]*)" has exactly (\d+) sales for customer$/
*/
public function targetHasExactlySalesForCustomer(string $target, int $count)
{
$sales = $this->builder->findHistoricalSales([
'target' => $target,
]);
Assert::assertCount($count, $sales);
}
/**
* @Then /^caught error is "([^"]*)"$/
*/
public function caughtErrorIs(string $errorMessage): void
{
$this->assertCaughtExceptionMatches(\Throwable::class, $errorMessage);
}
/**
* @Given /^target "([^"]*)"$/
*/
public function target(string $target)
{
$this->builder->buildTarget($target);
}
/**
* @Then /^flush entities cache$/
*/
public function flushEntitiesCache()
{
$this->builder->flushEntitiesCache();
}
/**
* @Given /^target "([^"]*)" has the following uses:$/
*/
public function targetHasTheFollowingUses(string $target, TableNode $usesTable)
{
foreach ($usesTable->getColumnsHash() as $row) {
$uses = $this->builder->findUsage($row['time'], $target, $row['type']);
Assert::assertCount(1, $uses);
$use = reset($uses);
Assert::assertSame(
$row['unit'], $use['unit'],
sprintf('Exptected unit to be %s, got %s instead', $row['unit'], $use['unit'])
);
Assert::assertEquals(
$row['amount'], $use['total'],
sprintf('Exptected total to be %s, got %s instead', $row['amount'], $use['total'])
);
}
}
}