/
AssetInventory.php
318 lines (275 loc) · 10.3 KB
/
AssetInventory.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
<?php
namespace Drupal\farm_inventory;
use Drupal\asset\Entity\AssetInterface;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\fraction\Fraction;
/**
* Asset inventory logic.
*/
class AssetInventory implements AssetInventoryInterface {
/**
* The database object.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* Entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected EntityTypeManagerInterface $entityTypeManager;
/**
* Class constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, TimeInterface $time) {
$this->database = Database::getConnection();
$this->entityTypeManager = $entity_type_manager;
$this->time = $time;
}
/**
* {@inheritdoc}
*/
public function getInventory(AssetInterface $asset, string $measure = '', int $units = 0, $timestamp = NULL): array {
// If the asset is new, it won't have inventory.
if ($asset->isNew()) {
return [];
}
// Get a list of the measure+units pairs we will calculate inventory for.
$measure_units_pairs = $this->getMeasureUnitsPairs($asset, $measure, $units);
// Iterate through the measure+units pairs and build inventory summaries.
$inventories = [];
foreach ($measure_units_pairs as $pair) {
$total = $this->calculateInventory($asset, $pair['measure'], $pair['units'], $timestamp);
$units_label = '';
if (!empty($pair['units'])) {
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($pair['units']);
if (!empty($term)) {
$units_label = $term->label();
}
}
$inventories[] = [
'measure' => $pair['measure'] ? $pair['measure'] : '',
'value' => $total->toDecimal(0, TRUE),
'units' => $units_label,
];
}
// Return the inventory summaries.
return $inventories;
}
/**
* Query the database for all measure+units inventory pairs of an asset.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset we are querying inventory of.
* @param string $measure
* The quantity measure of the inventory. See quantity_measures().
* @param int $units
* The quantity units of the inventory (term ID).
*
* @return array
* An array of arrays. Each array will have a 'measure' and 'units' key.
*/
protected function getMeasureUnitsPairs(AssetInterface $asset, string $measure = '', int $units = 0) {
// If both a measure and units are provided, that is the only pair.
if (!empty($measure) && !empty($units)) {
return [
[
'measure' => $measure,
'units' => $units,
],
];
}
// Query the database for measure+units pairs.
$query = $this->database->select('quantity', 'q');
$query->condition('q.inventory_asset', $asset->id());
$query->addField('q', 'measure');
$query->addField('q', 'units');
$query->groupBy('q.measure');
$query->groupBy('q.units');
// Filter by measure or units, if provided.
if (!empty($measure)) {
$query->condition('q.measure', $measure);
}
if (!empty($units)) {
$query->condition('q.units', $units);
}
// Execute the query and build the array of measure+units pairs.
$result = $query->execute();
$pairs = [];
foreach ($result as $row) {
$pairs[] = [
'measure' => !empty($row->measure) ? $row->measure : '',
'units' => !empty($row->units) ? $row->units : 0,
];
}
return $pairs;
}
/**
* Query the database for the latest asset "reset" adjustment timestamp.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset we are querying inventory of.
* @param string $measure
* The quantity measure of the inventory. See quantity_measures().
* @param int $units
* The quantity units of the inventory (term ID).
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return int|null
* Returns a unix timestamp, or NULL if no "reset" adjustment is available.
*/
protected function getLatestResetTimestamp(AssetInterface $asset, string $measure = '', int $units = 0, $timestamp = NULL) {
// Query the database for the latest asset "reset" adjustment timestamp.
$query = $this->baseQuery($asset, $measure, $units, $timestamp);
$query->condition('q.inventory_adjustment', 'reset');
$query->addExpression('MAX(l.timestamp)');
return $query->execute()->fetchField();
}
/**
* Calculate the inventory of an asset, for a given measure+units pair.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset we are querying inventory of.
* @param string $measure
* The quantity measure of the inventory. See quantity_measures().
* @param int $units
* The quantity units of the inventory (term ID).
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return \Drupal\fraction\Fraction
* Returns a Fraction object representing the total inventory.
*/
protected function calculateInventory(AssetInterface $asset, string $measure = '', int $units = 0, $timestamp = NULL) {
// Query the database for inventory adjustments of the given asset,
// measure, and units.
$adjustments = $this->getAdjustments($asset, $measure, $units, $timestamp);
// Iterate through the results and calculate the inventory.
// This will use fraction math to maintain maximum precision.
$total = new Fraction();
foreach ($adjustments as $adjustment) {
// Create a Fraction object from the numerator and denominator.
$value = new Fraction($adjustment->numerator, $adjustment->denominator);
// Reset/increment/decrement the total.
switch ($adjustment->type) {
// Reset.
case 'reset':
$total = $value;
break;
// Increment.
case 'increment':
$total = $total->add($value);
break;
// Decrement.
case 'decrement':
$total = $total->subtract($value);
break;
}
}
return $total;
}
/**
* Query the database for all inventory adjustments of an asset.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset we are querying inventory of.
* @param string $measure
* The quantity measure of the inventory. See quantity_measures().
* @param int $units
* The quantity units of the inventory (term ID).
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return array
* An array of objects with the following properties: type (reset,
* increment, or decrement), numerator, and denominator.
*/
protected function getAdjustments(AssetInterface $asset, string $measure = '', int $units = 0, $timestamp = NULL) {
// First, query the database to find the timestamp of the most recent
// "reset" adjustment log for this asset (if available).
$latest_reset = $this->getLatestResetTimestamp($asset, $measure, $units, $timestamp);
// Then, query the database for all inventory adjustments.
$query = $this->baseQuery($asset, $measure, $units, $timestamp);
$query->addField('q', 'inventory_adjustment', 'type');
$query->addField('q', 'value__numerator', 'numerator');
$query->addField('q', 'value__denominator', 'denominator');
$query->condition('q.inventory_adjustment', NULL, 'IS NOT NULL');
// Sort by log timestamp and then ID, ascending.
$query->orderBy('l.timestamp', 'ASC');
$query->orderBy('l.id', 'ASC');
// Filter to logs that happened after the the latest reset, if available.
if (!empty($latest_reset)) {
$query->condition('l.timestamp', $latest_reset, '>=');
}
// Execute the query and return the results.
return $query->execute()->fetchAll();
}
/**
* Build a base query for getting asset inventory adjustments.
*
* @param \Drupal\asset\Entity\AssetInterface $asset
* The asset we are querying inventory of.
* @param string $measure
* The quantity measure of the inventory. See quantity_measures().
* @param int $units
* The quantity units of the inventory (term ID).
* @param int|null $timestamp
* Include logs with a timestamp less than or equal to this.
* If this is NULL (default), the current time will be used.
*
* @return \Drupal\Core\Database\Query\SelectInterface
* A database query object.
*/
protected function baseQuery(AssetInterface $asset, string $measure = '', int $units = 0, $timestamp = NULL) {
// If $timestamp is NULL, use the current time.
if (is_null($timestamp)) {
$timestamp = $this->time->getRequestTime();
}
// Start with a query of the quantity base table.
$query = $this->database->select('quantity', 'q');
// Only include adjustments that reference the asset.
$query->condition('q.inventory_asset', $asset->id());
// Filter by measure and units. If either is empty, then explicitly filter
// to only include rows with NULL values.
if (!empty($measure)) {
$query->condition('q.measure', $measure);
}
else {
$query->condition('q.measure', NULL, 'IS NULL');
}
if (!empty($units)) {
$query->condition('q.units', $units);
}
else {
$query->condition('q.units', NULL, 'IS NULL');
}
// Join the {log_field_data} table (via reverse reference through
// the {log__quantity} table).
$query->join('log__quantity', 'lq', 'q.id = lq.quantity_target_id');
$query->join('log_field_data', 'l', 'lq.entity_id = l.id');
// Filter out logs that are not done.
$query->condition('l.status', 'done');
// Filter out future logs.
$query->condition('l.timestamp', $timestamp, '<=');
// Return the query.
return $query;
}
}