Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1758 lines
69KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  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 backend\controllers\BackendController;
  39. use common\helpers\GlobalParam;
  40. use common\models\DeliveryNote;
  41. use common\models\Distribution;
  42. use common\models\Document;
  43. use common\models\PointSale;
  44. use common\models\Product;
  45. use common\models\Producer;
  46. use common\models\Order;
  47. use common\models\ProductCategory;
  48. use common\models\User;
  49. use common\models\Subscription;
  50. use common\helpers\Price;
  51. use common\models\PointSaleDistribution;
  52. use common\models\UserProducer;
  53. use DateTime;
  54. class DistributionController extends BackendController
  55. {
  56. public function behaviors()
  57. {
  58. return [
  59. 'access' => [
  60. 'class' => AccessControl::className(),
  61. 'rules' => [
  62. [
  63. 'actions' => ['report-cron', 'report-terredepains'],
  64. 'allow' => true,
  65. 'roles' => ['?']
  66. ],
  67. [
  68. 'allow' => true,
  69. 'roles' => ['@'],
  70. 'matchCallback' => function ($rule, $action) {
  71. return User::getCurrentStatus() == USER::STATUS_ADMIN
  72. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  73. }
  74. ]
  75. ],
  76. ],
  77. ];
  78. }
  79. public function actionIndex($date = '', $idOrderUpdate = 0)
  80. {
  81. $this->checkProductsPointsSale();
  82. $format = 'Y-m-d';
  83. $theDate = '';
  84. $dateObject = DateTime::createFromFormat($format, $date);
  85. if ($dateObject && $dateObject->format($format) === $date) {
  86. $theDate = $date;
  87. }
  88. $orderUpdate = null;
  89. if ($idOrderUpdate) {
  90. $orderUpdate = Order::searchOne(['id' => $idOrderUpdate]);
  91. }
  92. return $this->render('index', [
  93. 'date' => $theDate,
  94. 'orderUpdate' => $orderUpdate
  95. ]);
  96. }
  97. public function actionAjaxInfos($date = '')
  98. {
  99. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  100. $json = [
  101. 'distribution' => [],
  102. 'products' => []
  103. ];
  104. $format = 'Y-m-d';
  105. $dateObject = DateTime::createFromFormat($format, $date);
  106. $numberOfLoadedMonthes = '3 month';
  107. if (is_object($dateObject)) {
  108. $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  109. $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
  110. } else {
  111. $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
  112. $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
  113. }
  114. $producer = GlobalParam::getCurrentProducer();
  115. $json['producer'] = [
  116. 'credit' => $producer->credit,
  117. 'tiller' => $producer->tiller,
  118. 'option_display_export_grid' => $producer->option_display_export_grid
  119. ];
  120. $json['means_payment'] = MeanPayment::getAll();
  121. $distributionsArray = Distribution::searchAll([
  122. 'active' => 1
  123. ], [
  124. 'conditions' => [
  125. 'date > :date_begin',
  126. 'date < :date_end'
  127. ],
  128. 'params' => [
  129. ':date_begin' => date(
  130. 'Y-m-d',
  131. $dateBegin
  132. ),
  133. ':date_end' => date(
  134. 'Y-m-d',
  135. $dateEnd
  136. ),
  137. ],
  138. ]);
  139. $json['distributions'] = $distributionsArray;
  140. if ($dateObject && $dateObject->format($format) === $date) {
  141. // distribution
  142. $distribution = Distribution::initDistribution($date);
  143. $json['distribution'] = [
  144. 'id' => $distribution->id,
  145. 'active' => $distribution->active,
  146. 'url_report' => Yii::$app->urlManagerBackend->createUrl(
  147. ['distribution/report', 'date' => $distribution->date]
  148. ),
  149. 'url_report_grid' => Yii::$app->urlManagerBackend->createUrl(
  150. ['distribution/report-grid', 'date' => $distribution->date]
  151. ),
  152. ];
  153. // commandes
  154. $ordersArray = Order::searchAll([
  155. 'distribution.id' => $distribution->id,
  156. ], [
  157. 'orderby' => 'user.lastname ASC, user.name ASC'
  158. ]);
  159. // montant et poids des commandes
  160. $revenues = 0;
  161. $weight = 0;
  162. if ($ordersArray) {
  163. foreach ($ordersArray as $order) {
  164. if (is_null($order->date_delete)) {
  165. $revenues += $order->getAmountWithTax();
  166. $weight += $order->weight;
  167. }
  168. }
  169. }
  170. $json['distribution']['revenues'] = Price::format($revenues);
  171. $json['distribution']['weight'] = number_format($weight, 2);
  172. // products
  173. $productsQuery = Product::find()
  174. ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
  175. ->joinWith([
  176. 'taxRate',
  177. 'productDistribution' => function ($query) use ($distribution) {
  178. $query->andOnCondition(
  179. 'product_distribution.id_distribution = ' . $distribution->id
  180. );
  181. }
  182. ])
  183. ->orderBy('product_distribution.active DESC, order ASC');
  184. $productsArray = $productsQuery->asArray()->all();
  185. $potentialRevenues = 0;
  186. $potentialWeight = 0;
  187. foreach ($productsArray as &$theProduct) {
  188. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray);
  189. $theProduct['quantity_ordered'] = $quantityOrder;
  190. if (!isset($theProduct['productDistribution'][0])) {
  191. $theProductObject = (object)$theProduct;
  192. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject);
  193. }
  194. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  195. $theProduct['quantity_remaining'] = null;
  196. } else {
  197. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  198. }
  199. $theProduct['quantity_form'] = 0;
  200. if ($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  201. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  202. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  203. }
  204. if (!isset($theProduct['taxRate'])) {
  205. $theProduct['taxRate'] = $producer->taxRate;
  206. }
  207. }
  208. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
  209. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2);
  210. $json['products'] = $productsArray;
  211. // orders as array
  212. $ordersArrayObject = $ordersArray;
  213. if ($ordersArray) {
  214. foreach ($ordersArray as &$order) {
  215. $productOrderArray = [];
  216. foreach ($order->productOrder as $productOrder) {
  217. $productOrderArray[$productOrder->id_product] = [
  218. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  219. 'unit' => $productOrder->unit,
  220. 'price' => number_format($productOrder->price, 3),
  221. 'invoice_price' => number_format($productOrder->invoice_price, 2),
  222. 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
  223. ];
  224. }
  225. foreach ($productsArray as $product) {
  226. if (!isset($productOrderArray[$product['id']])) {
  227. $productOrderArray[$product['id']] = [
  228. 'quantity' => 0,
  229. 'unit' => $product['unit'],
  230. 'price' => number_format($product['price'], 3),
  231. 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  232. ];
  233. }
  234. }
  235. $creditHistoryArray = [];
  236. foreach ($order->creditHistory as $creditHistory) {
  237. $creditHistoryArray[] = [
  238. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  239. 'user' => $creditHistory->user->getUsername(),
  240. 'user_action' => $creditHistory->strUserAction(),
  241. 'wording' => $creditHistory->getStrWording(),
  242. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;' . $creditHistory->getAmount(
  243. Order::AMOUNT_TOTAL,
  244. true
  245. ) : ''),
  246. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;' . $creditHistory->getAmount(
  247. Order::AMOUNT_TOTAL,
  248. true
  249. ) : '')
  250. ];
  251. }
  252. $arrayCreditUser = [];
  253. if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
  254. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
  255. }
  256. $oneProductUnactivated = false;
  257. foreach ($order->productOrder as $productOrder) {
  258. foreach ($productsArray as $product) {
  259. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  260. $oneProductUnactivated = true;
  261. }
  262. }
  263. }
  264. $order = array_merge($order->getAttributes(), [
  265. 'selected' => false,
  266. 'weight' => $order->weight,
  267. 'amount' => Price::numberTwoDecimals($order->getAmountWithTax(Order::AMOUNT_TOTAL)),
  268. 'amount_paid' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_PAID)),
  269. 'amount_remaining' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_REMAINING)),
  270. 'amount_surplus' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_SURPLUS)),
  271. 'user' => (isset($order->user)) ? array_merge(
  272. $order->user->getAttributes(),
  273. $arrayCreditUser
  274. ) : null,
  275. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  276. 'productOrder' => $productOrderArray,
  277. 'creditHistory' => $creditHistoryArray,
  278. 'oneProductUnactivated' => $oneProductUnactivated,
  279. 'isLinkedToValidDocument' => $order->isLinkedToValidDocument(),
  280. ]);
  281. }
  282. }
  283. $json['orders'] = $ordersArray;
  284. // points de vente
  285. $pointsSaleArray = PointSale::find()
  286. ->joinWith([
  287. 'pointSaleDistribution' => function ($q) use ($distribution) {
  288. $q->where(['id_distribution' => $distribution->id]);
  289. }
  290. ])
  291. ->where([
  292. 'id_producer' => GlobalParam::getCurrentProducerId(),
  293. ])
  294. ->asArray()
  295. ->all();
  296. $idPointSaleDefault = 0;
  297. foreach ($pointsSaleArray as $pointSale) {
  298. if ($pointSale['default']) {
  299. $idPointSaleDefault = $pointSale['id'];
  300. }
  301. }
  302. $json['points_sale'] = $pointsSaleArray;
  303. // bons de livraison
  304. $deliveryNotesArray = DeliveryNote::searchAll([
  305. 'distribution.date' => $date,
  306. ], [
  307. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  308. ]);
  309. $deliveryNotesByPointSaleArray = [];
  310. foreach ($deliveryNotesArray as $deliveryNote) {
  311. if (isset($deliveryNote->orders[0])) {
  312. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  313. $deliveryNote->getAttributes();
  314. }
  315. }
  316. $json['delivery_notes'] = $deliveryNotesByPointSaleArray;
  317. // order create
  318. $productOrderArray = [];
  319. foreach ($productsArray as $product) {
  320. $productOrderArray[$product['id']] = [
  321. 'quantity' => 0,
  322. 'unit' => $product['unit'],
  323. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  324. ];
  325. }
  326. $json['order_create'] = [
  327. 'id_point_sale' => $idPointSaleDefault,
  328. 'id_user' => 0,
  329. 'username' => '',
  330. 'comment' => '',
  331. 'productOrder' => $productOrderArray
  332. ];
  333. // utilisateurs
  334. $usersArray = User::findBy()->all();
  335. $json['users'] = $usersArray;
  336. // une production de la semaine activée ou non
  337. $oneDistributionWeekActive = false;
  338. $week = sprintf('%02d', date('W', strtotime($date)));
  339. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  340. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  341. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  342. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  343. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  344. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  345. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  346. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  347. $weekDistribution = Distribution::find()
  348. ->andWhere([
  349. 'id_producer' => GlobalParam::getCurrentProducerId(),
  350. 'active' => 1,
  351. ])
  352. ->andWhere([
  353. 'or',
  354. ['date' => $dateMonday],
  355. ['date' => $dateTuesday],
  356. ['date' => $dateWednesday],
  357. ['date' => $dateThursday],
  358. ['date' => $dateFriday],
  359. ['date' => $dateSaturday],
  360. ['date' => $dateSunday],
  361. ])
  362. ->one();
  363. if ($weekDistribution) {
  364. $oneDistributionWeekActive = true;
  365. }
  366. $json['one_distribution_week_active'] = $oneDistributionWeekActive;
  367. // tiller
  368. if ($producer->tiller) {
  369. $tiller = new Tiller();
  370. $json['tiller_is_synchro'] = (int)$tiller->isSynchro($date);
  371. }
  372. // abonnements manquants
  373. $arraySubscriptions = Subscription::searchByDate($date);
  374. $json['missing_subscriptions'] = [];
  375. if ($distribution->active) {
  376. foreach ($arraySubscriptions as $subscription) {
  377. if (!$subscription->hasOrderAlreadyExist($ordersArrayObject)
  378. && $subscription->productSubscription && count($subscription->productSubscription)
  379. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  380. $json['missing_subscriptions'][] = [
  381. 'username' => $subscription->getUsername()
  382. ];
  383. }
  384. }
  385. }
  386. }
  387. return $json;
  388. }
  389. public function actionAjaxPointSaleFavorite($idUser)
  390. {
  391. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  392. $user = User::findOne(['id' => $idUser]);
  393. $favoritePointSale = $user->getFavoritePointSale();
  394. $idFavoritePointSale = 0;
  395. if ($favoritePointSale) {
  396. $idFavoritePointSale = $favoritePointSale->id;
  397. }
  398. return [
  399. 'id_favorite_point_sale' => $idFavoritePointSale
  400. ];
  401. }
  402. public function actionAjaxUpdateProductOrder(
  403. $idDistribution,
  404. $idUser = false,
  405. $idPointSale = false,
  406. $idOrder = false
  407. )
  408. {
  409. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  410. $order = Order::searchOne(['id' => $idOrder]);
  411. $distribution = Distribution::findOne($idDistribution);
  412. $user = User::findOne($idUser);
  413. $pointSale = PointSale::findOne($idPointSale);
  414. $productsArray = Product::find()
  415. ->where([
  416. 'id_producer' => GlobalParam::getCurrentProducerId(),
  417. ])->joinWith([
  418. 'productPrice',
  419. 'productDistribution' => function ($q) use ($distribution) {
  420. $q->where(['id_distribution' => $distribution->id]);
  421. }
  422. ])->all();
  423. $productOrderArray = [];
  424. foreach ($productsArray as $product) {
  425. $priceArray = $product->getPriceArray($user, $pointSale);
  426. $quantity = 0;
  427. $invoicePrice = null;
  428. if(isset($order->productOrder)) {
  429. foreach ($order->productOrder as $productOrder) {
  430. if ($productOrder->id_product == $product['id']) {
  431. if ($productOrder->invoice_price) {
  432. $invoicePrice = number_format($productOrder->invoice_price, 2);
  433. } else {
  434. $invoicePrice = number_format($productOrder->price, 3);
  435. }
  436. $quantity = $productOrder->quantity;
  437. }
  438. }
  439. }
  440. $productOrderArray[$product['id']] = [
  441. 'quantity' => $quantity,
  442. 'unit' => $product->unit,
  443. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  444. 'prices' => $priceArray,
  445. 'active' => $product->productDistribution[0]->active
  446. && (!$pointSale || $product->isAvailableOnPointSale($pointSale)),
  447. 'invoice_price' => $invoicePrice
  448. ];
  449. }
  450. return $productOrderArray;
  451. }
  452. public function actionAjaxUpdateInvoicePrices($idOrder)
  453. {
  454. $order = Order::searchOne([
  455. 'id' => (int)$idOrder
  456. ]);
  457. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  458. $userProducer = null;
  459. if ($order->id_user) {
  460. $userProducer = UserProducer::searchOne([
  461. 'id_user' => $order->id_user,
  462. 'id_producer' => GlobalParam::getCurrentProducerId()
  463. ]);
  464. }
  465. foreach ($order->productOrder as $productOrder) {
  466. $invoicePrice = $productOrder->product->getPrice([
  467. 'user' => $order->user ?: null,
  468. 'point_sale' => $order->pointSale,
  469. 'user_producer' => $userProducer,
  470. 'quantity' => $productOrder->quantity
  471. ]);
  472. if ($invoicePrice != $productOrder->price) {
  473. $productOrder->invoice_price = $invoicePrice;
  474. }
  475. else {
  476. $productOrder->invoice_price = null;
  477. }
  478. $productOrder->save();
  479. }
  480. }
  481. }
  482. /**
  483. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  484. * date donnée (Méthode appelable via CRON)
  485. *
  486. * @param string $date
  487. * @param boolean $save
  488. * @param integer $idProducer
  489. * @param string $key
  490. * @return PDF|null
  491. */
  492. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  493. {
  494. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  495. $this->actionReport($date, $save, $idProducer);
  496. }
  497. }
  498. /**
  499. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  500. * date donnée.
  501. *
  502. * @param string $date
  503. * @param boolean $save
  504. * @param integer $idProducer
  505. * @return PDF|null
  506. */
  507. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  508. {
  509. if (!Yii::$app->user->isGuest) {
  510. $idProducer = GlobalParam::getCurrentProducerId();
  511. }
  512. $ordersArray = Order::searchAll(
  513. [
  514. 'distribution.date' => $date,
  515. 'distribution.id_producer' => $idProducer
  516. ],
  517. [
  518. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  519. 'conditions' => 'date_delete IS NULL'
  520. ]
  521. );
  522. $distribution = Distribution::searchOne([
  523. 'id_producer' => $idProducer
  524. ], [
  525. 'conditions' => 'date LIKE :date',
  526. 'params' => [':date' => $date]
  527. ]);
  528. if ($distribution) {
  529. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  530. $pointsSaleArray = PointSale::searchAll([
  531. 'point_sale.id_producer' => $idProducer
  532. ]);
  533. foreach ($pointsSaleArray as $pointSale) {
  534. $pointSale->initOrders($ordersArray);
  535. }
  536. // produits
  537. $productsArray = Product::find()
  538. ->joinWith([
  539. 'productDistribution' => function ($q) use ($distribution) {
  540. $q->where(['id_distribution' => $distribution->id]);
  541. }
  542. ])
  543. ->where([
  544. 'id_producer' => $idProducer,
  545. ])
  546. ->orderBy('order ASC')
  547. ->all();
  548. if ($type == 'pdf') {
  549. $viewPdf = 'report';
  550. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  551. $producer = GlobalParam::getCurrentProducer();
  552. if ($producer->slug == 'bourlinguepacotille') {
  553. $viewPdf = 'report-bourlingue';
  554. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  555. }
  556. // get your HTML raw content without any layouts or scripts
  557. $content = $this->renderPartial($viewPdf, [
  558. 'date' => $date,
  559. 'distribution' => $distribution,
  560. 'selectedProductsArray' => $selectedProductsArray,
  561. 'pointsSaleArray' => $pointsSaleArray,
  562. 'productsArray' => $productsArray,
  563. 'ordersArray' => $ordersArray,
  564. 'producer' => Producer::searchOne(['id' => $idProducer])
  565. ]);
  566. $dateStr = date('d/m/Y', strtotime($date));
  567. if ($save) {
  568. $destination = Pdf::DEST_FILE;
  569. } else {
  570. $destination = Pdf::DEST_BROWSER;
  571. }
  572. $pdf = new Pdf([
  573. // set to use core fonts only
  574. 'mode' => Pdf::MODE_UTF8,
  575. // A4 paper format
  576. 'format' => Pdf::FORMAT_A4,
  577. // portrait orientation
  578. 'orientation' => $orientationPdf,
  579. // stream to browser inline
  580. 'destination' => $destination,
  581. 'filename' => Yii::getAlias(
  582. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  583. ),
  584. // your html content input
  585. 'content' => $content,
  586. // format content from your own css file if needed or use the
  587. // enhanced bootstrap css built by Krajee for mPDF formatting
  588. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  589. // any css to be embedded if required
  590. 'cssInline' => '
  591. table {
  592. border-spacing : 0px ;
  593. border-collapse : collapse ;
  594. width: 100% ;
  595. }
  596. table tr th,
  597. table tr td {
  598. padding: 0px ;
  599. margin: 0px ;
  600. border: solid 1px #e0e0e0 ;
  601. padding: 3px 8px ;
  602. vertical-align : top;
  603. page-break-inside: avoid !important;
  604. color: black;
  605. }
  606. table tr th {
  607. font-size: 13px ;
  608. }
  609. table tr td {
  610. font-size: 13px ;
  611. }
  612. ',
  613. // set mPDF properties on the fly
  614. //'options' => ['title' => 'Krajee Report Title'],
  615. // call mPDF methods on the fly
  616. 'methods' => [
  617. 'SetHeader' => ['Commandes du ' . $dateStr],
  618. 'SetFooter' => ['{PAGENO}'],
  619. ]
  620. ]);
  621. // return the pdf output as per the destination setting
  622. return $pdf->render();
  623. } elseif ($type == 'csv') {
  624. $datas = [];
  625. $optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products');
  626. $optionCsvExportByPiece = Producer::getConfig('option_csv_export_by_piece');
  627. // produits en colonne
  628. $productsNameArray = ['', 'Commentaire'];
  629. $productsIndexArray = [];
  630. $productsHasQuantity = [];
  631. $cpt = 2;
  632. foreach ($productsArray as $product) {
  633. $productsHasQuantity[$product->id] = 0;
  634. foreach (Product::$unitsArray as $unit => $dataUnit) {
  635. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  636. if ($quantity) {
  637. $productsHasQuantity[$product->id] += $quantity;
  638. }
  639. }
  640. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  641. $productName = $product->getNameExport();
  642. if ($optionCsvExportByPiece) {
  643. $productUnit = 'piece';
  644. } else {
  645. $productUnit = $product->unit;
  646. }
  647. $productName .= ' (' . Product::strUnit($productUnit, 'wording_short', true) . ')';
  648. $productsNameArray[] = $productName;
  649. $productsIndexArray[$product->id] = $cpt++;
  650. }
  651. }
  652. $datas[] = $productsNameArray;
  653. // points de vente
  654. foreach ($pointsSaleArray as $pointSale) {
  655. if (count($pointSale->orders)) {
  656. // listing commandes
  657. $datas[] = ['> ' . $pointSale->name];
  658. foreach ($pointSale->orders as $order) {
  659. $orderLine = [$order->getStrUser(), $order->getCommentReport()];
  660. if ($optionCsvExportByPiece) {
  661. foreach ($order->productOrder as $productOrder) {
  662. $orderLine[$productsIndexArray[$productOrder->id_product]] = Order::getProductQuantityPieces(
  663. $productOrder->id_product,
  664. [$order]
  665. );
  666. }
  667. } else {
  668. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  669. $orderLine[$indexProduct] = '';
  670. }
  671. foreach ($order->productOrder as $productOrder) {
  672. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  673. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  674. }
  675. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  676. if ($productOrder->product->unit != $productOrder->unit) {
  677. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit(
  678. $productOrder->unit,
  679. 'wording_short',
  680. true
  681. );
  682. }
  683. }
  684. }
  685. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  686. }
  687. // total point de vente
  688. if ($optionCsvExportByPiece) {
  689. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  690. 'Total',
  691. $pointSale->orders,
  692. $productsArray,
  693. $productsIndexArray
  694. );
  695. } else {
  696. $totalsPointSaleArray = $this->_totalReportCSV(
  697. 'Total',
  698. $pointSale->orders,
  699. $productsArray,
  700. $productsIndexArray
  701. );
  702. }
  703. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  704. $datas[] = [];
  705. }
  706. }
  707. // global
  708. if ($optionCsvExportByPiece) {
  709. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  710. '> Totaux',
  711. $ordersArray,
  712. $productsArray,
  713. $productsIndexArray
  714. );
  715. } else {
  716. $totalsGlobalArray = $this->_totalReportCSV(
  717. '> Totaux',
  718. $ordersArray,
  719. $productsArray,
  720. $productsIndexArray
  721. );
  722. }
  723. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  724. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  725. echo CSV::array2csv($datas);
  726. die();
  727. }
  728. }
  729. return null;
  730. }
  731. public function actionReportGrid($date = '', $save = false, $idProducer = 0, $type = "pdf")
  732. {
  733. if (!Yii::$app->user->isGuest) {
  734. $idProducer = GlobalParam::getCurrentProducerId();
  735. }
  736. $distribution = Distribution::searchOne([
  737. 'id_producer' => $idProducer
  738. ], [
  739. 'conditions' => 'date LIKE :date',
  740. 'params' => [':date' => $date]
  741. ]);
  742. if ($distribution) {
  743. $ordersArray = Order::searchAll(
  744. [
  745. 'distribution.date' => $date,
  746. 'distribution.id_producer' => $idProducer
  747. ],
  748. [
  749. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  750. 'conditions' => 'date_delete IS NULL'
  751. ]
  752. );
  753. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  754. $pointsSaleArray = PointSale::searchAll([
  755. 'point_sale.id_producer' => $idProducer
  756. ]);
  757. foreach ($pointsSaleArray as $pointSale) {
  758. $pointSale->initOrders($ordersArray);
  759. }
  760. $ordersByPage = 22;
  761. $nbPages = ceil(count($ordersArray) / $ordersByPage);
  762. $ordersArrayPaged = [];
  763. foreach ($pointsSaleArray as $pointSale) {
  764. $index = 0;
  765. $indexPage = 0;
  766. foreach ($pointSale->orders as $order) {
  767. if (!isset($ordersArrayPaged[$pointSale->id])) {
  768. $ordersArrayPaged[$pointSale->id] = [];
  769. }
  770. if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
  771. $ordersArrayPaged[$pointSale->id][$indexPage] = [];
  772. }
  773. $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;
  774. $index++;
  775. if ($index == $ordersByPage) {
  776. $index = 0;
  777. $indexPage++;
  778. }
  779. }
  780. }
  781. // catégories
  782. $categoriesArray = ProductCategory::searchAll(
  783. ['id_producer' => $idProducer],
  784. ['orderby' => 'product_category.position ASC']
  785. );
  786. array_unshift($categoriesArray, null);
  787. // produits
  788. $productsArray = Product::find()
  789. ->joinWith([
  790. 'productDistribution' => function ($q) use ($distribution) {
  791. $q->where(['id_distribution' => $distribution->id]);
  792. }
  793. ])
  794. ->where([
  795. 'id_producer' => $idProducer,
  796. ])
  797. ->orderBy('order ASC')
  798. ->all();
  799. $viewPdf = 'report-grid';
  800. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  801. $producer = GlobalParam::getCurrentProducer();
  802. if ($producer->slug == 'bourlinguepacotille') {
  803. $viewPdf = 'report-bourlingue';
  804. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  805. }
  806. // get your HTML raw content without any layouts or scripts
  807. $content = $this->renderPartial($viewPdf, [
  808. 'date' => $date,
  809. 'distribution' => $distribution,
  810. 'selectedProductsArray' => $selectedProductsArray,
  811. 'pointsSaleArray' => $pointsSaleArray,
  812. 'categoriesArray' => $categoriesArray,
  813. 'productsArray' => $productsArray,
  814. 'ordersArray' => $ordersArrayPaged,
  815. 'producer' => Producer::searchOne(['id' => $idProducer])
  816. ]);
  817. $dateStr = date('d/m/Y', strtotime($date));
  818. if ($save) {
  819. $destination = Pdf::DEST_FILE;
  820. } else {
  821. $destination = Pdf::DEST_BROWSER;
  822. }
  823. $pdf = new Pdf([
  824. // set to use core fonts only
  825. 'mode' => Pdf::MODE_UTF8,
  826. // A4 paper format
  827. 'format' => Pdf::FORMAT_A4,
  828. // portrait orientation
  829. 'orientation' => $orientationPdf,
  830. // stream to browser inline
  831. 'destination' => $destination,
  832. 'filename' => Yii::getAlias(
  833. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  834. ),
  835. // your html content input
  836. 'content' => $content,
  837. // format content from your own css file if needed or use the
  838. // enhanced bootstrap css built by Krajee for mPDF formatting
  839. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  840. // any css to be embedded if required
  841. 'cssInline' => '
  842. table {
  843. border-spacing : 0px ;
  844. border-collapse : collapse ;
  845. width: 100% ;
  846. }
  847. table tr th,
  848. table tr td {
  849. padding: 0px ;
  850. margin: 0px ;
  851. border: solid 1px #e0e0e0 ;
  852. padding: 3px ;
  853. vertical-align : top;
  854. page-break-inside: avoid !important;
  855. }
  856. table tr th {
  857. font-size: 10px ;
  858. }
  859. table tr td {
  860. font-size: 10px ;
  861. }
  862. table thead tr {
  863. line-height: 220px;
  864. text-align:left;
  865. }
  866. .th-user,
  867. .td-nb-products {
  868. /* width: 35px ; */
  869. text-align: center ;
  870. }
  871. .th-user {
  872. padding: 10px ;
  873. }
  874. .category-name {
  875. font-weight: bold ;
  876. }
  877. ',
  878. // set mPDF properties on the fly
  879. //'options' => ['title' => 'Krajee Report Title'],
  880. // call mPDF methods on the fly
  881. 'methods' => [
  882. 'SetHeader' => ['Commandes du ' . $dateStr],
  883. 'SetFooter' => ['{PAGENO}'],
  884. ]
  885. ]);
  886. // return the pdf output as per the destination setting
  887. return $pdf->render();
  888. }
  889. }
  890. /**
  891. * Génère un export des commandes au format CSV à destination du Google Drive
  892. * de Terre de pains.
  893. *
  894. * @param type $date
  895. * @return CSV
  896. */
  897. public function actionReportTerredepains($date, $key)
  898. {
  899. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  900. $producer = Producer::searchOne([
  901. 'producer.slug' => 'terredepains'
  902. ]);
  903. $idProducer = $producer->id;
  904. $ordersArray = Order::searchAll(
  905. [
  906. 'distribution.date' => $date,
  907. 'distribution.id_producer' => $idProducer
  908. ],
  909. [
  910. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  911. 'conditions' => 'date_delete IS NULL'
  912. ]
  913. );
  914. $distribution = Distribution::searchOne([
  915. 'distribution.id_producer' => $idProducer
  916. ], [
  917. 'conditions' => 'date LIKE :date',
  918. 'params' => [
  919. ':date' => $date,
  920. ]
  921. ]);
  922. if ($distribution) {
  923. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  924. $pointsSaleArray = PointSale::searchAll([
  925. 'point_sale.id_producer' => $idProducer
  926. ]);
  927. foreach ($pointsSaleArray as $pointSale) {
  928. $pointSale->initOrders($ordersArray);
  929. }
  930. // produits
  931. $productsArray = Product::find()
  932. ->joinWith([
  933. 'productDistribution' => function ($q) use ($distribution) {
  934. $q->where(['id_distribution' => $distribution->id]);
  935. }
  936. ])
  937. ->where([
  938. 'id_producer' => $idProducer,
  939. ])
  940. ->orderBy('order ASC')
  941. ->all();
  942. $datas = [];
  943. // produits en colonne
  944. $productsNameArray = [''];
  945. $productsIndexArray = [];
  946. $productsHasQuantity = [];
  947. $cpt = 1;
  948. foreach ($productsArray as $product) {
  949. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  950. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  951. $productsNameArray[] = $product->name . $theUnit;
  952. $productsIndexArray[$product->id] = $cpt++;
  953. }
  954. $productsNameArray[] = 'Total';
  955. $datas[] = $productsNameArray;
  956. // global
  957. $totalsGlobalArray = $this->_totalReportCSV(
  958. '> Totaux',
  959. $ordersArray,
  960. $productsArray,
  961. $productsIndexArray
  962. );
  963. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  964. $datas[] = [];
  965. // points de vente
  966. foreach ($pointsSaleArray as $pointSale) {
  967. if (count($pointSale->orders)) {
  968. // listing commandes
  969. /*foreach ($pointSale->orders as $order) {
  970. $orderLine = [$order->getStrUser()];
  971. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  972. $orderLine[$indexProduct] = '';
  973. }
  974. foreach ($order->productOrder as $productOrder) {
  975. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  976. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  977. }
  978. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  979. if ($productOrder->product->unit != $productOrder->unit) {
  980. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  981. }
  982. }
  983. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  984. }*/
  985. // total point de vente
  986. $totalsPointSaleArray = $this->_totalReportCSV(
  987. '> ' . $pointSale->name,
  988. $pointSale->orders,
  989. $productsArray,
  990. $productsIndexArray
  991. );
  992. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  993. }
  994. }
  995. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  996. echo CSV::array2csv($datas);
  997. die();
  998. }
  999. return null;
  1000. }
  1001. }
  1002. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  1003. {
  1004. $totalsPointSaleArray = [$label];
  1005. foreach ($productsArray as $product) {
  1006. foreach (Product::$unitsArray as $unit => $dataUnit) {
  1007. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  1008. if ($quantity) {
  1009. $index = $productsIndexArray[$product->id];
  1010. if (!isset($totalsPointSaleArray[$index])) {
  1011. $totalsPointSaleArray[$index] = '';
  1012. }
  1013. if (strlen($totalsPointSaleArray[$index])) {
  1014. $totalsPointSaleArray[$index] .= ' + ';
  1015. }
  1016. $totalsPointSaleArray[$index] .= $quantity;
  1017. if ($product->unit != $unit) {
  1018. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. return $totalsPointSaleArray;
  1024. }
  1025. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  1026. {
  1027. $totalsPointSaleArray = [$label];
  1028. foreach ($productsArray as $product) {
  1029. $quantity = 0;
  1030. foreach (Product::$unitsArray as $unit => $dataUnit) {
  1031. $quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  1032. if ($unit == 'piece') {
  1033. $quantity += $quantityProduct;
  1034. } else {
  1035. if ($product->weight > 0) {
  1036. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight;
  1037. }
  1038. }
  1039. }
  1040. if ($quantity) {
  1041. $index = $productsIndexArray[$product->id];
  1042. $totalsPointSaleArray[$index] = $quantity;
  1043. }
  1044. }
  1045. return $totalsPointSaleArray;
  1046. }
  1047. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  1048. {
  1049. $line = [];
  1050. $cptTotal = 0;
  1051. for ($i = 0; $i <= $cptMax; $i++) {
  1052. if (isset($orderLine[$i]) && $orderLine[$i]) {
  1053. $line[] = $orderLine[$i];
  1054. if (is_numeric($orderLine[$i])) {
  1055. $cptTotal += $orderLine[$i];
  1056. }
  1057. } else {
  1058. $line[] = '';
  1059. }
  1060. }
  1061. if ($cptTotal > 0 && $showTotal) {
  1062. $line[] = $cptTotal;
  1063. }
  1064. return $line;
  1065. }
  1066. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  1067. {
  1068. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1069. $productDistribution = ProductDistribution::searchOne([
  1070. 'id_distribution' => $idDistribution,
  1071. 'id_product' => $idProduct,
  1072. ]);
  1073. $productDistribution->quantity_max = (!$quantityMax) ? null : (float)$quantityMax;
  1074. $productDistribution->save();
  1075. return ['success'];
  1076. }
  1077. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  1078. {
  1079. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1080. $productDistribution = ProductDistribution::searchOne([
  1081. 'id_distribution' => $idDistribution,
  1082. 'id_product' => $idProduct,
  1083. ]);
  1084. $productDistribution->active = $active;
  1085. $productDistribution->save();
  1086. return ['success'];
  1087. }
  1088. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  1089. {
  1090. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1091. $pointSaleDistribution = PointSaleDistribution::searchOne([
  1092. 'id_distribution' => $idDistribution,
  1093. 'id_point_sale' => $idPointSale,
  1094. ]);
  1095. $pointSaleDistribution->delivery = $delivery;
  1096. $pointSaleDistribution->save();
  1097. return ['success'];
  1098. }
  1099. /**
  1100. * Active/désactive un jour de distribution.
  1101. *
  1102. * @param integer $idDistribution
  1103. * @param string $date
  1104. * @param boolean $active
  1105. * @return array
  1106. */
  1107. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  1108. {
  1109. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1110. if ($idDistribution) {
  1111. $distribution = Distribution::searchOne([
  1112. 'id' => $idDistribution
  1113. ]);
  1114. }
  1115. $format = 'Y-m-d';
  1116. $dateObject = DateTime::createFromFormat($format, $date);
  1117. if ($dateObject && $dateObject->format($format) === $date) {
  1118. $distribution = Distribution::initDistribution($date);
  1119. }
  1120. if ($distribution) {
  1121. $distribution->active($active);
  1122. return ['success'];
  1123. }
  1124. return ['error'];
  1125. }
  1126. /**
  1127. * Change l'état d'une semaine de production (activé, désactivé).
  1128. *
  1129. * @param string $date
  1130. * @param integer $active
  1131. */
  1132. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  1133. {
  1134. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1135. $week = sprintf('%02d', date('W', strtotime($date)));
  1136. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  1137. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  1138. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  1139. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  1140. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  1141. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  1142. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  1143. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  1144. $pointsSaleArray = PointSale::searchAll();
  1145. $activeMonday = false;
  1146. $activeTuesday = false;
  1147. $activeWednesday = false;
  1148. $activeThursday = false;
  1149. $activeFriday = false;
  1150. $activeSaturday = false;
  1151. $activeSunday = false;
  1152. foreach ($pointsSaleArray as $pointSale) {
  1153. if ($pointSale->delivery_monday) {
  1154. $activeMonday = true;
  1155. }
  1156. if ($pointSale->delivery_tuesday) {
  1157. $activeTuesday = true;
  1158. }
  1159. if ($pointSale->delivery_wednesday) {
  1160. $activeWednesday = true;
  1161. }
  1162. if ($pointSale->delivery_thursday) {
  1163. $activeThursday = true;
  1164. }
  1165. if ($pointSale->delivery_friday) {
  1166. $activeFriday = true;
  1167. }
  1168. if ($pointSale->delivery_saturday) {
  1169. $activeSaturday = true;
  1170. }
  1171. if ($pointSale->delivery_sunday) {
  1172. $activeSunday = true;
  1173. }
  1174. }
  1175. if ($activeMonday || !$active) {
  1176. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  1177. }
  1178. if ($activeTuesday || !$active) {
  1179. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  1180. }
  1181. if ($activeWednesday || !$active) {
  1182. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  1183. }
  1184. if ($activeThursday || !$active) {
  1185. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  1186. }
  1187. if ($activeFriday || !$active) {
  1188. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  1189. }
  1190. if ($activeSaturday || !$active) {
  1191. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  1192. }
  1193. if ($activeSunday || !$active) {
  1194. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  1195. }
  1196. return ['success'];
  1197. }
  1198. /**
  1199. * Ajoute les commandes récurrentes pour une date donnée.
  1200. *
  1201. * @param string $date
  1202. */
  1203. public function actionAjaxProcessAddSubscriptions($date)
  1204. {
  1205. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1206. Subscription::addAll($date, true);
  1207. return ['success'];
  1208. }
  1209. /**
  1210. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  1211. *
  1212. * @param string $date
  1213. */
  1214. public function actionAjaxProcessSynchroTiller($date)
  1215. {
  1216. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1217. $return = [];
  1218. $producerTiller = Producer::getConfig('tiller');
  1219. if ($producerTiller) {
  1220. $tiller = new Tiller();
  1221. $isSynchro = $tiller->isSynchro($date);
  1222. if (!$isSynchro) {
  1223. $orders = Order::searchAll([
  1224. 'distribution.date' => $date,
  1225. 'order.tiller_synchronization' => 1
  1226. ], [
  1227. 'conditions' => 'date_delete IS NULL'
  1228. ]);
  1229. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  1230. if ($orders && count($orders)) {
  1231. foreach ($orders as $order) {
  1232. $lines = [];
  1233. foreach ($order->productOrder as $productOrder) {
  1234. $lines[] = [
  1235. 'name' => $productOrder->product->name,
  1236. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  1237. 'tax' => $productOrder->taxRate->value * 100,
  1238. 'date' => $strDate,
  1239. 'quantity' => $productOrder->quantity
  1240. ];
  1241. }
  1242. $typePaymentTiller = '';
  1243. if ($order->mean_payment == MeanPayment::MONEY) {
  1244. $typePaymentTiller = 'CASH';
  1245. }
  1246. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1247. || $order->mean_payment == MeanPayment::CREDIT
  1248. || $order->mean_payment == MeanPayment::TRANSFER
  1249. || $order->mean_payment == MeanPayment::OTHER) {
  1250. $typePaymentTiller = 'CARD';
  1251. }
  1252. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1253. $typePaymentTiller = 'BANK_CHECK';
  1254. }
  1255. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1256. $typePaymentTiller = 'CASH';
  1257. }
  1258. $returnTiller = $tiller->postOrder([
  1259. 'externalId' => $order->id,
  1260. 'type' => 1,
  1261. 'status' => 'IN_PROGRESS',
  1262. 'openDate' => $strDate,
  1263. 'closeDate' => $strDate,
  1264. 'lines' => $lines,
  1265. 'payments' => [
  1266. [
  1267. 'type' => $typePaymentTiller,
  1268. 'amount' => $order->getAmountWithTax(
  1269. Order::AMOUNT_TOTAL
  1270. ) * 100,
  1271. 'status' => 'ACCEPTED',
  1272. 'date' => $strDate
  1273. ]
  1274. ]
  1275. ]);
  1276. $returnTillerObject = json_decode($returnTiller);
  1277. $order->tiller_external_id = '' . $returnTillerObject->id;
  1278. $order->save();
  1279. $return[] = $returnTiller;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return $return;
  1285. }
  1286. public function actionAjaxValidateDeliveryNotes($idOrders)
  1287. {
  1288. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1289. if (strlen($idOrders)) {
  1290. $idOrders = json_decode($idOrders, true);
  1291. if (is_array($idOrders) && count($idOrders) > 0) {
  1292. foreach ($idOrders as $idOrder) {
  1293. $order = Order::searchOne([
  1294. 'id' => (int)$idOrder
  1295. ]);
  1296. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1297. $deliveryNote = DeliveryNote::searchOne([
  1298. 'id' => (int)$order->id_delivery_note
  1299. ]);
  1300. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1301. $deliveryNote->changeStatus(Document::STATUS_VALID);
  1302. $deliveryNote->save();
  1303. }
  1304. }
  1305. }
  1306. return [
  1307. 'return' => 'success',
  1308. 'alert' => [
  1309. 'type' => 'success',
  1310. 'message' => 'Bon(s) de livraison validé(s)'
  1311. ]
  1312. ];
  1313. }
  1314. }
  1315. return [
  1316. 'return' => 'error',
  1317. 'alert' => [
  1318. 'type' => 'danger',
  1319. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1320. ]
  1321. ];
  1322. }
  1323. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1324. {
  1325. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1326. if (strlen($idOrders)) {
  1327. $idOrders = json_decode($idOrders, true);
  1328. if (is_array($idOrders) && count($idOrders) > 0) {
  1329. foreach ($idOrders as $idOrder) {
  1330. $order = Order::searchOne([
  1331. 'id' => (int)$idOrder
  1332. ]);
  1333. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_user) {
  1334. $deliveryNote = null;
  1335. $idDeliveryNote = $order->id_delivery_note;
  1336. if ($idDeliveryNote) {
  1337. $deliveryNote = DeliveryNote::searchOne([
  1338. 'id' => (int)$idDeliveryNote
  1339. ]);
  1340. }
  1341. // on regénére le document si c'est un brouillon
  1342. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1343. $deliveryNote->delete();
  1344. $deliveryNote = null;
  1345. }
  1346. if (!$deliveryNote) {
  1347. $deliveryNote = new DeliveryNote();
  1348. $deliveryNote->initTaxCalculationMethod();
  1349. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1350. $deliveryNote->id_user = $order->id_user;
  1351. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date(
  1352. 'd/m/Y',
  1353. strtotime(
  1354. $order->distribution->date
  1355. )
  1356. ) . ')';
  1357. $deliveryNote->address = $order->user->getFullAddress();
  1358. $deliveryNote->save();
  1359. }
  1360. if ($deliveryNote) {
  1361. $order->id_delivery_note = $deliveryNote->id;
  1362. $order->save();
  1363. // init invoice prices
  1364. $user = User::searchOne([
  1365. 'id' => $deliveryNote->id_user
  1366. ]);
  1367. $userProducer = UserProducer::searchOne([
  1368. 'id_user' => $deliveryNote->id_user,
  1369. 'id_producer' => GlobalParam::getCurrentProducerId()
  1370. ]);
  1371. $order->initInvoicePrices([
  1372. 'user' => $user,
  1373. 'user_producer' => $userProducer,
  1374. 'point_sale' => $order->pointSale
  1375. ]);
  1376. }
  1377. }
  1378. }
  1379. }
  1380. return [
  1381. 'return' => 'success',
  1382. 'alert' => [
  1383. 'type' => 'success',
  1384. 'message' => 'Bon(s) de livraison généré(s)'
  1385. ]
  1386. ];
  1387. }
  1388. return [
  1389. 'return' => 'error',
  1390. 'alert' => [
  1391. 'type' => 'danger',
  1392. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1393. ]
  1394. ];
  1395. }
  1396. public function actionAjaxGenerateDeliveryNote($idOrders)
  1397. {
  1398. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1399. if (strlen($idOrders)) {
  1400. $idOrders = json_decode($idOrders, true);
  1401. if (is_array($idOrders) && count($idOrders) > 0) {
  1402. // récupération première commande pour obtenir des infos
  1403. reset($idOrders);
  1404. $firstOrder = Order::searchOne([
  1405. 'id' => (int)$idOrders[key($idOrders)]
  1406. ]);
  1407. // deliveryNote existant
  1408. $deliveryNote = null;
  1409. $isUpdate = false;
  1410. $i = 0;
  1411. $ordersArray = Order::searchAll([
  1412. 'id' => $idOrders,
  1413. ]);
  1414. do {
  1415. $order = $ordersArray[$i];
  1416. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  1417. $deliveryNote = DeliveryNote::searchOne([
  1418. 'id' => $order->id_delivery_note
  1419. ]);
  1420. $isUpdate = true;
  1421. }
  1422. $i++;
  1423. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1424. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1425. return [
  1426. 'return' => 'error',
  1427. 'alert' => [
  1428. 'type' => 'danger',
  1429. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1430. ]
  1431. ];
  1432. }
  1433. if ($firstOrder) {
  1434. // génération du BL
  1435. if (!$deliveryNote) {
  1436. $deliveryNote = new DeliveryNote;
  1437. $deliveryNote->initTaxCalculationMethod();
  1438. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1439. 'd/m/Y',
  1440. strtotime(
  1441. $firstOrder->distribution->date
  1442. )
  1443. ) . ')';
  1444. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1445. if ($firstOrder->pointSale->id_user) {
  1446. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1447. $user = User::searchOne([
  1448. 'id' => $deliveryNote->id_user
  1449. ]);
  1450. $userProducer = UserProducer::searchOne([
  1451. 'id_user' => $deliveryNote->id_user,
  1452. 'id_producer' => GlobalParam::getCurrentProducerId()
  1453. ]);
  1454. } else {
  1455. $user = new User;
  1456. $user->type = User::TYPE_LEGAL_PERSON;
  1457. $user->name_legal_person = $firstOrder->pointSale->name;
  1458. $user->address = $firstOrder->pointSale->address;
  1459. $user->id_producer = 0;
  1460. $user->setPassword(Password::generate());
  1461. $user->generateAuthKey();
  1462. $user->email = '';
  1463. if (!strlen($user->email)) {
  1464. $user->username = 'inconnu@opendistrib.net';
  1465. }
  1466. $user->save();
  1467. $userProducer = new UserProducer;
  1468. $userProducer->id_user = $user->id;
  1469. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1470. $userProducer->credit = 0;
  1471. $userProducer->active = 1;
  1472. $userProducer->save();
  1473. $firstOrder->pointSale->id_user = $user->id;
  1474. $firstOrder->pointSale->save();
  1475. $deliveryNote->id_user = $user->id;
  1476. }
  1477. $deliveryNote->address = $user->getFullAddress();
  1478. $deliveryNote->save();
  1479. } else {
  1480. // réinitialisation des order.id_delivery_note
  1481. Order::updateAll([
  1482. 'id_delivery_note' => null
  1483. ], [
  1484. 'id_delivery_note' => $deliveryNote->id
  1485. ]);
  1486. }
  1487. if (!isset($user) || !$user) {
  1488. $user = User::searchOne([
  1489. 'id' => $deliveryNote->id_user
  1490. ]);
  1491. $userProducer = UserProducer::searchOne([
  1492. 'id_user' => $deliveryNote->id_user,
  1493. 'id_producer' => GlobalParam::getCurrentProducerId()
  1494. ]);
  1495. }
  1496. // affectation du BL aux commandes
  1497. foreach ($idOrders as $idOrder) {
  1498. $order = Order::searchOne([
  1499. 'id' => (int)$idOrder
  1500. ]);
  1501. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1502. $order->id_delivery_note = $deliveryNote->id;
  1503. $order->save();
  1504. }
  1505. // init invoice price
  1506. $order = Order::searchOne(['id' => $idOrder]);
  1507. if ($order) {
  1508. $order->initInvoicePrices([
  1509. 'user' => $user,
  1510. 'user_producer' => $userProducer,
  1511. 'point_sale' => $firstOrder->pointSale
  1512. ]);
  1513. }
  1514. }
  1515. return [
  1516. 'return' => 'success',
  1517. 'alert' => [
  1518. 'type' => 'success',
  1519. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1520. ]
  1521. ];
  1522. }
  1523. }
  1524. }
  1525. return [
  1526. 'return' => 'error',
  1527. 'alert' => [
  1528. 'type' => 'danger',
  1529. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1530. ]
  1531. ];
  1532. }
  1533. }