This repository has been archived by the owner on Apr 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcommerce_stock.module
80 lines (67 loc) · 2.55 KB
/
commerce_stock.module
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
<?php
use Drupal\commerce_stock\Entity\Stock;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\Views;
/**
* @file
* Defines common functionality for all Commerce Stock modules.
*/
/**
* When a new stock instance is added to an existing product variation
*
* @param \Drupal\Core\Entity\EntityInterface $entity
*
*/
function commerce_stock_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'commerce_product_variation') {
$stockList = $entity->stock;
foreach ($stockList as $stockItem) {
$stock_id = $stockItem->get('entity')->getTargetIdentifier();
$stock = Stock::load($stock_id);
// Check if a stock has movement, if none, then it's new.
$query = \Drupal::entityQuery('commerce_stock_movement');
$result = $query->condition('stock_id', $stock_id)->execute();
if (empty($result)) {
$movement = Drupal::entityTypeManager()
->getStorage('commerce_stock_movement')
->create([
'variation_id' => $entity->id(),
'stock_id' => $stock_id,
'qty' => $stock->getQuantity(),
'location_id' => $stock->getStockLocation()->id(),
'uid' => \Drupal::currentUser()->id(),
'description' => $entity->stockChangeReason,
]);
$movement->save();
}
}
}
}
function commerce_stock_theme($existing, $type, $theme, $path) {
return [
'commerce_stock_inventory_control_form' => [
'render element' => 'form',
],
];
}
/**
* Implements hook_views_query_alter().
*/
function commerce_stock_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'stock_movement') {
$user = \Drupal::currentUser();
if ($user->hasPermission('view stock movement at own location') && !$user->hasPermission('view stock movement at any location')) {
// Create a new join to relate the 'commerce_stock_location__uid' table to our current 'commerce_stock_location' table.
$definition = array(
'table' => 'commerce_stock_location__uid',
'field' => 'entity_id',
'left_table' => 'commerce_stock_location_field_data_commerce_stock_movement_field_data',
'left_field' => 'stock_location_id',
);
$join = Views::pluginManager('join')->createInstance('standard', $definition);
$alias = $query->addRelationship('commerce_stock_location__uid', $join, 'commerce_stock_location_field_data');
$query->addWhere(0, 'uid_target_id', $user->id(), '=');
}
}
}