Как верно трактовать логику данного скрипта?

ДД, дали скрип представлен тестовый для вакансии не связанной с разработкой, просят максимально похоже перевести логику скрипта в обывательский язык, т.е какой функционал хотел видеть человек дающей такое задание на разработку?

из скрипта у меня сложилось следующее, что мы получаем данные, проверяем ,код страны, проходим условия по ценам, в зависимости от цены берем или одну или другую транспортную компанию, далее формируем массивы продукта, адреса, и закидываем их в результирующий массив, который потом в json и отправляется далее по api, в самом низу оправляются письма из блоков try/catch.

Если не затруднит подскажите более развернутую логики, мб моя глобально -+ верно описывает ее работу, код:


ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// fix json_encode bug
// https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue/43056278
if (version_compare(phpversion(), '7.1', '>=')) {
   ini_set( 'precision', 17 );
   ini_set( 'serialize_precision', -1 );
}

use PHPMailer\PHPMailer\PHPMailer;

require __DIR__ . '/PHPMailer/PHPMailer.php';
require __DIR__ . '/PHPMailer/SMTP.php';
require __DIR__ . '/PHPMailer/Exception.php';

header('Content-Type: text/html; charset=utf-8');

$webhookResponse = json_decode(file_get_contents('php://input'), true);

$log = date('Y-m-d H:i:s') . ' ' . print_r($webhookResponse, true);
file_put_contents(__DIR__ . '/webhookResponse.log', $log . PHP_EOL, FILE_APPEND);

//$countries = ['DZ', 'EG', 'JO', 'IQ', 'YE', 'LB', 'LY', 'MR', 'MA', 'SA', 'SY', 'SD', 'TN', 'QA', 'KW', 'AE', 'IL', 'BH'];
$countries = ['AL', 'AD', 'AT', 'BE', 'BA', 'BG', 'HR', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'VA', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MK', 'MT', 'MD', 'MC', 'ME', 'NL', 'PL', 'PT', 'RO', 'SM', 'RS', 'SK', 'SL', 'ES', 'SE', 'US', 'CA', 'GB', 'SI', 'CY'];
$countries_post = ['IL', 'SA', 'AE', 'QA', 'BH', 'LB'];
$country_code = $webhookResponse['shipping_address']['country_code'];
$country = $webhookResponse['shipping_address']['country'];

if (!in_array($country_code, $countries)) {
   //$apiKey = 'JiV';
   $apiKey = '7gM';
   $project_id = '14K';

   $site = parse_url($webhookResponse['order_status_url'], PHP_URL_HOST);

   if ($site === 'unidragon.eu') {
       $order_source_id = '154';
   } else {
       $order_source_id = '12P';
   }

   $price = $webhookResponse['total_price_set']['shop_money']['amount']*100;
   $currency = $webhookResponse['total_price_set']['shop_money']['currency_code'];
   $reference = (string)$webhookResponse['order_number'];

   if (in_array($country_code, $countries_post) && $price < 20000) {
       $company_id = 'e6Q9';
       $extra = array(
           'carrier' => 'RussianPost',
           'service' => 'SmallPacket',
       );
   } else {
       $company_id = '12t';
       $extra = array(
           'carrier' => 'DHL',
           'service' => 'WorldwideExpress',
       );
   }

   $extra['shopify_order_id'] = (float)$webhookResponse['id'];

   $items = array();
   foreach ($webhookResponse['line_items'] as $item) {
       $items[] = array(
           'product_title'  => $item['name'],
           'product_sku'    => $item['sku'],
           'price'          => round($item['price_set']['shop_money']['amount']*100, 2),
           'product_weight' => $item['grams'],
           'currency'       => $item['price_set']['shop_money']['currency_code'],
           'quantity'       => $item['quantity'],
       );
   }

   $address = array(
       'street'  => $webhookResponse['shipping_address']['address1'],
       'city'    => $webhookResponse['shipping_address']['city'],
       'country' => $webhookResponse['shipping_address']['country_code'],
       'zip'     => $webhookResponse['shipping_address']['zip'],
       'name'    => $webhookResponse['shipping_address']['name'],
       'phone'   => $webhookResponse['shipping_address']['phone'],
       'email'   => $webhookResponse['customer']['email'],
   );

   $data = array(
       'order' => array(
           'company_id' => $company_id,
           'reference'  => $reference,
           //'comment'    => 'Не отправлять, тест',
           'price'      => round($price, 2),
           'currency'   => $currency,
           'extra'      => $extra,
           'to_address' => $address,
           'line_items' => $items,
           'project_id' => $project_id,
           'order_source_id' => $order_source_id,
       ),
   );

   if ($country_code == 'CH' || $country_code == 'NO' || $country_code == 'IS') {
       $data['order']['archived'] = true;
   }

   $fields = json_encode($data);

   $log = date('Y-m-d H:i:s') . ' ' . print_r($fields, true);
   file_put_contents(__DIR__ . '/fields.log', $log . PHP_EOL, FILE_APPEND);

   $ch = curl_init();

   curl_setopt($ch, CURLOPT_URL, "https://api.post.ru:5433/v1/orders");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURLOPT_HEADER, TRUE);
   curl_setopt($ch, CURLOPT_POST, TRUE);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     "Content-Type: application/json",
     "Authorization: Basic ".$apiKey,));

   $response = curl_exec($ch);
   $info = curl_getinfo($ch);
   curl_close($ch);

   $log = date('Y-m-d H:i:s') . ' id ' . print_r($webhookResponse['id'], true) . PHP_EOL;
   $log .= 'response ' . print_r($response, true) . PHP_EOL;
   $log .= 'info ' . print_r($info, true) . PHP_EOL;
   $log .= 'fields ' . print_r($fields, true) . PHP_EOL;

   if ($info["http_code"] == 201) {
       file_put_contents(__DIR__ . '/success.log', $log . PHP_EOL, FILE_APPEND);
   } else {
       file_put_contents(__DIR__ . '/error.log', $log . PHP_EOL, FILE_APPEND);

       $mail = new PHPMailer(true);
       try {
           $mail->CharSet = $mail::CHARSET_UTF8;
           $mail->isSMTP();
           $mail->SMTPAuth = true;
           $mail->Host = 'ssl://smtp.web.ru';
           $mail->Port = 465;
           $mail->Username = '[email protected]';
           $mail->Password = '253';
           $mail->setFrom('[email protected]');
           $mail->addAddress('[email protected]');
           $mail->isHTML(true);
           $mail->Subject = 'Ошибка при отправке заказа ' . $reference;
           $mail->Body = '<pre>' . $log . '</pre>';
           $mail->send();
       } catch (\Exception $e) {
           $log = 'Ошибка при отправке письма: ' . $mail->ErrorInfo;
           file_put_contents(__DIR__ . '/error.log', $log . PHP_EOL, FILE_APPEND);
       }
   }

} else {
   $log = date('Y-m-d H:i:s') . ' id ' . print_r($webhookResponse['id'], true) . PHP_EOL;
   $log .= 'country ' . print_r($country, true) . PHP_EOL;
   file_put_contents(__DIR__ . '/not_sent.log', $log . PHP_EOL, FILE_APPEND);
}

Ответы (1 шт):

Автор решения: Aziz Umarov

Идея проще. Если кратко.

Это формирование заказа и отправка его на АПИ через curl.

Если чуть более развернуто то идет

  1. Проверка перед формированием.
  2. Само формирование заказа
  3. Обработка результата отправки заказа
→ Ссылка