1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
ordercreate.php
См. документацию.
1<?
2namespace Sale\Handlers\Delivery\Additional\DeliveryRequests\RusPost\Requests;
3
4use Bitrix\Main\Error;
5use Bitrix\Main\Web\HttpClient;
6use Bitrix\Sale\Delivery\Requests;
7use Bitrix\Main\Localization\Loc;
8use Bitrix\Sale\Delivery\Packing\Packer;
9use Sale\Handlers\Delivery\AdditionalHandler;
10use Sale\Handlers\Delivery\Additional\DeliveryRequests\RusPost\Reference;
11use Sale\Handlers\Delivery\Additional\DeliveryRequests\RusPost\Handler;
12
13Loc::loadMessages(__FILE__);
14
21class OrderCreate extends Base
22{
23 protected $path = "/1.0/user/backlog";
24 protected $type = HttpClient::HTTP_PUT;
26 protected $deliveryService = null;
27
33 protected function convertResponse($rawData, $requestData)
34 {
35 $result = new Requests\Result();
36 $errorPositions = array();
38 $createResults = array();
39
40 if(is_array($rawData['errors']))
41 {
42 foreach($rawData['errors'] as $error)
43 {
44 if(!isset($requestData[$error['position']]['order-num']))
45 continue;
46
47 $internalId = $requestData[$error['position']]['order-num'];
48
49 if(!isset($createResults[$internalId]))
50 $createResults[$internalId] = new Requests\ShipmentResult($internalId, '');
51
52 $errorPositions[] = $error['position'];
53
54 if(is_array($error['error-codes']))
55 {
56 foreach($error['error-codes'] as $errorcode)
57 {
58 $message = Reference::getErrorDescription($errorcode['code'], 'PUT /1.0/user/backlog');
59
60 if(!empty($errorcode['details']))
61 $details = $errorcode['details'];
62 elseif(!empty($errorcode['description']))
63 $details = $errorcode['description'];
64 else
65 $details = '';
66
67 if(!empty($details))
68 {
69 if($errorcode['code'] == 'ILLEGAL_MAIL_CATEGORY')
70 $message = str_replace('%s', Reference::getRpoCategory($details), $message);
71 else
72 $message .= ' ('.$details.')';
73 }
74
75 $createResults[$internalId]->addError(new Error($message));
76 }
77 }
78 }
79 }
80
81 $idsMap = $this->getShipmentsMap($rawData['result-ids'], $errorPositions, $requestData);
82 $idsMapFlipped = array_flip($idsMap);
83
84 if(is_array($rawData['result-ids']))
85 {
86 foreach($rawData['result-ids'] as $externalId)
87 {
88 if(!isset($idsMapFlipped[$externalId]))
89 continue;
90
91 $internalId = $idsMapFlipped[$externalId];
92
93 if(!isset($createResults[$internalId]))
94 $createResults[$internalId] = new Requests\ShipmentResult($internalId, $externalId);
95 }
96 }
97
98 $result->setResults($createResults);
99 return $result;
100 }
101
108 protected function getShipmentsMap($successIds, $errorPositions, $requestData)
109 {
110 $idsMap = array();
111
112 if(empty($successIds) || !is_array($successIds))
113 return array();
114
115 $shift = 0;
116
117 foreach($requestData as $position => $request)
118 {
119 if(!empty($errorPositions) && in_array($position, $errorPositions))
120 {
121 $shift++;
122 continue;
123 }
124
125 if(!empty($requestData[$position]['order-num']) && !empty($successIds[$position - $shift]))
126 $idsMap[$request['order-num']] = $successIds[$position - $shift];
127 }
128
129 return $idsMap;
130 }
131
136 protected function normalizeAddresses(array $addresses)
137 {
138 $requestData = array();
139
140 foreach($addresses as $id => $address)
141 {
142 $address = str_replace(["\n", "\t", "\r"], " ", $address);
143
144 $requestData[] = array(
145 'id' => $id,
146 'original-address' => $address
147 );
148 }
149
151 $deliveryRequest = $this->deliveryService->getDeliveryRequestHandler();
152 return $deliveryRequest->send('CLEAN_ADDRESS', $requestData);
153 }
154
159 protected function normalizeFios(array $fios)
160 {
161 $requestData = array();
162
163 foreach($fios as $id => $fio)
164 {
165 $requestData[] = array(
166 'id' => $id,
167 'original-fio' => $fio
168 );
169 }
170
172 $deliveryRequest = $this->deliveryService->getDeliveryRequestHandler();
173 return $deliveryRequest->send('NORMALIZE_FIO', $requestData);
174 }
175
180 protected function isAddressGood(array $address)
181 {
182 $quality = $address['quality-code'] == 'GOOD'
183 || $address['quality-code'] == 'POSTAL_BOX'
184 || $address['quality-code'] == 'ON_DEMAND'
185 || $address['quality-code'] == 'UNDEF_05';
186
187 $valid = $address['validation-code'] == 'VALIDATED'
188 || $address['validation-code'] == 'OVERRIDDEN'
189 || $address['validation-code'] == 'CONFIRMED_MANUALLY';
190
191 return $quality && $valid;
192 }
193
199 public function createBody(array $shipmentIds, array $additional = array())
200 {
201 $result = new Requests\Result();
202 $resultData = array();
203 $shipments = Requests\Helper::getShipmentsByIds($shipmentIds);
204 $rpoCategory = Reference::getRpoCategoriesMap();
205 $qualityCodes = Reference::getQualityCodesList();
206 $addresses = array();
207 $fios = array();
208 $notValidShipmentIds = array();
209
211 foreach($shipments as $shipment)
212 {
213 $shipmentParams = AdditionalHandler::getShipmentParams($shipment, $this->deliveryService->getServiceType());
214 $deliveryConfig = $shipment->getDelivery() ? $shipment->getDelivery()->getConfig() : [];
215 $shipmentId = $shipment->getId();
216
217 $mailType = $deliveryConfig['MAIN']['ITEMS']['OTPRAVKA_RPO']['VALUE'];
218
219 if($mailType == '')
220 {
221 $shpResult = new Requests\ShipmentResult($shipmentId);
222 $shpResult->addError(
223 new Error(
224 Loc::getMessage(
225 'SALE_DLVRS_ADD_DREQ_ROC_NOT_SUPPORTED',
226 array(
227 '#DELIVERY_PROFILE_LINK#' =>
228 Requests\Helper::getDeliveryEditLink($shipment->getDeliveryId(), $shipmentParams['DELIVERY_SERVICE_CONFIG']['MAIN']['NAME']),
229 )
230 )));
231
232 $result->addResult($shpResult);
233 continue;
234 }
235
236 $shpDim = array();
237
238 foreach($shipmentParams['ITEMS'] as $item)
239 {
240 if(!empty($item['DIMENSIONS']) && is_array($item['DIMENSIONS']))
241 {
242 if(intval($item['DIMENSIONS']['HEIGHT']) > 0
243 && intval($item['DIMENSIONS']['WIDTH']) > 0
244 && intval($item['DIMENSIONS']['LENGTH']) > 0)
245 {
246 for($i=0; $i < $item['QUANTITY']; $i++)
247 {
248 $shpDim[] = array(
249 intval($item['DIMENSIONS']['LENGTH']),
250 intval($item['DIMENSIONS']['WIDTH']),
251 intval($item['DIMENSIONS']['HEIGHT'])
252 );
253 }
254 }
255 }
256 }
257
258 $mailCategory = $rpoCategory[$shipmentParams['DELIVERY_SERVICE_CONFIG']['MAIN']['CATEGORY']];
259
260 if($mailCategory == '')
261 $mailCategory = 'ORDINARY';
262
263 $item = array(
264 'address-type-to' => 'DEFAULT',
265 //'brand-name' => ''
266 //'envelope-type' =>
267 'fragile' => isset($shipmentParams['EXTRA_SERVICES'][4]) && $shipmentParams['EXTRA_SERVICES'][4] =='Y', // 4 - code of extra service fragile
268 'mail-category' => $mailCategory,
269 'order-num' => strval($shipmentParams['SHIPMENT_ID']),
270 'sms-notice-recipient' => isset($shipmentParams['EXTRA_SERVICES'][42]) && $shipmentParams['EXTRA_SERVICES'][4] == 'Y' ? 1 : 0,
271 'mail-direct' => 643, //Russia
272 'mail-type' => $mailType
273 );
274
275 $item['courier'] = isset($shipmentParams['EXTRA_SERVICES'][26]) && $shipmentParams['EXTRA_SERVICES'][26] == 'Y';
276
277 if(isset($shipmentParams['EXTRA_SERVICES'][1]))
278 {
279 if($shipmentParams['EXTRA_SERVICES'][1] == "1")
280 $item['with-simple-notice'] = true;
281 elseif($shipmentParams['EXTRA_SERVICES'][1] == "2")
282 $item['with-order-of-notice'] = true;
283 }
284
285 if(intval($shipmentParams['WEIGHT']) > 0)
286 {
287 $item['mass'] = intval($shipmentParams['WEIGHT']);
288 }
289 else
290 {
291 $dlvConfig = $this->deliveryService->getConfigValues();
292
293 if(intval($dlvConfig['MAIN']['WEIGHT_DEFAULT']) > 0)
294 $item['mass'] = intval($dlvConfig['MAIN']['WEIGHT_DEFAULT']);
295 }
296
297 if(!empty($shpDim))
298 {
299 $dimensions = Packer::countMinContainerSize($shpDim);
300
301 $item['dimension'] = array(
302 'length' => $dimensions[0]/10, //milimeters ->santimeters
303 'width' => $dimensions[1]/10,
304 'height' => $dimensions[2]/10
305 );
306 }
307 else
308 {
309 $dlvConfig = $this->deliveryService->getConfigValues();
310
311 if(intval($dlvConfig['MAIN']['LENGTH_DEFAULT']) > 0
312 && intval($dlvConfig['MAIN']['WIDTH_DEFAULT']) > 0
313 && intval($dlvConfig['MAIN']['HEIGHT_DEFAULT']) > 0)
314 {
315 $item['dimension'] = array(
316 'length' => intval($dlvConfig['MAIN']['LENGTH_DEFAULT']/10), //milimeters ->santimeters
317 'width' => intval($dlvConfig['MAIN']['WIDTH_DEFAULT']/10),
318 'height' => intval($dlvConfig['MAIN']['HEIGHT_DEFAULT']/10)
319 );
320 }
321 }
322
323 $OVERSIZED_DIM = 60;
324 $OVERSIZED_DIM_SUM = 120;
325
326 if($item['dimension']['length'] < $OVERSIZED_DIM
327 && $item['dimension']['width'] < $OVERSIZED_DIM
328 && $item['dimension']['height'] < $OVERSIZED_DIM
329 && array_sum($item['dimension']) < $OVERSIZED_DIM_SUM
330 )
331 {
332 unset($item['dimension']);
333 }
334
335 if(!empty($additional['OPS']))
336 $item['postoffice-code'] = $additional['OPS'];
337
338 if(!empty($shipmentParams['PHONE']))
339 $item['tel-address'] = preg_replace('/[^\d]/','',$shipmentParams['PHONE']);
340
341 $price = ($shipmentParams['PRICE'] + $shipmentParams['PRICE_DELIVERY']) * 100; //rubles -> kopeck
342
343 if($shipmentParams['DELIVERY_SERVICE_CONFIG']['MAIN']['CATEGORY'] == 2 || $shipmentParams['DELIVERY_SERVICE_CONFIG']['MAIN']['CATEGORY'] == 4)
344 $item['insr-value'] = $price; // https://www.pochta.ru/support/post-rules/valuable-departure
345
346 if($shipmentParams['DELIVERY_SERVICE_CONFIG']['MAIN']['CATEGORY'] == 4)
347 $item['payment'] = $price;
348
349 if (!empty($shipmentParams['LOCATION_TO_TYPES']['REGION']))
350 {
351 $item['region-to'] = $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES']['REGION']);
352 }
353
354 if (!empty($shipmentParams['LOCATION_TO_TYPES']['SUBREGION']))
355 {
356 $item['area-to'] = $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES']['SUBREGION']);
357 }
358
359 if (!empty($shipmentParams['LOCATION_TO_TYPES']['STREET']))
360 {
361 $item['street-to'] = $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES']['STREET']);
362 }
363
364 if (!empty($shipmentParams['LOCATION_TO_TYPES']['VILLAGE']))
365 {
366 $item['place-to'] = $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES']['VILLAGE']);
367 }
368 elseif (!empty($shipmentParams['LOCATION_TO_TYPES']['CITY']))
369 {
370 $item['place-to'] = $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES']['CITY']);
371 }
372
373 if (!empty($shipmentParams['ZIP_TO']))
374 {
375 $item['index-to'] = $shipmentParams['ZIP_TO'];
376 }
377
378 $address = '';
379 $types = ['COUNTRY', 'REGION', 'SUBREGION', 'CITY', 'VILLAGE', 'STREET'];
380
381 foreach($types as $type)
382 {
383 if (empty($shipmentParams['LOCATION_TO_TYPES'][$type]))
384 {
385 continue;
386 }
387
388 if ($address <> '')
389 {
390 $address .= ', ';
391 }
392
393 $address .= $this->convertLocationTypeToString($shipmentParams['LOCATION_TO_TYPES'][$type]);
394 }
395
396 if(!empty($shipmentParams['ADDRESS']))
397 {
398 if($address <> '')
399 $address .= ', ';
400
401 $address .= $shipmentParams['ADDRESS'];
402 }
403
404 $addresses[$shipment->getId()] = $address;
405 $fios[$shipment->getId()] = $shipmentParams['PAYER_NAME'];
406 $resultData[$shipment->getId()] = $item;
407 }
408
409 if(!empty($resultData))
410 {
411 $normalizeResult = $this->normalizeAddresses($addresses);
412
413 if(!$normalizeResult->isSuccess())
414 {
415 $result->addErrors($normalizeResult->getErrors());
416 return $result;
417 }
418 else
419 {
420 foreach($normalizeResult->getData() as $address)
421 {
422 $shipmentId = $address['id'];
423
424 if(!isset($resultData[$shipmentId]))
425 continue;
426
427 if(!$this->isAddressGood($address))
428 {
429 $shpResult = new Requests\ShipmentResult($shipmentId);
430 $shpResult->addError(new Error(
431 $qualityCodes[$address['quality-code']].'. '.Loc::getMessage('SALE_DLVRS_ADD_DREQ_ROC_02').'. "'.
432 print_r($address['original-address'], true).'"',
433 $shipmentId
434 ));
435 $result->addResult($shpResult);
436 $notValidShipmentIds[$shipmentId] = true;
437 continue;
438 }
439
440 if(!empty($address['area']) && empty($resultData[$shipmentId]['area-to']))
441 $resultData[$shipmentId]['area-to'] = $address['area'];
442
443 if(!empty($address['house']))
444 $resultData[$shipmentId]['house-to'] = $address['house'];
445
446 if(!empty($address['place']))
447 $resultData[$shipmentId]['place-to'] = $address['place'];
448
449 if(!empty($address['region']) && empty($resultData[$shipmentId]['region-to']))
450 $resultData[$shipmentId]['region-to'] = $address['region'];
451
452 if(!empty($address['room']))
453 $resultData[$shipmentId]['room-to'] = $address['room'];
454
455 if(!empty($address['slash']))
456 $resultData[$shipmentId]['slash-to'] = $address['slash'];
457
458 if(!empty($address['building']))
459 $resultData[$shipmentId]['building-to'] = $address['building'];
460
461 if(!empty($address['corpus']))
462 $resultData[$shipmentId]['corpus-to'] = $address['corpus'];
463
464 if(!empty($address['hotel']))
465 $resultData[$shipmentId]['hotel-to'] = $address['hotel'];
466
467 if(!empty($address['letter']))
468 $resultData[$shipmentId]['letter-to'] = $address['letter'];
469
470 if(!empty($address['location']))
471 $resultData[$shipmentId]['location-to'] = $address['location'];
472
473 if(!empty($address['street']) && empty($resultData[$shipmentId]['street-to']))
474 $resultData[$shipmentId]['street-to'] = $address['street'];
475
476 if(!empty($address['place']) && empty($resultData[$shipmentId]['place-to']))
477 $resultData[$shipmentId]['place-to'] = $address['place'];
478
479 if(!empty($address['index']) && empty($resultData[$shipmentId]['index-to']))
480 $resultData[$shipmentId]['index-to'] = $address['index'];
481
482 if(!empty($address['num-address-type']))
483 $resultData[$shipmentId]['num-address-type-to'] = $address['num-address-type'];
484 }
485 }
486
487 $normalizeResult = $this->normalizeFios($fios);
488
489 if(!$normalizeResult->isSuccess())
490 {
491 $result->addErrors($normalizeResult->getErrors());
492 return $result;
493 }
494
495 foreach($normalizeResult->getData() as $fio)
496 {
497 $shipmentId = $fio['id'];
498
499 if(!isset($resultData[$shipmentId]) || $notValidShipmentIds[$shipmentId])
500 continue;
501
502 if((!isset($fio["valid"]) || $fio["valid"] !== false) && $fio["quality-code"] != 'NOT_SURE' )
503 {
504 if(!empty($fio['middle-name']))
505 $resultData[$shipmentId]['middle-name'] = $fio['middle-name'];
506
507 if(!empty($fio['surname']))
508 $resultData[$shipmentId]['surname'] = $fio['surname'];
509
510 if(!empty($fio['name']))
511 $resultData[$shipmentId]['given-name'] = $fio['name'];
512 }
513
514 $resultData[$shipmentId]['recipient-name'] = $fio['original-fio'];
515 }
516 }
517
518 if(!empty($notValidShipmentIds))
519 foreach($notValidShipmentIds as $shipmentId => $t)
520 unset($resultData[$shipmentId]);
521
522 if(!empty($resultData))
523 $result->setData(array_values($resultData));
524 else
525 $result->addError(new Error(Loc::getMessage('SALE_DLVRS_ADD_DREQ_ROC_DATA_EMPTY')));
526
527 return $result;
528 }
529
534 private function convertLocationTypeToString(array $locationTypeComponent): string
535 {
536 return implode(', ', $locationTypeComponent);
537 }
538}
if(!Loader::includeModule('catalog')) if(!AccessController::getCurrent() ->check(ActionDictionary::ACTION_PRICE_EDIT)) if(!check_bitrix_sessid()) $request
Определения catalog_reindex.php:36
static countMinContainerSize(array $boxesSizes)
Определения packer.php:16
if(errorBox) return true
Определения file_new.php:1035
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
if(!function_exists(__NAMESPACE__.'\\___972068685'))
Определения license.php:1
trait Error
Определения error.php:11
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$i
Определения factura.php:643
$error
Определения subscription_card_product.php:20