You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
12KB

  1. <?php
  2. /**
  3. Copyright Guillaume Bourgeois (2018)
  4. contact@souke.fr
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace domain\Order\Order;
  32. use common\components\Tiller\TillerClientInterface;
  33. use common\components\Tiller\TillerClientV2;
  34. use common\components\Tiller\TillerClientV3;
  35. use common\helpers\MeanPayment;
  36. use common\helpers\Price;
  37. use domain\Order\OrderStatus\OrderStatus;
  38. use domain\Order\ProductOrder\ProductOrderSolver;
  39. use domain\Producer\Producer\ProducerSolver;
  40. use domain\_\AbstractManager;
  41. class TillerManager extends AbstractManager
  42. {
  43. protected ?bool $tillerActivated;
  44. protected ProducerSolver $producerSolver;
  45. protected TillerClientInterface $tillerClient;
  46. protected OrderSolver $orderSolver;
  47. protected OrderBuilder $orderBuilder;
  48. protected ProductOrderSolver $productOrderSolver;
  49. public function loadDependencies(): void
  50. {
  51. $this->producerSolver = $this->loadService(ProducerSolver::class);
  52. if($this->producerSolver->getProducerContext(false)) {
  53. $this->tillerActivated = $this->producerSolver->getConfig('tiller');
  54. $this->tillerClient = $this->getClient();
  55. }
  56. $this->orderSolver = $this->loadService(OrderSolver::class);
  57. $this->orderBuilder = $this->loadService(OrderBuilder::class);
  58. $this->productOrderSolver = $this->loadService(ProductOrderSolver::class);
  59. }
  60. public function getClient(): ?TillerClientInterface
  61. {
  62. $apiVersion = $this->producerSolver->getConfig('tiller_api_version');
  63. if($apiVersion == 'v2') {
  64. return new TillerClientV2(
  65. $this->producerSolver->getConfig('tiller_provider_token'),
  66. $this->producerSolver->getConfig('tiller_restaurant_token')
  67. );
  68. }
  69. elseif($apiVersion == 'v3') {
  70. return new TillerClientV3(
  71. $this->producerSolver->getConfig('tiller_store_id'),
  72. $this->producerSolver->getConfig('tiller_access_token')
  73. );
  74. }
  75. return null;
  76. }
  77. public function getUrlAuthorizeCode(): string
  78. {
  79. return $this->tillerClient->getUrlAuthorizeCode(
  80. $this->producerSolver->getConfig('tiller_client_id'),
  81. $this->producerSolver->getConfig('tiller_redirect_uri')
  82. );
  83. }
  84. public function isAuthenticated(): bool
  85. {
  86. return $this->tillerClient->isAuthenticated();
  87. }
  88. public function synchronizeDistribution(string $date): array
  89. {
  90. $return = [];
  91. if($this->tillerActivated) {
  92. $isSynchro = $this->isSynchronized($date);
  93. if (!$isSynchro) {
  94. $orders = Order::searchAll([
  95. 'distribution.date' => $date,
  96. 'order.tiller_synchronization' => 1,
  97. ], [
  98. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  99. ]);
  100. if ($orders && count($orders)) {
  101. foreach ($orders as $order) {
  102. $res = $this->synchronizeOrder($order);
  103. if($res) {
  104. $return[] = $res;
  105. }
  106. }
  107. }
  108. }
  109. }
  110. return $return;
  111. }
  112. public function synchronizeOrder(Order $order, bool $force = false)
  113. {
  114. $apiVersion = $this->producerSolver->getConfig('tiller_api_version');
  115. $date = $order->distribution->date;
  116. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  117. $datetime = new \DateTime(date('Y-m-d 12:i:s', strtotime($date)));
  118. $this->orderBuilder->initOrder($order);
  119. $lines = [];
  120. foreach ($order->productOrder as $productOrder) {
  121. // v3
  122. if($apiVersion == 'v3') {
  123. $amount = round($this->productOrderSolver->getPriceWithTax($productOrder) * 100);
  124. // classique
  125. if(is_int($productOrder->quantity)) {
  126. $quantity = $productOrder->quantity;
  127. }
  128. // vrac
  129. else {
  130. $amount = $amount * $productOrder->quantity;
  131. $quantity = 1;
  132. }
  133. $lines[] = [
  134. 'name' => $productOrder->product->name,
  135. 'unitPrice' => [
  136. 'amount' => $amount,
  137. ],
  138. 'taxRate' => $productOrder->taxRate->value * 100,
  139. 'quantity' => $quantity
  140. ];
  141. }
  142. // v2
  143. else {
  144. $lines[] = [
  145. 'name' => $productOrder->product->name,
  146. 'price' => $this->productOrderSolver->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
  147. 'tax' => $productOrder->taxRate->value * 100,
  148. 'date' => $strDate,
  149. 'quantity' => $productOrder->quantity
  150. ];
  151. }
  152. }
  153. $typePaymentTiller = '';
  154. if ($order->mean_payment == MeanPayment::MONEY) {
  155. $typePaymentTiller = 'CASH';
  156. }
  157. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  158. || $order->mean_payment == MeanPayment::CREDIT
  159. || $order->mean_payment == MeanPayment::TRANSFER
  160. || $order->mean_payment == MeanPayment::OTHER) {
  161. $typePaymentTiller = 'CARD';
  162. }
  163. if ($order->mean_payment == MeanPayment::CHEQUE) {
  164. $typePaymentTiller = 'BANK_CHECK';
  165. }
  166. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  167. $typePaymentTiller = 'CASH';
  168. }
  169. if (!$this->isSynchronized($date, $order->id) || $force) {
  170. // v3
  171. if($apiVersion == 'v3') {
  172. $payments = [];
  173. $amountPayment = round($this->orderSolver->getOrderAmountWithTax($order, Order::AMOUNT_PAID) * 100);
  174. if($amountPayment) {
  175. $payments[] = [
  176. 'externalId' => ''.$order->id,
  177. 'amount' => $amountPayment
  178. ];
  179. }
  180. $returnTiller = $this->tillerClient->postOrder([
  181. 'externalId' => ''.$order->id,
  182. 'purchaseRequestType' => 'clickAndCollect',
  183. 'date' => $datetime->format(\DateTime::ATOM),
  184. 'order' => [
  185. 'currencyCode' => 'EUR',
  186. 'itemLines' => $lines,
  187. 'payments' => $payments
  188. ]
  189. ]);
  190. }
  191. // v2
  192. else {
  193. $returnTiller = $this->tillerClient->postOrder([
  194. 'externalId' => $order->id,
  195. 'type' => 1,
  196. 'status' => 'IN_PROGRESS',
  197. 'openDate' => $strDate,
  198. 'closeDate' => $strDate,
  199. 'lines' => $lines,
  200. 'payments' => [
  201. [
  202. 'type' => $typePaymentTiller,
  203. 'amount' => $this->orderSolver->getOrderAmountWithTax(
  204. $order,
  205. Order::AMOUNT_PAID
  206. ) * 100,
  207. 'status' => 'ACCEPTED',
  208. 'date' => $strDate
  209. ]
  210. ]
  211. ]);
  212. }
  213. $returnTillerObject = json_decode($returnTiller);
  214. if($apiVersion == 'v3') {
  215. $order->tiller_external_id = '' . $returnTillerObject->referenceId;
  216. }
  217. else {
  218. $order->tiller_external_id = '' . $returnTillerObject->id;
  219. }
  220. $order->save();
  221. return $returnTiller;
  222. }
  223. return null;
  224. }
  225. public function isSynchronized($date, $idOrder = null): bool
  226. {
  227. if ($this->tillerActivated) {
  228. $ordersTiller = $this->tillerClient->getOrders($date);
  229. $ordersOpendistrib = Order::searchAll([
  230. 'distribution.date' => $date,
  231. 'order.tiller_synchronization' => 1,
  232. ], [
  233. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  234. ]);
  235. $ordersOpendistribSynchro = [];
  236. if ($ordersOpendistrib) {
  237. foreach ($ordersOpendistrib as $orderOpendistrib) {
  238. $this->orderBuilder->initOrder($orderOpendistrib);
  239. if($orderOpendistrib->tiller_external_id) {
  240. $ordersOpendistribSynchro[$orderOpendistrib->id] = true;
  241. }
  242. else {
  243. $ordersOpendistribSynchro[$orderOpendistrib->id] = false;
  244. }
  245. /*if (isset($ordersTiller->orders)) {
  246. foreach ($ordersTiller->orders as $orderTiller) {
  247. if ($orderOpendistrib->tiller_external_id == $orderTiller->id) {
  248. $amountTotalPaidOrderOpendistrib = (int)round(
  249. $this->orderSolver->getOrderAmountWithTax($orderOpendistrib, Order::AMOUNT_PAID) * 100
  250. );
  251. if ($amountTotalPaidOrderOpendistrib >= (int)$orderTiller->currentPayedAmount
  252. || $amountTotalPaidOrderOpendistrib >= (int)$orderTiller->currentBill) {
  253. $ordersOpendistribSynchro[$orderOpendistrib->id] = true;
  254. }
  255. }
  256. }
  257. }*/
  258. }
  259. }
  260. if($idOrder && isset($ordersOpendistribSynchro[$idOrder])) {
  261. return $ordersOpendistribSynchro[$idOrder];
  262. }
  263. else {
  264. foreach ($ordersOpendistribSynchro as $idOrder => $isSynchro) {
  265. if (!$isSynchro) {
  266. return false;
  267. }
  268. }
  269. }
  270. return true;
  271. }
  272. return false;
  273. }
  274. public function getTotalAmountOrdersByDate(string $date, bool $format = false)
  275. {
  276. $totalAmount = 0;
  277. $ordersArray = Order::searchAll([
  278. 'distribution.date' => $date,
  279. 'order.tiller_synchronization' => 1,
  280. ], [
  281. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  282. ]);
  283. foreach($ordersArray as $order) {
  284. $this->orderBuilder->initOrder($order);
  285. $totalAmount += $this->orderSolver->getOrderAmountWithTax($order);
  286. }
  287. if($format) {
  288. return Price::format($totalAmount);
  289. }
  290. return $totalAmount;
  291. }
  292. }