-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCalculator.php
More file actions
224 lines (197 loc) · 7.03 KB
/
Calculator.php
File metadata and controls
224 lines (197 loc) · 7.03 KB
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
<?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\order;
use Exception;
use hiqdev\php\billing\action\ActionInterface;
use hiqdev\php\billing\action\TemporaryActionInterface;
use hiqdev\php\billing\charge\Charge;
use hiqdev\php\billing\charge\ChargeInterface;
use hiqdev\php\billing\charge\ChargeModifier;
use hiqdev\php\billing\charge\GeneralizerInterface;
use hiqdev\php\billing\Exception\ActionChargingException;
use hiqdev\php\billing\plan\Plan;
use hiqdev\php\billing\plan\PlanInterface;
use hiqdev\php\billing\plan\PlanRepositoryInterface;
use hiqdev\php\billing\price\PriceInterface;
use hiqdev\php\billing\sale\SaleInterface;
use hiqdev\php\billing\sale\SaleRepositoryInterface;
use hiqdev\php\billing\tools\ActualDateTimeProvider;
use hiqdev\php\billing\tools\CurrentDateTimeProviderInterface;
use hiqdev\php\units\QuantityInterface;
use Money\Money;
use Throwable;
/**
* Calculator calculates charges for given order or action.
*
* @author Andrii Vasyliev <sol@hiqdev.com>
*/
class Calculator implements CalculatorInterface
{
private readonly CurrentDateTimeProviderInterface $dateTimeProvider;
public function __construct(
protected GeneralizerInterface $generalizer,
private readonly SaleRepositoryInterface $saleRepository,
private readonly PlanRepositoryInterface $planRepository,
?CurrentDateTimeProviderInterface $dateTimeProvider = null
) {
$this->dateTimeProvider = $dateTimeProvider ?? new ActualDateTimeProvider();
}
/**
* {@inheritdoc}
*/
public function calculateOrder(OrderInterface $order): array
{
$plans = $this->findPlans($order);
$charges = [];
foreach ($order->getActions() as $actionKey => $action) {
if (!empty($plans[$actionKey])) {
try {
$charges = array_merge($charges, $this->calculatePlan($plans[$actionKey], $action));
} catch (Throwable $e) {
throw ActionChargingException::forAction($action, $e);
}
}
}
return $charges;
}
public function calculatePlan(PlanInterface $plan, ActionInterface $action): array
{
$result = [];
foreach ($plan->getPrices() as $price) {
$charges = $this->calculatePrice($price, $action);
if (!empty($charges)) {
$result = array_merge($result, $charges);
}
}
return $result;
}
/**
* {@inheritdoc}
*/
public function calculatePrice(PriceInterface $price, ActionInterface $action): array
{
$charge = $this->calculateCharge($price, $action);
if (!$charge instanceof ChargeInterface) {
return [];
}
if ($price instanceof ChargeModifier) {
$charges = $price->modifyCharge($charge, $action);
} else {
$charges = [$charge];
}
if ($action->isFinished()) {
foreach ($charges as $charge) {
$charge->setFinished();
}
}
return $charges;
}
/**
* Calculates charge for given action and price.
* Returns `null`, if $price is not applicable to $action.
*/
public function calculateCharge(PriceInterface $price, ActionInterface $action): ?ChargeInterface
{
if (!$action->isApplicable($price)) {
return null;
}
if ($action->getSale() instanceof SaleInterface && $action->getSale()->getTime() > $this->dateTimeProvider->dateTimeImmutable()) {
return null;
}
$usage = $price->calculateUsage($action->getQuantity());
if (!$usage instanceof QuantityInterface) {
return null;
}
$sum = $price->calculateSum($action->getQuantity());
if (!$sum instanceof Money) {
return null;
}
$type = $this->generalizer->specializeType($price->getType(), $action->getType());
$target = $this->generalizer->specializeTarget($price->getTarget(), $action->getTarget());
/* sorry, debugging facility
* var_dump([
'unit' => $usage->getUnit()->getName(),
'quantity' => $usage->getQuantity(),
'price' => $price->calculatePrice($usage)->getAmount(),
'sum' => $sum->getAmount(),
]);*/
return new Charge(null, $type, $target, $action, $price, $usage, $sum);
}
/**
* @throws Exception
* @return PlanInterface[]
*/
private function findPlans(OrderInterface $order): array
{
$sales = $this->findSales($order);
$plans = [];
$lookPlanIds = [];
foreach ($order->getActions() as $actionKey => $action) {
if (!empty($sales[$actionKey])) {
$sale = $sales[$actionKey];
/** @var Plan|PlanInterface[] $plan */
$plan = $sale->getPlan();
if ($action instanceof TemporaryActionInterface && $plan->getId() && !$action->hasSale()) {
$action->setSale($sale);
}
if ($plan->hasPrices()) {
$plans[$actionKey] = $plan;
} elseif ($plan->getId() !== null) {
$lookPlanIds[$actionKey] = $plan->getId();
} else {
$plans[$actionKey] = null;
}
} else {
// It is ok when no sale found for upper resellers
$plans[$actionKey] = null;
}
}
if ($lookPlanIds !== []) {
$foundPlans = $this->planRepository->findByIds($lookPlanIds);
foreach ($foundPlans as $plan) {
$foundPlans[$plan->getId()] = $plan;
}
foreach ($lookPlanIds as $actionKey => $planId) {
if (empty($foundPlans[$planId])) {
throw new Exception('not found plan');
}
$plans[$actionKey] = $foundPlans[$planId];
}
}
return $plans;
}
/**
* @return SaleInterface[]
*/
private function findSales(OrderInterface $order): array
{
$sales = [];
$lookActions = [];
foreach ($order->getActions() as $actionKey => $action) {
$sale = $action->getSale();
if ($sale) {
$sales[$actionKey] = $sale;
} else {
$lookActions[$actionKey] = $action;
}
}
if ($lookActions !== []) {
$lookOrder = new Order(null, $order->getCustomer(), $lookActions);
$foundSales = $this->saleRepository->findByOrder($lookOrder);
foreach ($foundSales as $actionKey => $sale) {
$sales[$actionKey] = $sale;
if ($sale !== false) {
$lookActions[$actionKey]->setSale($sale);
}
}
}
return $sales;
}
}