-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommerce_unleashed.module
More file actions
62 lines (53 loc) · 2.17 KB
/
commerce_unleashed.module
File metadata and controls
62 lines (53 loc) · 2.17 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
<?php
/**
* @file
* Main file.
*/
use Drupal\commerce_cart\Form\AddToCartFormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Implements hook_cron().
*/
function commerce_unleashed_cron(): void {
$settings = Drupal::configFactory()->get('commerce_unleashed.settings');
if ($settings->get('products.cron')) {
$last_product_sync = Drupal::keyValue('commerce_unleashed')->get('products') ?? 0;
$query = 'brief=true';
if ($last_product_sync > 0) {
$last_modified_date = date('Y-m-d', $last_product_sync);
$query .= '&modifiedSince=' . $last_modified_date;
}
Drupal::service('commerce_unleashed.manager')->syncProducts($query);
Drupal::keyValue('commerce_unleashed')->set('products', time());
}
if ($settings->get('stock.sync')) {
$last_sync = Drupal::keyValue('commerce_unleashed')->get('stock_on_hand_sync') ?? 0;
if ($last_sync < time() - 60 * 10) {
Drupal::service('commerce_unleashed.manager')->syncStockOnHand();
Drupal::keyValue('commerce_unleashed')->set('stock_on_hand_sync', time());
}
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter() for 'commerce_order_item_add_to_cart_form'.
*/
function commerce_unleashed_form_commerce_order_item_add_to_cart_form_alter(&$form, FormStateInterface $form_state): void {
$form_object = $form_state->getFormObject();
if ($form_object instanceof AddToCartFormInterface) {
/** @var \Drupal\commerce_unleashed\UnleashedManagerInterface $unleashed_manager */
$unleashed_manager = \Drupal::service('commerce_unleashed.manager');
if ($unleashed_manager->enforceStockAvailability()) {
// Get order item from the form.
/** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
$order_item = $form_object->getEntity();
// Purchasable entity to be used in the form.
if ($purchased_entity = $order_item->getPurchasedEntity()) {
if ($unleashed_manager->getStockOnHand($purchased_entity) === 0) {
$form['actions']['submit']['#disabled'] = TRUE;
$form['actions']['submit']['#value'] = new TranslatableMarkup('Sold out');
}
}
}
}
}