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

1753 line
68KB

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