60 $this->settingsContainer = $settings;
62 $this->errorsContainer->setAcceptableErrorCodes(
63 $this->settingsContainer->getItemValue(
'acceptableErrorCodes')
80 ->buildTradeBindings()
87 ->setRelatedProperties()
106 $fields[
"ID"] = (isset($fields[
"ID"]) ? (int)$fields[
"ID"] : 0);
113 $this->formData = $data;
128 if($this->order = $this->
delegate->createOrder($data))
130 $this->isStartField = $this->order->isStartField();
138 $shipmentClassName = $this->registry->getShipmentClassName();
139 return array_merge([
'PROPERTIES'], $shipmentClassName::getAvailableFields());
144 $paymentClassName = $this->registry->getPaymentClassName();
145 return $paymentClassName::getAvailableFields();
150 return [
'RESPONSIBLE_ID',
'USER_DESCRIPTION',
'ORDER_TOPIC',
'ACCOUNT_NUMBER'];
153 public function setFields()
157 foreach($fields as $field)
159 if(isset($this->formData[$field]))
161 $r = $this->order->setField($field, $this->formData[$field]);
170 if(isset($this->formData[
"PERSON_TYPE_ID"]) && intval($this->formData[
"PERSON_TYPE_ID"]) > 0)
173 $r = $this->order->setPersonTypeId(intval($this->formData[
'PERSON_TYPE_ID']));
178 $r = $this->order->setPersonTypeId(
180 $this->order->getSiteId()
195 if (empty($this->formData[
"PROPERTIES"]))
200 $propCollection = $this->order->getPropertyCollection();
201 $res = $propCollection->setValuesFromPost(
203 $this->settingsContainer->getItemValue(
'propsFiles')
206 if (!$res->isSuccess())
214 public function setRelatedProperties()
216 if (empty($this->formData[
"PROPERTIES"]))
221 $propCollection = $this->order->getPropertyCollection();
224 foreach ($propCollection as $propertyValue)
226 if (!$propertyValue->getRelations())
231 $post = Internals\Input\File::getPostWithFiles($this->formData, $this->settingsContainer->getItemValue(
'propsFiles'));
233 $res = $propertyValue->setValueFromPost($post);
234 if (!$res->isSuccess())
251 if (empty($this->formData[
"PROPERTIES"]) || empty($this->formData[
"USER_ID"]))
256 $profileId = $this->formData[
"USER_PROFILE"][
"ID"] ?? 0;
257 $profileName = $this->formData[
"USER_PROFILE"][
"NAME"] ??
'';
260 \CSaleOrderUserProps::DoSaveUserProfile(
264 $this->order->getPersonTypeId(),
265 $this->formData[
"PROPERTIES"],
269 foreach ($errors as $error)
271 $this->errorsContainer->addError(
new Main\
Error($error[
'TEXT'], $error[
'CODE'],
'PROFILE'));
279 if(isset($this->formData[
"DISCOUNTS"]) && is_array($this->formData[
"DISCOUNTS"]))
281 $this->order->getDiscount()->setApplyResult($this->formData[
"DISCOUNTS"]);
283 $r = $this->order->getDiscount()->calculate();
287 $discountData = $r->getData();
288 $this->order->applyDiscount($discountData);
303 $shipments = $this->order->getShipmentCollection();
304 return $shipments->createItem();
311 $shipmentCollection = $this->order->getShipmentCollection();
314 foreach($this->formData[
"SHIPMENT"] as $shipmentData)
316 if(!isset($shipmentData[
'ID']))
319 $shipment = $shipmentCollection->getItemById($shipmentData[
'ID']);
321 if ($shipment ==
null)
324 $shipmentIds[] = $shipment->getId();
327 foreach ($shipmentCollection as $shipment)
329 if($shipment->isSystem())
332 if(!in_array($shipment->getId(), $shipmentIds))
334 $r = $shipment->delete();
335 if (!$r->isSuccess())
337 $this->errorsContainer->addErrors($r->getErrors());
352 $deliveryStatusClassName = $this->registry->getDeliveryStatusClassName();
353 $statusId = $deliveryStatusClassName::getInitialStatus();
355 elseif (isset($item[
'STATUS_ID']) && $item[
'STATUS_ID'] !== $defaultFields[
'STATUS_ID'])
357 $statusId = $item[
'STATUS_ID'];
363 public function buildShipments()
365 $isEmptyShipmentData = empty($this->formData[
"SHIPMENT"]) || !is_array($this->formData[
"SHIPMENT"]);
366 if ($isEmptyShipmentData)
368 $this->formData[
"SHIPMENT"] = [];
371 if ($isEmptyShipmentData && !$this->
getSettingsContainer()->getItemValue(
'createDefaultShipmentIfNeed'))
376 if($isEmptyShipmentData && $this->
getOrder()->isNew())
384 throw new BuildingException();
388 $shipmentCollection = $this->order->getShipmentCollection();
390 foreach($this->formData[
"SHIPMENT"] as $item)
392 $shipmentId = intval($item[
'ID'] ?? 0);
393 $isNew = ($shipmentId <= 0);
394 $deliveryService =
null;
397 if (!isset($item[
'DEDUCTED']) || $item[
'DEDUCTED'] !==
'Y')
399 $item[
'DEDUCTED'] =
'N';
403 isset($item[
'EXTRA_SERVICES']) && is_array($item[
'EXTRA_SERVICES'])
404 ? $item[
'EXTRA_SERVICES']
409 if (!empty($settableShipmentFields))
412 $product = $item[
'PRODUCT'] ??
null;
413 $storeId = (int)($item[
'DELIVERY_STORE_ID'] ?? 0);
414 $item = array_intersect_key($item, array_flip($settableShipmentFields));
415 if ($product !==
null)
417 $item[
'PRODUCT'] = $product;
424 $shipment = $shipmentCollection->createItem();
428 $shipment = $shipmentCollection->getItemById($shipmentId);
432 $this->errorsContainer->addError(
new Error(
Loc::getMessage(
"SALE_HLP_ORDERBUILDER_SHIPMENT_NOT_FOUND").
" - ".$shipmentId));
437 $defaultFields = $shipment->getFieldValues();
440 $systemShipment = $shipmentCollection->getSystemShipment();
441 $systemShipmentItemCollection = $systemShipment->getShipmentItemCollection();
446 !isset($item[
'PRODUCT'])
447 && $shipment->getId() <= 0
451 $basket = $this->order->getBasket();
455 $basketItems = $basket->getBasketItems();
456 foreach($basketItems as $product)
458 $systemShipmentItem = $systemShipmentItemCollection->getItemByBasketCode($product->getBasketCode());
460 if($product->isBundleChild() || !$systemShipmentItem || $systemShipmentItem->getQuantity() <= 0)
464 'AMOUNT' => $systemShipmentItem->getQuantity(),
465 'BASKET_CODE' => $product->getBasketCode(),
470 elseif (isset($item[
'PRODUCT']) && is_array($item[
'PRODUCT']))
472 $products = $item[
'PRODUCT'];
475 if($item[
'DEDUCTED'] ==
'Y' && $products !==
null)
477 $basketResult = $this->buildShipmentBasket($shipment, $products);
479 if(!$basketResult->isSuccess())
481 $this->errorsContainer->addErrors($basketResult->getErrors());
485 $shipmentFields = array(
486 'COMPANY_ID' => (isset($item[
'COMPANY_ID']) && intval($item[
'COMPANY_ID']) > 0) ? intval($item[
'COMPANY_ID']) : 0,
487 'DEDUCTED' => $item[
'DEDUCTED'] ??
'N',
488 'DELIVERY_DOC_NUM' => $item[
'DELIVERY_DOC_NUM'] ??
'',
489 'TRACKING_NUMBER' => $item[
'TRACKING_NUMBER'] ??
'',
490 'CURRENCY' => $this->order->getCurrency(),
491 'COMMENTS' => $item[
'COMMENTS'] ??
'',
494 if (!empty($item[
'IS_REALIZATION']))
496 $shipmentFields[
'IS_REALIZATION'] = $item[
'IS_REALIZATION'];
499 if (!empty($item[
'ACCOUNT_NUMBER']))
501 $shipmentFields[
'ACCOUNT_NUMBER'] = $item[
'ACCOUNT_NUMBER'];
504 if (!empty($item[
'XML_ID']))
506 $shipmentFields[
'XML_ID'] = $item[
'XML_ID'];
510 if ($statusId !==
'')
512 $shipmentFields[
'STATUS_ID'] = $statusId;
515 if (empty($item[
'COMPANY_ID']))
517 $shipmentFields[
'COMPANY_ID'] = $this->order->getField(
'COMPANY_ID');
520 if (empty($item[
'RESPONSIBLE_ID']))
522 $shipmentFields[
'RESPONSIBLE_ID'] = $this->order->getField(
'RESPONSIBLE_ID');
523 $shipmentFields[
'EMP_RESPONSIBLE_ID'] = $USER->GetID();
527 if (isset($item[
'PROFILE_ID']) && (
int)$item[
'PROFILE_ID'] > 0)
529 $deliveryId = (int)$item[
'PROFILE_ID'];
531 elseif (isset($item[
'DELIVERY_ID']))
533 $deliveryId = (int)$item[
'DELIVERY_ID'];
535 elseif ($shipment->getField(
'DELIVERY_ID'))
537 $deliveryId = $shipment->getField(
'DELIVERY_ID');
540 $shipmentFields[
'DELIVERY_ID'] = $deliveryId;
542 $dateFields = [
'DELIVERY_DOC_DATE',
'DATE_DEDUCTED',
'DATE_MARKED',
'DATE_CANCELED',
'DATE_RESPONSIBLE_ID'];
544 foreach($dateFields as $fieldName)
546 if(isset($item[$fieldName]))
548 if (is_string($item[$fieldName]))
552 $shipmentFields[$fieldName] =
new DateTime($item[$fieldName]);
554 catch (ObjectException $exception)
556 $this->errorsContainer->addError(
new Error(
'Wrong field "'.$fieldName.
'"'));
559 elseif ($item[$fieldName] instanceof Date)
561 $shipmentFields[$fieldName] = $item[$fieldName];
568 if($deliveryService = Delivery\Services\Manager::getObjectById($shipmentFields[
'DELIVERY_ID']))
570 if($deliveryService->isProfile())
572 $shipmentFields[
'DELIVERY_NAME'] = $deliveryService->getNameWithParent();
576 $shipmentFields[
'DELIVERY_NAME'] = $deliveryService->getName();
580 catch (ArgumentNullException $e)
582 $this->errorsContainer->addError(
new Error(
Loc::getMessage(
'SALE_HLP_ORDERBUILDER_DELIVERY_NOT_FOUND'),
'OB_DELIVERY_NOT_FOUND'));
586 $responsibleId = $shipment->getField(
'RESPONSIBLE_ID');
588 if (($item[
'RESPONSIBLE_ID'] ??
null) !== $responsibleId || empty($responsibleId))
590 if (isset($item[
'RESPONSIBLE_ID']))
592 $shipmentFields[
'RESPONSIBLE_ID'] = $item[
'RESPONSIBLE_ID'];
596 $shipmentFields[
'RESPONSIBLE_ID'] = $this->order->getField(
'RESPONSIBLE_ID');
599 if (!empty($shipmentFields[
'RESPONSIBLE_ID']))
601 $shipmentFields[
'EMP_RESPONSIBLE_ID'] = $USER->getID();
607 $shipment->setExtraServices($extraServices);
610 $setFieldsResult = $shipment->setFields($shipmentFields);
612 if(!$setFieldsResult->isSuccess())
614 $this->errorsContainer->addErrors($setFieldsResult->getErrors());
618 if (isset($item[
'PROPERTIES']) && is_array($item[
'PROPERTIES']))
621 $propCollection = $shipment->getPropertyCollection();
622 $res = $propCollection->setValuesFromPost($item, []);
624 if (!$res->isSuccess())
626 foreach ($res->getErrors() as $error)
629 new Main\
Error($error->getMessage(), $error->getCode(),
'SHIPMENT_PROPERTIES')
635 foreach ($propCollection as $propValue)
637 if ($propValue->isUtil())
642 $property = $propValue->getProperty();
643 $relatedDeliveryIds = (isset($property[
'RELATION']) && is_array($property[
'RELATION']))
646 $property[
'RELATION'],
649 return $item[
'ENTITY_TYPE'] ===
'D';
657 !empty($relatedDeliveryIds)
658 && !in_array($shipment->getField(
'DELIVERY_ID'), $relatedDeliveryIds)
664 $res = $propValue->verify();
665 if (!$res->isSuccess())
667 foreach ($res->getErrors() as $error)
670 new Main\
Error($error->getMessage(), $propValue->getPropertyId(),
'SHIPMENT_PROPERTIES')
675 $res = $propValue->checkRequiredValue($propValue->getPropertyId(), $propValue->getValue());
676 if (!$res->isSuccess())
678 foreach ($res->getErrors() as $error)
681 new Main\
Error($error->getMessage(), $propValue->getPropertyId(),
'SHIPMENT_PROPERTIES')
691 $shipment->setStoreId($storeId);
694 if($item[
'DEDUCTED'] ==
'N' && $products !==
null)
696 $basketResult = $this->buildShipmentBasket($shipment, $products);
698 if(!$basketResult->isSuccess())
700 $this->errorsContainer->addErrors($basketResult->getErrors());
704 $isCustomPrice =
false;
705 if (isset($item[
'CUSTOM_PRICE_DELIVERY']))
707 $isCustomPrice = $item[
'CUSTOM_PRICE_DELIVERY'] ===
'Y';
711 'CUSTOM_PRICE_DELIVERY' => $isCustomPrice ?
'Y' :
'N',
712 'PRICE_DELIVERY' => (float)str_replace(
',',
'.', $item[
'PRICE_DELIVERY'] ?? 0),
715 if (isset($item[
'ALLOW_DELIVERY']))
717 $fields[
'ALLOW_DELIVERY'] = $item[
'ALLOW_DELIVERY'] ===
'Y' ?
'Y' :
'N';
720 if (isset($item[
'BASE_PRICE_DELIVERY']))
722 $fields[
'BASE_PRICE_DELIVERY'] = (float)str_replace(
',',
'.', $item[
'BASE_PRICE_DELIVERY']);
725 $shipment = $this->
delegate->setShipmentPriceFields($shipment, $fields);
727 if($deliveryService && !empty($item[
'ADDITIONAL']))
729 $modifiedShipment = $deliveryService->processAdditionalInfoShipmentEdit($shipment, $item[
'ADDITIONAL']);
732 if ($modifiedShipment && get_class($modifiedShipment) ==
$registry->getShipmentClassName())
734 $shipment = $modifiedShipment;
742 protected function removeShipmentItems(\
Bitrix\
Sale\Shipment $shipment, $products, $idsFromForm)
744 $result =
new Result();
746 $shipmentItemCollection = $shipment->getShipmentItemCollection();
749 foreach ($shipmentItemCollection as $shipmentItem)
751 if (!array_key_exists($shipmentItem->getBasketCode(), $idsFromForm))
754 $r = $shipmentItem->delete();
755 if (!$r->isSuccess())
757 $result->addErrors($r->getErrors());
761 $shipmentItemStoreCollection = $shipmentItem->getShipmentItemStoreCollection();
762 if ($shipmentItemStoreCollection)
765 foreach ($shipmentItemStoreCollection as $shipmentItemStore)
767 $shipmentItemId = $shipmentItemStore->getId();
768 if (!isset($idsFromForm[$shipmentItem->getBasketCode()][
'BARCODE_IDS'][$shipmentItemId]))
770 $delResult = $shipmentItemStore->delete();
771 if (!$delResult->isSuccess())
773 $result->addErrors($delResult->getErrors());
795 public function buildShipmentBasket(&$shipment, $shipmentBasket)
798 $result =
new Result();
799 $shippingItems = array();
800 $idsFromForm = array();
801 $basket = $this->order->getBasket();
802 $shipmentItemCollection = $shipment->getShipmentItemCollection();
805 if(is_array($shipmentBasket))
808 foreach ($shipmentBasket as $items)
810 $items[
'QUANTITY'] = floatval(str_replace(
',',
'.', $items[
'QUANTITY']));
811 $items[
'AMOUNT'] = floatval(str_replace(
',',
'.', $items[
'AMOUNT']));
816 $items = $r->getData()[0];
820 $result->addErrors($r->getErrors());
826 if (!$basketItem = $basket->getItemById($items[
'BASKET_ID']))
828 $result->addError(
new Error(
829 Loc::getMessage(
'SALE_ORDER_SHIPMENT_BASKET_BASKET_ITEM_NOT_FOUND', array(
830 '#BASKET_ITEM_ID#' => $items[
'BASKET_ID'],
832 'PROVIDER_UNRESERVED_SHIPMENT_ITEM_WRONG_BASKET_ITEM')
837 $basketCode = $basketItem->getBasketCode();
841 $basketCode = $items[
'BASKET_CODE'];
842 if(!$basketItem = $basket->getItemByBasketCode($basketCode))
844 $result->addError(
new Error(
845 Loc::getMessage(
'SALE_ORDER_SHIPMENT_BASKET_BASKET_ITEM_NOT_FOUND', array(
846 '#BASKET_ITEM_ID#' => $basketCode,
848 'PROVIDER_UNRESERVED_SHIPMENT_ITEM_WRONG_BASKET_ITEM')
854 $isSupportedMarkingCode =
false;
855 if (isset($items[
'IS_SUPPORTED_MARKING_CODE']))
857 $isSupportedMarkingCode = $items[
'IS_SUPPORTED_MARKING_CODE'] ===
'Y';
861 'BASKET_CODE' => $basketCode,
862 'AMOUNT' => $items[
'AMOUNT'] ?? 0,
863 'ORDER_DELIVERY_BASKET_ID' => $items[
'ORDER_DELIVERY_BASKET_ID'] ?? 0,
864 'IS_SUPPORTED_MARKING_CODE' => $isSupportedMarkingCode ?
'Y' :
'N',
866 if (array_key_exists(
'XML_ID', $items))
868 $tmp[
'XML_ID'] = $items[
'XML_ID'];
870 $idsFromForm[$basketCode] = array();
873 isset($items[
'BARCODE_INFO'])
874 && $items[
'BARCODE_INFO']
875 && ($useStoreControl || $isSupportedMarkingCode)
878 foreach ($items[
'BARCODE_INFO'] as $item)
880 if (!$basketItem->isReservableItem())
882 $shippingItems[] = $tmp;
886 $barcodeQuantity = ($basketItem->isBarcodeMulti() || $basketItem->isSupportedMarkingCode()) ? 1 : $item[
'QUANTITY'];
887 $barcodeStoreId = $item[
'STORE_ID'];
889 $tmp[
'BARCODE'] = array(
890 'ORDER_DELIVERY_BASKET_ID' => $items[
'ORDER_DELIVERY_BASKET_ID'] ?? 0,
891 'STORE_ID' => $barcodeStoreId,
892 'QUANTITY' => $barcodeQuantity,
895 $tmp[
'BARCODE_INFO'] = [
896 $item[
'STORE_ID'] => [
897 'STORE_ID' => (int)$barcodeStoreId,
898 'QUANTITY' => (
float)$barcodeQuantity,
903 if ($item[
'BARCODE'])
905 foreach ($item[
'BARCODE'] as $barcode)
907 $barcode[
'ID'] = (int)($barcode[
'ID'] ?? 0);
909 $tmp[
'BARCODE_INFO'][$barcodeStoreId][
'BARCODE'] = [
$barcode];
911 if (isset($barcode[
'MARKING_CODE']))
913 $barcode[
'MARKING_CODE'] = (string)$barcode[
'MARKING_CODE'];
920 $idsFromForm[$basketCode][
'BARCODE_IDS'][
$barcode[
'ID']] =
true;
922 if ($barcode[
'ID'] > 0)
924 $tmp[
'BARCODE'][
'ID'] =
$barcode[
'ID'];
928 unset($tmp[
'BARCODE'][
'ID']);
931 $tmp[
'BARCODE'][
'BARCODE'] = (string)$barcode[
'VALUE'];
932 $tmp[
'BARCODE'][
'MARKING_CODE'] =
$barcode[
'MARKING_CODE'];
934 $shippingItems[] = $tmp;
938 elseif (!$basketItem->isBarcodeMulti() && !$basketItem->isSupportedMarkingCode())
940 $shippingItems[] = $tmp;
945 if ($basketItem->isBarcodeMulti() || $basketItem->isSupportedMarkingCode())
947 while ($barcodeCount < $item[
'QUANTITY'])
949 unset($tmp[
'BARCODE'][
'ID']);
950 $tmp[
'BARCODE'][
'BARCODE'] =
'';
951 $tmp[
'BARCODE'][
'MARKING_CODE'] =
'';
952 $shippingItems[] = $tmp;
960 $shippingItems[] = $tmp;
966 $r = $this->removeShipmentItems($shipment, $shipmentBasket, $idsFromForm);
968 $result->addErrors($r->getErrors());
973 foreach ($shippingItems as $shippingItem)
975 if ((
int)$shippingItem[
'ORDER_DELIVERY_BASKET_ID'] <= 0)
977 $basketCode = $shippingItem[
'BASKET_CODE'];
979 $basketItem = $this->order->getBasket()->getItemByBasketCode($basketCode);
982 $shipmentItem = $shipmentItemCollection->createItem($basketItem);
984 if ($shipmentItem ===
null)
994 unset($shippingItem[
'BARCODE'][
'ORDER_DELIVERY_BASKET_ID']);
998 $shipmentItem = $shipmentItemCollection->getItemById($shippingItem[
'ORDER_DELIVERY_BASKET_ID']);
1002 $basketItem = $shipmentItem->getBasketItem();
1007 $systemShipment = $shipment->getCollection()->getSystemShipment();
1009 $systemShipmentItemCollection = $systemShipment->getShipmentItemCollection();
1011 $shipmentItem = $systemShipmentItemCollection->getItemById($shippingItem[
'ORDER_DELIVERY_BASKET_ID']);
1015 $basketItem = $shipmentItem->getBasketItem();
1016 $shipmentItem = $shipmentItemCollection->createItem($basketItem);
1017 $shipmentItem->setField(
'QUANTITY', $shipmentItem->getField(
'QUANTITY'));
1024 '#ID#' => $shippingItem[
'ORDER_DELIVERY_BASKET_ID'],
1034 if ($shippingItem[
'AMOUNT'] <= 0)
1038 Loc::getMessage(
'SALE_ORDER_SHIPMENT_BASKET_ERROR_QUANTITY', array(
'#BASKET_ITEM#' => $basketItem->getField(
'NAME'))),
1039 'BASKET_ITEM_'.$basketItem->getBasketCode()
1046 if(!$r->isSuccess())
1047 $result->addErrors($r->getErrors());
1049 if (array_key_exists(
'XML_ID', $shippingItem))
1051 $setFieldResult = $shipmentItem->setField(
'XML_ID', $shippingItem[
'XML_ID']);
1052 if (!$setFieldResult->isSuccess())
1054 $result->addErrors($setFieldResult->getErrors());
1061 $hasMeaningfulFields = $shipmentItemCollection->hasMeaningfulField();
1064 $r = $shipmentItemCollection->doFinalAction($hasMeaningfulFields);
1065 if (!$r->isSuccess())
1067 $result->addErrors($r->getErrors());
1077 return $result->setData([$items]);
1083 if ($shipmentItem->
getQuantity() < $params[
'AMOUNT'])
1085 $this->order->setMathActionOnly(
true);
1086 $setFieldResult = $shipmentItem->
setField(
'QUANTITY', $params[
'AMOUNT']);
1087 $this->order->setMathActionOnly(
false);
1089 if (!$setFieldResult->isSuccess())
1091 $result->addErrors($setFieldResult->getErrors());
1095 $r = $this->setBarcodeShipmentItem($shipmentItem, $params);
1097 if($r->isSuccess() ==
false)
1099 $result->addErrors($r->getErrors());
1102 $setFieldResult = $shipmentItem->
setField(
'QUANTITY', $params[
'AMOUNT']);
1104 if (!$setFieldResult->isSuccess())
1106 $result->addErrors($setFieldResult->getErrors());
1112 protected function setBarcodeShipmentItem(
ShipmentItem $shipmentItem, array $params)
1120 !empty($params[
'BARCODE'])
1121 && ($useStoreControl || $params[
'IS_SUPPORTED_MARKING_CODE'] ===
'Y' )
1122 && $basketItem->isReservableItem()
1125 $barcode = $params[
'BARCODE'];
1128 $shipmentItemStoreCollection = $shipmentItem->getShipmentItemStoreCollection();
1129 if ($shipmentItemStoreCollection)
1131 if (!$basketItem->isBarcodeMulti() && !$basketItem->isSupportedMarkingCode())
1134 $r = $shipmentItemStoreCollection->setBarcodeQuantityFromArray($params);
1135 if (!$r->isSuccess())
1137 $result->addErrors($r->getErrors());
1141 if (isset($barcode[
'ID']) && intval($barcode[
'ID']) > 0)
1144 if ($shipmentItemStore = $shipmentItemStoreCollection->getItemById($barcode[
'ID']))
1146 unset($barcode[
'ID']);
1147 $setFieldResult = $shipmentItemStore->setFields($barcode);
1149 if (!$setFieldResult->isSuccess())
1151 $result->addErrors($setFieldResult->getErrors());
1157 $shipmentItemStore = $shipmentItemStoreCollection->createItem($basketItem);
1158 $setFieldResult = $shipmentItemStore->setFields($barcode);
1159 if (!$setFieldResult->isSuccess())
1161 $result->addErrors($setFieldResult->getErrors());
1172 $innerPaySystem = PaySystem\Manager::getObjectById(PaySystem\Manager::getInnerPaySystemId());
1174 $paymentCollection = $this->order->getPaymentCollection();
1175 $payment = $paymentCollection->createItem($innerPaySystem);
1176 $payment->setField(
'SUM', $this->order->getPrice());
1185 $paymentCollection = $this->order->getPaymentCollection();
1188 foreach($this->formData[
"PAYMENT"] as $paymentData)
1190 if(!isset($paymentData[
'ID']))
1193 $payment = $paymentCollection->getItemById($paymentData[
'ID']);
1195 if ($payment ==
null)
1198 $paymentIds[] = $payment->getId();
1201 foreach ($paymentCollection as $payment)
1203 if(!in_array($payment->getId(), $paymentIds))
1205 $r = $payment->delete();
1206 if (!$r->isSuccess())
1208 $this->errorsContainer->addErrors($r->getErrors());
1222 return empty($this->formData[
"PAYMENT"]) || !is_array($this->formData[
"PAYMENT"]);
1233 public function buildPayments()
1238 if ($isEmptyPaymentData)
1240 $this->formData[
'PAYMENT'] = [];
1248 if($isEmptyPaymentData && $this->
getOrder()->isNew())
1256 $this->errorsContainer->addError(
new Error(
'Payments remove - error'));
1257 throw new BuildingException();
1260 $paymentCollection = $this->order->getPaymentCollection();
1262 foreach($this->formData[
"PAYMENT"] as $paymentData)
1264 $paymentId = (int)($paymentData[
'ID'] ?? 0);
1265 $isNew = ($paymentId <= 0);
1267 $products = $paymentData[
'PRODUCT'] ?? [];
1271 if(count($settablePaymentFields)>0)
1272 $paymentData = array_intersect_key($paymentData, array_flip($settablePaymentFields));
1277 $paymentItem = $paymentCollection->createItem();
1278 if (isset($paymentData[
'CURRENCY']) && !empty($paymentData[
'CURRENCY']) && $paymentData[
'CURRENCY'] !== $this->order->getCurrency())
1280 $paymentData[
"SUM"] = \CCurrencyRates::ConvertCurrency($paymentData[
"SUM"], $paymentData[
"CURRENCY"], $this->order->getCurrency());
1281 $paymentData[
'CURRENCY'] = $this->order->getCurrency();
1286 $paymentItem = $paymentCollection->getItemById($paymentId);
1290 $this->errorsContainer->addError(
new Error(
Loc::getMessage(
"SALE_HLP_ORDERBUILDER_PAYMENT_NOT_FOUND").
" - ".$paymentId));
1295 $isReturn = (isset($paymentData[
'IS_RETURN']) && ($paymentData[
'IS_RETURN'] ==
'Y' || $paymentData[
'IS_RETURN'] ==
'P'));
1298 if((
int)$paymentData[
'PAY_SYSTEM_ID'] > 0)
1300 $psService = PaySystem\Manager::getObjectById((
int)$paymentData[
'PAY_SYSTEM_ID']);
1302 $paymentData[
'PAY_SYSTEM_NAME'] = ($psService) ? $psService->getField(
'NAME') :
'';
1305 if (isset($paymentData[
'COMPANY_ID']))
1307 $paymentData[
'COMPANY_ID'] = (int)$paymentData[
'COMPANY_ID'];
1310 if (isset($paymentData[
'PAID']))
1312 $paymentFields[
'PAID'] = ($paymentData[
'PAID'] ===
'Y') ?
'Y' :
'N';
1313 unset($paymentData[
'PAID']);
1318 if(empty($paymentData[
'COMPANY_ID']))
1320 $paymentData[
'COMPANY_ID'] = $this->order->getField(
'COMPANY_ID');
1323 if(empty($paymentData[
'RESPONSIBLE_ID']))
1325 $paymentData[
'RESPONSIBLE_ID'] = $this->order->getField(
'RESPONSIBLE_ID');
1326 $paymentData[
'EMP_RESPONSIBLE_ID'] = $USER->GetID();
1330 $dateFields = [
'DATE_PAID',
'DATE_PAY_BEFORE',
'DATE_BILL',
'PAY_RETURN_DATE',
'PAY_VOUCHER_DATE'];
1332 foreach($dateFields as $fieldName)
1334 if(isset($paymentData[$fieldName]) && is_string($paymentData[$fieldName]))
1338 $paymentData[$fieldName] =
new Date($paymentData[$fieldName]);
1340 catch (ObjectException $exception)
1342 $this->errorsContainer->addError(
new Error(
'Wrong field "'.$fieldName.
'"'));
1348 if($paymentItem->isPaid()
1349 && isset($paymentData[
'SUM'])
1350 && abs(floatval($paymentData[
'SUM']) - floatval($paymentItem->getSum())) > 0.001)
1352 $this->errorsContainer->addError(
new Error(
Loc::getMessage(
"SALE_HLP_ORDERBUILDER_ERROR_PAYMENT_SUM")));
1361 if(isset($paymentData[
'SUM']))
1363 $paymentData[
'SUM'] = (float)str_replace(
',',
'.', $paymentData[
'SUM']);
1366 if(isset($paymentData[
'RESPONSIBLE_ID']))
1368 $paymentData[
'RESPONSIBLE_ID'] = !empty($paymentData[
'RESPONSIBLE_ID']) ? $paymentData[
'RESPONSIBLE_ID'] : $USER->GetID();
1370 if($paymentData[
'RESPONSIBLE_ID'] != $paymentItem->getField(
'RESPONSIBLE_ID'))
1374 $paymentData[
'EMP_RESPONSIBLE_ID'] = $USER->GetID();
1381 if($paymentItem->isInner() && isset($paymentData[
'SUM']) && $paymentData[
'SUM'] === 0)
1383 unset($paymentData[
'SUM']);
1386 $setResult = $paymentItem->setFields($paymentData);
1388 if(!$setResult->isSuccess())
1390 $this->errorsContainer->addErrors($setResult->getErrors());
1395 $this->buildPayableItems($paymentItem, $products);
1398 if($isReturn && $paymentData[
'IS_RETURN'])
1400 $setResult = $paymentItem->setReturn($paymentData[
'IS_RETURN']);
1402 if(!$setResult->isSuccess())
1404 $this->errorsContainer->addErrors($setResult->getErrors());
1408 if(!empty($paymentFields[
'PAID']))
1410 $setResult = $paymentItem->setPaid($paymentFields[
'PAID']);
1412 if(!$setResult->isSuccess())
1414 $this->errorsContainer->addErrors($setResult->getErrors());
1434 public function buildPayableItems(Payment $payment, array $payableItems): Result
1436 $result =
new Result();
1438 $basket = $this->order->getBasket();
1439 $payableItemCollection = $payment->getPayableItemCollection();
1441 foreach ($payableItems as $item)
1443 $payableItem =
null;
1445 if (isset($item[
'BASKET_CODE']))
1448 $basketItem = $basket->getItemByBasketCode($item[
'BASKET_CODE']);
1451 $payableItem = $payableItemCollection->createItemByBasketItem($basketItem);
1454 elseif (isset($item[
'DELIVERY_ID']))
1457 foreach ($this->order->getShipmentCollection()->getNotSystemItems() as $shipment)
1460 $shipment->getId() === 0
1461 && (
int)$item[
'DELIVERY_ID'] === $shipment->getDeliveryId()
1464 $payableItem = $payableItemCollection->createItemByShipment($shipment);
1469 if ($payableItem ===
null)
1474 $quantity = floatval(str_replace(
',',
'.', $item[
'QUANTITY']));
1476 $payableItem->setField(
'QUANTITY', $quantity);
1484 if(!isset($this->formData[
"TRADE_BINDINGS"]))
1494 if(isset($this->formData[
"TRADE_BINDINGS"]) && count($this->formData[
"TRADE_BINDINGS"])>0)
1496 $tradeBindingCollection = $this->order->getTradeBindingCollection();
1498 foreach($this->formData[
"TRADE_BINDINGS"] as $fields)
1500 $tradingPlatformId = (int)($fields[
'TRADING_PLATFORM_ID'] ?? 0);
1501 if ($tradingPlatformId === 0)
1510 $id = (int)($fields[
'ID'] ?? 0);
1511 $isNew = ($id <= 0);
1515 $binding = $tradeBindingCollection->createItem();
1519 $binding = $tradeBindingCollection->getItemById($id);
1523 $this->errorsContainer->addError(
new Error(
'Can\'t find Trade Binding with id:"'.$id.
'"',
'TRADE_BINDING_NOT_EXISTS'));
1530 $r = $binding->setFields($fields);
1533 if(!$r->isSuccess())
1534 $this->errorsContainer->addErrors($r->getErrors());
1545 $platformFields = TradingPlatformTable::getById($id)->fetchAll();
1547 if (!isset($platformFields[0]))
1549 $r->addError(
new Error(
'tradingPlatform is not exists'));
1559 $tradeBindingCollection = $this->order->getTradeBindingCollection();
1562 foreach($this->formData[
"TRADE_BINDINGS"] as $tradeBinding)
1564 if(!isset($tradeBinding[
'ID']))
1567 $binding = $tradeBindingCollection->getItemById($tradeBinding[
'ID']);
1569 if ($binding ==
null)
1572 $internalIx[] = $binding->getId();
1575 foreach ($tradeBindingCollection as $binding)
1577 if(!in_array($binding->getId(), $internalIx))
1579 $r = $binding->delete();
1580 if (!$r->isSuccess())
1582 $this->errorsContainer->addErrors($r->getErrors());
1594 if($this->isStartField)
1596 $hasMeaningfulFields = $this->order->hasMeaningfulField();
1597 $r = $this->order->doFinalAction($hasMeaningfulFields);
1599 if(!$r->isSuccess())
1601 $this->errorsContainer->addErrors($r->getErrors());
1625 if($fieldName <>
'')
1627 $result = $this->formData[$fieldName] ??
null;
1645 reset($personTypes);
1646 return key($personTypes);
1651 static $result = array();
1653 if(!isset($result[$siteId]))
1655 $result[$siteId] = array();
1657 $res = \Bitrix\Sale\Internals\PersonTypeTable::getList(array(
1658 'order' => array(
'SORT' =>
'ASC',
'NAME' =>
'ASC'),
1659 'filter' => array(
'=ACTIVE' =>
'Y',
'=PERSON_TYPE_SITE.SITE_ID' => $siteId),
1662 while ($personType = $res->fetch())
1664 $result[$siteId][$personType[
"ID"]] = htmlspecialcharsbx($personType[
"NAME"]).
" [".$personType[
"ID"].
"]";
1668 return $result[$siteId];
1673 $userId = (int)($this->formData[
"USER_ID"] ?? 0);
1684 $userId = \CSaleUser::GetAnonymousUserID();
1691 if ($userId > 0 && empty($this->formData[
"USER_ID"]))
1693 $this->formData[
"USER_ID"] = $userId;
1710 $orderProps = $this->order->getPropertyCollection();
1712 if ($email = $orderProps->getUserEmail())
1714 $email = $email->getValue();
1717 if ($name = $orderProps->getPayerName())
1719 $name = $name->getValue();
1722 if ($phone = $orderProps->getPhone())
1724 $phone = $phone->getValue();
1729 $userId = $this->searchExistingUser($email, $phone);
1732 if (!isset($userId))
1734 $userId = $this->searchExistingUser($email, $phone);
1737 if (!isset($userId))
1739 $userId = \CSaleUser::DoAutoRegisterUser(
1742 $this->formData[
'SITE_ID'],
1745 'PERSONAL_PHONE' => $phone,
1746 'PHONE_NUMBER' => $phone,
1750 if (!empty($errors))
1752 foreach ($errors as $val)
1754 $this->errorsContainer->addError(
new Error($val[
'TEXT'], 0,
'USER'));
1761 $USER->Authorize($userId);
1776 private function searchExistingUser($email, $phone): ?int
1778 $existingUserId =
null;
1782 $res = Main\UserTable::getRow([
1789 if (isset($res[
'ID']))
1791 $existingUserId = (int)$res[
'ID'];
1795 if (!$existingUserId && !empty($phone))
1797 $normalizedPhone = NormalizePhone($phone);
1798 $normalizedPhoneForRegistration = Main\UserPhoneAuthTable::normalizePhoneNumber($phone);
1800 if (!empty($normalizedPhone))
1802 $res = Main\UserTable::getRow([
1807 '=PHONE_AUTH.PHONE_NUMBER' => $normalizedPhoneForRegistration,
1808 '=PERSONAL_PHONE' => $normalizedPhone,
1809 '=PERSONAL_MOBILE' => $normalizedPhone,
1814 if (isset($res[
'ID']))
1816 $existingUserId = (int)$res[
'ID'];
1821 return $existingUserId;