Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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