-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommerce_stock_notifications.module
194 lines (161 loc) · 6.49 KB
/
commerce_stock_notifications.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
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
<?php
/**
* @file
* Contains commerce_stock_notifications.module.
*/
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_stock_notifications\Entity\StockNotification;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Render\RenderContext;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
function commerce_stock_notifications_form_alter(&$form, &$form_state, $form_id) {
if (substr($form_id, 0, 36) == 'commerce_order_item_add_to_cart_form') {
if (strpos($form_id, 'commerce_product_bundle') !== FALSE) {
// Do not trigger this code for product bundle add to cart forms.
return;
}
$form_data = $form_state->getStorage();
$variation_id = $form_data['selected_variation'];
$commerce_product_variation = ProductVariation::load($variation_id);
$stock_service_manager = \Drupal::service('commerce_stock.service_manager');
$drupal_stock = $stock_service_manager->getStockLevel($commerce_product_variation);
$always_in_stock = FALSE;
if ($drupal_stock < 1) {
$stock_service = $stock_service_manager->getService($commerce_product_variation);
$stock_checker = $stock_service->getStockChecker();
if ($stock_checker->getIsAlwaysInStock($commerce_product_variation)) {
$always_in_stock = TRUE;
}
}
if ($drupal_stock < 1 && !$always_in_stock) {
$current_user = \Drupal::currentUser();
$form['stock_notification'] = [
'#type' => 'container',
'#tree' => TRUE,
];
$form['stock_notification']['email'] = [
'#type' => 'email',
'#title' => t('Email'),
'#required' => TRUE,
'#default_value' => $current_user->getEmail(),
];
$form['stock_notification']['variation_id'] = [
'#type' => 'hidden',
'#value' => $variation_id,
];
$form['stock_notification']['notify_stock'] = [
'#type' => 'submit',
'#value' => t('Please notify me when this product is back in stock.'),
"#weight" => 10,
'#validate' => ['commerce_stock_notifications_subscribe_form_validate'],
'#submit' => ['commerce_stock_notifications_subscribe_form_submit'],
];
}
}
}
function commerce_stock_notifications_subscribe_form_validate($form, $form_state) {
$email = $form_state->getValue(['stock_notification', 'email']);
$variation_id = $form_state->getValue(['stock_notification', 'variation_id']);
$total = \Drupal::entityQuery('commerce_stock_notification')
->condition('email', $email)
->condition("product_id", $variation_id)
->notExists("sent_time")
->count()
->execute();
if ($total) {
$form_state->setError($form['stock_notification']['email'], t('A request for notification has already been made for this product with this email address.'));
}
}
function commerce_stock_notifications_subscribe_form_submit($form, $form_state) {
$current_user = \Drupal::currentUser();
$email = $form_state->getValue(['stock_notification', 'email']);
$variation_id = $form_state->getValue(['stock_notification', 'variation_id']);
$notification = StockNotification::create(
[
'langcode' => \Drupal::languageManager()->getCurrentLanguage()->getId(),
'email' => $email,
'uid' => $current_user->id(),
'product_id' => $variation_id,
]);
$notification->save();
drupal_set_message(t('You will be notified when this product is back in stock.'));
}
/*
* Implement hook_cron().
*/
function commerce_stock_notifications_cron() {
// TODO: implement queue system here for big datasets.
$awaiting_notification_ids = \Drupal::entityQuery('commerce_stock_notification')
->notExists("sent_time")
->execute();
$stock_service_manager = \Drupal::service('commerce_stock.service_manager');
$awaiting_notifications = StockNotification::loadMultiple($awaiting_notification_ids);
foreach ($awaiting_notifications as $awaiting_notification) {
$commerce_product_variation = ProductVariation::load($awaiting_notification->product_id->target_id);
if(!$commerce_product_variation){
continue; // TODO: we probably should delete the notification ids instead of skipping when they do not exist anymore.
}
$drupal_stock = $stock_service_manager->getStockLevel($commerce_product_variation);
$always_in_stock = FALSE;
if ($drupal_stock < 1) {
$stock_service = $stock_service_manager->getService($commerce_product_variation);
$stock_checker = $stock_service->getStockChecker();
if ($stock_checker->getIsAlwaysInStock($commerce_product_variation)) {
$always_in_stock = TRUE;
}
}
if ($drupal_stock > 0 || $always_in_stock) {
// Send email and flag as sent.
$build = [
'#theme' => 'commerce_stock_notifications_back_in_stock',
'#product_variation_entity' => $commerce_product_variation,
];
$params['body'] = \Drupal::getContainer()
->get('renderer')
->executeInRenderContext(new RenderContext(), function () use ($build) {
return \Drupal::getContainer()->get('renderer')->render($build);
});
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'commerce_stock_notifications';
$key = 'back_in_stock';
$to = $awaiting_notification->email->value;
$params['product_name'] = $commerce_product_variation->label();
$langcode = $awaiting_notification->langcode->value;
$send = TRUE;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
$now = new DrupalDateTime('now');
$awaiting_notification->sent_time->value = $now->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, ['timezone' => 'UTC']);
$awaiting_notification->save();
}
}
}
/**
* Implements hook_mail().
*/
function commerce_stock_notifications_mail($key, &$message, $params) {
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
case 'back_in_stock':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = t('@product_name is back in stock on @sitename', [
'@product_name' => $params['product_name'],
'@sitename' => \Drupal::config('system.site')->get('name'),
], $options);
$message['body'][] = $params['body'];
break;
}
}
/**
* Implements hook_theme().
*/
function commerce_stock_notifications_theme($existing, $type, $theme, $path) {
return [
'commerce_stock_notifications_back_in_stock' => [
'variables' => [
'product_variation_entity' => NULL,
],
],
];
}