Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
ordercompatibility.php
1<?php
2
4
10
11Main\Localization\Loc::loadMessages(__FILE__);
12
18{
20 protected $order = null;
21
23 protected $requestFields = null;
24
26 protected $basket = null;
27
28 protected $externalPrice = null;
29
30
34
35 protected $runtimeFields = array();
36 protected $propertyRuntimeList = array();
37
41 protected static function getRegistryType()
42 {
43 return Sale\Registry::REGISTRY_TYPE_ORDER;
44 }
45
51 protected static function getEntity()
52 {
53 return OrderTable::getEntity();
54 }
55
59 protected static function getBasketCompatibilityClassName()
60 {
61 return BasketCompatibility::class;
62 }
63
70 protected function __construct(array $fields = array())
71 {
73 $this->query = new OrderQuery(static::getEntity());
74 $this->fields = new Sale\Internals\Fields($fields);
75 }
76
80 public function getOrder()
81 {
82 return $this->order;
83 }
84
88 public function getRequestFields()
89 {
91 }
92
96 public function setBasketCompatibility(BasketCompatibility $basketCompatibility)
97 {
98 $this->basket = $basketCompatibility;
99 }
100
105 public static function create(array $fields)
106 {
107 $adminSection = (defined('ADMIN_SECTION') && ADMIN_SECTION === true);
108
109 $orderCompatibility = new static();
110
111
112
113 $registry = Sale\Registry::getInstance(static::getRegistryType());
115 $orderClassName = $registry->getOrderClassName();
116
117 if (isset($fields['ID']) && intval($fields['ID']) > 0)
118 {
119 if (!$order = $orderClassName::load($fields['ID']))
120 {
121 throw new Sale\UserMessageException('Order not found');
122 }
123 }
124 else
125 {
126 $lid = $fields['LID'] ?? '';
127 $userId = $fields['USER_ID'] ?? null;
128 $currency = $fields['CURRENCY'] ?? null;
129 if (!$order = $orderClassName::create($lid, $userId, $currency))
130 {
131 throw new Sale\UserMessageException('Order not create');
132 }
133 }
134
135 if (isset($fields['PERSON_TYPE_ID']) && intval($fields['PERSON_TYPE_ID']) > 0)
136 {
137 $order->setPersonTypeId($fields['PERSON_TYPE_ID']);
138 }
139
140 $orderFields = static::replaceFields($fields, static::getOrderReplaceFields());
141
142 $orderFields = $orderCompatibility->parseRawFields(static::ENTITY_ORDER, $orderFields);
143
144 $orderFields = static::clearFields($orderFields);
145 foreach (static::getFieldsFromOtherEntities() as $wrongField)
146 {
147 if (array_key_exists($wrongField, $fields))
148 unset($orderFields[$wrongField]);
149 }
150
151 $orderFields = static::convertDateFields($orderFields, static::getOrderDateFields());
152
153 unset($orderFields['MARKED']);
154 unset($orderFields['CANCELED']);
155
156 if (array_key_exists('PRICE', $orderFields))
157 {
158 $orderCompatibility->externalPrice = $orderFields['PRICE'];
159 }
160
161 if ($order->getId() > 0)
162 {
163 if ($adminSection)
164 {
165 unset($orderFields['PRICE']);
166 }
167
168 unset($orderFields['PRICE_DELIVERY']);
169 unset($orderFields['DISCOUNT_VALUE']);
170 unset($orderFields['TAX_VALUE']);
171 $order->setField('DATE_UPDATE', new Main\Type\DateTime());
172 }
173 else
174 {
175 if (!$adminSection)
176 unset($orderFields['SUM_PAID']);
177
178 $order->setField('DATE_INSERT', new Main\Type\DateTime());
179 $order->setField('DATE_UPDATE', new Main\Type\DateTime());
180 }
181
182 unset($orderFields['TAX_PRICE']);
183
184 if (array_key_exists('STATUS_ID', $orderFields) && $order->getId() > 0)
185 {
186 $order->setField('STATUS_ID', $orderFields['STATUS_ID']);
187 unset($orderFields['STATUS_ID']);
188 }
189
190 if (isset($orderFields['USE_VAT']) && $orderFields['USE_VAT'] === true)
191 {
192 $orderFields['USE_VAT'] = 'Y';
193 }
194
195 $order->setFieldsNoDemand($orderFields);
196
197 $orderCompatibility->order = $order;
198
199 $orderCompatibility->requestFields = $fields;
200
201 $order->getDiscount();
202
203 return $orderCompatibility;
204 }
205
216 public static function fillOrderFromRequest(Sale\Order $order, array $fields)
217 {
218 global $USER;
219 $result = new Sale\Result();
220 if (isset($fields['CANCELED']))
221 {
222 if ($order->getId() > 0 && $order->getField('CANCELED') != $fields['CANCELED'])
223 {
224 if (!(\CSaleOrder::CanUserCancelOrder($order->getId(), $USER->GetUserGroupArray(), $USER->GetID())))
225 {
226 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_CANCEL_NO_PERMISSION'), 'SALE_COMPATIBLE_ORDER_CANCEL_NO_PERMISSION') );
227 return $result;
228 }
229
231 $r = $order->setField('CANCELED', $fields['CANCELED']);
232 if (!$r->isSuccess())
233 {
234 $result->addErrors($r->getErrors());
235 return $result;
236 }
237
238 if (array_key_exists("REASON_CANCELED", $fields))
239 {
241 $r = $order->setField('REASON_CANCELED', $fields['REASON_CANCELED']);
242 if (!$r->isSuccess())
243 {
244 $result->addErrors($r->getErrors());
245 return $result;
246 }
247 }
248
249 }
250 }
251
252
253 if (isset($fields['MARKED']))
254 {
255 if ($order->getId() > 0)
256 {
257 if ($fields['MARKED'] == 'Y')
258 {
259 $reasonMarked = '';
260 if (!empty($fields['REASON_MARKED']))
261 {
262 $reasonMarked = trim($fields['REASON_MARKED']);
263 }
264
265 $r = new Sale\Result();
266 $r->addError(new Sale\ResultWarning($reasonMarked, 'SALE_ORDER_MARKER_ERROR'));
267
268 $registry = Sale\Registry::getInstance(static::getRegistryType());
269
271 $entityMarkerClassName = $registry->getEntityMarkerClassName();
272 $entityMarkerClassName::addMarker($order, $order, $r);
273 }
274
275 if ($order->getField('MARKED') != $fields['MARKED'])
276 {
278 $r = $order->setField('MARKED', $fields['MARKED']);
279 if (!$r->isSuccess())
280 {
281 $result->addErrors($r->getErrors());
282 }
283 }
284 }
285 }
286
287 if ($order->getId() > 0 && !empty($fields['ACCOUNT_NUMBER']) && !empty($fields['SITE_ID']))
288 {
289 $filter = array(
290 'filter' => array(
291 '=ACCOUNT_NUMBER' => $fields['ACCOUNT_NUMBER'],
292 '!ID' => $order->getId()
293 ),
294 'select' => array('ID')
295 );
296
297 $registry = Sale\Registry::getInstance(static::getRegistryType());
298
300 $orderClassName = $registry->getOrderClassName();
301 if (($res = $orderClassName::getList($filter)) && ($res->fetch()))
302 {
303 $result->addError(new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_ACCOUNT_NUMBER_ALREADY_EXISTS'), 'SALE_COMPATIBLE_ORDER_ACCOUNT_NUMBER_ALREADY_EXISTS'));
304 }
305 }
306
307
308 return $result;
309 }
310
311
328 public function fillShipmentCollectionFromRequest(Sale\ShipmentCollection $shipmentCollection, array $fields)
329 {
330 $result = new Sale\Result();
331
333 if (!$order = $shipmentCollection->getOrder())
334 {
335 throw new Main\ObjectNotFoundException('Entity "Order" not found');
336 }
337
338 $shipment = null;
339 $deliveryId = null;
340 $deliveryCode = isset($fields['DELIVERY_ID']) && strval(trim($fields['DELIVERY_ID'])) != '' ? trim($fields['DELIVERY_ID']) : null;
341
342 if (strval(trim($deliveryCode)) != '')
343 {
344 $deliveryId = \CSaleDelivery::getIdByCode($deliveryCode);
345 }
346
347 if ($order->getId() > 0)
348 {
349 //todo: check $deliveryId
350
351 if (count($shipmentCollection) == 2 && $shipmentCollection->isExistsSystemShipment())
352 {
354 foreach($shipmentCollection as $shipment)
355 {
356 if ($shipment->isSystem())
357 continue;
358
359 if ($deliveryId > 0 && $deliveryId != $shipment->getDeliveryId())
360 {
362 $r = $shipment->setField('DELIVERY_ID', $deliveryId);
363 if ($r->isSuccess())
364 {
366 $deliveryService = Sale\Delivery\Services\Manager::getObjectById($deliveryId);
367 if ($deliveryService)
368 {
369 $fields['DELIVERY_NAME'] = $deliveryService->isProfile()
370 ? $deliveryService->getNameWithParent()
371 : $deliveryService->getName();
372 }
373 else
374 {
375 $fields['DELIVERY_NAME'] = 'Not found [' . $deliveryId . ']';
376 }
377 }
378 else
379 {
380 $result->addErrors($r->getErrors());
381 }
382 }
383 elseif (intval($deliveryId) == 0 && array_key_exists('DELIVERY_ID', $fields) || (intval($deliveryId) !== intval($deliveryCode)))
384 {
385 unset($fields['DELIVERY_ID']);
386 }
387
388 if (array_key_exists('PRICE_DELIVERY', $fields) && (float)$fields['PRICE_DELIVERY'] != $shipment->getField('PRICE_DELIVERY'))
389 {
390 $fields['BASE_PRICE_DELIVERY'] = (float)$fields['PRICE_DELIVERY'];
391 $fields['CUSTOM_PRICE_DELIVERY'] = "Y";
392
393 unset($fields['PRICE_DELIVERY']);
394 }
395
396 $shipmentFields = static::convertDateFields($fields, static::getEntityDateFields($shipment));
397
398 unset($shipmentFields['ALLOW_DELIVERY']);
399 unset($shipmentFields['DEDUCTED']);
400
401 if ($fields['CURRENCY'] != $shipmentFields['CURRENCY'])
402 {
403 $shipmentFields['CURRENCY'] = $fields['CURRENCY'];
404 }
405
407 $r = $shipment->setFields(static::clearFields($shipmentFields, static::getShipmentAvailableFields()));
408 if ($r->isSuccess())
409 {
410 static::fillOrderFieldsFromEntity($order, $shipment, $fields, static::getShipmentFieldsToConvert());
411 }
412 else
413 {
414 $result->addErrors($r->getErrors());
415 }
416
417 if ($shipment !== null)
418 {
419 DiscountCompatibility::setShipment($order->getId(), $shipment->getId());
420 }
421
422 unset($fields['DELIVERY_ID']);
423 }
424 }
425
426 }
427 else
428 {
429 if (intval($deliveryId) == 0)
430 {
431 $deliveryId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
432 }
433
434 if (intval($deliveryId) > 0)
435 {
437 if ($shipment = static::createShipmentFromRequest($shipmentCollection, $deliveryId, $fields))
438 {
439 if (isset($fields['TRACKING_NUMBER']) && strval($fields['TRACKING_NUMBER']) != '')
440 {
441 $shipment->setField('TRACKING_NUMBER', $fields['TRACKING_NUMBER']);
442 }
443
444 if (isset($fields['DELIVERY_EXTRA_SERVICES']) && is_array($fields['DELIVERY_EXTRA_SERVICES']))
445 {
446 $shipment->setExtraServices($fields['DELIVERY_EXTRA_SERVICES']);
447 }
448
449 if (isset($fields['STORE_ID']) && intval($fields['STORE_ID']) > 0)
450 {
451 $shipment->setStoreId($fields['STORE_ID']);
452 }
453
454 if ($shipment !== null)
455 {
456 DiscountCompatibility::setShipment($order->getId(), $shipment->getId());
457 }
458
459 static::fillOrderFieldsFromEntity($order, $shipment, $fields, static::getShipmentFieldsToConvert());
460 }
461 }
462 }
463
464 if ($basket = $order->getBasket())
465 {
467 $basketCompatibilityClassName = static::getBasketCompatibilityClassName();
468
470 $r = $basketCompatibilityClassName::syncShipmentCollectionAndBasket($shipmentCollection, $basket);
471 if (!$r->isSuccess())
472 {
473 $result->addErrors($r->getErrors());
474 return $result;
475 }
476
477 }
478
480 $r = static::syncShipmentCollectionFromRequest($shipmentCollection, $fields);
481 if (!$r->isSuccess())
482 {
483 $result->addErrors($r->getErrors());
484 return $result;
485 }
486 if ($basket)
487 {
489 foreach ($shipmentCollection as $shipment)
490 {
491 if ($shipment->isSystem())
492 continue;
493
495 if (!$shipmentItemCollection = $shipment->getShipmentItemCollection())
496 {
497 throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
498 }
499
500 if (!empty($fields['BARCODE_LIST']) && is_array($fields['BARCODE_LIST']))
501 {
503 $r = static::fillShipmentItemCollectionFromRequest($shipmentItemCollection, $fields['BARCODE_LIST'], $basket);
504 if (!$r->isSuccess())
505 {
506 $result->addErrors($r->getErrors());
507 return $result;
508 }
509 }
510
511 }
512 }
513 return $result;
514 }
515
522 private static function fillOrderFieldsFromEntity(Sale\Order $order, Sale\Internals\CollectableEntity $entity, array $requestFields, array $allowFields)
523 {
524 $dateFields = static::getEntityDateFields($entity);
525 foreach ($allowFields as $checkField)
526 {
527 $checkOrderField = $order->getField($checkField);
528
529 $isDate = false;
530
531 if (array_key_exists($checkField, $dateFields))
532 {
533 $isDate = true;
534 $checkOrderField = static::convertDateFieldToOldFormat($order->getField($checkField));
535 }
536
537 if (!empty($requestFields[$checkField]) && $checkOrderField != trim($requestFields[$checkField]))
538 {
539 $setValue = $entity->getField($checkField);
540 if ($isDate)
541 {
542 $setValue = static::convertDateField($checkField, $requestFields[$checkField], static::getEntityDateFields($entity));
543 }
544
545 if (in_array($checkField, static::getAvailableFields()))
546 {
547 $order->setFieldNoDemand($checkField, $setValue);
548 }
549 }
550 }
551 }
552
560 public static function createShipmentFromRequest(Sale\ShipmentCollection $shipmentCollection, $deliveryId, array $requestFields)
561 {
562
563 $shipment = null;
564
565 if (intval($deliveryId) > 0 && $service = Sale\Delivery\Services\Manager::getObjectById($deliveryId))
566 {
567
568 $shipment = $shipmentCollection->createItem($service);
569
570 if ($service->isProfile())
571 $serviceName = $service->getNameWithParent();
572 else
573 $serviceName = $service->getName();
574 $shipment->setField('DELIVERY_NAME', $serviceName);
575
576
577 if (isset($requestFields['DELIVERY_PRICE']) && floatval($requestFields['DELIVERY_PRICE']) > 0)
578 {
579 $basePriceDelivery = $requestFields['DELIVERY_PRICE'];
580 $priceDelivery = $requestFields['PRICE_DELIVERY'];
581
582 if (!empty($requestFields['PRICE_DELIVERY_DIFF']))
583 {
584 $basePriceDelivery = $priceDelivery + floatval($requestFields['PRICE_DELIVERY_DIFF']);
585 }
586
587 $shipment->setFieldNoDemand('BASE_PRICE_DELIVERY', $basePriceDelivery);
588 $shipment->setFieldNoDemand('CURRENCY', $requestFields['CURRENCY']);
589
590 $shipment->setFieldNoDemand('PRICE_DELIVERY', $priceDelivery);
591
592 if (isset($requestFields['PRICE_DELIVERY']) && $requestFields['PRICE_DELIVERY'] < $requestFields['DELIVERY_PRICE'])
593 $shipment->setFieldNoDemand('PRICE_DELIVERY', $requestFields['PRICE_DELIVERY']);
594 }
595 elseif (array_key_exists("PRICE_DELIVERY", $requestFields) && floatval($requestFields['PRICE_DELIVERY']) >= 0)
596 {
597 $shipment->setFieldNoDemand('PRICE_DELIVERY', floatval($requestFields['PRICE_DELIVERY']));
598 $shipment->setFieldNoDemand('BASE_PRICE_DELIVERY', floatval($requestFields['PRICE_DELIVERY']));
599 $shipment->setFieldNoDemand('CURRENCY', $requestFields['CURRENCY']);
600 $shipment->setFieldNoDemand('CUSTOM_PRICE_DELIVERY', "Y");
601 }
602 }
603
604 return $shipment;
605 }
606
618 public static function syncShipmentCollectionFromRequest(Sale\ShipmentCollection $shipmentCollection, array $fields)
619 {
620 $result = new Sale\Result();
621
622 $countShipments = count($shipmentCollection);
623 $baseShipment = null;
624
625 if ($countShipments <= 2 && $shipmentCollection->isExistsSystemShipment())
626 {
628 foreach ($shipmentCollection as $shipment)
629 {
630 if ($shipment->isSystem())
631 continue;
632
633 $baseShipment = $shipment;
634 }
635 }
636 else
637 {
638 return $result;
639 }
640
642 if (!$order = $shipmentCollection->getOrder())
643 {
644 throw new Main\ObjectNotFoundException('Entity "Order" not found');
645 }
646
647
648 if ($baseShipment === null)
649 {
650 return $result;
651 }
652
653 if (isset($fields['ALLOW_DELIVERY']) && strval($fields['ALLOW_DELIVERY']) != '')
654 {
655 if ($baseShipment->getField('ALLOW_DELIVERY') != $fields['ALLOW_DELIVERY'])
656 {
657 if ($fields['ALLOW_DELIVERY'] == "Y")
658 {
660 $r = $baseShipment->allowDelivery();
661 }
662 else
663 {
665 $r = $baseShipment->disallowDelivery();
666 }
667
668 if ($r->isSuccess())
669 {
670 $order->setFieldNoDemand('ALLOW_DELIVERY', $fields['ALLOW_DELIVERY']);
671 }
672 else
673 {
674 $result->addErrors($r->getErrors());
675 }
676 }
677 }
678
679
680 if (isset($fields['DEDUCTED']) && strval($fields['DEDUCTED']) != '')
681 {
682 if ($baseShipment->getField('DEDUCTED') != $fields['DEDUCTED'])
683 {
684 if ($fields['DEDUCTED'] == "Y")
685 {
687 $r = $baseShipment->tryShip();
688 }
689 else
690 {
692 $r = $baseShipment->tryUnship();
693 }
694
695 if ($r->isSuccess())
696 {
697 $order->setFieldNoDemand('DEDUCTED', $fields['DEDUCTED']);
698 }
699 else
700 {
701 $result->addErrors($r->getErrors());
702 }
703 }
704 }
705
706 return $result;
707 }
717 public function fillPaymentCollectionFromRequest(array $fields)
718 {
720 if (!$order = $this->getOrder())
721 {
722 throw new Main\ObjectNotFoundException('Entity "Order" not found');
723 }
724
726 if (!$paymentCollection = $order->getPaymentCollection())
727 {
728 throw new Main\ObjectNotFoundException('Entity "PaymentCollection" not found');
729 }
730
731 $result = new Sale\Result();
732 $sum = floatval($fields['PRICE']);
733
734 if (isset($fields['SUM_PAID'])
735 && floatval($fields['SUM_PAID']) >= floatval($fields['PRICE']))
736 {
737 $sum = floatval($fields['SUM_PAID']);
738 }
739
740 $isPayFromUserBudget = null;
741 $backToUserBudget = null;
742
743 if (array_key_exists('ONLY_FULL_PAY_FROM_ACCOUNT', $fields))
744 {
745 $isPayFromUserBudget = $fields['ONLY_FULL_PAY_FROM_ACCOUNT'];
746 }
747
748 if ($isPayFromUserBudget === null && array_key_exists('PAY_CURRENT_ACCOUNT', $fields) && $fields['PAY_CURRENT_ACCOUNT'] !== null)
749 {
750 $isPayFromUserBudget = ($fields['PAY_CURRENT_ACCOUNT'] != "Y");
751 }
752
753 if (array_key_exists('PAY_FROM_ACCOUNT_BACK', $fields))
754 {
755 $backToUserBudget = ($fields['PAY_FROM_ACCOUNT_BACK'] == "Y");
756 }
757
758 $paySystemId = null;
759 $paySystemName = null;
760
761 $userId = $order->getUserId();
762 $currency = $order->getCurrency();
763
764 $rawFields = array();
765 $paymentInner = null;
766 $paymentOuter = null;
767 $countPayments = count($paymentCollection);
768
769 $orderPaid = false;
770
771 if ((($countPayments == 0 && $order->getId() == 0)
772 || ($countPayments == 2 && $paymentCollection->isExistsInnerPayment())
773 || ($countPayments == 1 && !$paymentCollection->isExistsInnerPayment())))
774 {
775
776 $needSum = $order->getPrice() - $order->getSumPaid();
777
778 if ($countPayments <= 1)
779 {
780
781 if ($order->getId() == 0)
782 {
783 if (!isset($fields["PAY_SYSTEM_ID"]))
784 $fields["PAY_SYSTEM_ID"] = static::getDefaultPaySystemId($order->getPersonTypeId());
785
786
788 if ($service = Sale\PaySystem\Manager::getObjectById($fields["PAY_SYSTEM_ID"]))
789 {
791 $paymentOuter = $paymentCollection->createItem($service);
792 $paymentOuter->setField('DATE_BILL', new Main\Type\DateTime());
793 $paymentOuter->setField('SUM', $needSum);
794 $paymentOuter->setField('PAY_SYSTEM_NAME', $service->getField('NAME'));
795 $order->setFieldNoDemand('PAY_SYSTEM_ID', $fields["PAY_SYSTEM_ID"]);
796 $countPayments = 1;
797 }
798 }
799 else
800 {
801 $paymentOuter = null;
802
804 foreach ($paymentCollection as $payment)
805 {
806 if ($payment->isInner())
807 continue;
808
809 $paymentOuter = $payment;
810 }
811
812 if ($paymentOuter !== null
813 && ($paymentOuter->getPaymentSystemId() != intval($fields["PAY_SYSTEM_ID"]))
814 )
815 {
817 if ($service = Sale\PaySystem\Manager::getObjectById($fields["PAY_SYSTEM_ID"]))
818 {
820 $paymentOuter->setField('PAY_SYSTEM_NAME', $service->getField('NAME'));
821 $paymentOuter->setField('PAY_SYSTEM_ID', intval($fields["PAY_SYSTEM_ID"]));
822 $order->setFieldNoDemand('PAY_SYSTEM_ID', intval($fields["PAY_SYSTEM_ID"]));
823 }
824 }
825
826 }
827
828
829 }
830
831 if (isset($fields['PAYED']))
832 {
833 $paidFlag = null;
834
835
836 if ($countPayments > 0)
837 {
839 foreach($paymentCollection as $payment)
840 {
841 if ($paidFlag === null && $payment->isPaid() && $needSum == 0)
842 {
843 $paidFlag = 'Y';
844 }
845
846 if ($payment->isInner())
847 continue;
848
849 $paymentOuter = $payment;
850 }
851 }
852
853 if ($paidFlag === null)
854 {
855 $paidFlag = 'N';
856 }
857
858
859 if ($paidFlag != $fields['PAYED'])
860 {
861 if ($fields['PAYED'] == "Y")
862 {
863 $pay = true;
864 $orderPaid = true;
865
866 if ($isPayFromUserBudget !== null)
867 {
868 if (static::canPayWithUserBudget($needSum, $userId, $currency, $isPayFromUserBudget))
869 {
870 $userBudget = Sale\Internals\UserBudgetPool::getUserBudget($userId, $currency);
871
872 if ($userBudget >= $needSum)
873 {
874 $pay = false;
875 }
876 }
877 }
878
880 $r = static::payFromBudget($order, $pay, $isPayFromUserBudget);
881 if ($r->isSuccess())
882 {
883 $needSum = $order->getPrice() - $order->getSumPaid();
884
885 if (!$pay)
886 {
888 $r = $paymentOuter->setField('SUM', $needSum);
889 }
890
891 if (!$r->isSuccess())
892 {
893 $result->addErrors($r->getErrors());
894 }
895 }
896 else
897 {
898 $result->addErrors($r->getErrors());
899 }
900 }
901 else
902 {
903 //
905 foreach($paymentCollection as $payment)
906 {
907 if ($payment->isPaid())
908 {
909 if ($backToUserBudget && $payment->isInner())
910 {
911 $payment->setReturn('Y');
912 }
913 else
914 {
915 $payment->setPaid('N');
916 }
917 }
918
919 if ($payment->isInner())
920 {
921 $payment->delete();
922 }
923 else
924 {
925 $payment->setField('SUM', $order->getPrice());
926 }
927 }
928
929
930 }
931
932 unset($fields['PAYED']);
933 }
934 elseif ($order->getId() == 0)
935 {
936 if ($isPayFromUserBudget !== null)
937 {
938 if (static::canPayWithUserBudget($needSum, $userId, $currency, $isPayFromUserBudget))
939 {
940 $userBudget = Sale\Internals\UserBudgetPool::getUserBudget($userId, $currency);
941
942 $setSum = $userBudget;
943
945 $r = static::payFromBudget($order, false);
946 if ($r->isSuccess())
947 {
948 $sum -= $setSum;
949 }
950 else
951 {
952 $result->addErrors($r->getErrors());
953 }
954 }
955 }
956 }
957
958 if ($order->getId() > 0)
959 {
960 $payment = null;
961
963 foreach($paymentCollection as $paymentItem)
964 {
965 if ($paymentItem->isInner())
966 {
967 $paymentInner = $paymentItem;
968 if ($payment === null && $paymentItem->isPaid())
969 {
970 $payment = $paymentItem;
971 }
972 }
973 else
974 {
975 $paymentOuter = $paymentItem;
976 if ($payment === null && $paymentItem->isPaid())
977 {
978 $payment = $paymentItem;
979 }
980 }
981 }
982
983 if ($payment === null)
984 {
985 if ($paymentOuter !== null)
986 $payment = $paymentOuter;
987 else
988 $payment = $paymentInner;
989 }
990
991 if ($payment === null)
992 {
993 return $result;
994 }
995
996 $paymentFields = static::convertDateFields($fields, static::getPaymentDateFields());
997
998
999 if (!empty($paymentFields['PAY_SYSTEM_ID']) && $paymentFields['PAY_SYSTEM_ID'] != $payment->getPaymentSystemId())
1000 {
1001 if ($payment->isInner())
1002 {
1003 unset($paymentFields['PAY_SYSTEM_ID']);
1004 }
1005 else
1006 {
1007 $paySystemId = (int)$paymentFields['PAY_SYSTEM_ID'];
1008
1010 if ($paysystem = Sale\PaySystem\Manager::getObjectById($paySystemId))
1011 {
1012 $paymentFields['PAY_SYSTEM_NAME'] = $paysystem->getField('NAME');
1013 }
1014 }
1015 }
1016
1017
1018 $paymentFields = static::replaceFields($paymentFields, static::getPaymentReplaceFields());
1019 $paymentFields = static::clearFields($paymentFields, static::getPaymentAvailableFields());
1020
1022 $r = $payment->setFields($paymentFields);
1023 if ($r->isSuccess())
1024 {
1025
1026 static::fillOrderFieldsFromEntity($order, $payment, $fields, static::getPaymentFieldsToConvert());
1027 }
1028 else
1029 {
1030 $result->addErrors($r->getErrors());
1031 }
1032
1033
1034 if ($result->isSuccess() && intval($paySystemId) > 0)
1035 {
1036 $order->setFieldNoDemand('PAY_SYSTEM_ID', $paySystemId);
1037 }
1038 }
1039 }
1040
1041 $paymentOuter = null;
1042 $calcSum = 0;
1044 foreach($paymentCollection as $payment)
1045 {
1046 $calcSum += $payment->getSum();
1047 if ($payment->isInner())
1048 continue;
1049
1050 $paymentOuter = $payment;
1051 }
1052
1053 if ($paymentOuter && !$paymentOuter->isPaid())
1054 {
1055 if ($order->getPrice() != $calcSum)
1056 {
1057 $paymentOuter->setField('SUM', $paymentOuter->getSum() + ($order->getPrice() - $calcSum));
1058 }
1059 }
1060
1061 if (!$paymentOuter)
1062 return $result;
1063
1064 $fieldsFromOrder = array(
1065 'PS_STATUS', 'PS_STATUS_CODE', 'PS_STATUS_DESCRIPTION',
1066 'PS_STATUS_MESSAGE', 'PS_SUM', 'PS_CURRENCY', 'PS_RESPONSE_DATE',
1067 'PAY_VOUCHER_NUM', 'PAY_VOUCHER_DATE', 'DATE_PAY_BEFORE',
1068 'DATE_BILL', 'PAY_SYSTEM_NAME', 'PAY_SYSTEM_ID',
1069 'DATE_PAYED', 'EMP_PAYED_ID', 'CURRENCY'
1070 );
1071
1072 foreach ($fieldsFromOrder as $fieldName)
1073 {
1074 if (isset($fields[$fieldName]))
1075 {
1076 switch ($fieldName)
1077 {
1078 case 'DATE_BILL':
1079 case 'DATE_PAY_BEFORE':
1080 case 'PS_RESPONSE_DATE':
1081 if (!isset($fields[$fieldName]) || strval($fields[$fieldName]) == '')
1082 continue 2;
1083 $value = new Main\Type\DateTime($fields[$fieldName]);
1084 break;
1085 case 'PAY_VOUCHER_DATE':
1086 if (!isset($fields[$fieldName]) || strval($fields[$fieldName]) == '')
1087 continue 2;
1088 $value = new Main\Type\Date($fields[$fieldName]);
1089 break;
1090 case 'DATE_PAYED':
1091 if (!isset($fields[$fieldName]) || strval($fields[$fieldName]) == '')
1092 continue 2;
1093 $fieldName = 'DATE_PAID';
1094 $value = new Main\Type\DateTime($fields['DATE_PAYED']);
1095 break;
1096 case 'EMP_PAYED_ID':
1097 $fieldName = 'EMP_PAID_ID';
1098 $value = $fields['EMP_PAYED_ID'];
1099 break;
1100 default:
1101 $value = $fields[$fieldName];
1102 break;
1103 }
1104 $paymentOuter->setFieldNoDemand($fieldName, $value);
1105 if ($fieldName === 'PAY_SYSTEM_ID')
1106 {
1107 $order->setFieldNoDemand('PAY_SYSTEM_ID', $value);
1108
1110 if ($paysystem = Sale\PaySystem\Manager::getObjectById($value))
1111 $paymentOuter->setFieldNoDemand('PAY_SYSTEM_NAME', $paysystem->getField('NAME'));
1112 }
1113
1114 if ($fieldName == "DATE_PAID")
1115 $fieldName = 'DATE_PAYED';
1116
1117 if (in_array($fieldName, $this->getAvailableFields()))
1118 {
1119 $order->setFieldNoDemand($fieldName, $value);
1120 };
1121 }
1122 elseif (isset($fields['~'.$fieldName]))
1123 {
1124 $rawFields['~'.$fieldName] = $fields['~'.$fieldName];
1125 }
1126 }
1127
1128 if (isset($fields['PAY_SYSTEM_PRICE']))
1129 $paymentOuter->setField('PRICE_COD', $fields['PAY_SYSTEM_PRICE']);
1130
1131 if (!empty($rawFields))
1132 {
1133 $this->parseRawFields(static::ENTITY_PAYMENT, $rawFields);
1134 }
1135 }
1136
1137
1138 if (array_key_exists('SUM_PAID', $fields))
1139 {
1140 if ($orderPaid)
1141 {
1142 if ($fields['SUM_PAID'] == 0)
1143 {
1144 $fields['SUM_PAID'] = $order->getPrice();
1145 }
1146 }
1147
1148 if ($fields['SUM_PAID'] >= 0)
1149 {
1150 $oldSumPaid = $order->getSumPaid();
1151
1152 $deltaSumPaid = floatval($fields['SUM_PAID']) - $oldSumPaid;
1153
1154 if ($deltaSumPaid > 0)
1155 {
1156 $paidPayment = false;
1157
1159 foreach ($paymentCollection as $payment)
1160 {
1161 if ($payment->isPaid() || $payment->isInner())
1162 continue;
1163
1164 if (Sale\PriceMaths::roundPrecision($payment->getSum()) === Sale\PriceMaths::roundPrecision($deltaSumPaid))
1165 {
1166 $paidPayment = true;
1168 $r = $payment->setPaid("Y");
1169 if (!$r->isSuccess())
1170 {
1171 $result->addErrors($r->getErrors());
1172 }
1173 break;
1174 }
1175 }
1176
1177 if (!$paidPayment)
1178 {
1179 $service = null;
1180 $paymentSystemId = null;
1181
1182 if (count($paymentCollection) > 0)
1183 {
1185 if ($firstPayment = $paymentCollection->rewind())
1186 {
1187 $paymentSystemId = $firstPayment->getPaymentSystemId();
1188 if ($paymentSystemId > 0)
1189 {
1190 $service = Sale\PaySystem\Manager::getObjectById($paymentSystemId);
1191 }
1192 }
1193 }
1194
1195 if (!$service)
1196 {
1197 $paymentSystemId = static::getDefaultPaySystemId($order->getPersonTypeId());
1198 $service = Sale\PaySystem\Manager::getObjectById($paymentSystemId);
1199 }
1200
1202 if ($service)
1203 {
1205 $payment = $paymentCollection->createItem($service);
1206 $payment->setField('DATE_BILL', new Main\Type\DateTime());
1207 $payment->setField('SUM', $deltaSumPaid);
1208 $payment->setField('PAY_SYSTEM_NAME', $service->getField('NAME'));
1209 $order->setFieldNoDemand('PAY_SYSTEM_ID', $paymentSystemId);
1210
1212 $r = $payment->setPaid("Y");
1213 if (!$r->isSuccess())
1214 {
1215 $result->addErrors($r->getErrors());
1216 }
1217 }
1218 }
1219 }
1220 }
1221 }
1222
1223 return $result;
1224 }
1225
1226 private static function getDefaultPaySystemId($personTypeId)
1227 {
1228 $personTypeId = intval($personTypeId);
1229
1230 static $defaultPaySystemId = array();
1231 if (isset($defaultPaySystemId[$personTypeId]))
1232 return $defaultPaySystemId[$personTypeId];
1233
1234 $defaultPaySystemId[$personTypeId] = intval(Main\Config\Option::get('sale', '1C_IMPORT_DEFAULT_PS', 0));
1235 if (isset($defaultPaySystemId[$personTypeId]) && ($defaultPaySystemId[$personTypeId] > 0))
1236 return $defaultPaySystemId[$personTypeId];
1237
1238 if ($personTypeId > 0)
1239 {
1240 $dbPaySystem = Sale\PaySystem\Manager::getList(
1241 array(
1242 'select' => array("ID"),
1243 'filter' => array(
1244 '=ACTIVE' => 'Y',
1245 '=PERSON_TYPE_ID' => $personTypeId,
1246 '=ENTITY_REGISTRY_TYPE' => static::getRegistryType()
1247 ),
1248 'order' => array('SORT'),
1249 'limit' => 1
1250 )
1251 );
1252 if ($paySystem = $dbPaySystem->fetch())
1253 $defaultPaySystemId[$personTypeId] = intval($paySystem['ID']);
1254
1255 if (isset($defaultPaySystemId[$personTypeId]) && ($defaultPaySystemId[$personTypeId] > 0))
1256 return $defaultPaySystemId[$personTypeId];
1257 }
1258
1259 $dbPaySystem = Sale\PaySystem\Manager::getList(
1260 array(
1261 'select' => array("ID"),
1262 'filter' => array(
1263 '=ACTIVE' => 'Y',
1264 '=ENTITY_REGISTRY_TYPE' => static::getRegistryType()
1265 ),
1266 'order' => array('SORT'),
1267 'limit' => 1
1268 )
1269 );
1270 if ($paySystem = $dbPaySystem->fetch())
1271 $defaultPaySystemId[$personTypeId] = intval($paySystem['ID']);
1272
1273 return $defaultPaySystemId[$personTypeId];
1274 }
1275
1283 public function fillTaxFromRequest(Sale\Tax $tax, array $fields)
1284 {
1285 if (!empty($fields['COUNT_DELIVERY_TAX']))
1286 {
1287 $tax->setDeliveryCalculate(($fields['COUNT_DELIVERY_TAX'] == "Y"));
1288 }
1289
1290 if (!empty($fields['TAX_LIST']) && is_array($fields['TAX_LIST']))
1291 {
1292 $tax->initTaxList($fields['TAX_LIST']);
1293 }
1294 elseif (!empty($tax->getTaxList()))
1295 {
1297 if ($order = $this->getOrder())
1298 {
1299 $order->refreshVat();
1300 if ($tax = $order->getTax())
1301 {
1302 $tax->resetTaxList();
1303 }
1304 }
1305 }
1306
1307 if (array_key_exists('TAX_VALUE', $fields))
1308 {
1309 $order = $this->getOrder();
1310 $order->setFieldNoDemand('TAX_VALUE', floatval($fields['TAX_VALUE']));
1311 }
1312
1313 return new Sale\Result();
1314 }
1315
1325 public static function shipment($id, $value, array $storeData = array() )
1326 {
1327 global $USER;
1328
1329 $result = new Sale\Result();
1330
1331 $registry = Sale\Registry::getInstance(static::getRegistryType());
1332
1334 $orderClassName = $registry->getOrderClassName();
1335 if ($order = $orderClassName::load($id))
1336 {
1338 if (!$basket = $order->getBasket())
1339 {
1340 throw new Main\ObjectNotFoundException('Entity "Basket" not found');
1341 }
1342
1344 if(!$shipmentCollection = $order->getShipmentCollection())
1345 {
1346 throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
1347 }
1348
1350 foreach ($shipmentCollection as $shipment)
1351 {
1352 if ($shipment->isSystem())
1353 continue;
1354
1356 if (!$shipmentItemCollection = $shipment->getShipmentItemCollection())
1357 {
1358 throw new Main\ObjectNotFoundException('Entity "ShipmentItemCollection" not found');
1359 }
1360
1362 $r = static::fillShipmentItemCollectionFromRequest($shipmentItemCollection, $storeData, $basket);
1363 if (!$r->isSuccess())
1364 {
1365 $result->addErrors($r->getErrors());
1366 return $result;
1367 }
1368
1370 $r = $shipment->setField('DEDUCTED', $value === true ? 'Y' : 'N');
1371 if (!$r->isSuccess())
1372 {
1373 $result->addErrors($r->getErrors());
1374 continue;
1375 }
1376 }
1377 }
1378
1379
1381 $r = $order->save();
1382 if (!$r->isSuccess())
1383 {
1384 $result->addErrors($r->getErrors());
1385 }
1386
1387 return $result;
1388 }
1389
1400 public static function fillShipmentItemCollectionFromRequest(Sale\ShipmentItemCollection $shipmentItemCollection, array $storeData, Sale\Basket $basket = null)
1401 {
1402 $result = new Sale\Result();
1403
1404
1405 if ($basket === null)
1406 {
1407
1409 if (!$shipment = $shipmentItemCollection->getShipment())
1410 {
1411 throw new Main\ObjectNotFoundException('Entity "Shipment" not found');
1412 }
1413
1414
1416 if(!$shipmentCollection = $shipment->getCollection())
1417 {
1418 throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
1419 }
1420
1422 if (!$order = $shipmentCollection->getOrder())
1423 {
1424 throw new Main\ObjectNotFoundException('Entity "Order" not found');
1425 }
1426
1428 if (!$basket = $order->getBasket())
1429 {
1430 throw new Main\ObjectNotFoundException('Entity "Basket" not found');
1431 }
1432 }
1433
1435 foreach ($shipmentItemCollection as $shipmentItem)
1436 {
1438 if (($basketItem = $shipmentItem->getBasketItem()) && $basketItem->getId() == 0)
1439 {
1440 continue;
1441 }
1443 $shipmentItemStoreCollection = $shipmentItem->getShipmentItemStoreCollection();
1444 if (
1445 !$shipmentItemStoreCollection
1446 && $basketItem->isReservableItem()
1447 )
1448 {
1449 throw new Main\ObjectNotFoundException('Entity "ShipmentItemStoreCollection" not found');
1450 }
1451
1452 $barcodeList = array();
1454 foreach ($shipmentItemStoreCollection as $shipmentItemStore)
1455 {
1456 $storeId = $shipmentItemStore->getField('STORE_ID');
1457 $basketId = $shipmentItemStore->getField('BASKET_ID');
1458 $barcodeList[$basketId][$storeId][] = array(
1459 'ID' => $shipmentItemStore->getId(),
1460 'QUANTITY' => $shipmentItemStore->getQuantity(),
1461 'BARCODE' => $shipmentItemStore->getBarcode(),
1462 );
1463 }
1464
1465 $baseBarcode = null;
1466
1467 foreach($storeData as $basketId => $barcodeDataList)
1468 {
1469 if ((intval($basketId) != $basketId)
1470 || ($basketItem->getId() != $basketId))
1471 continue;
1472
1473 foreach ($barcodeDataList as $barcodeData)
1474 {
1475
1477 if (!$basketItem = $basket->getItemById($basketId))
1478 {
1479 throw new Main\ObjectNotFoundException('Entity "BasketItem" not found');
1480 }
1481
1482
1483 $saveBarcodeList = array();
1484
1485 if ($basketItem->isBarcodeMulti() && is_array($barcodeData['BARCODE']))
1486 {
1487 $barcodeQuantity = $barcodeData['QUANTITY'] / count($barcodeData['BARCODE']);
1488
1489 foreach ($barcodeData['BARCODE'] as $barcodeId => $barcodeValue)
1490 {
1491 $barcodeFields = array(
1492 'QUANTITY' => $barcodeQuantity,
1493 'BARCODE' => $barcodeValue,
1494 );
1495
1496 if (intval($barcodeId) > 0)
1497 {
1498 $barcodeFields['ID'] = intval($barcodeId);
1499 }
1500
1501 $saveBarcodeList[] = $barcodeFields;
1502 }
1503 }
1504 else
1505 {
1506 if (strval($barcodeData['BARCODE']) != '')
1507 {
1508 $baseBarcode = trim($barcodeData['BARCODE']);
1509 }
1510 elseif (!empty($baseBarcode))
1511 {
1512 $barcodeData['BARCODE'] = $baseBarcode;
1513 }
1514
1515 $barcodeFields = array(
1516 'QUANTITY' => $barcodeData['QUANTITY'],
1517 'BARCODE' => $barcodeData['BARCODE'],
1518 );
1519
1520 if (!empty($barcodeList[$basketId]) && !empty($barcodeList[$basketId][$barcodeData['STORE_ID']]))
1521 {
1522
1523 foreach ($barcodeList[$basketId][$barcodeData['STORE_ID']] as $existBarcodeData)
1524 {
1525 if ($existBarcodeData['BARCODE'] == $barcodeData['BARCODE'] && !empty($existBarcodeData['ID']))
1526 {
1527 if ($shipmentItemStoreCollection->getItemById($existBarcodeData['ID']))
1528 {
1529 $barcodeFields['ID'] = $existBarcodeData['ID'];
1530 }
1531 }
1532 }
1533 }
1534
1535 $saveBarcodeList = array(
1536 $barcodeFields
1537 );
1538 }
1539
1540 foreach ($saveBarcodeList as $saveBarcodeData)
1541 {
1542 $barcodeFields = array(
1543 'QUANTITY' => $saveBarcodeData['QUANTITY'],
1544 'BARCODE' => $saveBarcodeData['BARCODE'],
1545 );
1546
1548 $shipmentItemStore = $shipmentItemStoreCollection->getItemByBarcode($saveBarcodeData['BARCODE']);
1549
1550 if (!$shipmentItemStore)
1551 {
1552 $barcodeFields['STORE_ID'] = intval($barcodeData['STORE_ID']);
1553 $shipmentItemStore = $shipmentItemStoreCollection->createItem($basketItem);
1554 }
1555
1557 $r = $shipmentItemStore->setFields($barcodeFields);
1558 if (!$r->isSuccess())
1559 {
1560 $result->addErrors($r->getErrors());
1561 }
1562 }
1563 }
1564 }
1565 }
1566
1567 return $result;
1568 }
1569
1578 public static function allowDelivery($id, $value)
1579 {
1580 $result = new Sale\Result();
1581
1582 $registry = Sale\Registry::getInstance(static::getRegistryType());
1583
1585 $orderClassName = $registry->getOrderClassName();
1586 if ($order = $orderClassName::load($id))
1587 {
1589 if(!$shipmentCollection = $order->getShipmentCollection())
1590 {
1591 throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
1592 }
1593
1595 foreach ($shipmentCollection as $shipment)
1596 {
1597 if ($shipment->isSystem())
1598 continue;
1599
1601 $r = $shipment->setField('ALLOW_DELIVERY', $value === true ? 'Y' : 'N');
1602 if (!$r->isSuccess())
1603 {
1604 $result->addErrors($r->getErrors());
1605 return $result;
1606 }
1607 }
1608 }
1609
1610
1612 $r = $order->save();
1613 if (!$r->isSuccess())
1614 {
1615 $result->addErrors($r->getErrors());
1616 }
1617
1618 return $result;
1619 }
1620
1626 public static function add(array $fields)
1627 {
1628 return static::modifyOrder(static::ORDER_COMPAT_ACTION_ADD, $fields);
1629 }
1630
1638 public static function update($id, array $fields, $dateUpdate = false)
1639 {
1640 $result = new Sale\Result();
1641
1642 $id = (int)$id;
1643
1644 if ($id <= 0)
1645 {
1646 $result->addError(new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_ID_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_ID_NOT_FOUND'));
1647 return $result;
1648 }
1649
1650 $fields['ID'] = $id;
1651
1652 if (!$dateUpdate)
1653 {
1654 $fields['DATE_UPDATE'] = null;
1655 }
1656
1658 return static::modifyOrder(static::ORDER_COMPAT_ACTION_UPDATE, $fields);
1659 }
1660
1670 public static function modifyOrder($action, array $fields)
1671 {
1672 $result = new Sale\Result();
1673
1674 try
1675 {
1676 $adminSection = (defined('ADMIN_SECTION') && ADMIN_SECTION === true);
1677
1679 $orderCompatibility = static::create($fields);
1680
1682 $order = $orderCompatibility->getOrder();
1683
1685 $propCollection = $order->getPropertyCollection();
1686
1687 if (!empty($fields['ORDER_PROP']) && is_array($fields['ORDER_PROP']))
1688 {
1689 $fields['PROPERTIES'] = $fields['ORDER_PROP'];
1690 }
1691
1692 if (!isset($fields['PROPERTIES']) || !is_array($fields['PROPERTIES']))
1693 {
1694 $fields['PROPERTIES'] = array();
1695 }
1696
1697 // compatibility to prevent setting default values for empty properties
1699 foreach ($propCollection as $propertyValue)
1700 {
1701 $propertyFields = $propertyValue->getProperty();
1702 $key = isset($propertyFields['ID']) ? $propertyFields['ID'] : 'n'.$propertyValue->getId();
1703
1704 if ($propertyValue->getId() <=0
1705 && !array_key_exists($key, $fields['PROPERTIES'])
1706 )
1707 {
1708 $propertyValue->delete();
1709 }
1710 }
1711
1713 $r = $propCollection->setValuesFromPost($fields, $_FILES);
1714 if (!$r->isSuccess())
1715 {
1716 $result->addErrors($r->getErrors());
1717 return $result;
1718 }
1719
1720
1721 $oldPrice = $order->getPrice();
1722
1723// $isStartField = $order->isStartField();
1724
1725
1727 $basket = $order->getBasket();
1728
1729 if (!$basket && $action == static::ORDER_COMPAT_ACTION_SAVE)
1730 {
1731 $fUserId = null;
1732
1733
1734 if (!empty($fields['BASKET_ITEMS']) && is_array($fields['BASKET_ITEMS']))
1735 {
1736 foreach ($fields['BASKET_ITEMS'] as $basketItemData)
1737 {
1738 if (!empty($basketItemData['FUSER_ID']) && intval($basketItemData['FUSER_ID']) > 0)
1739 {
1740 $fUserId = intval($basketItemData['FUSER_ID']);
1741 break;
1742 }
1743 }
1744 }
1745
1746
1747 if (intval($fUserId) <= 0 && !$adminSection)
1748 {
1749 $fUserId = static::getDefaultFuserId();
1750 }
1751
1752 $userId = $order->getUserId();
1753 if ($userId > 0)
1754 {
1755 $fUserIdByUserId = Sale\Fuser::getIdByUserId($userId);
1756 if (intval($fUserId) > 0 && intval($fUserIdByUserId) > 0
1757 && intval($fUserId) != intval($fUserIdByUserId))
1758 {
1759 // TODO: ... [SALE_BASKET_001] - the call of old method of the basket
1760 \CSaleBasket::TransferBasket($fUserId, $fUserIdByUserId);
1761 }
1762
1763 $fUserId = $fUserIdByUserId;
1764 }
1765
1766 if (intval($fUserId) <= 0)
1767 {
1768 $result->addError(new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_FUSERID_NOT_FOUND'), "SALE_COMPATIBLE_ORDER_FUSERID_NOT_FOUND"));
1769 return $result;
1770 }
1771
1772
1773 $registry = Sale\Registry::getInstance(static::getRegistryType());
1775 $basketClassName = $registry->getBasketClassName();
1776
1777 if (!$adminSection)
1778 {
1779 $siteId = !empty($fields["SITE_ID"]) ? $fields["SITE_ID"] : (!empty($fields["LID"]) ? $fields['LID']: null);
1780 $allBasket = $basketClassName::loadItemsForFUser($fUserId, $siteId);
1781
1782 if ($allBasket)
1783 {
1784 $basket = $allBasket->getOrderableItems();
1785 }
1786 }
1787
1788
1789 if (!$basket)
1790 {
1791 $basket = $basketClassName::create($order->getSiteId());
1792 $basket->setFUserId($fUserId);
1793 }
1794 }
1795
1796 $isStartField = $order->isStartField(true);
1797
1798
1799 if ($basket)
1800 {
1802 $basketCompatibilityClassName = static::getBasketCompatibilityClassName();
1803 $basketCompatibility = $basketCompatibilityClassName::create($orderCompatibility);
1804
1806 $r = $basketCompatibility->fillBasket($basket, $fields);
1807 if (!$r->isSuccess())
1808 {
1809 $result->addErrors($r->getErrors());
1810 return $result;
1811 }
1812
1813 if ($action == static::ORDER_COMPAT_ACTION_SAVE && $order->getId() == 0 && count($basket) > 0)
1814 {
1815 $order->setMathActionOnly(true);
1816 $order->setBasket($basket);
1817 $order->setMathActionOnly(false);
1818 }
1819
1820 if ($orderCompatibility->isExistPrice() && $oldPrice == $order->getPrice())
1821 {
1822 $order->setFieldNoDemand('PRICE', $orderCompatibility->externalPrice);
1823 }
1824
1825 }
1826
1828 $r = $orderCompatibility->fillTaxFromRequest($order->getTax(), $fields);
1829 if (!$r->isSuccess())
1830 {
1831 $result->addErrors($r->getErrors());
1832 return $result;
1833 }
1834
1836 $r = $orderCompatibility->fillShipmentCollectionFromRequest( $order->getShipmentCollection(), $fields);
1837 if (!$r->isSuccess())
1838 {
1839 $result->addErrors($r->getErrors());
1840 return $result;
1841 }
1842
1843 if ($isStartField)
1844 {
1845 $hasMeaningfulFields = $order->hasMeaningfulField();
1846
1848 $r = $order->doFinalAction($hasMeaningfulFields);
1849 if (!$r->isSuccess())
1850 {
1851 $result->addErrors($r->getErrors());
1852 return $result;
1853 }
1854 }
1855
1856 $order->setMathActionOnly(false);
1857
1859 $r = $orderCompatibility->fillPaymentCollectionFromRequest($fields);
1860 if (!$r->isSuccess())
1861 {
1862 $result->addErrors($r->getErrors());
1863 return $result;
1864 }
1865
1867 $r = static::fillOrderFromRequest($order, $fields);
1868 if (!$r->isSuccess())
1869 {
1870 $result->addErrors($r->getErrors());
1871 return $result;
1872 }
1873
1874 }
1875 catch(Sale\UserMessageException $e)
1876 {
1877 $result->addError(new Sale\ResultError($e->getMessage(), $e->getCode()));
1878 return $result;
1879 }
1880
1881 static::transformationLocation($order);
1882
1884 $r = $order->save();
1885 if ($r->isSuccess())
1886 {
1887 if ($orderData = $r->getData())
1888 $result->setData($orderData);
1889
1890 if ($orderId = $r->getId())
1891 $result->setId($orderId);
1892
1894 $r = $orderCompatibility->saveRawFields($order, static::ENTITY_ORDER);
1895 }
1896
1897 if (!$r->isSuccess())
1898 {
1899 $result->addErrors($r->getErrors());
1900 }
1901 else
1902 {
1903 $oldFields = static::convertDateFieldsToOldFormat($order->getFieldValues());
1904 $oldFields = $oldFields + $orderCompatibility->rawFields;
1905
1907 if ($paymentCollection = $order->getPaymentCollection())
1908 {
1910 foreach ($paymentCollection as $payment)
1911 {
1912 if ($payment->getId() <= 0)
1913 {
1914 continue;
1915 }
1916
1918 $r = $orderCompatibility->saveRawFields($payment, static::ENTITY_PAYMENT);
1919 if (!$r->isSuccess())
1920 {
1921 $result->addErrors($r->getErrors());
1922 }
1923 }
1924 }
1925
1926 $result->setData(array(
1927 'OLD_FIELDS' => $oldFields
1928 ));
1929 }
1930
1931 return $result;
1932 }
1933
1941 public static function reserve($orderId, $value)
1942 {
1943 $result = new Sale\Result();
1944
1945 $registry = Sale\Registry::getInstance(static::getRegistryType());
1946
1948 $orderClassName = $registry->getOrderClassName();
1949 if (!$order = $orderClassName::load($orderId))
1950 {
1951 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_NOT_FOUND') );
1952 return $result;
1953 }
1954
1956 if (!$shipmentCollection = $order->getShipmentCollection())
1957 {
1958 throw new Main\ObjectNotFoundException('Entity "ShipmentCollection" not found');
1959 }
1960
1962 foreach ($shipmentCollection as $shipment)
1963 {
1964 if ($shipment->isSystem())
1965 continue;
1966
1967 if ($value == "Y")
1968 {
1970 $r = $shipment->tryReserve();
1971 if (!$r->isSuccess())
1972 {
1973 $registry = Sale\Registry::getInstance(static::getRegistryType());
1974
1976 $entityMarkerClassName = $registry->getEntityMarkerClassName();
1977 $entityMarkerClassName::addMarker($order, $shipment, $r);
1978 if (!$shipment->isSystem())
1979 {
1980 $shipment->setField('MARKED', 'Y');
1981 }
1982
1983 $result->addErrors($r->getErrors());
1984 }
1985 }
1986 else
1987 {
1988 if (!$shipment->isShipped())
1989 {
1991 $r = $shipment->tryUnreserve();
1992 if (!$r->isSuccess())
1993 {
1994 $registry = Sale\Registry::getInstance(static::getRegistryType());
1995
1997 $entityMarkerClassName = $registry->getEntityMarkerClassName();
1998 $entityMarkerClassName::addMarker($order, $shipment, $r);
1999 if (!$shipment->isSystem())
2000 {
2001 $shipment->setField('MARKED', 'Y');
2002 }
2003 $result->addErrors($r->getErrors());
2004 }
2005 }
2006 }
2007 }
2008
2010 $r = $order->save();
2011 if (!$r->isSuccess())
2012 {
2013 $result->addErrors($r->getErrors());
2014 }
2015
2016 return $result;
2017 }
2018
2028 public static function pay($orderId, array $values, $withdraw = false, $pay = false)
2029 {
2030 $result = new Sale\Result();
2031
2032 $paid = null;
2033 if (isset($values['PAYED']) && strval($values['PAYED']) != '')
2034 {
2035 $values['PAID'] = $values['PAYED'];
2036 }
2037
2038 if (intval($orderId) <= 0)
2039 {
2040 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_ID_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_ID_NOT_FOUND') );
2041 return $result;
2042 }
2043
2044 $registry = Sale\Registry::getInstance(static::getRegistryType());
2046 $orderClassName = $registry->getOrderClassName();
2047 if (!$order = $orderClassName::load($orderId))
2048 {
2049 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_NOT_FOUND') );
2050 return $result;
2051 }
2052
2053 if ($order->isCanceled())
2054 {
2056 $r = $order->setField('CANCELED', 'N');
2057 if (!$r->isSuccess())
2058 {
2059 $result->addErrors($r->getErrors());
2060 return $result;
2061 }
2062 }
2063
2065 if (!$paymentCollection = $order->getPaymentCollection())
2066 {
2067 throw new Main\ObjectNotFoundException('Entity "PaymentCollection" not found');
2068 }
2069
2070 $paidFormUserBudget = false;
2071
2072 if ($withdraw)
2073 {
2075 $r = static::payFromBudget($order, $pay);
2076 if (!$r->isSuccess())
2077 {
2078 $result->addErrors($r->getErrors());
2079 }
2080 else
2081 {
2082 $payBudgetData = $r->getData();
2083 if (array_key_exists('PAID_FROM_BUDGET', $payBudgetData))
2084 {
2085 $paidFormUserBudget = $payBudgetData['PAID_FROM_BUDGET'];
2086 }
2087 }
2088
2089 }
2090
2091
2092 if (!$paidFormUserBudget)
2093 {
2095 foreach ($paymentCollection as $payment)
2096 {
2097 if (empty($fields))
2098 {
2099 if (isset($values['=DATE_PAYED']))
2100 {
2101 $values['DATE_PAID'] = $values['=DATE_PAYED'];
2102 unset($values['=DATE_PAYED']);
2103 }
2104
2105 $values = static::convertDateFields($values, static::getPaymentDateFields());
2106 $fields = static::clearFields($values, $payment->getAvailableFields());
2107
2108 }
2109
2110 if ($values['PAID'] == "N" && !$payment->isPaid())
2111 continue;
2112
2113 if ($withdraw && $values['PAID'] == "N" && $payment->isInner())
2114 {
2116 $r = $payment->setReturn('Y');
2117 if (!$r->isSuccess())
2118 {
2119 $result->addErrors($r->getErrors());
2120 }
2121 }
2122 else
2123 {
2124 $oldPaid = $payment->isPaid();
2126 $r = $payment->setPaid($values['PAID']);
2127 if (!$r->isSuccess())
2128 {
2129 $result->addErrors($r->getErrors());
2130 }
2131
2132 if ($payment->isInner() && !$oldPaid && $payment->isPaid())
2133 {
2134 Sale\Internals\UserBudgetPool::addPoolItem($order, ( $payment->getSum() * -1 ), Sale\Internals\UserBudgetPool::BUDGET_TYPE_ORDER_UNPAY, $payment);
2135 if (!$r->isSuccess())
2136 {
2137 $result->addErrors($r->getErrors());
2138 }
2139 }
2140
2141 }
2142
2143 if (isset($fields['PAID']))
2144 {
2145 unset($fields['PAID']);
2146 }
2147
2148 $r = $payment->setFields($fields);
2149 if (!$r->isSuccess())
2150 {
2151 $result->addErrors($r->getErrors());
2152 }
2153 }
2154 }
2155
2156 if (!$result->isSuccess())
2157 {
2158 return $result;
2159 }
2160
2162 $r = $order->save();
2163 if (!$r->isSuccess())
2164 {
2165 $result->addErrors($r->getErrors());
2166 }
2167 return $result;
2168 }
2169
2181 public static function payFromBudget(Sale\Order $order, $pay, $paidFormUserBudget = null)
2182 {
2183 $result = new Sale\Result();
2184
2186 $paymentInner = null;
2187
2189 $paymentOuter = null;
2190
2192 if (!$paymentCollection = $order->getPaymentCollection())
2193 {
2194 throw new Main\ObjectNotFoundException('Entity "PaymentCollection" not found');
2195 }
2196
2197 if (count($paymentCollection) > 2)
2198 return $result;
2199
2200 $needSum = $order->getPrice() - $order->getSumPaid();
2201
2202 if ($needSum > 0)
2203 {
2204
2206 foreach ($paymentCollection as $payment)
2207 {
2208 if (!$payment->isInner())
2209 {
2210 $paymentOuter = $payment;
2211 break;
2212 }
2213 }
2214
2215 if (!$pay || ($pay && $paidFormUserBudget === false))
2216 {
2218 $paymentInner = $paymentCollection->getInnerPayment();
2219 if (!$paymentInner)
2220 {
2221 $paymentInner = $paymentCollection->createInnerPayment();
2222 }
2223
2224 if (!$paymentInner)
2225 {
2226 throw new Main\ObjectNotFoundException('Entity inner "Payment" not found');
2227 }
2228
2229 $userBudget = Sale\Internals\UserBudgetPool::getUserBudget($order->getUserId(), $order->getCurrency());
2230
2231 $setSum = $userBudget;
2232 if ($userBudget >= $needSum)
2233 {
2234 $setSum = $needSum;
2235 }
2236
2237 if ($paymentInner->getId() == 0)
2238 {
2239 $paymentInnerFields = array(
2240 'SUM' => $setSum,
2241 'CURRENCY' => $order->getCurrency(),
2242 'DATE_BILL' => new Main\Type\DateTime(),
2243 );
2244
2245 $r = $paymentInner->setFields($paymentInnerFields);
2246 if (!$r->isSuccess())
2247 {
2248 $result->addErrors($r->getErrors());
2249 }
2250 }
2251 else
2252 {
2253 if ($paymentInner->getSum() < $needSum)
2254 {
2255 $paymentInner->setField('SUM', $needSum - $paymentInner->getSum());
2256 }
2257 }
2258
2259 if ($pay && $paidFormUserBudget === false)
2260 {
2261 $paymentOuter->setField('SUM', $needSum - $setSum);
2262 }
2263
2264 $payment = $paymentInner;
2265
2266 }
2267 else
2268 {
2269 $payment = $paymentOuter;
2270 }
2271
2272 if ($pay)
2273 {
2274
2275 if ($payment === null)
2276 {
2277 $paySystemId = static::getDefaultPaySystemId($order->getPersonTypeId());
2278
2280 if ($paySystem = Sale\PaySystem\Manager::getObjectById($paySystemId))
2281 {
2282 $registry = Sale\Registry::getInstance(static::getRegistryType());
2284 $paymentClassName = $registry->getPaymentClassName();
2285
2286 $payment = $paymentClassName::create($paymentCollection, $paySystem);
2287 $payment->setField('SUM', $needSum);
2288 $payment->setField('DATE_BILL', new Main\Type\DateTime());
2289 $paymentCollection->addItem($payment);
2290 }
2291 }
2292
2293 $operationPayment = $payment;
2294 if ($paidFormUserBudget === false)
2295 {
2296 $operationPayment = $paymentOuter;
2297 }
2298
2299 $service = Sale\PaySystem\Manager::getObjectById($operationPayment->getPaymentSystemId());
2300 if ($service)
2301 {
2302 $r = $service->creditNoDemand($operationPayment);
2303 if (!$r->isSuccess())
2304 $result->addErrors($r->getErrors());
2305 }
2306 else
2307 {
2308 $result->addError(new Main\Entity\EntityError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_PAYSYSTEM_NOT_FOUND')));
2309 return $result;
2310 }
2311 }
2312
2313 if ($payment->isReturn() && $payment->isInner())
2314 {
2315 $r = $payment->setPaid('Y');
2316 }
2317 else
2318 {
2320 $r = $payment->setPaid('Y');
2321
2322 if ($r->isSuccess())
2323 {
2324 if ($pay)
2325 {
2326 $operationPayment = $payment;
2327 if ($paidFormUserBudget === false)
2328 {
2329 $operationPayment = $paymentOuter;
2330
2332 $resultPayment = $paymentOuter->setPaid('Y');
2333 if (!$resultPayment->isSuccess())
2334 {
2335 $result->addErrors($resultPayment->getErrors());
2336 }
2337 }
2338
2339 $service = Sale\PaySystem\Manager::getObjectById($operationPayment->getPaymentSystemId());
2340 if ($service)
2341 {
2342 $r = $service->creditNoDemand($operationPayment);
2343 if (!$r->isSuccess())
2344 $result->addErrors($r->getErrors());
2345 }
2346 else
2347 {
2348 $result->addError(new Main\Entity\EntityError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_PAYSYSTEM_NOT_FOUND')));
2349 return $result;
2350 }
2351 }
2352
2353 }
2354 else
2355 {
2356 $result->addErrors($r->getErrors());
2357 }
2358 }
2359
2360 if (!$r->isSuccess())
2361 {
2362 $result->addErrors($r->getErrors());
2363 }
2364
2365 }
2366
2367 $result->setData(array('PAID_FROM_BUDGET' => $paidFormUserBudget));
2368
2369 return $result;
2370 }
2371
2381 public static function cancel($orderId, $value, $comment = false)
2382 {
2383 $result = new Sale\Result();
2384
2385 if (intval($orderId) <= 0)
2386 {
2387 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_ID_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_ID_NOT_FOUND') );
2388 return $result;
2389 }
2390
2391 $registry = Sale\Registry::getInstance(static::getRegistryType());
2393 $orderClassName = $registry->getOrderClassName();
2394 if (!$order = $orderClassName::load($orderId))
2395 {
2396 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_NOT_FOUND') );
2397 return $result;
2398 }
2399
2400 if ($value === 'N')
2401 {
2402 if ($order->isCanceled())
2403 {
2404 $r = $order->setField('CANCELED', 'N');
2405 if (!$r->isSuccess())
2406 {
2407 return $result->addErrors($r->getErrors());
2408 }
2409
2410 $r = $order->save();
2411 if (!$r->isSuccess())
2412 {
2413 return $result->addErrors($r->getErrors());
2414 }
2415 }
2416
2417 return $result;
2418 }
2419
2420 if ($order->isCanceled())
2421 {
2422 return $result;
2423 }
2424
2425 $paymentCollection = $order->getPaymentCollection();
2427 foreach ($paymentCollection as $payment)
2428 {
2429 if ($payment->isPaid())
2430 $payment->setReturn('Y');
2431 }
2432
2433 $shipmentCollection = $order->getShipmentCollection();
2435 foreach ($shipmentCollection as $shipment)
2436 {
2437 if ($shipment->isSystem())
2438 continue;
2439
2440 if ($shipment->isShipped())
2441 $shipment->setField('DEDUCTED', 'N');
2442
2443 if ($shipment->isAllowDelivery())
2444 $shipment->disallowDelivery();
2445 }
2446
2447 $r = $order->setField('CANCELED', 'Y');
2448 if (!$r->isSuccess())
2449 {
2450 return $result->addErrors($r->getErrors());
2451 }
2452
2453 if (!empty($comment) && strval($comment) != '')
2454 {
2455 $r = $order->setField('REASON_CANCELED', $comment);
2456 if (!$r->isSuccess())
2457 {
2458 return $result->addErrors($r->getErrors());
2459 }
2460 }
2461
2462 return $order->save();
2463 }
2464
2471 public static function delete($id)
2472 {
2473 $result = new Sale\Result();
2474
2475 if (intval($id) <= 0)
2476 {
2477 $result->addError( new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_COMPATIBLE_ORDER_ID_NOT_FOUND'), 'SALE_COMPATIBLE_ORDER_ID_NOT_FOUND') );
2478 return $result;
2479 }
2480
2481 $registry = Sale\Registry::getInstance(static::getRegistryType());
2483 $orderClassName = $registry->getOrderClassName();
2484 if (!$order = $orderClassName::load($id))
2485 {
2486 $result->addError(new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_ORDER_ENTITY_NOT_FOUND'), 'SALE_ORDER_ENTITY_NOT_FOUND'));
2487 return $result;
2488 }
2489
2491 foreach ($order->getPaymentCollection() as $payment)
2492 {
2493 if ($payment->isPaid())
2494 {
2495 $payment->setPaid('N');
2496 }
2497 }
2498
2500 foreach ($order->getShipmentCollection() as $shipment)
2501 {
2502 if ($shipment->isShipped())
2503 {
2504 $shipment->setField('DEDUCTED', 'N');
2505 }
2506 }
2507
2508 $r = $order->save();
2509 if (!$r->isSuccess())
2510 {
2511 $result->addErrors($r->getErrors());
2512 return $result;
2513 }
2514
2515 try
2516 {
2517 $r = $orderClassName::delete($id);
2518 }
2519 catch (\Exception $exception)
2520 {
2521 $r = $orderClassName::deleteNoDemand($id);
2522 }
2523
2524 if (!$r->isSuccess())
2525 {
2526 $result->addErrors($r->getErrors());
2527 }
2528
2529 return $result;
2530 }
2531
2539 public static function canPayWithUserBudget($needSum, $userId, $currency, $fullPay = true)
2540 {
2541 $budget = Sale\Internals\UserBudgetPool::getUserBudget($userId, $currency);
2542 if ($fullPay === false && $budget > 0)
2543 return true;
2544
2545 if ($fullPay === true && $budget >= $needSum)
2546 return true;
2547
2548 return false;
2549 }
2550
2551
2558 public static function createShipmentFromShipmentSystem(Sale\ShipmentCollection $shipmentCollection)
2559 {
2560
2561 $shipment = null;
2562
2564 $systemShipment = $shipmentCollection->getSystemShipment();
2565
2566 if ($systemShipment->getDeliveryId() > 0)
2567 {
2569 $shipment = static::getShipmentByDeliveryId($shipmentCollection, $systemShipment->getDeliveryId());
2570
2571 if (!$shipment)
2572 {
2573 if ($service = Sale\Delivery\Services\Manager::getObjectById($systemShipment->getDeliveryId()))
2574 {
2576 $shipment = $shipmentCollection->createItem($service);
2577 $shipment->setField('DELIVERY_NAME', $service->getName());
2578 }
2579 }
2580 }
2581
2582 return $shipment;
2583 }
2584
2585
2593 public static function getShipmentByDeliveryId(Sale\ShipmentCollection $shipmentCollection, $deliveryId)
2594 {
2596 foreach($shipmentCollection as $shipment)
2597 {
2598 if ($shipment->isSystem())
2599 continue;
2600
2601 if ($shipment->getDeliveryId() == $deliveryId)
2602 {
2603 return $shipment;
2604 }
2605 }
2606
2607 return false;
2608 }
2609
2613 protected static function transformationLocation(Sale\Order $order)
2614 {
2616 if ($propertyCollection = $order->getPropertyCollection())
2617 {
2619 foreach ($propertyCollection as $valueItem)
2620 {
2621 if ($valueItem->getValue() != '')
2622 {
2623 $setValue = $valueItem->getValue();
2624
2625 $prop = $valueItem->getPropertyObject();
2626 if ($prop->getType() == 'LOCATION')
2627 {
2628 $setValue = \CSaleLocation::tryTranslateIDToCode($setValue);
2629 }
2630
2631 $valueItem->setField('VALUE', $setValue);
2632 }
2633
2634 }
2635 }
2636
2637 }
2638
2645 public static function getById($id)
2646 {
2647 $compatibility = new static();
2648
2649 $select = array('*');
2650
2651 $registry = Sale\Registry::getInstance(static::getRegistryType());
2653 $orderClassName = $registry->getOrderClassName();
2654
2655 if ($order = $orderClassName::load($id))
2656 {
2658 if ($paymentCollection = $order->getPaymentCollection())
2659 {
2660 if (count($paymentCollection) == 1)
2661 {
2662 $select = array_merge($select, array_keys(static::getAliasPaymentFields()));
2663 }
2664 }
2665
2667 if ($shipmentCollection = $order->getShipmentCollection())
2668 {
2669 if (count($shipmentCollection) == 1
2670 || (count($shipmentCollection) == 2 && $shipmentCollection->isExistsSystemShipment()))
2671 {
2672 $select = array_merge($select, array_keys(static::getAliasShipmentFields()));
2673 }
2674 }
2675 }
2676
2677 return static::setGetListParameters($compatibility, array(), array("ID" => $id), null, array(), $select);
2678 }
2679
2684 public static function getAliasFields()
2685 {
2686 $fields = array(
2687 'NAME_SEARCH' => array(
2688 'NAME' => 'USER.NAME',
2689 'LAST_NAME' => 'USER.LAST_NAME',
2690 'SECOND_NAME' => 'USER.SECOND_NAME',
2691 'EMAIL' => 'USER.EMAIL',
2692 'LOGIN' => 'USER.LOGIN',
2693 'NAME_SEARCH' => 'USER.ID',
2694 ),
2695 'USER_ID' => 'USER.ID',
2696 'USER_LOGIN' => 'USER.LOGIN',
2697 'USER_NAME' => 'USER.NAME',
2698 'USER_LAST_NAME' => 'USER.LAST_NAME',
2699 'USER_EMAIL' => 'USER.EMAIL',
2700 'RESPONSIBLE_ID' => 'RESPONSIBLE.ID',
2701 'RESPONSIBLE_LOGIN' => 'RESPONSIBLE.LOGIN',
2702 'RESPONSIBLE_NAME' => 'RESPONSIBLE.NAME',
2703 'RESPONSIBLE_LAST_NAME' => 'RESPONSIBLE.LAST_NAME',
2704 'RESPONSIBLE_SECOND_NAME' => 'RESPONSIBLE.SECOND_NAME',
2705 'RESPONSIBLE_EMAIL' => 'RESPONSIBLE.EMAIL',
2706 'RESPONSIBLE_WORK_POSITION' => 'RESPONSIBLE.WORK_POSITION',
2707 'RESPONSIBLE_PERSONAL_PHOTO' => 'RESPONSIBLE.PERSONAL_PHOTO',
2708
2709 'PROPERTY_ID' => 'PROPERTY.ID',
2710 'PROPERTY_ORDER_PROPS_ID' => 'PROPERTY.ORDER_PROPS_ID',
2711 'PROPERTY_NAME' => 'PROPERTY.NAME',
2712 'PROPERTY_VALUE' => 'PROPERTY.VALUE',
2713 'PROPERTY_CODE' => 'PROPERTY.CODE',
2714 'PROPERTY_VAL_BY_CODE' => 'PROPERTY.VALUE',
2715// 'COMPLETE_ORDERS' => 'PROPERTY.ORDER_PROPS_ID',
2716
2717 );
2718 return array_merge(
2719 $fields,
2720 static::getAliasPaymentFields(),
2721 static::getAliasShipmentFields(),
2722 static::getAliasBasketFields()
2723 );
2724 }
2725
2729 protected static function getAliasPaymentFields()
2730 {
2731 return array(
2732 'PAY_SYSTEM_ID' => 'PAYMENT.PAY_SYSTEM_ID',
2733 'PAYED' => 'PAYMENT.PAID',
2734
2735 'DATE_PAYED' => 'PAYMENT.DATE_PAID',
2736 'EMP_PAYED_ID' => 'PAYMENT.EMP_PAID_ID',
2737
2738 'PS_STATUS' => 'PAYMENT.PS_STATUS',
2739 'PS_STATUS_CODE' => 'PAYMENT.PS_STATUS_CODE',
2740 'PS_STATUS_DESCRIPTION' => 'PAYMENT.PS_STATUS_DESCRIPTION',
2741 'PS_STATUS_MESSAGE' => 'PAYMENT.PS_STATUS_MESSAGE',
2742 'PS_SUM' => 'PAYMENT.PS_SUM',
2743 'PS_CURRENCY' => 'PAYMENT.PS_CURRENCY',
2744 'PS_RESPONSE_DATE' => 'PAYMENT.PS_RESPONSE_DATE',
2745 );
2746 }
2747
2751 protected static function getAliasShipmentFields()
2752 {
2753 return array(
2754 'DELIVERY_ID' => 'SHIPMENT.DELIVERY.CODE',
2755 //'DELIVERY_ID' => 'SHIPMENT.DELIVERY_ID',
2756 'PRICE_DELIVERY' => 'SHIPMENT.PRICE_DELIVERY',
2757 'ALLOW_DELIVERY' => 'SHIPMENT.ALLOW_DELIVERY',
2758 'DATE_ALLOW_DELIVERY' => 'SHIPMENT.DATE_ALLOW_DELIVERY',
2759 'EMP_ALLOW_DELIVERY_ID' => 'SHIPMENT.EMP_ALLOW_DELIVERY_ID',
2760
2761 'DATE_DEDUCTED' => 'SHIPMENT.DATE_DEDUCTED',
2762 'EMP_DEDUCTED_ID' => 'SHIPMENT.EMP_DEDUCTED_ID',
2763 'REASON_UNDO_DEDUCTED' => 'SHIPMENT.REASON_UNDO_DEDUCTED',
2764
2765 'TRACKING_NUMBER' => 'SHIPMENT.TRACKING_NUMBER',
2766 'DELIVERY_DOC_NUM' => 'SHIPMENT.DELIVERY_DOC_NUM',
2767 'DELIVERY_DOC_DATE' => 'SHIPMENT.DELIVERY_DOC_DATE',
2768 );
2769 }
2770
2774 protected static function getAliasBasketFields()
2775 {
2776 return array(
2777 'BASKET_ID' => 'BASKET.ID',
2778 'BASKET_PRODUCT_ID' => 'BASKET.PRODUCT_ID',
2779 'BASKET_PRODUCT_XML_ID' => 'BASKET.PRODUCT_XML_ID',
2780 'BASKET_MODULE' => 'BASKET.MODULE',
2781 'BASKET_NAME' => 'BASKET.NAME',
2782 'BASKET_QUANTITY' => 'BASKET.QUANTITY',
2783 'BASKET_PRICE' => 'BASKET.PRICE',
2784 'BASKET_CURRENCY' => 'BASKET.CURRENCY',
2785 'BASKET_VAT_RATE' => 'BASKET.VAT_RATE',
2786 'BASKET_RECOMMENDATION' => 'BASKET.RECOMMENDATION',
2787 'BASKET_DISCOUNT_PRICE' => 'BASKET.DISCOUNT_PRICE',
2788 'BASKET_DISCOUNT_NAME' => 'BASKET.DISCOUNT_NAME',
2789 'BASKET_DISCOUNT_VALUE' => 'BASKET.DISCOUNT_VALUE',
2790 );
2791 }
2792
2796 protected static function getSelectFields()
2797 {
2798 $fields = array_keys(static::getEntity()->getScalarFields());
2799
2800 return array_merge($fields, array(
2801 'DATE_INSERT_FORMAT',
2802 'DATE_UPDATE_SHORT',
2803 'DATE_STATUS_SHORT',
2804 'DATE_CANCELED_SHORT',
2805 'BY_RECOMMENDATION',
2806
2807 'LOCK_STATUS',
2808 'LOCK_USER_NAME',
2809 'DATE_INSERT_FORMAT',
2810
2811 "RESPONSIBLE_ID",
2812 "RESPONSIBLE_LOGIN",
2813 "RESPONSIBLE_NAME",
2814 "RESPONSIBLE_LAST_NAME",
2815 "RESPONSIBLE_SECOND_NAME",
2816 "RESPONSIBLE_EMAIL",
2817 "RESPONSIBLE_WORK_POSITION",
2818 "RESPONSIBLE_PERSONAL_PHOTO",
2819 "RESPONSIBLE_GROUP_ID",
2820
2821 "PAY_SYSTEM_ID",
2822 "DELIVERY_ID",
2823 "DEDUCTED",
2824 "RESERVED",
2825 "PRICE_DELIVERY",
2826 "ALLOW_DELIVERY",
2827 "DATE_ALLOW_DELIVERY",
2828 "EMP_ALLOW_DELIVERY_ID",
2829 "DELIVERY_DOC_NUM",
2830 "DELIVERY_DOC_DATE",
2831 "PAYED",
2832 "DATE_PAYED",
2833 "EMP_PAYED_ID",
2834 "STATUS_ID",
2835 "DATE_STATUS",
2836 "EMP_STATUS_ID",
2837 "DATE_INSERT_FORMAT",
2838 "USER_LOGIN",
2839 "USER_NAME",
2840 "USER_LAST_NAME",
2841 "USER_EMAIL",
2842 "DATE_PAY_BEFORE",
2843 "DATE_BILL",
2844 "ACCOUNT_NUMBER",
2845 "TRACKING_NUMBER",
2846
2847
2848 ));
2849
2850 }
2851
2856 public static function getAvailableFields()
2857 {
2858 $registry = Sale\Registry::getInstance(static::getRegistryType());
2860 $orderClassName = $registry->getOrderClassName();
2861
2862 return array_merge($orderClassName::getAvailableFields(),
2863 array('PRICE_DELIVERY', "PAY_VOUCHER_DATE", "PAY_VOUCHER_NUM", "DATE_ALLOW_DELIVERY", "DATE_PAYED")
2864 );
2865 }
2866
2867
2871 protected static function getShipmentClearFields()
2872 {
2873 return array(
2874 'STATUS_ID',
2875 'ACCOUNT_NUMBER',
2876 'DATE_INSERT',
2877 'MARKED',
2878 'EMP_MARKED_ID',
2879 'DATE_MARKED',
2880 'REASON_MARKED',
2881 'DATE_CANCELED',
2882 'EMP_CANCELED_ID',
2883 );
2884 }
2885
2886
2890 protected static function getPaymentClearFields()
2891 {
2892 return array(
2893 'ACCOUNT_NUMBER',
2894 'MARKED',
2895 'EMP_MARKED_ID',
2896 'DATE_MARKED',
2897 'REASON_MARKED',
2898 );
2899 }
2900
2904 protected static function getPaymentAvailableFields()
2905 {
2906 $registry = Sale\Registry::getInstance(static::getRegistryType());
2908 $paymentClassName = $registry->getPaymentClassName();
2909
2910 return static::clearAvailableFields($paymentClassName::getAvailableFields(), static::getPaymentClearFields());
2911 }
2912
2916 protected static function getShipmentAvailableFields()
2917 {
2918 $registry = Sale\Registry::getInstance(static::getRegistryType());
2920 $shipmentClassName = $registry->getShipmentClassName();
2921
2922 return static::clearAvailableFields($shipmentClassName::getAvailableFields(), static::getShipmentClearFields());
2923 }
2924
2925
2926 protected function getWhiteListFields()
2927 {
2928 return array_merge(parent::getWhiteListFields(), array_keys(static::getAliasFields()));
2929 }
2930
2931
2938 protected static function clearAvailableFields(array $fields, array $clearFields = array())
2939 {
2940 $result = array();
2941 if (!empty($clearFields))
2942 {
2943 foreach ($fields as $field)
2944 {
2945 if (!in_array($field, $clearFields))
2946 {
2947 $result[] = $field;
2948 }
2949 }
2950 }
2951
2952 return $result;
2953 }
2954
2958 protected static function getFieldsFromOtherEntities()
2959 {
2960 return array_merge(
2961 static::getShipmentFieldsToConvert(),
2962 static::getPaymentFieldsToConvert()
2963 );
2964 }
2965
2970 public static function getOrderDateFields()
2971 {
2972 return array(
2973 'DATE_INSERT' => 'datetime',
2974 'DATE_UPDATE' => 'datetime',
2975 'DATE_PAYED' => 'datetime',
2976 'DATE_STATUS' => 'datetime',
2977 'DATE_LOCK' => 'datetime',
2978 'DATE_PAY_BEFORE' => 'date',
2979 'DATE_BILL' => 'date',
2980 'DATE_MARKED' => 'datetime',
2981 'DATE_CANCELED' => 'datetime',
2982 );
2983 }
2984
2988 protected static function getShipmentFieldsToConvert()
2989 {
2990 return array(
2991// 'ALLOW_DELIVERY',
2992 'DATE_ALLOW_DELIVERY',
2993 'EMP_ALLOW_DELIVERY_ID',
2994
2995 'DELIVERY_DOC_NUM',
2996 'DELIVERY_DOC_DATE',
2997 'TRACKING_NUMBER',
2998
2999// 'DEDUCTED',
3000 'DATE_DEDUCTED',
3001 'EMP_DEDUCTED_ID',
3002 'REASON_UNDO_DEDUCTED',
3003
3004 'RESERVED',
3005 );
3006 }
3007
3011 protected static function getPaymentFieldsToConvert()
3012 {
3013 return array(
3014// 'PAYED',
3015 'DATE_PAYED',
3016 'EMP_PAYED_ID',
3017 'PAY_VOUCHER_NUM',
3018 'PAY_VOUCHER_DATE',
3019 'PAY_SYSTEM_ID',
3020 );
3021 }
3022
3026 protected static function getEntityDateFields(Sale\Internals\CollectableEntity $entity)
3027 {
3028 if ($entity instanceof Sale\Shipment)
3029 {
3030 return array(
3031 'DATE_ALLOW_DELIVERY' => 'datetime',
3032 'DELIVERY_DOC_DATE' => 'date',
3033 'DATE_DEDUCTED' => 'datetime',
3034 'DATE_MARKED' => 'datetime',
3035 'DATE_RESPONSIBLE_ID' => 'date',
3036 'DATE_INSERT' => 'datetime',
3037 'TRACKING_LAST_CHECK' => 'datetime',
3038 'TRACKING_LAST_CHANGE' => 'datetime',
3039 );
3040 }
3041 elseif ($entity instanceof Sale\Payment)
3042 {
3043 return array(
3044 'DATE_PAYED' => 'datetime',
3045 'DATE_PAID' => 'datetime',
3046 'PAY_VOUCHER_DATE' => 'date',
3047 'PS_RESPONSE_DATE' => 'datetime',
3048 );
3049 }
3050 }
3051
3055 protected static function getPaymentDateFields()
3056 {
3057 return array(
3058 'DATE_PAYED' => 'datetime',
3059 'DATE_PAID' => 'datetime',
3060 'PAY_VOUCHER_DATE' => 'date',
3061 'PS_RESPONSE_DATE' => 'datetime',
3062 );
3063 }
3064
3065
3069 protected static function getPaymentReplaceFields()
3070 {
3071 return array(
3072 'PAYED' => 'PAID',
3073 'DATE_PAYED' => 'DATE_PAID',
3074 'EMP_PAYED_ID' => 'EMP_PAID_ID',
3075 );
3076 }
3077
3081 protected static function getOrderReplaceFields()
3082 {
3083 return array();
3084 }
3085
3086
3095 public function resetOrderPrice(Sale\Basket $basket, array $requestFields)
3096 {
3097
3098 if (empty($requestFields['BASKET_ITEMS']))
3099 return false;
3100
3101 $resetPrice = false;
3102 $resetPriceDelivery = false;
3103
3105 $order = $this->getOrder();
3106
3107 if ($order->getId() == 0)
3108 {
3109 $order->resetData(array('PRICE_DELIVERY'));
3110 $resetPriceDelivery = true;
3111 }
3112
3113 foreach ($requestFields['BASKET_ITEMS'] as $basketData)
3114 {
3115 if (!isset($basketData['ID']) || intval($basketData['ID']) <= 0)
3116 continue;
3117
3119 if (!$basketItem = $basket->getItemById($basketData['ID']))
3120 continue;
3121
3122 if ($resetPriceDelivery === false)
3123 {
3124 if ($order->getId() == 0 || isset($basketData['PRICE'])
3125 && floatval($basketData['PRICE']) != $basketItem->getPrice())
3126 {
3127
3128 $order->resetData(array('PRICE'));
3129 $resetPrice = true;
3130 }
3131 }
3132
3133
3134// if ($resetPriceDelivery === false)
3135// {
3136// if ($order->getId() == 0 || isset($basketData['QUANTITY'])
3137// && floatval($basketData['QUANTITY']) != $basketItem->getQuantity())
3138// {
3139// $order->resetData(array('PRICE_DELIVERY'));
3140// $resetPriceDelivery = true;
3141// }
3142// }
3143
3144 if ($resetPriceDelivery && $resetPrice)
3145 return true;
3146 }
3147
3148
3149 //
3150 return false;
3151 }
3152
3158 public static function getOrderFields(Sale\Order $order)
3159 {
3160 $result = new Sale\Result();
3161
3162 $fields = array(
3163 "SITE_ID" => $order->getSiteId(),
3164 "LID" => $order->getSiteId(),
3165 "PERSON_TYPE_ID" => $order->getPersonTypeId(),
3166 "PRICE" => $order->getPrice(),
3167 "CURRENCY" => $order->getCurrency(),
3168 "USER_ID" => $order->getUserId(),
3169 "PAY_SYSTEM_ID" => (int)$order->getField('PAY_SYSTEM_ID'),
3170 "PRICE_DELIVERY" => $order->getDeliveryPrice(),
3171 "DELIVERY_ID" => (int)$order->getField('DELIVERY_ID'),
3172 "DISCOUNT_VALUE" => $order->getDiscountPrice(),
3173 "TAX_VALUE" => $order->getTaxValue(),
3174 "TRACKING_NUMBER" => $order->getField('TRACKING_NUMBER'),
3175 "PAYED" => $order->getField('PAYED'),
3176 "CANCELED" => $order->getField('CANCELED'),
3177 "STATUS_ID" => $order->getField('STATUS_ID'),
3178 "RESERVED" => $order->getField('RESERVED'),
3179 );
3180
3181 $orderFields = static::convertOrderToArray($order);
3182 if (is_array($orderFields))
3183 {
3184 $orderFields = $fields + $orderFields;
3185 $orderFields = static::convertDateFieldsToOldFormat($orderFields);
3186 }
3187
3188 $result->setData([
3189 'FIELDS' => $fields,
3190 'ORDER_FIELDS' => $orderFields,
3191 ]);
3192
3193 return $result;
3194 }
3195
3201 public static function convertOrderToArray(Sale\Order $order)
3202 {
3203 $fields = $order->getFieldValues();
3204
3205 //getWeight
3206 $fields = array_merge(
3207 $fields,
3208 [
3209 'ORDER_WEIGHT' => 0,
3210 'BASKET_ITEMS' => [],
3211 'ORDER_PROP' => [],
3212 'DISCOUNT_LIST' => [],
3213 'TAX_LIST' => [],
3214 'VAT_RATE' => $order->getVatRate(),
3215 'VAT_SUM' => $order->getVatSum(),
3216 ]
3217 );
3218
3220 if ($basket = $order->getBasket())
3221 {
3223 foreach ($basket as $basketItem)
3224 {
3226 $basketCompatibilityClassName = static::getBasketCompatibilityClassName();
3227
3228 $fields['BASKET_ITEMS'][] = $basketCompatibilityClassName::convertBasketItemToArray($basketItem);
3229 }
3230
3231 $fields['ORDER_WEIGHT'] = $basket->getWeight();
3232 }
3233
3235 if ($propertyCollection = $order->getPropertyCollection())
3236 {
3238 foreach ($propertyCollection as $property)
3239 {
3240// $propertyValue = $property->getValue();
3241 $fields['ORDER_PROP'][$property->getPropertyId()] = $property->getValue();
3242 }
3243 }
3244
3245
3246 if ($propProfileName = $propertyCollection->getProfileName())
3247 $fields['PROFILE_NAME'] = $propProfileName->getValue();
3248
3249 if ($propPayerName = $propertyCollection->getPayerName())
3250 $fields['PAYER_NAME'] = $propPayerName->getValue();
3251
3252 if ($propUserEmail = $propertyCollection->getUserEmail())
3253 $fields['USER_EMAIL'] = $propUserEmail->getValue();
3254
3255 if ($propDeliveryLocationZip = $propertyCollection->getDeliveryLocationZip())
3256 $fields['DELIVERY_LOCATION_ZIP'] = $propDeliveryLocationZip->getValue();
3257
3258 if ($propDeliveryLocation = $propertyCollection->getDeliveryLocation())
3259 $fields['DELIVERY_LOCATION'] = $propDeliveryLocation->getValue();
3260
3261 if ($propTaxLocation = $propertyCollection->getTaxLocation())
3262 $fields['TAX_LOCATION'] = $propTaxLocation->getValue();
3263
3265
3267 if ($tax = $order->getTax())
3268 {
3269 $fields['TAX_LIST'] = $tax->getTaxList();
3270 }
3271
3272 return $fields;
3273 }
3274
3275 public function isExistPrice()
3276 {
3277 return ($this->externalPrice !== null);
3278 }
3279
3285 public function parseField($key)
3286 {
3287 $output = null;
3288 $locationPropInfo = \CSaleOrder::getLocationPropertyInfo();
3289
3290 static $propIndex = 0;
3291
3292 $propIDTmp = false;
3293 if (mb_strpos($key, "PROPERTY_ID_") === 0)
3294 {
3295 $propIndex++;
3296 $this->addPropertyRuntime($propIndex);
3297 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3298 {
3299 return null;
3300 }
3301
3302 $propIDTmp = intval(mb_substr($key, mb_strlen("PROPERTY_ID_")));
3303
3304 $this->query->addFilter('='.$propRuntimeName.'.ORDER_PROPS_ID', $propIDTmp);
3305 if(isset($locationPropInfo['ID'][$propIDTmp]))
3306 {
3307 $this->addQueryAlias('PROPERTY_ID_'.$propIDTmp, 'LOCATION.ID');
3308 }
3309 else
3310 {
3311 $this->addQueryAlias('PROPERTY_ID_'.$propIDTmp, $propRuntimeName.'.ID');
3312 }
3313
3314 $output = 'PROPERTY_ID_'.$propIDTmp;
3315
3316 }
3317 elseif (mb_strpos($key, "PROPERTY_ORDER_PROPS_ID_") === 0)
3318 {
3319 $propIndex++;
3320 $this->addPropertyRuntime($propIndex);
3321 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3322 {
3323 return null;
3324 }
3325
3326 $propIDTmp = intval(mb_substr($key, mb_strlen("PROPERTY_ORDER_PROPS_ID_")));
3327
3328 $this->query->addFilter('='.$propRuntimeName.'.ORDER_PROPS_ID', $propIDTmp);
3329 if(isset($locationPropInfo['ID'][$propIDTmp]))
3330 {
3331 $this->addQueryAlias('PROPERTY_ORDER_PROPS_ID_'.$propIDTmp, 'LOCATION.ID');
3332 }
3333 else
3334 {
3335 $this->addQueryAlias('PROPERTY_ORDER_PROPS_ID_'.$propIDTmp, $propRuntimeName.'.ORDER_PROPS_ID');
3336 }
3337
3338 $output = 'PROPERTY_ORDER_PROPS_ID_'.$propIDTmp;
3339 }
3340 elseif (mb_strpos($key, "PROPERTY_NAME_") === 0)
3341 {
3342 $propIndex++;
3343 $this->addPropertyRuntime($propIndex);
3344 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3345 {
3346 return null;
3347 }
3348
3349 $propIDTmp = intval(mb_substr($key, mb_strlen("PROPERTY_NAME_")));
3350
3351 $this->addQueryAlias('PROPERTY_NAME_'.$propIDTmp, $propRuntimeName.'.NAME');
3352 $this->query->addFilter('='.$propRuntimeName.'.ORDER_PROPS_ID', $propIDTmp);
3353
3354 $output = 'PROPERTY_NAME_'.$propIDTmp;
3355 }
3356 elseif (mb_strpos($key, "PROPERTY_VALUE_") === 0)
3357 {
3358 $propIndex++;
3359 $this->addPropertyRuntime($propIndex);
3360 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3361 {
3362 return null;
3363 }
3364
3365 $propIDTmp = intval(mb_substr($key, mb_strlen("PROPERTY_VALUE_")));
3366
3367 if(isset($locationPropInfo['ID'][$propIDTmp]))
3368 {
3369 $this->addQueryAlias('PROPERTY_ID_'.$propIDTmp, 'LOCATION.ID');
3370 }
3371 else
3372 {
3373 $this->addQueryAlias('PROPERTY_ID_'.$propIDTmp, $propRuntimeName.'.VALUE');
3374 }
3375
3376 $output = 'PROPERTY_ID_'.$propIDTmp;
3377 }
3378 elseif (mb_strpos($key, "PROPERTY_CODE_") === 0)
3379 {
3380 $propIndex++;
3381 $this->addPropertyRuntime($propIndex);
3382 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3383 {
3384 return null;
3385 }
3386
3387 $propIDTmp = intval(mb_substr($key, mb_strlen("PROPERTY_CODE_")));
3388 $this->addQueryAlias('PROPERTY_CODE_'.$propIDTmp, $propRuntimeName.'.CODE');
3389 $this->query->addFilter('='.$propRuntimeName.'.ORDER_PROPS_ID', $propIDTmp);
3390
3391 $output = 'PROPERTY_CODE_'.$propIDTmp;
3392 }
3393 elseif (mb_strpos($key, "PROPERTY_VAL_BY_CODE_") === 0)
3394 {
3395 $propIndex++;
3396 $this->addPropertyRuntime($propIndex);
3397 if (!($propRuntimeName = $this->getPropertyRuntimeName($propIndex)))
3398 {
3399 return null;
3400 }
3401
3402 $propIDTmp = preg_replace("/[^a-zA-Z0-9_-]/is", "", trim(mb_substr($key, mb_strlen("PROPERTY_VAL_BY_CODE_"))));
3403
3404 $this->addQueryAlias('PROPERTY_VAL_BY_CODE_'.$propIDTmp, $propRuntimeName.'.VALUE');
3405 if(isset($locationPropInfo['CODE'][$propIDTmp]))
3406 {
3407 $this->addQueryAlias('PROPERTY_VAL_BY_CODE_'.$propIDTmp, 'LOCATION.ID');
3408 }
3409 else
3410 {
3411 $this->addQueryAlias('PROPERTY_VAL_BY_CODE_'.$propIDTmp, $propRuntimeName.'.VALUE');
3412 }
3413
3414 $this->query->addFilter('='.$propRuntimeName.'.CODE', $propIDTmp);
3415
3416 $output = 'PROPERTY_VAL_BY_CODE_'.$propIDTmp;
3417 }
3418 elseif (mb_strpos($key, "BASKET_") === 0)
3419 {
3420 $output = static::addBasketRuntime($key);
3421 }
3422
3423 if(isset($locationPropInfo['ID'][$propIDTmp]))
3424 {
3425 $this->query->registerRuntimeField(
3426 'LOCATION',
3427 array(
3428 'data_type' => '\Bitrix\Sale\Location\LocationTable',
3429 'reference' => array(
3430 '=this.PROPERTY.VALUE' => 'ref.CODE'
3431 ),
3432 'join_type' => 'inner'
3433 )
3434 );
3435 }
3436
3437 return $output;
3438 }
3439
3440
3444 protected function addPropertyRuntime($index)
3445 {
3446 if ($this->getPropertyRuntimeName($index))
3447 return;
3448
3449 $this->query->registerRuntimeField(
3450 'PROPERTY_'.$index,
3451 array(
3452 'data_type' => '\Bitrix\Sale\Internals\OrderPropsValueTable',
3453 'reference' => array(
3454 'ref.ORDER_ID' => 'this.ID',
3455 ),
3456 'join_type' => 'inner'
3457 )
3458 );
3459
3460 $this->runtimeFields[] = 'PROPERTY_'.$index;
3461 $this->propertyRuntimeList[$index] = 'PROPERTY_'.$index;
3462 }
3463
3464
3465 protected function getPropertyRuntimeName($index)
3466 {
3467 return (!empty($this->propertyRuntimeList[$index]) ? $this->propertyRuntimeList[$index] : null);
3468 }
3469
3470
3478 protected function addBasketRuntime($key)
3479 {
3480 $output = null;
3481
3482 if ($key == "BASKET_DISCOUNT_COUPON")
3483 {
3484 if (!in_array('COUPONS', $this->runtimeFields))
3485 {
3486 $this->query->registerRuntimeField(
3487 'COUPONS',
3488 array(
3489 'data_type' => '\Bitrix\Sale\Internals\OrderCouponsTable',
3490 'reference' => array(
3491 '=ref.ORDER_ID' => 'this.ID'
3492 ),
3493 )
3494 );
3495 $this->runtimeFields[] = "COUPONS";
3496 }
3497
3498 $this->addQueryAlias('BASKET_DISCOUNT_COUPON', 'COUPONS.COUPON');
3499 $output = 'BASKET_DISCOUNT_COUPON';
3500
3501 }
3502 elseif ($key == "BASKET_DISCOUNT_NAME")
3503 {
3504 if (!in_array('DISCOUNT_ORDER_RULES', $this->runtimeFields))
3505 {
3506 $this->query->registerRuntimeField(
3507 'DISCOUNT_ORDER_RULES',
3508 array(
3509 'data_type' => '\Bitrix\Sale\Internals\OrderRulesTable',
3510 'reference' => array(
3511 '=ref.ORDER_ID' => 'this.ID',
3512 ),
3513 )
3514 );
3515 $this->runtimeFields[] = "DISCOUNT_ORDER_RULES";
3516 }
3517
3518 if (!in_array('DISCOUNT', $this->runtimeFields))
3519 {
3520 $this->query->registerRuntimeField(
3521 'DISCOUNT',
3522 array(
3523 'data_type' => '\Bitrix\Sale\Internals\OrderDiscountTable',
3524 'reference' => array(
3525 '=ref.ID' => 'this.DISCOUNT_ORDER_RULES.ORDER_DISCOUNT_ID'
3526 ),
3527 )
3528 );
3529
3530 $this->runtimeFields[] = "DISCOUNT";
3531 }
3532
3533 $this->addQueryAlias('BASKET_DISCOUNT_NAME', 'DISCOUNT.NAME');
3534 $output = 'BASKET_DISCOUNT_NAME';
3535 }
3536
3537 return $output;
3538 }
3539
3540 protected static function getDefaultFuserId()
3541 {
3542 return Sale\Fuser::getId();
3543 }
3544}
3545
3547{
3548
3549 protected static function getMoneyFields()
3550 {
3551 return array(
3552 "PRICE_DELIVERY",
3553 "PRICE",
3554 "DISCOUNT_VALUE",
3555 "DISCOUNT_ALL",
3556 "BASKET_PRICE_TOTAL",
3557 "PS_SUM",
3558 "PRICE_DELIVERY",
3559 );
3560 }
3566 public function adapt(array $row)
3567 {
3568 $data = Internals\EntityCompatibility::convertDateFieldsToOldFormat($row);
3569 return static::convertRowData($data);
3570 }
3571
3577 public static function convertRowData(array $data)
3578 {
3579 if (isset($data['DELIVERY_ID']) && intval($data['DELIVERY_ID']) > 0)
3580 {
3581 $data['DELIVERY_ID'] = \CSaleDelivery::getCodeById($data['DELIVERY_ID']);
3582 }
3583
3584 if (isset($data['CURRENCY']) && !empty($data['CURRENCY']))
3585 {
3586 foreach (static::getMoneyFields() as $field)
3587 {
3588 if (array_key_exists($field, $data))
3589 {
3590 $data[$field] = SaleFormatCurrency($data[$field], $data["CURRENCY"], false, true);
3591 }
3592 }
3593 }
3594
3595 return $data;
3596 }
3597}
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
parseRawFields($entityName, array $fields, array $availableFields=array())
static clearAvailableFields(array $fields, array $clearFields=array())
setBasketCompatibility(BasketCompatibility $basketCompatibility)
static canPayWithUserBudget($needSum, $userId, $currency, $fullPay=true)
static createShipmentFromRequest(Sale\ShipmentCollection $shipmentCollection, $deliveryId, array $requestFields)
static getEntityDateFields(Sale\Internals\CollectableEntity $entity)
static roundPrecision($value)