<?php
namespace App\Services\Insales;
use \InSales\API;
use App\Entity;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Response;
/**
* Class Client
* @package App\Services\Insales
*/
class Client
{
const INSALES_FINANCIAL_STATUS_PAID = 'paid';
const INSALES_FINANCIAL_STATUS_PENDING = 'pending';
/** @var EntityManagerInterface $entityManager' */
protected $entityManager;
/** @var string $appId */
protected $appId;
/** @var Entity\Shop|null $shop */
protected $shop = null;
/** @var API\ApiClient|null $client */
protected $client = null;
/** @var ParameterBagInterface */
protected $parameterBag;
/**
* Orders constructor.
* @param EntityManagerInterface $entityManager
* @param ParameterBagInterface $parameterBag
*/
public function __construct(EntityManagerInterface $entityManager, ParameterBagInterface $parameterBag)
{
$this->parameterBag = $parameterBag;
$this->appId = $this->parameterBag->get('app.insales.id');
$this->entityManager = $entityManager;
}
/**
* @param string $password
* @param string $shopDomain
* @return self
*/
public function createClientByShopData(string $password, string $shopDomain): self
{
$this->client = new API\ApiClient(
$this->appId,
$password,
$shopDomain
);
return $this;
}
/**
* @return Entity\Shop|null
*/
public function getShop(): ?Entity\Shop
{
return $this->shop;
}
/**
* @param Entity\Shop|null $shop
* @return self
*/
public function setShop(?Entity\Shop $shop): self
{
$this->shop = $shop;
/** @var API\ApiClient $client */
$this->client = new API\ApiClient(
$this->appId,
$this->shop->getPassword(),
$this->shop->getShop()
);
return $this;
}
/**
* @param array $fields
* @param Entity\Shop $shop
* @return bool
*/
public function downloadOrder(array $fields, bool $setManageToken = false) : bool
{
/** @var Api\ApiResponse $response */
$response = $this->client->getOrderById($fields['id']);
if($response->getHttpCode() !== Response::HTTP_OK)
return false;
/** @var Entity\Order $order */
$order = $this->entityManager->getRepository(Entity\Order::class)
->getOrderForUpdate($this->shop, $fields['id']);
$order->setKey($response->getData()['key'])
->setNumber($response->getData()['number'])
->setPayed($response->getData()['financial_status'] === 'paid')
->setDeliveryVariantId($response->getData()['delivery_variant_id'])
->setDeliveryInformation($response->getData()['delivery_info'])
->setFieldValues($response->getData()['fields_values'])
->setProducts($response->getData()['order_lines'])
->setShippingAddress($response->getData()['shipping_address'])
->setClient($response->getData()['client'])
->setPrice($order::calcOrderSum($order->getProducts()))
->setComment($response->getData()['comment'])
->setManagerComment($response->getData()['manager_comment'])
->setPaymentGatewayId(intval($response->getData()['payment_gateway_id']))
;
if ($setManageToken)
$order->setManageToken();
$this->entityManager->persist($order);
$this->entityManager->flush();
return true;
}
/**
* Скачивание и получение объекта заказа
* @param $orderId
* @return Entity\Order|object|null
*/
public function getByOrderId($orderId, bool $setManageToken = false)
{
$this->downloadOrder(['id' => $orderId],$setManageToken);
return $this->entityManager->getRepository(Entity\Order::class)
->findOneBy(
[
'shop' => $this->shop,
'orderId' => $orderId
]
);
}
/**
* Получение статусов insales
* @return array[]
*/
public function getStatuses()
{
return $this->client->getCustomStatuses()->getData();
}
/**
* Получение заказа
* @param string|integer $id Идентификатор заказа
* @return \InSales\API\ApiResponse
*/
public function getOrderById($id)
{
return $this->client->getOrderById($id);
}
/**
* Обновление статуса заказа
* @param $orderId
* @param $statusCode
* @param false $customStatus
*/
public function updateOrderStatus($orderId, $statusCode, $customStatus = false)
{
if($customStatus)
{
$this->client->updateOrder(
$orderId,
[
'custom_status_permalink' => $statusCode,
]
);
}
else
{
$this->client->updateOrder(
$orderId,
[
'fulfillment_status' => $statusCode
]
);
}
}
/**
* Обновление свойств заказа
* @param int $orderId id заказа
* @param string $handle символьный код свойства
* @param mixed $value значение свойства
*
* @return API\ApiResponse
*/
public function updateOrderField(int $orderId, string $handle, $value)
{
$response = $this->client->updateOrder(
$orderId,
[
'fields_values_attributes' => [
[
"handle" => $handle,
"value" => $value
]
]
]
);
return $response;
}
/**
* Обновление свойств заказа
* @param int $orderId id заказа
* @param string $financial_status pending or paid
* @return API\ApiResponse
*/
public function updateFinalcialStatus(int $orderId, string $financial_status)
{
$response = $this->client->updateOrder(
$orderId,
[
'financial_status' => $financial_status
]
);
return $response;
}
/**
* Получения списка оплат
* @return API\ApiResponse
*/
public function getPaymentGateways() {
return $this->client->getPaymentGateways();
}
public function getFields() {
return $this->client->getFields();
}
public function updateTrackNumber(int $orderId, $trackNumber){
return $this->updateOrderField(
$orderId,
$this->parameterBag->get('app.insales.property.track.number.handle'),
$trackNumber
);
}
public function updateOrder(int $orderId,array $data)
{
return $this->client->updateOrder($orderId,$data);
}
public function updateInsalesDelivery(int $deliveryId, string $script1Url, string $script2Url, string $insalesServiceName = '')
{
$data = [
'javascript' => sprintf(
'<script type="text/javascript" src="%s"></script><script type="module" src="%s"></script>',
$script1Url,
$script2Url
)
];
if (!empty($insalesServiceName)) {
$data['title'] = $insalesServiceName;
}
return $this->client->updateDeliveryVariant($deliveryId, $data);
}
}