-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommerce_customizations.module
More file actions
438 lines (361 loc) · 13.9 KB
/
commerce_customizations.module
File metadata and controls
438 lines (361 loc) · 13.9 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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
<?php
/**
* @file
* Contains commerce_checkout_customizations.module.
*/
use Drupal\commerce_customizations\CommerceEmailHelper;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\views\ViewExecutable;
/**
* Implements hook_help().
*/
function commerce_customizations_help($route_name, RouteMatchInterface $route_match)
{
if ($route_name === 'help.page.commerce_customizations') {
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Allows customization of many aspects of Commerce 2.x.') . '</p>';
return $output;
}
}
/**
* Implements hook_aluminum_storage_phone_numbers().
*/
function commerce_customizations_aluminum_storage_phone_numbers()
{
return [];
}
/**
* Implements hook_theme_registry_alter().
*/
function commerce_customizations_theme_registry_alter(&$theme_registry)
{
if (isset($theme_registry['commerce_order__admin'])) {
$theme_registry['commerce_order__admin']['path'] = drupal_get_path('module', 'commerce_customizations') . '/templates';
}
if (isset($theme_registry['commerce_order__user'])) {
$theme_registry['commerce_order__user']['path'] = drupal_get_path('module', 'commerce_customizations') . '/templates';
}
}
/**
* Gets the customer name from the provided order.
*
* @param \Drupal\commerce_order\Entity\OrderInterface $order
* The order.
*
* @return \Drupal\Component\Render\MarkupInterface|mixed|string
* The customer name as markup or a string.
*/
function commerce_customizations_get_customer_name(\Drupal\commerce_order\Entity\OrderInterface $order)
{
try {
$customer = $order->getCustomer();
$name = '';
if (NULL !== $customer) {
if ($order->getCustomer()->isAnonymous()) {
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $order->get('shipments')->first()->entity;
$profile = \Drupal\commerce_quote_cart\QuoteCartHelper::isPurchaseCart($order)
? $order->getBillingProfile()
: $shipment->getShippingProfile();
/** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $address */
$address = $profile->get('address')->first();
$name = $address->getGivenName();
} else {
$name = (NULL !== $customer) ? $customer->getDisplayName() : '';
}
}
return $name;
} catch (\Drupal\Core\TypedData\Exception\MissingDataException $e) {
return '';
}
}
/**
* Implements hook_preprocess_commerce_order_receipt().
*/
function commerce_customizations_preprocess_commerce_order_receipt(&$variables)
{
/** @var Drupal\commerce_order\Entity\OrderInterface $order */
$order = $variables['order_entity'];
$variables['shipping_info'] = commerce_customizations_expand_shipping_info($order);
$variables['billing_info'] = commerce_customizations_expand_billing_info($order);
$variables['customer_name'] = commerce_customizations_get_customer_name($order);
$variables['site_url'] = \Drupal\Core\Url::fromRoute('<front>')->setAbsolute(TRUE)->toString();
$variables['support_url'] = CommerceEmailHelper::nodeUrl(51);
$variables['resources_url'] = CommerceEmailHelper::nodeUrl(28);
$variables['product_registration_url'] = \Drupal\Core\Url::fromUserInput('/me/registered-products')->setAbsolute(TRUE)->toString();
$variables['order_items'] = CommerceEmailHelper::orderItems($order);
$variables['order_label'] = \Drupal\commerce_quote_cart\QuoteCartHelper::isPurchaseCart($order) ? t('Order') : t('Quote');
$variables['is_quote'] = !\Drupal\commerce_quote_cart\QuoteCartHelper::isPurchaseCart($order);
$variables['order_email'] = $order->getEmail();
$variables['order_comments'] = !$order->get('field_comments')->isEmpty() ? $order->get('field_comments')->value : '';
/** @var \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter */
$dateFormatter = \Drupal::service('date.formatter');
$variables['order_date'] = $dateFormatter->format($order->getPlacedTime(), 'short');
$variables['coupons'] = '';
if ($order->hasField('coupons') && !$order->get('coupons')->isEmpty()) {
$variables['coupons'] = \Drupal\commerce_customizations\CouponsTable::build($order);
}
}
function commerce_customizations_expand_billing_info(\Drupal\commerce_order\Entity\OrderInterface $order)
{
$billing_info = [];
if (!$order->get('billing_profile')->isEmpty()) {
/** @var \Drupal\profile\Entity\ProfileInterface $billing_profile */
$billing_profile = $order->get('billing_profile')->entity;
$billing_info = commerce_customizations_expand_profile_variables($billing_profile);
}
return $billing_info;
}
function commerce_customizations_expand_shipping_info(\Drupal\commerce_order\Entity\OrderInterface $order)
{
$shipping_info = [];
$shipping_data = \Drupal::service('commerce_shipping.order_shipment_summary')->build($order);
if (isset($shipping_data['shipping_profile']['#profile'])) {
/** @var \Drupal\profile\Entity\ProfileInterface $shipping_profile */
$shipping_profile = $shipping_data['shipping_profile']['#profile'];
$shipping_info = commerce_customizations_expand_profile_variables($shipping_profile);
}
/** @var \Drupal\commerce_shipping\Entity\ShipmentInterface $shipment */
$shipment = $shipping_data[0]['shipment']['#commerce_shipment'];
$shipping_service = $shipment->getShippingService();
$services = $shipment->getShippingMethod()->getPlugin()->getServices();
$service = $services[$shipping_service]->getLabel();
$shipping_info['method'] = $service;
return $shipping_info;
}
/**
* @param \Drupal\profile\Entity\ProfileInterface $profile
* The profile.
*
* @return array
* The expanded profile variables.
*/
function commerce_customizations_expand_profile_variables(\Drupal\profile\Entity\ProfileInterface $profile)
{
try {
/** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $address */
$address = $profile->get('address')->first();
/** @var \Drupal\Core\Locale\CountryManagerInterface $country_manager */
$country_manager = \Drupal::service('country_manager');
$country_list = $country_manager->getList();
$profile_variables = [
'first_name' => $address->get('given_name')->getValue(),
'last_name' => $address->get('family_name')->getValue(),
'job_title' => $profile->get('field_job_title')->value,
'company' => $address->get('organization')->getValue(),
'address_line1' => $address->get('address_line1')->getValue(),
'address_line2' => $address->get('address_line2')->getValue(),
'city' => $address->get('locality')->getValue(),
'state' => $address->get('administrative_area')->getValue(),
'postal_code' => $address->get('postal_code')->getValue(),
'country' => $country_list[$address->get('country_code')->getValue()],
'phone' => $profile->get('field_phone_number')->value,
'address' => $address
];
return $profile_variables;
} catch (\Drupal\Core\TypedData\Exception\MissingDataException $e) {
return [];
}
}
function commerce_customizations_preprocess_commerce_order(&$variables)
{
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $variables['elements']['#commerce_order'];
unset($variables['order']['order_items']);
$variables['order']['order_items']['view'] = [
'#type' => 'view',
'#name' => 'commerce_order_item_table',
'#arguments' => [$order->id()],
];
$variables['order_url'] = '/user/' . $order->getCustomerId() . '/orders/' . $order->id();
$variables['field_comments'] = !$order->get('field_comments')->isEmpty() ? $order->get('field_comments')->value : '';
}
/**
* Implements hook_entity_presave().
*/
function commerce_customizations_commerce_product_presave(Drupal\Core\Entity\EntityInterface $entity)
{
/** @var \Drupal\commerce_product\Entity\ProductInterface $entity */
if ($entity->hasField('field_main_category')) {
$fields = [
'field_accessory_category',
'field_product_category',
];
$targetId = NULL;
foreach ($fields as $field) {
if ($entity->hasField($field) && !$entity->get($field)->isEmpty()) {
$targetId = $entity->get($field)->target_id;
break;
}
}
if (NULL !== $targetId) {
$entity->get('field_main_category')->target_id = $targetId;
}
}
if ($entity->hasField('field_is_product')) {
$entity->get('field_is_product')->value = (
$entity->hasField('field_product_category')
&& !$entity->get('field_product_category')->isEmpty()
);
}
}
/**
* Implements hook_mail_alter().
*/
function commerce_customizations_mail_alter(&$message)
{
if ($message['id'] === 'commerce_order_receipt') {
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $message['params']['order'];
if (!\Drupal\commerce_quote_cart\QuoteCartHelper::isPurchaseCart($order)) {
$message['subject'] = t('Quote #@number confirmed', [
'@number' => $order->id(),
]);
}
}
}
/**
* Implements hook_views_pre_build().
*/
function commerce_customizations_views_pre_build(ViewExecutable $view) {
if ($view->id() == 'unpublished_products_with_published_translations') {
/** @var \Drupal\views\Plugin\views\argument\NumericArgument $argument */
//$argument = $view->argument['product_id'];
$view->args[0] = commerce_customizations_get_unpublished_product_ids_with_published_translations();
}
}
function commerce_customizations_get_unpublished_product_ids_with_published_translations() {
$enQuery = \Drupal::entityQuery('commerce_product')
->condition('status', 0)
->condition('langcode', 'en');
$enResult = $enQuery->execute();
if (empty($enResult)) {
return '';
}
$enIds = array_keys($enResult);
$esQuery = \Drupal::entityQuery('commerce_product')
->condition('status', 1)
->condition('langcode', 'es');
$esResult = $esQuery->execute();
if (empty($esResult)) {
return '';
}
$esIds = array_keys($esResult);
$ids = array_intersect($enIds, $esIds);
return implode('+', $ids);
}
/**
* Implements hook_views_pre_render().
*/
function commerce_customizations_views_pre_render(ViewExecutable $view)
{
$view_ids = [
'order_report',
'order_report_no_detail',
'order_report_products',
'variation_pricing',
'contact_messages',
];
if (!empty($view->footer) && in_array($view->id(), $view_ids, FALSE)) {
foreach ($view->footer as $key => $area) {
if ($area instanceof \Drupal\views\Plugin\views\area\Text && isset($area->options['content']['value'])) {
$area->options['content']['value'] = commerce_customizations_append_query_string_for_csv($area->options['content']['value']);
}
}
}
}
function commerce_customizations_append_query_string_for_csv($value) {
if (strpos($value, '.csv') === FALSE) {
return $value;
}
$search = '.csv';
$replacement = '.csv?_format=csv';
if (\Drupal::request()->getQueryString() !== null) {
$replacement .= '&' . \Drupal::request()->getQueryString();
}
if (strpos($value, '.csv?') !== FALSE) {
$search = '.csv?';
$replacement .= '&';
}
return str_replace($search, $replacement, $value);
}
/**
* Implements hook_form_alter().
*/
function commerce_customizations_form_profile_customer_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
$form['#attached']['library'][] = 'commerce_customizations/profile-form';
}
/**
* Implements hook_field_widget_form_alter().
*/
function commerce_customizations_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context)
{
$autofillMap = [
'field_job_title' => 'organization-title',
'field_phone_number' => 'tel',
];
/** @var \Drupal\Core\Field\WidgetInterface $widget */
$widget = $context['widget'];
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
$items = $context['items'];
$fieldName = $items->getName();
if (array_key_exists($fieldName, $autofillMap)) {
$element['value']['#attributes']['autocomplete'] = $autofillMap[$fieldName];
}
if ($widget->getPluginId() === 'address_default') {
$element['address']['#process'][] = [\Drupal\address\Element\Address::class, 'processAddress'];
$element['address']['#process'][] = [\Drupal\address\Element\Address::class, 'processGroup'];
$element['address']['#process'][] = 'commerce_customizations_process_address';
}
}
function commerce_customizations_process_address($element, \Drupal\Core\Form\FormStateInterface $form_state, $form)
{
$element['organization']['#required'] = TRUE;
$type = $element['#parents'][0] === 'shipping_information' ? 'shipping' : 'billing';
$autofillMap = [
'country_code' => 'country',
'given_name' => 'given-name',
'family_name' => 'family-name',
'organization' => 'organization',
'address_line1' => 'address-line1',
'address_line2' => 'address-line2',
'locality' => 'locality',
'administrative_area' => 'region',
'postal_code' => 'postal-code',
];
foreach ($autofillMap as $field => $value) {
if (array_key_exists($field, $element)) {
$element[$field]['#attributes']['autocomplete'] = "$type $value";
}
}
return $element;
}
function commerce_customizations_preprocess_commerce_product_variation(&$variables) {
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
$variation = $variables['product_variation_entity'];
$variables['variation_url'] = $variation->toUrl();
}
// @todo move this to a separate module
/**
* Implements hook_preprocess_video_embed_iframe().
*/
function commerce_customizations_preprocess_video_embed_iframe__youtube(&$variables) {
$variables['query']['enablejsapi'] = 1;
}
/**
* Implements hook_mail().
*/
function commerce_customizations_mail($key, &$message, $params) {
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
case 'out_of_stock_alert':
$message['from'] = Drupal::config('system.site')->get('mail');
$message['subject'] = t('Item out of stock: @sku', ['@sku' => $params['sku']], $options);
$message['body'][] = $params['message'];
break;
}
}