/
class-wc-retailcrm-orders.php
642 lines (532 loc) · 21.9 KB
/
class-wc-retailcrm-orders.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
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
<?php
if (!class_exists('WC_Retailcrm_Orders')) :
/**
* PHP version 7.0
*
* Class WC_Retailcrm_Orders - Allows transfer data orders with CMS.
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Orders
{
/** @var bool|WC_Retailcrm_Proxy|WC_Retailcrm_Client_V5 */
protected $retailcrm;
/** @var array */
protected $retailcrm_settings;
/** @var WC_Retailcrm_Order_Item */
protected $order_item;
/** @var WC_Retailcrm_Order_Address */
protected $order_address;
/** @var WC_Retailcrm_Order_Payment */
protected $order_payment;
/** @var WC_Retailcrm_Customers */
protected $customers;
/** @var WC_Retailcrm_Order */
protected $orders;
/** @var array */
private $ordersGetRequestCache = [];
/** @var array */
private $order = [];
/** @var array */
private $payment = [];
/**@var array */
private $customFields = [];
public function __construct(
$retailcrm,
$retailcrm_settings,
$order_item,
$order_address,
$customers,
$orders,
$order_payment
) {
$this->retailcrm = $retailcrm;
$this->retailcrm_settings = $retailcrm_settings;
$this->order_item = $order_item;
$this->order_address = $order_address;
$this->customers = $customers;
$this->orders = $orders;
$this->order_payment = $order_payment;
if (!empty($retailcrm_settings['order-meta-data-retailcrm'])) {
$this->customFields = json_decode($retailcrm_settings['order-meta-data-retailcrm'], true);
}
}
/**
* Create order. Returns wc_get_order data or error string.
*
* @param $orderId
*
* @return bool|WC_Order|string
* @throws \Exception
*/
public function orderCreate($orderId)
{
if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null;
}
try {
$this->order_payment->resetData();
$wcOrder = wc_get_order($orderId);
$this->processOrder($wcOrder);
$response = $this->retailcrm->ordersCreate($this->order);
// Allows you to verify order creation and perform additional actions
$response = apply_filters('retailcrm_order_create_after', $response, $wcOrder);
if (!$response instanceof WC_Retailcrm_Response || !$response->isSuccessful()) {
return $response->getErrorString();
}
} catch (Throwable $exception) {
writeBaseLogs(
sprintf(
'Error message: %s, file: %s on line: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
)
);
return null;
}
return $wcOrder;
}
/**
* Process order customer data
*
* @param \WC_Order $wcOrder
* @param bool $update
*
* @return bool Returns false if order cannot be processed
* @throws \Exception
*/
protected function processOrderCustomerInfo($wcOrder, $update = false)
{
$customerWasChanged = false;
$wpUser = $wcOrder->get_user();
if ($update) {
$response = $this->getCrmOrder($wcOrder->get_id());
if (!empty($response)) {
$customerWasChanged = self::isOrderCustomerWasChanged($wcOrder, $response);
}
}
if ($wpUser instanceof WP_User) {
if (!$this->customers->isCustomer($wpUser)) {
return false;
}
$wpUserId = (int) $wpUser->get('ID');
if (!$update || ($update && $customerWasChanged)) {
$this->fillOrderCreate($wpUserId, $wpUser->get('billing_email'), $wcOrder);
}
} else {
$wcCustomer = $this->customers->buildCustomerFromOrderData($wcOrder);
if (!$update || ($update && $customerWasChanged)) {
$this->fillOrderCreate(0, $wcCustomer->get_billing_email(), $wcOrder);
}
}
return true;
}
/**
* Fill order on create
*
* @param int $wcCustomerId
* @param string $wcCustomerEmail
* @param \WC_Order $wcOrder
*
* @throws \Exception
*/
protected function fillOrderCreate($wcCustomerId, $wcCustomerEmail, $wcOrder)
{
$isContact = $this->retailcrm->getCorporateEnabled() && static::isCorporateOrder($wcOrder);
$foundCustomer = $this->customers->findCustomerEmailOrId(
$wcCustomerId,
strtolower($wcCustomerEmail),
$isContact
);
if (empty($foundCustomer)) {
$foundCustomerId = $this->customers->createCustomer($wcCustomerId, $wcOrder);
if (!empty($foundCustomerId)) {
$this->order['customer']['id'] = $foundCustomerId;
}
} else {
$this->order['customer']['id'] = $foundCustomer['id'];
$foundCustomerId = $foundCustomer['id'];
}
$this->order['contragent']['contragentType'] = 'individual';
if ($this->retailcrm->getCorporateEnabled() && static::isCorporateOrder($wcOrder)) {
unset($this->order['contragent']['contragentType']);
$crmCorporate = $this->customers->searchCorporateCustomer(array(
'contactIds' => array($foundCustomerId),
'companyName' => $wcOrder->get_billing_company()
));
if (empty($crmCorporate)) {
$crmCorporate = $this->customers->searchCorporateCustomer(array(
'companyName' => $wcOrder->get_billing_company()
));
}
if (empty($crmCorporate)) {
$corporateId = $this->customers->createCorporateCustomerForOrder(
$foundCustomerId,
$wcCustomerId,
$wcOrder
);
$this->order['customer']['id'] = $corporateId;
} else {
// Testing of this method occurs in customers tests.
// @codeCoverageIgnoreStart
$addressFound = $this->customers->fillCorporateAddress(
$crmCorporate['id'],
new WC_Customer($wcCustomerId),
$wcOrder
);
// If address not found create new address.
if (!$addressFound) {
WC_Retailcrm_Logger::add(
sprintf(
'[%d] => %s',
$this->order['customer']['id'],
'Notification: Create new address for corporate customer'
)
);
}
$this->order['customer']['id'] = $crmCorporate['id'];
// @codeCoverageIgnoreEnd
}
$companiesResponse = $this->retailcrm->customersCorporateCompanies(
$this->order['customer']['id'],
[],
null,
null,
'id'
);
if (!empty($companiesResponse) && $companiesResponse->isSuccessful()) {
foreach ($companiesResponse['companies'] as $company) {
if ($company['name'] == $wcOrder->get_billing_company()) {
$this->order['company'] = [
'id' => $company['id'],
'name' => $company['name']
];
break;
}
}
}
$this->order['contact']['id'] = $foundCustomerId;
}
}
/**
* Edit order in CRM
*
* @param int $orderId
*
* @return WC_Order $order | null
* @throws \Exception
*/
public function updateOrder($orderId)
{
if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null;
}
try {
$wcOrder = wc_get_order($orderId);
$this->processOrder($wcOrder, true);
$response = $this->retailcrm->ordersEdit($this->order);
// Allows you to verify order changes and perform additional actions
$response = apply_filters('retailcrm_order_update_after', $response, $wcOrder);
if ($response instanceof WC_Retailcrm_Response && $response->isSuccessful()) {
$this->payment = $this->orderUpdatePaymentType($wcOrder);
}
} catch (Throwable $exception) {
writeBaseLogs(
sprintf(
'Error message: %s, file: %s on line: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
)
);
return null;
}
return $wcOrder;
}
/**
* Update order payment type
*
* @param WC_Order $order
*
* @return null | array $payment
*/
protected function orderUpdatePaymentType($order)
{
if (!isset($this->retailcrm_settings[$order->get_payment_method()])) {
return null;
}
$retailcrmOrder = $this->getCrmOrder($order->get_id());
if (empty($retailcrmOrder)) {
return null;
}
foreach ($retailcrmOrder['payments'] as $paymentData) {
$paymentId = explode('-', $paymentData['externalId']);
if ($paymentId[0] == $order->get_id()) {
$payment = $paymentData;
}
}
if (empty($payment)) {
return null;
}
if ($payment['type'] == $this->retailcrm_settings[$order->get_payment_method()] && $order->is_paid()) {
return $this->sendPayment($order, true, $payment['externalId']);
}
if ($payment['type'] != $this->retailcrm_settings[$order->get_payment_method()]) {
$response = $this->retailcrm->ordersPaymentDelete($payment['id']);
if (!empty($response) && $response->isSuccessful()) {
return $this->sendPayment($order);
}
}
return null;
}
/**
* process to combine order data
*
* @param WC_Order $order
* @param boolean $update
*
* @return void
* @throws \Exception
*/
protected function processOrder($order, $update = false)
{
if (!$order instanceof WC_Order) {
return;
}
if ('auto-draft' === $order->get_status()) {
return;
}
if ($update) {
$this->orders->is_new = false;
}
$orderData = $this->orders->build($order)->getData();
if ($order->get_items('shipping')) {
$shippings = $order->get_items('shipping');
$shipping = reset($shippings);
$shipping_code = explode(':', $shipping['method_id']);
if (isset($this->retailcrm_settings[$shipping['method_id']])) {
$shipping_method = $shipping['method_id'];
} elseif (isset($this->retailcrm_settings[$shipping_code[0]])) {
$shipping_method = $shipping_code[0];
} else {
$shipping_method = $shipping['method_id'] . ':' . $shipping['instance_id'];
}
if (!empty($shipping_method) && !empty($this->retailcrm_settings[$shipping_method])) {
$orderData['delivery']['code'] = $this->retailcrm_settings[$shipping_method];
$service = retailcrm_get_delivery_service($shipping['method_id'], $shipping['instance_id']);
if ($service) {
$orderData['delivery']['service'] = [
'name' => $service['title'],
'code' => $service['instance_id'],
'active' => true
];
}
}
if (isset($shipping['total'])) {
$orderData['delivery']['netCost'] = $shipping['total'];
$orderData['delivery']['cost'] = isset($shipping['total_tax'])
? $shipping['total'] + $shipping['total_tax']
: $shipping['total'];
if (wc_tax_enabled()) {
$shippingTaxClass = get_option('woocommerce_shipping_tax_class');
$rate = $shippingTaxClass == 'inherit'
? getOrderItemRate($order)
: getShippingRate();
if ($rate !== null) {
$orderData['delivery']['vatRate'] = $rate;
}
}
}
}
$orderData['delivery']['address'] = $this->order_address->build($order)->getData();
$orderItems = [];
/** @var WC_Order_Item_Product $item */
foreach ($order->get_items() as $item) {
$orderItems[] = $this->order_item->build($item)->getData();
$this->order_item->resetData();
}
$orderData['items'] = $orderItems;
$orderData['discountManualAmount'] = 0;
$orderData['discountManualPercent'] = 0;
if (!$update && $order->get_total() > 0) {
$this->order_payment->isNew = true;
$orderData['payments'][] = $this->order_payment->build($order)->getData();
}
if (!empty($this->customFields)) {
foreach ($this->customFields as $metaKey => $customKey) {
$metaValue = $order->get_meta($metaKey);
if (empty($metaValue)) {
continue;
}
if (strpos($customKey, 'default-crm-field') !== false) {
$crmField = explode('#', $customKey);
if (count($crmField) === 2 && isset($crmField[1])) {
$orderData[$crmField[1]] = $metaValue;
} elseif (isset($crmField[1], $crmField[2], $crmField[3])) {
// For order delivery
$orderData[$crmField[1]][$crmField[2]][$crmField[3]] = $metaValue;
}
} else {
$orderData['customFields'][$customKey] = $metaValue;
}
}
}
$couponCustomField = $this->retailcrm_settings['woo_coupon_apply_field'];
if ($couponCustomField !== 'not-upload') {
$codeCoupons = [];
foreach ($order->get_coupons() as $coupon) {
if (!empty($coupon->get_code())) {
$codeCoupons[] = $coupon->get_code();
}
}
$orderData['customFields'][$couponCustomField] = implode('; ', $codeCoupons);
}
$this->order = WC_Retailcrm_Plugin::clearArray($orderData);
$this->processOrderCustomerInfo($order, $update);
$this->order = apply_filters(
'retailcrm_process_order',
WC_Retailcrm_Plugin::clearArray($this->order),
$order
);
}
/**
* Send payment in CRM
*
* @param WC_Order $order
* @param boolean $update
* @param mixed $externalId
*
* @return array $payment
*/
protected function sendPayment($order, $update = false, $externalId = false)
{
$this->order_payment->isNew = !$update;
$payment = $this->order_payment->build($order, $externalId)->getData();
$integrationPayments = get_option('retailcrm_integration_payments');
if (is_array($integrationPayments)) {
$integrationPayments = array_flip($integrationPayments);
}
if ($update === true && isset($integrationPayments[$payment['type']])) {
return $payment;
}
if ($update === false) {
$this->retailcrm->ordersPaymentCreate($payment);
} else {
$this->retailcrm->ordersPaymentEdit($payment);
}
return $payment;
}
/**
* ordersGet wrapper with cache (in order to minimize request count).
*
* @param int|string $orderId
* @param bool $cached
*
* @return array
*/
protected function getCrmOrder($orderId, $cached = true)
{
if ($cached && isset($this->ordersGetRequestCache[$orderId])) {
return (array) $this->ordersGetRequestCache[$orderId];
}
$crmOrder = [];
$response = $this->retailcrm->ordersGet($orderId);
if (!empty($response) && $response->isSuccessful() && isset($response['order'])) {
$crmOrder = (array) $response['order'];
$this->ordersGetRequestCache[$orderId] = $crmOrder;
}
return $crmOrder;
}
/**
* @return array
*/
public function getOrder()
{
return $this->order;
}
/**
* @return array
*/
public function getPayment()
{
return $this->payment;
}
/**
* Returns true if provided order is for corporate customer
*
* @param WC_Order $order
*
* @return bool
*/
public static function isCorporateOrder($order)
{
$billingCompany = $order->get_billing_company();
return !empty($billingCompany);
}
/**
* Returns true if passed crm order is corporate
*
* @param array|\ArrayAccess $order
*
* @return bool
*/
public static function isCorporateCrmOrder($order)
{
return (is_array($order) || $order instanceof ArrayAccess)
&& isset($order['customer'])
&& isset($order['customer']['type'])
&& $order['customer']['type'] == 'customer_corporate';
}
/**
* Returns true if customer in order was changed. `true` will be returned if one of these four conditions is met:
*
* 1. If CMS order is corporate and retailCRM order is not corporate or vice versa, then customer obviously
* needs to be updated in retailCRM.
* 2. If billing company from CMS order is not the same as the one in the retailCRM order,
* then company needs to be updated.
* 3. If contact person or individual externalId is different from customer ID in the CMS order, then
* contact person or customer in retailCRM should be updated (even if customer id in the order is not set).
* 4. If contact person or individual email is not the same as the CMS order billing email, then
* contact person or customer in retailCRM should be updated.
*
* @param \WC_Order $wcOrder
* @param array|\ArrayAccess $crmOrder
*
* @return bool
*/
public static function isOrderCustomerWasChanged($wcOrder, $crmOrder)
{
if (!isset($crmOrder['customer'])) {
return false;
}
$customerWasChanged = self::isCorporateOrder($wcOrder) != self::isCorporateCrmOrder($crmOrder);
$synchronizableUserData = (self::isCorporateCrmOrder($crmOrder) && isset($crmOrder['contact']))
? $crmOrder['contact'] : $crmOrder['customer'];
if (!$customerWasChanged) {
if (self::isCorporateCrmOrder($crmOrder)) {
$currentCrmCompany = isset($crmOrder['company']) ? $crmOrder['company']['name'] : '';
if (!empty($currentCrmCompany) && $currentCrmCompany != $wcOrder->get_billing_company()) {
$customerWasChanged = true;
}
}
if (
isset($synchronizableUserData['externalId'])
&& $synchronizableUserData['externalId'] != $wcOrder->get_customer_id()
) {
$customerWasChanged = true;
} elseif (
isset($synchronizableUserData['email'])
&& $synchronizableUserData['email'] != $wcOrder->get_billing_email()
) {
$customerWasChanged = true;
}
}
return $customerWasChanged;
}
}
endif;