diff --git a/src/upload/catalog/model/extension/retailcrm/order.php b/src/upload/catalog/model/extension/retailcrm/order.php index c8e67fb..f01a10c 100644 --- a/src/upload/catalog/model/extension/retailcrm/order.php +++ b/src/upload/catalog/model/extension/retailcrm/order.php @@ -37,28 +37,7 @@ class ModelExtensionRetailcrmOrder extends Model { } if (!isset($order['customer']['externalId']) && !isset($order['customer']['id'])) { - $new_customer = array( - 'firstName' => $data['firstname'], - 'lastName' => $data['lastname'], - 'email' => $data['email'], - 'createdAt' => $data['date_added'], - 'address' => array( - 'countryIso' => $data['payment_iso_code_2'], - 'index' => $data['payment_postcode'], - 'city' => $data['payment_city'], - 'region' => $data['payment_zone'], - 'text' => $data['payment_address_1'] . ' ' . $data['payment_address_2'] - ) - ); - - if (!empty($data['telephone'])) { - $new_customer['phones'] = array( - array( - 'number' => $data['telephone'] - ) - ); - } - + $new_customer = $this->createCustomer($data); $res = $retailcrmApiClient->customersCreate($new_customer); if ($res->isSuccessful() && isset($res['id'])) { @@ -68,12 +47,20 @@ class ModelExtensionRetailcrmOrder extends Model { if ($create) { $order = self::filterRecursive($order); - $retailcrmApiClient->ordersCreate($order); + $response = $retailcrmApiClient->ordersCreate($order); + if ($response->getStatusCode() === 400 && !empty($response->__get('errors')['customer.externalId'])) { + $order['customer'] = $this->createCustomer($data); + $response = $retailcrmApiClient->ordersEdit($order); + } } else { $order_payment = reset($order['payments']); unset($order['payments']); $order = self::filterRecursive($order); $response = $retailcrmApiClient->ordersEdit($order); + if ($response->getStatusCode() === 400 && !empty($response->__get('errors')['customer.externalId'])) { + $order['customer'] = $this->createCustomer($data); + $response = $retailcrmApiClient->ordersEdit($order); + } if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { $this->updatePayment($order_payment, $order['externalId'], $retailcrmApiClient); @@ -423,4 +410,36 @@ class ModelExtensionRetailcrmOrder extends Model { } return $haystack; } + + /** + * @param array $data + * + * @return array + */ + private function createCustomer($data) + { + $customer = array( + 'firstName' => $data['firstname'], + 'lastName' => $data['lastname'], + 'email' => $data['email'], + 'createdAt' => $data['date_added'], + 'address' => array( + 'countryIso' => $data['payment_iso_code_2'], + 'index' => $data['payment_postcode'], + 'city' => $data['payment_city'], + 'region' => $data['payment_zone'], + 'text' => $data['payment_address_1'] . ' ' . $data['payment_address_2'] + ) + ); + + if (!empty($data['telephone'])) { + $customer['phones'] = array( + array( + 'number' => $data['telephone'] + ) + ); + } + + return $customer; + } }