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.

DistributionController.php 38KB

6 jaren geleden
3 maanden geleden
6 jaren geleden
6 jaren geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 maanden geleden
6 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. <?php
  2. /**
  3. * Copyright Guillaume Bourgeois (2018)
  4. *
  5. * contact@souke.fr
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use common\helpers\Ajax;
  39. use common\helpers\GlobalParam;
  40. use common\helpers\MeanPayment;
  41. use common\helpers\Price;
  42. use domain\Distribution\Distribution\Distribution;
  43. use domain\Document\DeliveryNote\DeliveryNote;
  44. use domain\Feature\Feature\Feature;
  45. use domain\Order\Order\Order;
  46. use domain\Producer\Producer\Producer;
  47. use DateTime;
  48. use domain\Product\Product\Product;
  49. use yii\base\ErrorException;
  50. use yii\base\Exception;
  51. use yii\filters\AccessControl;
  52. class DistributionController extends BackendController
  53. {
  54. public function behaviors()
  55. {
  56. return [
  57. 'access' => [
  58. 'class' => AccessControl::class,
  59. 'rules' => [
  60. [
  61. 'actions' => ['report-cron', 'report-terredepains'],
  62. 'allow' => true,
  63. 'roles' => ['?']
  64. ],
  65. [
  66. 'allow' => true,
  67. 'roles' => ['@'],
  68. 'matchCallback' => function ($rule, $action) {
  69. return $this->getUserModule()
  70. ->getAuthorizationChecker()
  71. ->isGrantedAsProducer($this->getUserCurrent());
  72. }
  73. ]
  74. ],
  75. ],
  76. ];
  77. }
  78. public function actionIndex(string $date = '', int $idOrderUpdate = 0)
  79. {
  80. $this->checkProductsPointsSale();
  81. if(!$this->getDistributionModule()->getSolver()->validateDistributionDate($date)) {
  82. $date = '';
  83. }
  84. $orderUpdate = null;
  85. if($idOrderUpdate) {
  86. $orderUpdate = $this->getOrderModule()->getRepository()
  87. ->findOneOrderById($idOrderUpdate);
  88. }
  89. return $this->render('index', [
  90. 'date' => $date,
  91. 'orderUpdate' => $orderUpdate
  92. ]);
  93. }
  94. public function actionAjaxInfos($date = '')
  95. {
  96. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  97. $distributionModule = $this-> getDistributionModule();
  98. $orderModule = $this->getOrderModule();
  99. $productModule = $this->getProductModule();
  100. $producer = $this->getProducerCurrent();
  101. $dateObject = DateTime::createFromFormat('Y-m-d', $date);
  102. $json = ['distribution' => [], 'products' => []];
  103. $json['means_payment'] = MeanPayment::getAll();
  104. $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
  105. $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
  106. $json['leave_period_dates'] = $this->buildAjaxInfosResponseLeavePeriod($producer);
  107. $json['units'] = Product::$unitsArray;
  108. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  109. $distribution = $distributionModule->createDistributionIfNotExist($date);
  110. $ordersArray = $orderModule->findOrdersByDistribution($distribution, false);
  111. $ordersArrayObject = $ordersArray;
  112. $productsArray = $productModule->findProductsByDistribution($distribution, false);
  113. $json['products'] = $this->buildAjaxInfosResponseProducts($distribution, $productsArray, $ordersArray);
  114. $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
  115. $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
  116. $json['points_sale'] = $this->buildAjaxInfosResponsePointsSale($distribution);
  117. $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
  118. $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
  119. $json['users'] = $this->buildAjaxInfosResponseUsers();
  120. $json['one_distribution_week_active'] = $distributionModule->isOneDistributionWeekActive($date);
  121. $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
  122. $json['tiller_is_authenticated'] = $this->getOrderModule()->getTillerManager()->isAuthenticated();
  123. $json['tiller_url_authorize_code'] = $this->getOrderModule()->getTillerManager()->getUrlAuthorizeCode();
  124. $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
  125. }
  126. return $json;
  127. }
  128. public function buildAjaxInfosResponseUsers()
  129. {
  130. $usersArray = $this->getUserModule()->getRepository()->findUsers();
  131. foreach($usersArray as $key => $user) {
  132. $usersArray[$key]['username'] = $this->getUserModule()->getSolver()->getUsernameFromArray($user, true);
  133. }
  134. return $usersArray;
  135. }
  136. public function buildAjaxInfosResponseLeavePeriod(Producer $producer)
  137. {
  138. $producerModule = $this->getProducerModule();
  139. $leavePeriodDatesArray = [];
  140. if($producerModule->getSolver()->hasLeavePeriodDefined($producer)) {
  141. $leavePeriodStart = $producerModule->getSolver()->getLeavePeriodStartDateTime($producer);
  142. $leavePeriodEnd = $producerModule->getSolver()->getLeavePeriodEndDateTime($producer);
  143. for($date = $leavePeriodStart; $date <= $leavePeriodEnd; $date->modify('+1 day')) {
  144. $leavePeriodDatesArray[] = $date->format('Y-m-d');
  145. }
  146. }
  147. return $leavePeriodDatesArray;
  148. }
  149. public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
  150. {
  151. $producerModule = $this->getProducerModule();
  152. $pointSaleModule = $this->getPointSaleModule();
  153. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  154. $sharedPointSaleModule = $this->getSharedPointSaleModule();
  155. $featureModule = $this->getFeatureModule();
  156. $pointsSaleArray = $pointSaleModule->findPointSalesByDistributionAsArray($distribution);
  157. // @TODO : à gérer autrement
  158. foreach($pointsSaleArray as &$pointSaleArray) {
  159. $idPointSale = $pointSaleArray['id'];
  160. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  161. if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
  162. $pointSaleDistribution = $pointSaleDistributionModule->createPointSaleDistributionIfNotExist($distribution, $pointSale);
  163. $pointSaleArray['pointSaleDistribution'] = [
  164. [
  165. 'id_distribution' => $pointSaleDistribution->id_distribution,
  166. 'id_point_sale' => $pointSaleDistribution->id_point_sale,
  167. 'delivery' => $pointSaleDistribution->delivery
  168. ]
  169. ];
  170. }
  171. $pointSaleArray['credit_functioning'] = $producerModule->getPointSaleCreditFunctioning($pointSale);
  172. $pointSaleArray['producers_sharing_point_sale_as_string'] = false;
  173. if($featureModule->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  174. $pointSaleArray['producers_sharing_point_sale_as_string'] = $sharedPointSaleModule->getResolver()->getProducersSharingPointSaleAsString($pointSale, $distribution);
  175. }
  176. }
  177. return $pointsSaleArray;
  178. }
  179. public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray)
  180. {
  181. $distributionModule = $this-> getDistributionModule();
  182. $orderModule = $this->getOrderModule();
  183. $jsonProductsArray = [];
  184. foreach ($productsArray as $product) {
  185. $jsonProduct = $product->getAttributes();
  186. $quantityOrder = $orderModule->getProductQuantity($product, $ordersArray);
  187. $jsonProduct['quantity_ordered'] = $quantityOrder;
  188. if (!isset($product->productDistribution[0])) {
  189. $productDistributionAdd = $distributionModule->addProduct($distribution, $product);
  190. if($productDistributionAdd) {
  191. $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes();
  192. $product->populateRelation('productDistribution', [$productDistributionAdd]);
  193. }
  194. }
  195. else {
  196. foreach($product->productDistribution as $key => $productDistribution) {
  197. $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes();
  198. }
  199. }
  200. $jsonProduct['quantity_max'] = $orderModule->getResolver()->getProductQuantityMax($product, $distribution);
  201. $jsonProduct['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution);
  202. $jsonProduct['quantity_form'] = 0;
  203. $jsonProduct['accessories'] = [];
  204. foreach($product->getProductAccessories() as $productAccessory) {
  205. $jsonProduct['accessories'][] = [
  206. 'id_accessory' => $productAccessory->getAccessory()->getId(),
  207. 'quantity' => $productAccessory->getQuantity(),
  208. ];
  209. }
  210. if ($product->taxRate) {
  211. $jsonProduct['taxRate'] = $product->taxRate->getAttributes();
  212. }
  213. else {
  214. $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes();
  215. }
  216. $jsonProductsArray[] = $jsonProduct;
  217. }
  218. return $jsonProductsArray;
  219. }
  220. public function buildAjaxInfosResponseProducer($producer)
  221. {
  222. return [
  223. 'credit' => $producer->credit,
  224. 'tiller' => $producer->tiller,
  225. 'option_distribution_export_orders_grid_pdf' => $producer->option_distribution_export_orders_grid_pdf,
  226. 'feature_product_accessory_enabled' => $this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_PRODUCT_ACCESSORY)
  227. ];
  228. }
  229. public function buildAjaxInfosResponseDistributions($dateObject)
  230. {
  231. $numberOfLoadedMonthes = '3 month';
  232. if (is_object($dateObject)) {
  233. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  234. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  235. } else {
  236. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  237. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  238. }
  239. return Distribution::searchAll([
  240. 'active' => 1
  241. ], [
  242. 'conditions' => [
  243. 'date > :date_begin',
  244. 'date < :date_end'
  245. ],
  246. 'params' => [
  247. ':date_begin' => date(
  248. 'Y-m-d',
  249. $dateBegin
  250. ),
  251. ':date_end' => date(
  252. 'Y-m-d',
  253. $dateEnd
  254. ),
  255. ],
  256. 'as_array' => true
  257. ]);
  258. }
  259. public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
  260. {
  261. $producerModule = $this->getProducerModule();
  262. $productModule = $this->getProductModule();
  263. $orderModule = $this->getOrderModule();
  264. $distributionModule = $this-> getDistributionModule();
  265. $distributionJsonData = [
  266. 'id' => $distribution->id,
  267. 'active' => $distribution->active,
  268. 'exports' => $distributionModule->getExportManager()->getAjaxArray($distribution),
  269. 'url_order' => $distributionModule->getLinkOrder($distribution),
  270. 'is_leave_period' => $producerModule->getSolver()->isOnLeavePeriod($distribution->producer, DateTime::createFromFormat('Y-m-d', $distribution->date))
  271. ];
  272. // montant et poids des commandes
  273. $revenues = 0;
  274. $revenuesWithTax = 0;
  275. $weight = 0;
  276. if ($ordersArray) {
  277. foreach ($ordersArray as $order) {
  278. $orderModule->initOrder($order);
  279. if($order->isOrderStatusValid()) {
  280. $revenues += $orderModule->getOrderAmount($order);
  281. $revenuesWithTax += $orderModule->getOrderAmountWithTax($order);
  282. $weight += $order->weight;
  283. }
  284. }
  285. }
  286. $distributionJsonData['revenues'] = Price::format($revenues);
  287. $distributionJsonData['revenues_with_tax'] = Price::format($revenuesWithTax);
  288. $distributionJsonData['weight'] = number_format($weight, 2);
  289. $distributionJsonData['potential_revenues'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray));
  290. $distributionJsonData['potential_revenues_with_tax'] = Price::format($productModule->getProductDistributionPotentialRevenues($productsArray, true));
  291. $distributionJsonData['potential_weight'] = number_format($productModule->getProductDistributionPotentialWeight($productsArray), 2);
  292. $distributionJsonData['user_create_href'] = \Yii::$app->urlManager->createUrl([
  293. 'user/create',
  294. 'redirectUrl' => \Yii::$app->urlManager->createAbsoluteUrl([
  295. 'distribution/index',
  296. 'date' => $distribution->date,
  297. 'displayFormOrderCreate' => 1
  298. ])
  299. ]);
  300. return $distributionJsonData;
  301. }
  302. public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
  303. {
  304. $userModule = $this->getUserModule();
  305. $orderModule = $this->getOrderModule();
  306. $paymentManager = $this->getPaymentModule();
  307. $productOrderModule = $this->getProductOrderModule();
  308. $userProducerModule = $this->getUserProducerModule();
  309. if ($ordersArray) {
  310. foreach ($ordersArray as &$order) {
  311. $orderModule->initOrder($order);
  312. $productOrderArray = [];
  313. foreach ($order->productOrder as $productOrder) {
  314. $productOrderArray[$productOrder->id_product] = [
  315. 'quantity' => $productOrderModule->getSolver()->getQuantityToCoefficientOfUnit($productOrder),
  316. 'unit' => $productOrder->unit,
  317. 'price' => number_format($productOrder->price, 5),
  318. 'invoice_price' => number_format($productOrder->invoice_price, 5),
  319. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  320. ];
  321. }
  322. foreach ($productsArray as $product) {
  323. if (!isset($productOrderArray[$product['id']])) {
  324. $productOrderArray[$product['id']] = [
  325. 'quantity' => 0,
  326. 'unit' => $product['unit'],
  327. 'price' => number_format($product['price'], 5),
  328. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  329. ];
  330. }
  331. }
  332. $paymentArray = [];
  333. foreach ($order->payment as $payment) {
  334. $paymentArray[] = [
  335. 'type' => $payment->type,
  336. 'wording_type' => $paymentManager->getStrType($payment),
  337. 'mean_payment' => $payment->mean_payment,
  338. 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment),
  339. 'date' => date('d/m/Y H:i:s', strtotime($payment->date)),
  340. 'user' => $payment->getUserObject() ? $userModule->getSolver()->getUsername($payment->getUserObject()) : '',
  341. 'user_action' => $userModule->getSolver()->getPaymentUsernameUserAction($payment),
  342. 'wording' => $paymentManager->getStrWording($payment, $order),
  343. 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true),
  344. ];
  345. }
  346. $arrayDatasUser = [];
  347. if(isset($order->user) && $order->user) {
  348. $arrayDatasUser['credit'] = $userModule->getCredit($order->user);
  349. $arrayDatasUser['credit_active'] = $userModule->getCreditActive($order->user);
  350. $userProducer = $userProducerModule->getRepository()->findOneUserProducer($order->user);
  351. $arrayDatasUser['trust_alert'] = $userProducer->trust_alert;
  352. $arrayDatasUser['trust_alert_comment'] = $userProducer->trust_alert_comment;
  353. }
  354. $oneProductUnactivated = false;
  355. foreach ($order->productOrder as $productOrder) {
  356. foreach ($productsArray as $product) {
  357. if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$product['productDistribution'][0]['active']) {
  358. $oneProductUnactivated = true;
  359. }
  360. }
  361. }
  362. $order = array_merge($order->getAttributes(), [
  363. 'selected' => false,
  364. 'weight' => $order->weight,
  365. 'amount' => (float) Price::numberTwoDecimals($orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
  366. 'amount_paid' => (float) Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_PAID)),
  367. 'amount_remaining' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_REMAINING)),
  368. 'amount_surplus' => Price::numberTwoDecimals($orderModule->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
  369. 'user' => (isset($order->user)) ? array_merge(
  370. $order->user->getAttributes(),
  371. $arrayDatasUser
  372. ) : null,
  373. 'username_user' => (isset($order->user)) ? $userModule->getSolver()->getUsername($order->user) : '',
  374. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  375. 'productOrder' => $productOrderArray,
  376. 'paymentsArray' => $paymentArray,
  377. 'oneProductUnactivated' => $oneProductUnactivated,
  378. 'isLinkedToValidDocument' => $orderModule->getSolver()->isLinkedToValidDocument($order),
  379. 'isLinkedToValidInvoice' => $orderModule->getSolver()->isLinkedToValidInvoice($order),
  380. 'isCreditAutoPayment' => $orderModule->getRepository()->isCreditAutoPayment($order),
  381. 'isCreditContext' => $orderModule->getRepository()->isCreditContext($order),
  382. 'isPaid' => $orderModule->getRepository()->isOrderPaid($order),
  383. 'isPaidViaInvoice' => $orderModule->getRepository()->isOrderPaidViaInvoice($order),
  384. 'paymentLabelShort' => $orderModule->getRepository()->getPaymentLabelShort($order),
  385. 'isCreditFunctioningMandatory' => $orderModule->getRepository()->isOrderCreditFunctioningMandatory($order),
  386. 'isCreditFunctioningUser' => $orderModule->getRepository()->isOrderCreditFunctioningUser($order),
  387. 'debitCredit' => false,
  388. 'deliveryNote' => $order->deliveryNote ? $order->deliveryNote->getAttributes() : null,
  389. 'labelDeleteAction' => $orderModule->getSolver()->getLabelDeleteAction($order),
  390. 'labelOrigin' => $orderModule->getSolver()->getLabelOrigin($order, true),
  391. 'orderStatusHistorySummaryTitleTag' => $orderModule->getSolver()->getOrderStatusHistorySummaryTitleTag($order, "\n"),
  392. ]);
  393. }
  394. }
  395. return $ordersArray;
  396. }
  397. public function buildAjaxInfosResponseDeliveryNotes(string $date)
  398. {
  399. $deliveryNotesArray = DeliveryNote::searchAll([
  400. 'distribution.date' => $date,
  401. ], [
  402. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  403. ]);
  404. $deliveryNotesByPointSaleArray = [];
  405. foreach ($deliveryNotesArray as $deliveryNote) {
  406. if (isset($deliveryNote->orders[0])) {
  407. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  408. $deliveryNote->getAttributes();
  409. }
  410. }
  411. return $deliveryNotesByPointSaleArray;
  412. }
  413. public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
  414. {
  415. $pointSaleModule = $this->getPointSaleModule();
  416. $pointSaleDefault = $pointSaleModule->findOnePointSaleDefaultByDistribution($distribution);
  417. $productOrderArray = [];
  418. foreach ($productsArray as $product) {
  419. $productOrderArray[$product['id']] = [
  420. 'quantity' => 0,
  421. 'unit' => $product['unit'],
  422. 'price' => number_format($product['price'], 5),
  423. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  424. ];
  425. }
  426. return [
  427. 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
  428. 'id_user' => 0,
  429. 'username' => '',
  430. 'comment' => '',
  431. 'productOrder' => $productOrderArray
  432. ];
  433. }
  434. public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
  435. {
  436. return $this->getOrderModule()->getTillerManager()->isSynchronized($date);
  437. }
  438. public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
  439. {
  440. $subscriptionModule = $this->getSubscriptionModule();
  441. $missingSubscriptionsArray = [];
  442. $arraySubscriptions = $subscriptionModule->findSubscriptionsByDate($date);
  443. if ($distribution->active) {
  444. foreach ($arraySubscriptions as $subscription) {
  445. if (!$subscriptionModule->hasOrderAlreadyExist($subscription, $ordersArray)
  446. && $subscription->productSubscription && count($subscription->productSubscription)
  447. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  448. $missingSubscriptionsArray[] = [
  449. 'username' => $subscriptionModule->getUsername($subscription)
  450. ];
  451. }
  452. }
  453. }
  454. return $missingSubscriptionsArray;
  455. }
  456. public function actionAjaxPointSaleFavorite($idUser, $idDistribution)
  457. {
  458. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  459. $userModule = $this->getUserModule();
  460. $orderModule = $this->getOrderModule();
  461. $distributionModule = $this->getDistributionModule();
  462. $user = $userModule->findOneUserById($idUser);
  463. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  464. $idFavoritePointSale = 0;
  465. if($user) {
  466. $favoritePointSale = $orderModule->getUserFavoritePointSale($user, $distribution);
  467. if ($favoritePointSale) {
  468. $idFavoritePointSale = $favoritePointSale->id;
  469. }
  470. }
  471. return [
  472. 'id_favorite_point_sale' => $idFavoritePointSale
  473. ];
  474. }
  475. public function actionAjaxUpdateProductOrder(
  476. $idDistribution,
  477. $idUser = false,
  478. $idPointSale = false,
  479. $idOrder = false,
  480. $productOrderFormArray = ''
  481. )
  482. {
  483. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  484. $productOrderFormArray = json_decode($productOrderFormArray, true);
  485. $distributionModule = $this-> getDistributionModule();
  486. $orderModule = $this->getOrderModule();
  487. $userModule = $this->getUserModule();
  488. $pointSaleModule = $this->getPointSaleModule();
  489. $productModule = $this->getProductModule();
  490. $order = $orderModule->findOneOrderById($idOrder);
  491. $distribution = $distributionModule->findOneDistributionById($idDistribution);
  492. $user = $userModule->findOneUserById($idUser);
  493. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  494. $productsArray = Product::find()
  495. ->where([
  496. 'id_producer' => GlobalParam::getCurrentProducerId(),
  497. ])->joinWith([
  498. 'productPrice',
  499. 'productDistribution' => function ($q) use ($distribution) {
  500. $q->where(['id_distribution' => $distribution->id]);
  501. }
  502. ])->all();
  503. $productOrderArray = [];
  504. foreach ($productsArray as $product) {
  505. $priceArray = $productModule->getPriceArray($product, $user, $pointSale);
  506. $quantity = 0;
  507. $invoicePrice = null;
  508. if (isset($order->productOrder)) {
  509. foreach ($order->productOrder as $productOrder) {
  510. if ($productOrder->id_product == $product->id) {
  511. if ($productOrder->invoice_price) {
  512. $invoicePrice = number_format($productOrder->invoice_price, 5);
  513. } else {
  514. $invoicePrice = number_format($productOrder->price, 5);
  515. }
  516. $quantity = $productOrder->quantity;
  517. }
  518. }
  519. }
  520. // Quantité définie dans le formulaire
  521. if(isset($productOrderFormArray[$product->id]['quantity']) && $productOrderFormArray[$product->id]['quantity']) {
  522. $quantity = $productOrderFormArray[$product->id]['quantity'] / $productModule->getSolver()->getUnitCoefficient($product);
  523. }
  524. $productOrderArray[$product->id] = [
  525. 'quantity' => $quantity,
  526. 'unit' => $product->unit,
  527. 'prices' => $priceArray,
  528. 'active' => $product->productDistribution[0]->active
  529. && (!$pointSale || $productModule->isAvailableOnPointSale($product, $pointSale)),
  530. 'invoice_price' => $invoicePrice,
  531. ];
  532. }
  533. // construction de $orderOverride
  534. $orderOverride = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrderArray, $order);
  535. foreach($productOrderArray as $idProduct => $productOrder) {
  536. $product = $productModule->getRepository()->findOneProductById($idProduct);
  537. if($product) {
  538. $productOrderArray[$idProduct]['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($product, $distribution, $orderOverride);
  539. }
  540. }
  541. return $productOrderArray;
  542. }
  543. public function actionAjaxUpdateInvoicePrices($idOrder)
  544. {
  545. $orderModule = $this->getOrderModule();
  546. $userProducerModule = $this->getUserProducerModule();
  547. $productModule = $this->getProductModule();
  548. $order = $orderModule->findOneOrderById($idOrder);
  549. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  550. $userProducer = null;
  551. if ($order->id_user) {
  552. $userProducer = $userProducerModule->findOneUserProducer($order->user);
  553. }
  554. foreach ($order->productOrder as $productOrder) {
  555. $invoicePrice = $productModule->getPrice($productOrder->product, [
  556. 'user' => $orderModule->getUserForInvoicing($order),
  557. 'point_sale' => $order->pointSale,
  558. 'user_producer' => $userProducer,
  559. 'quantity' => $productOrder->quantity
  560. ]);
  561. if ($invoicePrice != $productOrder->price) {
  562. $productOrder->invoice_price = $invoicePrice;
  563. } else {
  564. $productOrder->invoice_price = null;
  565. }
  566. $productOrder->save();
  567. }
  568. }
  569. }
  570. /**
  571. * Génére un export pour une distribution.
  572. */
  573. public function actionExport(string $name, string $date = '')
  574. {
  575. $distributionModule = $this-> getDistributionModule();
  576. $distribution = $distributionModule->getRepository()->findOneDistribution($date);
  577. if ($distribution) {
  578. try {
  579. return $distributionModule->getExportManager()->getGenerator($name)->generate($distribution);
  580. }
  581. catch(ErrorException $exception) {
  582. //$this->setFlash('error', "Une erreur est survenue lors de la génération de l'export.");
  583. $this->setFlash('error', $exception->getMessage());
  584. return $this->redirectReferer();
  585. }
  586. }
  587. }
  588. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  589. {
  590. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  591. $orderModule = $this->getOrderModule();
  592. $productDistributionModule = $this->getProductDistributionModule();
  593. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  594. $productDistributionModule->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
  595. return [
  596. 'quantity_max' => $orderModule->getResolver()
  597. ->getProductQuantityMax(
  598. $productDistribution->product,
  599. $productDistribution->distribution
  600. ),
  601. 'quantity_remaining' => $orderModule->getResolver()
  602. ->getProductQuantityRemaining(
  603. $productDistribution->product,
  604. $productDistribution->distribution
  605. )
  606. ];
  607. }
  608. public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
  609. {
  610. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  611. $productDistributionModule = $this->getProductDistributionModule();
  612. $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
  613. $productDistributionModule->updateProductDistributionActive($productDistribution, $active);
  614. return ['success'];
  615. }
  616. public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
  617. {
  618. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  619. $distributionModule = $this-> getDistributionModule();
  620. $pointSaleModule = $this->getPointSaleModule();
  621. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  622. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution(
  623. $distributionModule->findOneDistributionById($idDistribution),
  624. $pointSaleModule->findOnePointSaleById($idPointSale)
  625. );
  626. $pointSaleDistribution->delivery = $delivery;
  627. $pointSaleDistributionModule->update($pointSaleDistribution);
  628. return ['success'];
  629. }
  630. public function getProductDistribution(int $idProduct, int $idDistribution)
  631. {
  632. $distributionModule = $this-> getDistributionModule();
  633. $productModule = $this->getProductModule();
  634. $productDistributionModule = $this->getProductDistributionModule();
  635. return $productDistributionModule->findOneProductDistribution(
  636. $distributionModule->findOneDistributionById($idDistribution),
  637. $productModule->findOneProductById($idProduct)
  638. );
  639. }
  640. /**
  641. * Active/désactive un jour de distribution.
  642. */
  643. public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
  644. {
  645. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  646. $distributionModule = $this-> getDistributionModule();
  647. $distribution = null;
  648. if ($idDistribution) {
  649. $distribution = $distributionModule->getRepository()->findOneDistributionById($idDistribution);
  650. }
  651. if ($distributionModule->getSolver()->validateDistributionDate($date)) {
  652. $distribution = $distributionModule->getBuilder()->createDistributionIfNotExist($date);
  653. }
  654. if ($distribution) {
  655. $distributionModule->getBuilder()->activeDistribution($distribution, $active);
  656. return ['success'];
  657. }
  658. return ['error'];
  659. }
  660. /**
  661. * Change l'état d'une semaine de distribution (activé, désactivé).
  662. */
  663. public function actionAjaxProcessActiveWeekDistribution(string $date, int $active)
  664. {
  665. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  666. $this->getDistributionModule()->getBuilder()->activeDistributionsOfWeek($date, $active);
  667. return ['success'];
  668. }
  669. /**
  670. * Ajoute les commandes récurrentes pour une date donnée.
  671. */
  672. public function actionAjaxProcessAddSubscriptions(string $date)
  673. {
  674. $ordersArray = $this->getOrderModule()->getManager()
  675. ->createAllOrdersFromSubscriptions($date, $this->getUserCurrent(), true);
  676. if($ordersArray && count($ordersArray)) {
  677. return Ajax::responseSuccess('Les abonnements ont bien été importés.');
  678. }
  679. return Ajax::responseError('Aucun abonnement à importer.');
  680. }
  681. /**
  682. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  683. */
  684. public function actionAjaxProcessSynchroTiller(string $date)
  685. {
  686. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  687. return $this->getOrderModule()->getTillerManager()->synchronizeDistribution($date);
  688. }
  689. public function actionAjaxForceSynchronizeOrderTiller(int $idOrder)
  690. {
  691. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  692. $order = $this->getOrderModule()->getRepository()->findOneOrderById($idOrder);
  693. return $this->getOrderModule()->getTillerManager()->synchronizeOrder($order, true);
  694. }
  695. public function actionAjaxGenerateDeliveryNotePointSale(string $idOrders)
  696. {
  697. if (strlen($idOrders)) {
  698. $idOrders = json_decode($idOrders, true);
  699. if(is_array($idOrders)) {
  700. try {
  701. if($this->getOrderModule()->getDocumentManager()->generateDeliveryNoteForPointSale($idOrders)) {
  702. return Ajax::responseSuccess("Bon de livraison généré");
  703. }
  704. }
  705. catch(Exception $exception) {
  706. return Ajax::responseError($exception->getMessage());
  707. }
  708. }
  709. }
  710. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  711. }
  712. public function actionAjaxGenerateDeliveryNote(int $idOrder)
  713. {
  714. $orderModule = $this->getOrderModule();
  715. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  716. $orderModule->getDocumentManager()->generateDeliveryNoteForUser($order);
  717. return Ajax::responseSuccess('Bon de livraison généré');
  718. }
  719. public function actionAjaxSendDeliveryNote(int $idOrder)
  720. {
  721. $orderModule = $this->getOrderModule();
  722. $documentModule = $this->getDocumentModule();
  723. $order = $orderModule->getRepository()->findOneOrderById($idOrder);
  724. if($order->deliveryNote) {
  725. $documentModule->getManager()->sendDocument($order->deliveryNote);
  726. return Ajax::responseSuccess('Bon de livraison envoyé');
  727. }
  728. return Ajax::responseSuccess('Une erreur est survenue lors de l\'envoi du bon de livraison.');
  729. }
  730. public function actionAjaxGenerateDeliveryNoteEachUser(string $idOrders)
  731. {
  732. if (strlen($idOrders)) {
  733. $idOrders = json_decode($idOrders, true);
  734. $this->getOrderModule()->getDocumentManager()->generateDeliveryNotesForUser($idOrders);
  735. return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
  736. }
  737. return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
  738. }
  739. public function actionAjaxValidateDeliveryNotes(string $idOrders)
  740. {
  741. if (strlen($idOrders)) {
  742. $idOrders = json_decode($idOrders, true);
  743. if($this->getOrderModule()->getDocumentManager()->validateDeliveryNotes($idOrders)) {
  744. return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
  745. }
  746. }
  747. return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
  748. }
  749. }