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

DistributionController.php 64KB

6 jaren geleden
6 jaren geleden
6 jaren geleden
6 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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\Product;
  44. use common\models\Producer;
  45. use common\models\Order;
  46. use common\models\User;
  47. use common\models\Subscription;
  48. use common\helpers\Price;
  49. use common\models\PointSaleDistribution;
  50. use common\models\UserProducer;
  51. use DateTime;
  52. class DistributionController extends BackendController
  53. {
  54. public function behaviors()
  55. {
  56. return [
  57. 'access' => [
  58. 'class' => AccessControl::className(),
  59. 'rules' => [
  60. [
  61. 'actions' => ['report-cron', 'report-terredepains'],
  62. 'allow' => true,
  63. 'roles' => ['?']
  64. ],
  65. [
  66. 'allow' => true,
  67. 'roles' => ['@'],
  68. 'matchCallback' => function ($rule, $action) {
  69. return User::getCurrentStatus() == USER::STATUS_ADMIN
  70. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  71. }
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionIndex($date = '')
  78. {
  79. $this->checkProductsPointsSale();
  80. $format = 'Y-m-d';
  81. $theDate = '';
  82. $dateObject = DateTime::createFromFormat($format, $date);
  83. if ($dateObject && $dateObject->format($format) === $date) {
  84. $theDate = $date;
  85. }
  86. return $this->render('index', [
  87. 'date' => $theDate
  88. ]);
  89. }
  90. public function actionAjaxInfos($date = '')
  91. {
  92. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  93. $json = [
  94. 'distribution' => [],
  95. 'products' => []
  96. ];
  97. $format = 'Y-m-d';
  98. $dateObject = DateTime::createFromFormat($format, $date);
  99. $producer = GlobalParam::getCurrentProducer();
  100. $json['producer'] = [
  101. 'credit' => $producer->credit,
  102. 'tiller' => $producer->tiller
  103. ];
  104. $json['means_payment'] = MeanPayment::getAll();
  105. $distributionsArray = Distribution::searchAll([
  106. 'active' => 1
  107. ], [
  108. 'conditions' => ['date > :date_begin', 'date < :date_end'],
  109. 'params' => [':date_begin' => date('Y-m-d', strtotime('-1 month')), ':date_end' => date('Y-m-d', strtotime('+3 month')),],
  110. ]);
  111. $json['distributions'] = $distributionsArray;
  112. if ($dateObject && $dateObject->format($format) === $date) {
  113. // distribution
  114. $distribution = Distribution::initDistribution($date);
  115. $json['distribution'] = [
  116. 'id' => $distribution->id,
  117. 'active' => $distribution->active,
  118. 'url_report' => Yii::$app->urlManagerBackend->createUrl(['distribution/report', 'date' => $distribution->date])
  119. ];
  120. // commandes
  121. $ordersArray = Order::searchAll([
  122. 'distribution.id' => $distribution->id,
  123. ], [
  124. 'orderby' => 'user.lastname ASC, user.name ASC'
  125. ]);
  126. // montant et poids des commandes
  127. $revenues = 0;
  128. $weight = 0;
  129. if ($ordersArray) {
  130. foreach ($ordersArray as $order) {
  131. if (is_null($order->date_delete)) {
  132. $revenues += $order->getAmountWithTax();
  133. $weight += $order->weight;
  134. }
  135. }
  136. }
  137. $json['distribution']['revenues'] = Price::format($revenues);
  138. $json['distribution']['weight'] = number_format($weight, 2);
  139. // products
  140. $productsArray = Product::find()
  141. ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
  142. ->joinWith(['taxRate','productDistribution' => function ($query) use ($distribution) {
  143. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  144. }])
  145. ->orderBy('product_distribution.active DESC, order ASC')
  146. ->asArray()
  147. ->all();
  148. $potentialRevenues = 0;
  149. $potentialWeight = 0;
  150. foreach ($productsArray as &$theProduct) {
  151. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray);
  152. $theProduct['quantity_ordered'] = $quantityOrder;
  153. if (!isset($theProduct['productDistribution'][0])) {
  154. $theProductObject = (object)$theProduct;
  155. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject);
  156. }
  157. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  158. $theProduct['quantity_remaining'] = null;
  159. } else {
  160. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  161. }
  162. $theProduct['quantity_form'] = 0;
  163. if ($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  164. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  165. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  166. }
  167. if(!isset($theProduct['taxRate'])) {
  168. $theProduct['taxRate'] = $producer->taxRate ;
  169. }
  170. }
  171. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
  172. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2);
  173. $json['products'] = $productsArray;
  174. // orders as array
  175. $ordersArrayObject = $ordersArray ;
  176. if ($ordersArray) {
  177. foreach ($ordersArray as &$order) {
  178. $productOrderArray = [];
  179. foreach ($order->productOrder as $productOrder) {
  180. $productOrderArray[$productOrder->id_product] = [
  181. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  182. 'unit' => $productOrder->unit,
  183. 'price' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value)
  184. ];
  185. }
  186. foreach ($productsArray as $product) {
  187. if (!isset($productOrderArray[$product['id']])) {
  188. $productOrderArray[$product['id']] = [
  189. 'quantity' => 0,
  190. 'unit' => $product['unit'],
  191. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  192. ];
  193. }
  194. }
  195. $creditHistoryArray = [];
  196. foreach ($order->creditHistory as $creditHistory) {
  197. $creditHistoryArray[] = [
  198. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  199. 'user_action' => $creditHistory->strUserAction(),
  200. 'wording' => $creditHistory->getStrWording(),
  201. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;' . $creditHistory->getAmount(Order::AMOUNT_TOTAL, true) : ''),
  202. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;' . $creditHistory->getAmount(Order::AMOUNT_TOTAL, true) : '')
  203. ];
  204. }
  205. $arrayCreditUser = [];
  206. if (isset($order->user) && isset($order->user->userProducer)) {
  207. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
  208. }
  209. $oneProductUnactivated = false;
  210. foreach ($order->productOrder as $productOrder) {
  211. foreach ($productsArray as $product) {
  212. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  213. $oneProductUnactivated = true;
  214. }
  215. }
  216. }
  217. $order = array_merge($order->getAttributes(), [
  218. 'selected' => false,
  219. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  220. 'amount_paid' => $order->getAmount(Order::AMOUNT_PAID),
  221. 'amount_remaining' => $order->getAmount(Order::AMOUNT_REMAINING),
  222. 'amount_surplus' => $order->getAmount(Order::AMOUNT_SURPLUS),
  223. 'user' => (isset($order->user)) ? array_merge($order->user->getAttributes(), $arrayCreditUser) : null,
  224. 'pointSale' => ['id' => $order->pointSale->id, 'name' => $order->pointSale->name],
  225. 'productOrder' => $productOrderArray,
  226. 'creditHistory' => $creditHistoryArray,
  227. 'oneProductUnactivated' => $oneProductUnactivated
  228. ]);
  229. }
  230. }
  231. $json['orders'] = $ordersArray;
  232. // points de vente
  233. $pointsSaleArray = PointSale::find()
  234. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  235. $q->where(['id_distribution' => $distribution->id]);
  236. }])
  237. ->where([
  238. 'id_producer' => GlobalParam::getCurrentProducerId(),
  239. ])
  240. ->asArray()
  241. ->all();
  242. $idPointSaleDefault = 0;
  243. foreach ($pointsSaleArray as $pointSale) {
  244. if ($pointSale['default']) {
  245. $idPointSaleDefault = $pointSale['id'] ;
  246. }
  247. }
  248. $json['points_sale'] = $pointsSaleArray;
  249. // bons de livraison
  250. $deliveryNotesArray = DeliveryNote::searchAll([
  251. 'distribution.date' => $date,
  252. ]) ;
  253. $deliveryNotesByPointSaleArray = [] ;
  254. foreach($deliveryNotesArray as $deliveryNote) {
  255. if(isset($deliveryNote->orders[0])) {
  256. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  257. $deliveryNote->getAttributes() ;
  258. }
  259. }
  260. $json['delivery_notes'] = $deliveryNotesByPointSaleArray ;
  261. // order create
  262. $productOrderArray = [];
  263. foreach ($productsArray as $product) {
  264. $productOrderArray[$product['id']] = [
  265. 'quantity' => 0,
  266. 'unit' => $product['unit'],
  267. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  268. ];
  269. }
  270. $json['order_create'] = [
  271. 'id_point_sale' => $idPointSaleDefault,
  272. 'id_user' => 0,
  273. 'username' => '',
  274. 'comment' => '',
  275. 'productOrder' => $productOrderArray
  276. ];
  277. // utilisateurs
  278. $usersArray = User::findBy()->all();
  279. $json['users'] = $usersArray;
  280. // une production de la semaine activée ou non
  281. $oneDistributionWeekActive = false;
  282. $week = sprintf('%02d', date('W', strtotime($date)));
  283. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  284. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  285. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  286. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  287. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  288. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  289. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  290. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  291. $weekDistribution = Distribution::find()
  292. ->andWhere([
  293. 'id_producer' => GlobalParam::getCurrentProducerId(),
  294. 'active' => 1,
  295. ])
  296. ->andWhere(['or',
  297. ['date' => $dateMonday],
  298. ['date' => $dateTuesday],
  299. ['date' => $dateWednesday],
  300. ['date' => $dateThursday],
  301. ['date' => $dateFriday],
  302. ['date' => $dateSaturday],
  303. ['date' => $dateSunday],
  304. ])
  305. ->one();
  306. if ($weekDistribution) {
  307. $oneDistributionWeekActive = true;
  308. }
  309. $json['one_distribution_week_active'] = $oneDistributionWeekActive;
  310. // tiller
  311. if ($producer->tiller) {
  312. $tiller = new Tiller();
  313. $json['tiller_is_synchro'] = (int)$tiller->isSynchro($date);
  314. }
  315. }
  316. return $json;
  317. }
  318. public function actionAjaxPointSaleFavorite($idUser)
  319. {
  320. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  321. $user = User::findOne(['id' => $idUser]);
  322. $favoritePointSale = $user->getFavoritePointSale();
  323. $idFavoritePointSale = 0;
  324. if ($favoritePointSale) {
  325. $idFavoritePointSale = $favoritePointSale->id;
  326. }
  327. return [
  328. 'id_favorite_point_sale' => $idFavoritePointSale
  329. ];
  330. }
  331. /**
  332. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  333. * date donnée (Méthode appelable via CRON)
  334. *
  335. * @param string $date
  336. * @param boolean $save
  337. * @param integer $idProducer
  338. * @param string $key
  339. * @return PDF|null
  340. */
  341. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  342. {
  343. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  344. $this->actionReport($date, $save, $idProducer);
  345. }
  346. }
  347. /**
  348. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  349. * date donnée.
  350. *
  351. * @param string $date
  352. * @param boolean $save
  353. * @param integer $idProducer
  354. * @return PDF|null
  355. */
  356. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  357. {
  358. if (!Yii::$app->user->isGuest) {
  359. $idProducer = GlobalParam::getCurrentProducerId();
  360. }
  361. $ordersArray = Order::searchAll([
  362. 'distribution.date' => $date,
  363. 'distribution.id_producer' => $idProducer
  364. ],
  365. [
  366. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  367. 'conditions' => 'date_delete IS NULL'
  368. ]);
  369. $distribution = Distribution::searchOne([
  370. 'id_producer' => $idProducer
  371. ], [
  372. 'conditions' => 'date LIKE :date',
  373. 'params' => [':date' => $date]
  374. ]);
  375. if ($distribution) {
  376. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  377. $pointsSaleArray = PointSale::searchAll([
  378. 'point_sale.id_producer' => $idProducer
  379. ]);
  380. foreach ($pointsSaleArray as $pointSale) {
  381. $pointSale->initOrders($ordersArray);
  382. }
  383. // produits
  384. $productsArray = Product::find()
  385. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  386. $q->where(['id_distribution' => $distribution->id]);
  387. }])
  388. ->where([
  389. 'id_producer' => $idProducer,
  390. ])
  391. ->orderBy('order ASC')
  392. ->all();
  393. if ($type == 'pdf') {
  394. // get your HTML raw content without any layouts or scripts
  395. $content = $this->renderPartial('report', [
  396. 'date' => $date,
  397. 'distribution' => $distribution,
  398. 'selectedProductsArray' => $selectedProductsArray,
  399. 'pointsSaleArray' => $pointsSaleArray,
  400. 'productsArray' => $productsArray,
  401. 'ordersArray' => $ordersArray
  402. ]);
  403. $dateStr = date('d/m/Y', strtotime($date));
  404. if ($save) {
  405. $destination = Pdf::DEST_FILE;
  406. } else {
  407. $destination = Pdf::DEST_BROWSER;
  408. }
  409. $pdf = new Pdf([
  410. // set to use core fonts only
  411. 'mode' => Pdf::MODE_UTF8,
  412. // A4 paper format
  413. 'format' => Pdf::FORMAT_A4,
  414. // portrait orientation
  415. 'orientation' => Pdf::ORIENT_PORTRAIT,
  416. // stream to browser inline
  417. 'destination' => $destination,
  418. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  419. // your html content input
  420. 'content' => $content,
  421. // format content from your own css file if needed or use the
  422. // enhanced bootstrap css built by Krajee for mPDF formatting
  423. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  424. // any css to be embedded if required
  425. 'cssInline' => '
  426. table {
  427. border-spacing : 0px ;
  428. border-collapse : collapse ;
  429. width: 100% ;
  430. }
  431. table tr th,
  432. table tr td {
  433. padding: 0px ;
  434. margin: 0px ;
  435. border: solid 1px #e0e0e0 ;
  436. padding: 3px 8px ;
  437. vertical-align : top;
  438. page-break-inside: avoid !important;
  439. }
  440. table tr th {
  441. font-size: 13px ;
  442. }
  443. table tr td {
  444. font-size: 13px ;
  445. }
  446. ',
  447. // set mPDF properties on the fly
  448. //'options' => ['title' => 'Krajee Report Title'],
  449. // call mPDF methods on the fly
  450. 'methods' => [
  451. 'SetHeader' => ['Commandes du ' . $dateStr],
  452. 'SetFooter' => ['{PAGENO}'],
  453. ]
  454. ]);
  455. // return the pdf output as per the destination setting
  456. return $pdf->render();
  457. } elseif ($type == 'csv') {
  458. $datas = [];
  459. // produits en colonne
  460. $productsNameArray = [''];
  461. $productsIndexArray = [];
  462. $productsHasQuantity = [];
  463. $cpt = 1;
  464. foreach ($productsArray as $product) {
  465. $productsHasQuantity[$product->id] = 0;
  466. foreach (Product::$unitsArray as $unit => $dataUnit) {
  467. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  468. if ($quantity) {
  469. $productsHasQuantity[$product->id] += $quantity;
  470. }
  471. }
  472. if ($productsHasQuantity[$product->id] > 0) {
  473. $productsNameArray[] = $product->name . ' (' . Product::strUnit($product->unit, 'wording_short', true) . ')';
  474. $productsIndexArray[$product->id] = $cpt++;
  475. }
  476. }
  477. $datas[] = $productsNameArray;
  478. // points de vente
  479. foreach ($pointsSaleArray as $pointSale) {
  480. if (count($pointSale->orders)) {
  481. // listing commandes
  482. $datas[] = ['> ' . $pointSale->name];
  483. foreach ($pointSale->orders as $order) {
  484. $orderLine = [$order->getStrUser()];
  485. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  486. $orderLine[$indexProduct] = '';
  487. }
  488. foreach ($order->productOrder as $productOrder) {
  489. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  490. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  491. }
  492. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  493. if ($productOrder->product->unit != $productOrder->unit) {
  494. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  495. }
  496. }
  497. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  498. }
  499. // total point de vente
  500. $totalsPointSaleArray = $this->_totalReportCSV(
  501. 'Total',
  502. $pointSale->orders,
  503. $productsArray,
  504. $productsIndexArray
  505. );
  506. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  507. $datas[] = [];
  508. }
  509. }
  510. // global
  511. $totalsGlobalArray = $this->_totalReportCSV(
  512. '> Totaux',
  513. $ordersArray,
  514. $productsArray,
  515. $productsIndexArray
  516. );
  517. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  518. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  519. echo CSV::array2csv($datas);
  520. die();
  521. }
  522. }
  523. return null;
  524. }
  525. /**
  526. * Génère un export des commandes au format CSV à destination du Google Drive
  527. * de Terre de pains.
  528. *
  529. * @param type $date
  530. * @return CSV
  531. */
  532. public function actionReportTerredepains($date, $key)
  533. {
  534. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  535. $producer = Producer::searchOne([
  536. 'producer.slug' => 'terredepains'
  537. ]);
  538. $idProducer = $producer->id;
  539. $ordersArray = Order::searchAll([
  540. 'distribution.date' => $date,
  541. 'distribution.id_producer' => $idProducer
  542. ],
  543. [
  544. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  545. 'conditions' => 'date_delete IS NULL'
  546. ]);
  547. $distribution = Distribution::searchOne([
  548. 'distribution.id_producer' => $idProducer
  549. ], [
  550. 'conditions' => 'date LIKE :date',
  551. 'params' => [
  552. ':date' => $date,
  553. ]
  554. ]);
  555. if ($distribution) {
  556. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  557. $pointsSaleArray = PointSale::searchAll([
  558. 'point_sale.id_producer' => $idProducer
  559. ]);
  560. foreach ($pointsSaleArray as $pointSale) {
  561. $pointSale->initOrders($ordersArray);
  562. }
  563. // produits
  564. $productsArray = Product::find()
  565. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  566. $q->where(['id_distribution' => $distribution->id]);
  567. }])
  568. ->where([
  569. 'id_producer' => $idProducer,
  570. ])
  571. ->orderBy('order ASC')
  572. ->all();
  573. $datas = [];
  574. // produits en colonne
  575. $productsNameArray = [''];
  576. $productsIndexArray = [];
  577. $productsHasQuantity = [];
  578. $cpt = 1;
  579. foreach ($productsArray as $product) {
  580. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  581. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  582. $productsNameArray[] = $product->name . $theUnit;
  583. $productsIndexArray[$product->id] = $cpt++;
  584. }
  585. $productsNameArray[] = 'Total';
  586. $datas[] = $productsNameArray;
  587. // global
  588. $totalsGlobalArray = $this->_totalReportCSV(
  589. '> Totaux',
  590. $ordersArray,
  591. $productsArray,
  592. $productsIndexArray
  593. );
  594. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  595. $datas[] = [];
  596. // points de vente
  597. foreach ($pointsSaleArray as $pointSale) {
  598. if (count($pointSale->orders)) {
  599. // listing commandes
  600. $datas[] = ['> ' . $pointSale->name];
  601. foreach ($pointSale->orders as $order) {
  602. $orderLine = [$order->getStrUser()];
  603. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  604. $orderLine[$indexProduct] = '';
  605. }
  606. foreach ($order->productOrder as $productOrder) {
  607. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  608. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  609. }
  610. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  611. if ($productOrder->product->unit != $productOrder->unit) {
  612. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  613. }
  614. }
  615. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  616. }
  617. // total point de vente
  618. $totalsPointSaleArray = $this->_totalReportCSV(
  619. 'Total point de vente',
  620. $pointSale->orders,
  621. $productsArray,
  622. $productsIndexArray
  623. );
  624. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  625. $datas[] = [];
  626. }
  627. }
  628. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  629. echo CSV::array2csv($datas);
  630. die();
  631. }
  632. return null;
  633. }
  634. }
  635. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  636. {
  637. $totalsPointSaleArray = [$label];
  638. foreach ($productsArray as $product) {
  639. foreach (Product::$unitsArray as $unit => $dataUnit) {
  640. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  641. if ($quantity) {
  642. $index = $productsIndexArray[$product->id];
  643. if (!isset($totalsPointSaleArray[$index])) {
  644. $totalsPointSaleArray[$index] = '';
  645. }
  646. if (strlen($totalsPointSaleArray[$index])) {
  647. $totalsPointSaleArray[$index] .= ' + ';
  648. }
  649. $totalsPointSaleArray[$index] .= $quantity;
  650. if ($product->unit != $unit) {
  651. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  652. }
  653. }
  654. }
  655. }
  656. return $totalsPointSaleArray;
  657. }
  658. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  659. {
  660. $line = [];
  661. $cptTotal = 0;
  662. for ($i = 0; $i <= $cptMax; $i++) {
  663. if (isset($orderLine[$i]) && $orderLine[$i]) {
  664. $line[] = $orderLine[$i];
  665. $cptTotal += $orderLine[$i];
  666. } else {
  667. $line[] = '';
  668. }
  669. }
  670. if ($cptTotal > 0 && $showTotal) {
  671. $line[] = $cptTotal;
  672. }
  673. return $line;
  674. }
  675. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  676. {
  677. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  678. $productDistribution = ProductDistribution::searchOne([
  679. 'id_distribution' => $idDistribution,
  680. 'id_product' => $idProduct,
  681. ]);
  682. $productDistribution->quantity_max = (!$quantityMax) ? null : (float) $quantityMax;
  683. $productDistribution->save();
  684. return ['success'];
  685. }
  686. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  687. {
  688. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  689. $productDistribution = ProductDistribution::searchOne([
  690. 'id_distribution' => $idDistribution,
  691. 'id_product' => $idProduct,
  692. ]);
  693. $productDistribution->active = $active;
  694. $productDistribution->save();
  695. return ['success'];
  696. }
  697. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  698. {
  699. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  700. $pointSaleDistribution = PointSaleDistribution::searchOne([
  701. 'id_distribution' => $idDistribution,
  702. 'id_point_sale' => $idPointSale,
  703. ]);
  704. $pointSaleDistribution->delivery = $delivery;
  705. $pointSaleDistribution->save();
  706. return ['success'];
  707. }
  708. /**
  709. * Active/désactive un jour de distribution.
  710. *
  711. * @param integer $idDistribution
  712. * @param string $date
  713. * @param boolean $active
  714. * @return array
  715. */
  716. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  717. {
  718. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  719. if ($idDistribution) {
  720. $distribution = Distribution::searchOne([
  721. 'id' => $idDistribution
  722. ]);
  723. }
  724. $format = 'Y-m-d';
  725. $dateObject = DateTime::createFromFormat($format, $date);
  726. if ($dateObject && $dateObject->format($format) === $date) {
  727. $distribution = Distribution::initDistribution($date);
  728. }
  729. if ($distribution) {
  730. $distribution->active($active);
  731. return ['success'];
  732. }
  733. return ['error'];
  734. }
  735. /**
  736. * Change l'état d'une semaine de production (activé, désactivé).
  737. *
  738. * @param string $date
  739. * @param integer $active
  740. */
  741. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  742. {
  743. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  744. $week = sprintf('%02d', date('W', strtotime($date)));
  745. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  746. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  747. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  748. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  749. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  750. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  751. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  752. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  753. $pointsSaleArray = PointSale::searchAll();
  754. $activeMonday = false;
  755. $activeTuesday = false;
  756. $activeWednesday = false;
  757. $activeThursday = false;
  758. $activeFriday = false;
  759. $activeSaturday = false;
  760. $activeSunday = false;
  761. foreach ($pointsSaleArray as $pointSale) {
  762. if ($pointSale->delivery_monday) $activeMonday = true;
  763. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  764. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  765. if ($pointSale->delivery_thursday) $activeThursday = true;
  766. if ($pointSale->delivery_friday) $activeFriday = true;
  767. if ($pointSale->delivery_saturday) $activeSaturday = true;
  768. if ($pointSale->delivery_sunday) $activeSunday = true;
  769. }
  770. if ($activeMonday || !$active) {
  771. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  772. }
  773. if ($activeTuesday || !$active) {
  774. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  775. }
  776. if ($activeWednesday || !$active) {
  777. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  778. }
  779. if ($activeThursday || !$active) {
  780. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  781. }
  782. if ($activeFriday || !$active) {
  783. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  784. }
  785. if ($activeSaturday || !$active) {
  786. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  787. }
  788. if ($activeSunday || !$active) {
  789. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  790. }
  791. return ['success'];
  792. }
  793. /**
  794. * Ajoute les commandes récurrentes pour une date donnée.
  795. *
  796. * @param string $date
  797. */
  798. public function actionAjaxProcessAddSubscriptions($date)
  799. {
  800. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  801. Subscription::addAll($date, true);
  802. return ['success'];
  803. }
  804. /**
  805. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  806. *
  807. * @param string $date
  808. */
  809. public function actionAjaxProcessSynchroTiller($date)
  810. {
  811. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  812. $return = [] ;
  813. $producerTiller = Producer::getConfig('tiller');
  814. if ($producerTiller) {
  815. $tiller = new Tiller();
  816. $isSynchro = $tiller->isSynchro($date);
  817. if (!$isSynchro) {
  818. $orders = Order::searchAll([
  819. 'distribution.date' => $date,
  820. 'order.tiller_synchronization' => 1
  821. ]);
  822. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  823. if ($orders && count($orders)) {
  824. foreach ($orders as $order) {
  825. $lines = [];
  826. foreach ($order->productOrder as $productOrder) {
  827. $lines[] = [
  828. 'name' => $productOrder->product->name,
  829. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  830. 'tax' => $productOrder->taxRate->value * 100,
  831. 'date' => $strDate,
  832. 'quantity' => $productOrder->quantity
  833. ];
  834. }
  835. $typePaymentTiller = '';
  836. if ($order->mean_payment == MeanPayment::MONEY
  837. || $order->mean_payment == MeanPayment::CREDIT
  838. || $order->mean_payment == MeanPayment::TRANSFER
  839. || $order->mean_payment == MeanPayment::OTHER) {
  840. $typePaymentTiller = 'CASH';
  841. }
  842. if ($order->mean_payment == MeanPayment::CREDIT_CARD) {
  843. $typePaymentTiller = 'CARD';
  844. }
  845. if ($order->mean_payment == MeanPayment::CHEQUE) {
  846. $typePaymentTiller = 'BANK_CHECK';
  847. }
  848. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  849. $typePaymentTiller = 'CASH';
  850. }
  851. $return[] = $tiller->postOrder([
  852. 'externalId' => $order->id,
  853. 'type' => 1,
  854. 'status' => "CLOSED",
  855. 'openDate' => $strDate,
  856. 'closeDate' => $strDate,
  857. 'lines' => $lines,
  858. 'payments' => [[
  859. 'type' => $typePaymentTiller,
  860. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL) * 100,
  861. 'status' => 'ACCEPTED',
  862. 'date' => $strDate
  863. ]]
  864. ]);
  865. }
  866. }
  867. }
  868. }
  869. return $return ;
  870. }
  871. public function actionAjaxValidateDeliveryNotes($idOrders)
  872. {
  873. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  874. if (strlen($idOrders)) {
  875. $idOrders = json_decode($idOrders, true);
  876. if (is_array($idOrders) && count($idOrders) > 0) {
  877. foreach($idOrders as $idOrder) {
  878. $order = Order::searchOne([
  879. 'id' => (int)$idOrder
  880. ]);
  881. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  882. $deliveryNote = DeliveryNote::searchOne([
  883. 'id' => (int) $order->id_delivery_note
  884. ]) ;
  885. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  886. $deliveryNote->changeStatus(Document::STATUS_VALID);
  887. $deliveryNote->save();
  888. }
  889. }
  890. }
  891. return [
  892. 'return' => 'success',
  893. 'alert' => [
  894. 'type' => 'success',
  895. 'message' => 'Bon(s) de livraison validé(s)'
  896. ]
  897. ] ;
  898. }
  899. }
  900. return [
  901. 'return' => 'error',
  902. 'alert' => [
  903. 'type' => 'danger',
  904. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  905. ]
  906. ];
  907. }
  908. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  909. {
  910. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  911. if (strlen($idOrders)) {
  912. $idOrders = json_decode($idOrders, true);
  913. if (is_array($idOrders) && count($idOrders) > 0) {
  914. foreach ($idOrders as $idOrder) {
  915. $order = Order::searchOne([
  916. 'id' => (int)$idOrder
  917. ]);
  918. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  919. $deliveryNote = null ;
  920. $idDeliveryNote = $order->id_delivery_note ;
  921. if($idDeliveryNote) {
  922. $deliveryNote = DeliveryNote::searchOne([
  923. 'id' => (int) $idDeliveryNote
  924. ]);
  925. }
  926. // on regénére le document si c'est un brouillon
  927. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  928. $deliveryNote->delete() ;
  929. $deliveryNote = null ;
  930. }
  931. if(!$deliveryNote) {
  932. $deliveryNote = new DeliveryNote() ;
  933. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  934. $deliveryNote->id_user = $order->id_user;
  935. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date('d/m/Y', strtotime($order->distribution->date)) . ')';
  936. $deliveryNote->address = $order->user->getFullAddress() ;
  937. $deliveryNote->save();
  938. }
  939. if($deliveryNote) {
  940. $order->id_delivery_note = $deliveryNote->id;
  941. $order->save();
  942. }
  943. }
  944. }
  945. }
  946. return [
  947. 'return' => 'success',
  948. 'alert' => [
  949. 'type' => 'success',
  950. 'message' => 'Bon(s) de livraison généré(s)'
  951. ]
  952. ] ;
  953. }
  954. return [
  955. 'return' => 'error',
  956. 'alert' => [
  957. 'type' => 'danger',
  958. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  959. ]
  960. ];
  961. }
  962. public function actionAjaxGenerateDeliveryNote($idOrders)
  963. {
  964. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  965. if (strlen($idOrders)) {
  966. $idOrders = json_decode($idOrders, true);
  967. if (is_array($idOrders) && count($idOrders) > 0) {
  968. // récupération première commande pour obtenir des infos
  969. reset($idOrders) ;
  970. $firstOrder = Order::searchOne([
  971. 'id' => (int)$idOrders[key($idOrders)]
  972. ]);
  973. // deliveryNote existant
  974. $deliveryNote = null ;
  975. $isUpdate = false ;
  976. $i = 0 ;
  977. $ordersArray = Order::searchAll([
  978. 'id' => $idOrders,
  979. ]) ;
  980. do {
  981. $order = $ordersArray[$i] ;
  982. if($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  983. $deliveryNote = DeliveryNote::searchOne([
  984. 'id' => $order->id_delivery_note
  985. ]) ;
  986. $isUpdate = true ;
  987. }
  988. $i ++ ;
  989. } while($deliveryNote == null && isset($ordersArray[$i])) ;
  990. if($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  991. return [
  992. 'return' => 'error',
  993. 'alert' => [
  994. 'type' => 'danger',
  995. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  996. ]
  997. ] ;
  998. }
  999. if ($firstOrder) {
  1000. // génération du BL
  1001. if(!$deliveryNote) {
  1002. $deliveryNote = new DeliveryNote;
  1003. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date('d/m/Y', strtotime($firstOrder->distribution->date)) . ')';
  1004. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1005. if($firstOrder->pointSale->id_user) {
  1006. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1007. }
  1008. else {
  1009. $user = new User ;
  1010. $user->type = User::TYPE_LEGAL_PERSON ;
  1011. $user->name_legal_person = $firstOrder->pointSale->name ;
  1012. $user->address = $firstOrder->pointSale->address ;
  1013. $user->id_producer = 0 ;
  1014. $user->setPassword(Password::generate());
  1015. $user->generateAuthKey();
  1016. $user->email = '' ;
  1017. if (!strlen($user->email)) {
  1018. $user->username = 'inconnu@opendistrib.net';
  1019. }
  1020. $user->save() ;
  1021. $userProducer = new UserProducer;
  1022. $userProducer->id_user = $user->id;
  1023. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1024. $userProducer->credit = 0;
  1025. $userProducer->active = 1;
  1026. $userProducer->save();
  1027. $firstOrder->pointSale->id_user = $user->id ;
  1028. $firstOrder->pointSale->save() ;
  1029. $deliveryNote->id_user = $user->id;
  1030. }
  1031. if(!isset($user)) {
  1032. $user = User::searchOne([
  1033. 'id' => $deliveryNote->id_user
  1034. ]) ;
  1035. }
  1036. $deliveryNote->address = $user->getFullAddress() ;
  1037. $deliveryNote->save();
  1038. }
  1039. else {
  1040. // réinitialisation des order.id_delivery_order
  1041. Order::updateAll([
  1042. 'id_delivery_note' => null
  1043. ], [
  1044. 'id_delivery_note' => $deliveryNote->id
  1045. ]) ;
  1046. }
  1047. // affectation du BL aux commandes
  1048. foreach ($idOrders as $idOrder) {
  1049. $order = Order::searchOne([
  1050. 'id' => (int)$idOrder
  1051. ]);
  1052. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1053. $order->id_delivery_note = $deliveryNote->id;
  1054. $order->save();
  1055. }
  1056. }
  1057. return [
  1058. 'return' => 'success',
  1059. 'alert' => [
  1060. 'type' => 'success',
  1061. 'message' => 'Bon de livraison '.($isUpdate ? 'modifié' : 'généré')
  1062. ]
  1063. ] ;
  1064. }
  1065. }
  1066. }
  1067. return [
  1068. 'return' => 'error',
  1069. 'alert' => [
  1070. 'type' => 'danger',
  1071. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1072. ]
  1073. ];
  1074. }
  1075. }