您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

DistributionController.php 65KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  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. $viewPdf = 'report' ;
  395. $orientationPdf = Pdf::ORIENT_PORTRAIT ;
  396. $producer = GlobalParam::getCurrentProducer() ;
  397. if($producer->slug == 'bourlinguepacotille') {
  398. $viewPdf = 'report-bourlingue' ;
  399. $orientationPdf = Pdf::ORIENT_LANDSCAPE ;
  400. }
  401. // get your HTML raw content without any layouts or scripts
  402. $content = $this->renderPartial($viewPdf, [
  403. 'date' => $date,
  404. 'distribution' => $distribution,
  405. 'selectedProductsArray' => $selectedProductsArray,
  406. 'pointsSaleArray' => $pointsSaleArray,
  407. 'productsArray' => $productsArray,
  408. 'ordersArray' => $ordersArray
  409. ]);
  410. $dateStr = date('d/m/Y', strtotime($date));
  411. if ($save) {
  412. $destination = Pdf::DEST_FILE;
  413. } else {
  414. $destination = Pdf::DEST_BROWSER;
  415. }
  416. $pdf = new Pdf([
  417. // set to use core fonts only
  418. 'mode' => Pdf::MODE_UTF8,
  419. // A4 paper format
  420. 'format' => Pdf::FORMAT_A4,
  421. // portrait orientation
  422. 'orientation' => $orientationPdf,
  423. // stream to browser inline
  424. 'destination' => $destination,
  425. 'filename' => Yii::getAlias('@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'),
  426. // your html content input
  427. 'content' => $content,
  428. // format content from your own css file if needed or use the
  429. // enhanced bootstrap css built by Krajee for mPDF formatting
  430. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  431. // any css to be embedded if required
  432. 'cssInline' => '
  433. table {
  434. border-spacing : 0px ;
  435. border-collapse : collapse ;
  436. width: 100% ;
  437. }
  438. table tr th,
  439. table tr td {
  440. padding: 0px ;
  441. margin: 0px ;
  442. border: solid 1px #e0e0e0 ;
  443. padding: 3px 8px ;
  444. vertical-align : top;
  445. page-break-inside: avoid !important;
  446. }
  447. table tr th {
  448. font-size: 13px ;
  449. }
  450. table tr td {
  451. font-size: 13px ;
  452. }
  453. ',
  454. // set mPDF properties on the fly
  455. //'options' => ['title' => 'Krajee Report Title'],
  456. // call mPDF methods on the fly
  457. 'methods' => [
  458. 'SetHeader' => ['Commandes du ' . $dateStr],
  459. 'SetFooter' => ['{PAGENO}'],
  460. ]
  461. ]);
  462. // return the pdf output as per the destination setting
  463. return $pdf->render();
  464. } elseif ($type == 'csv') {
  465. $datas = [];
  466. // produits en colonne
  467. $productsNameArray = [''];
  468. $productsIndexArray = [];
  469. $productsHasQuantity = [];
  470. $cpt = 1;
  471. foreach ($productsArray as $product) {
  472. $productsHasQuantity[$product->id] = 0;
  473. foreach (Product::$unitsArray as $unit => $dataUnit) {
  474. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  475. if ($quantity) {
  476. $productsHasQuantity[$product->id] += $quantity;
  477. }
  478. }
  479. if ($productsHasQuantity[$product->id] > 0) {
  480. $productsNameArray[] = $product->name . ' (' . Product::strUnit($product->unit, 'wording_short', true) . ')';
  481. $productsIndexArray[$product->id] = $cpt++;
  482. }
  483. }
  484. $datas[] = $productsNameArray;
  485. // points de vente
  486. foreach ($pointsSaleArray as $pointSale) {
  487. if (count($pointSale->orders)) {
  488. // listing commandes
  489. $datas[] = ['> ' . $pointSale->name];
  490. foreach ($pointSale->orders as $order) {
  491. $orderLine = [$order->getStrUser()];
  492. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  493. $orderLine[$indexProduct] = '';
  494. }
  495. foreach ($order->productOrder as $productOrder) {
  496. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  497. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  498. }
  499. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  500. if ($productOrder->product->unit != $productOrder->unit) {
  501. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  502. }
  503. }
  504. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  505. }
  506. // total point de vente
  507. $totalsPointSaleArray = $this->_totalReportCSV(
  508. 'Total',
  509. $pointSale->orders,
  510. $productsArray,
  511. $productsIndexArray
  512. );
  513. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  514. $datas[] = [];
  515. }
  516. }
  517. // global
  518. $totalsGlobalArray = $this->_totalReportCSV(
  519. '> Totaux',
  520. $ordersArray,
  521. $productsArray,
  522. $productsIndexArray
  523. );
  524. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  525. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  526. echo CSV::array2csv($datas);
  527. die();
  528. }
  529. }
  530. return null;
  531. }
  532. /**
  533. * Génère un export des commandes au format CSV à destination du Google Drive
  534. * de Terre de pains.
  535. *
  536. * @param type $date
  537. * @return CSV
  538. */
  539. public function actionReportTerredepains($date, $key)
  540. {
  541. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  542. $producer = Producer::searchOne([
  543. 'producer.slug' => 'terredepains'
  544. ]);
  545. $idProducer = $producer->id;
  546. $ordersArray = Order::searchAll([
  547. 'distribution.date' => $date,
  548. 'distribution.id_producer' => $idProducer
  549. ],
  550. [
  551. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  552. 'conditions' => 'date_delete IS NULL'
  553. ]);
  554. $distribution = Distribution::searchOne([
  555. 'distribution.id_producer' => $idProducer
  556. ], [
  557. 'conditions' => 'date LIKE :date',
  558. 'params' => [
  559. ':date' => $date,
  560. ]
  561. ]);
  562. if ($distribution) {
  563. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  564. $pointsSaleArray = PointSale::searchAll([
  565. 'point_sale.id_producer' => $idProducer
  566. ]);
  567. foreach ($pointsSaleArray as $pointSale) {
  568. $pointSale->initOrders($ordersArray);
  569. }
  570. // produits
  571. $productsArray = Product::find()
  572. ->joinWith(['productDistribution' => function ($q) use ($distribution) {
  573. $q->where(['id_distribution' => $distribution->id]);
  574. }])
  575. ->where([
  576. 'id_producer' => $idProducer,
  577. ])
  578. ->orderBy('order ASC')
  579. ->all();
  580. $datas = [];
  581. // produits en colonne
  582. $productsNameArray = [''];
  583. $productsIndexArray = [];
  584. $productsHasQuantity = [];
  585. $cpt = 1;
  586. foreach ($productsArray as $product) {
  587. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  588. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  589. $productsNameArray[] = $product->name . $theUnit;
  590. $productsIndexArray[$product->id] = $cpt++;
  591. }
  592. $productsNameArray[] = 'Total';
  593. $datas[] = $productsNameArray;
  594. // global
  595. $totalsGlobalArray = $this->_totalReportCSV(
  596. '> Totaux',
  597. $ordersArray,
  598. $productsArray,
  599. $productsIndexArray
  600. );
  601. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  602. $datas[] = [];
  603. // points de vente
  604. foreach ($pointsSaleArray as $pointSale) {
  605. if (count($pointSale->orders)) {
  606. // listing commandes
  607. /*foreach ($pointSale->orders as $order) {
  608. $orderLine = [$order->getStrUser()];
  609. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  610. $orderLine[$indexProduct] = '';
  611. }
  612. foreach ($order->productOrder as $productOrder) {
  613. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  614. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  615. }
  616. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  617. if ($productOrder->product->unit != $productOrder->unit) {
  618. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  619. }
  620. }
  621. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  622. }*/
  623. // total point de vente
  624. $totalsPointSaleArray = $this->_totalReportCSV(
  625. '> ' . $pointSale->name,
  626. $pointSale->orders,
  627. $productsArray,
  628. $productsIndexArray
  629. );
  630. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  631. }
  632. }
  633. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  634. echo CSV::array2csv($datas);
  635. die();
  636. }
  637. return null;
  638. }
  639. }
  640. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  641. {
  642. $totalsPointSaleArray = [$label];
  643. foreach ($productsArray as $product) {
  644. foreach (Product::$unitsArray as $unit => $dataUnit) {
  645. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  646. if ($quantity) {
  647. $index = $productsIndexArray[$product->id];
  648. if (!isset($totalsPointSaleArray[$index])) {
  649. $totalsPointSaleArray[$index] = '';
  650. }
  651. if (strlen($totalsPointSaleArray[$index])) {
  652. $totalsPointSaleArray[$index] .= ' + ';
  653. }
  654. $totalsPointSaleArray[$index] .= $quantity;
  655. if ($product->unit != $unit) {
  656. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  657. }
  658. }
  659. }
  660. }
  661. return $totalsPointSaleArray;
  662. }
  663. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  664. {
  665. $line = [];
  666. $cptTotal = 0;
  667. for ($i = 0; $i <= $cptMax; $i++) {
  668. if (isset($orderLine[$i]) && $orderLine[$i]) {
  669. $line[] = $orderLine[$i];
  670. $cptTotal += $orderLine[$i];
  671. } else {
  672. $line[] = '';
  673. }
  674. }
  675. if ($cptTotal > 0 && $showTotal) {
  676. $line[] = $cptTotal;
  677. }
  678. return $line;
  679. }
  680. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  681. {
  682. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  683. $productDistribution = ProductDistribution::searchOne([
  684. 'id_distribution' => $idDistribution,
  685. 'id_product' => $idProduct,
  686. ]);
  687. $productDistribution->quantity_max = (!$quantityMax) ? null : (float) $quantityMax;
  688. $productDistribution->save();
  689. return ['success'];
  690. }
  691. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  692. {
  693. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  694. $productDistribution = ProductDistribution::searchOne([
  695. 'id_distribution' => $idDistribution,
  696. 'id_product' => $idProduct,
  697. ]);
  698. $productDistribution->active = $active;
  699. $productDistribution->save();
  700. return ['success'];
  701. }
  702. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  703. {
  704. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  705. $pointSaleDistribution = PointSaleDistribution::searchOne([
  706. 'id_distribution' => $idDistribution,
  707. 'id_point_sale' => $idPointSale,
  708. ]);
  709. $pointSaleDistribution->delivery = $delivery;
  710. $pointSaleDistribution->save();
  711. return ['success'];
  712. }
  713. /**
  714. * Active/désactive un jour de distribution.
  715. *
  716. * @param integer $idDistribution
  717. * @param string $date
  718. * @param boolean $active
  719. * @return array
  720. */
  721. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  722. {
  723. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  724. if ($idDistribution) {
  725. $distribution = Distribution::searchOne([
  726. 'id' => $idDistribution
  727. ]);
  728. }
  729. $format = 'Y-m-d';
  730. $dateObject = DateTime::createFromFormat($format, $date);
  731. if ($dateObject && $dateObject->format($format) === $date) {
  732. $distribution = Distribution::initDistribution($date);
  733. }
  734. if ($distribution) {
  735. $distribution->active($active);
  736. return ['success'];
  737. }
  738. return ['error'];
  739. }
  740. /**
  741. * Change l'état d'une semaine de production (activé, désactivé).
  742. *
  743. * @param string $date
  744. * @param integer $active
  745. */
  746. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  747. {
  748. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  749. $week = sprintf('%02d', date('W', strtotime($date)));
  750. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  751. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  752. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  753. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  754. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  755. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  756. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  757. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  758. $pointsSaleArray = PointSale::searchAll();
  759. $activeMonday = false;
  760. $activeTuesday = false;
  761. $activeWednesday = false;
  762. $activeThursday = false;
  763. $activeFriday = false;
  764. $activeSaturday = false;
  765. $activeSunday = false;
  766. foreach ($pointsSaleArray as $pointSale) {
  767. if ($pointSale->delivery_monday) $activeMonday = true;
  768. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  769. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  770. if ($pointSale->delivery_thursday) $activeThursday = true;
  771. if ($pointSale->delivery_friday) $activeFriday = true;
  772. if ($pointSale->delivery_saturday) $activeSaturday = true;
  773. if ($pointSale->delivery_sunday) $activeSunday = true;
  774. }
  775. if ($activeMonday || !$active) {
  776. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  777. }
  778. if ($activeTuesday || !$active) {
  779. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  780. }
  781. if ($activeWednesday || !$active) {
  782. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  783. }
  784. if ($activeThursday || !$active) {
  785. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  786. }
  787. if ($activeFriday || !$active) {
  788. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  789. }
  790. if ($activeSaturday || !$active) {
  791. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  792. }
  793. if ($activeSunday || !$active) {
  794. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  795. }
  796. return ['success'];
  797. }
  798. /**
  799. * Ajoute les commandes récurrentes pour une date donnée.
  800. *
  801. * @param string $date
  802. */
  803. public function actionAjaxProcessAddSubscriptions($date)
  804. {
  805. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  806. Subscription::addAll($date, true);
  807. return ['success'];
  808. }
  809. /**
  810. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  811. *
  812. * @param string $date
  813. */
  814. public function actionAjaxProcessSynchroTiller($date)
  815. {
  816. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  817. $return = [] ;
  818. $producerTiller = Producer::getConfig('tiller');
  819. if ($producerTiller) {
  820. $tiller = new Tiller();
  821. $isSynchro = $tiller->isSynchro($date);
  822. if (!$isSynchro) {
  823. $orders = Order::searchAll([
  824. 'distribution.date' => $date,
  825. 'order.tiller_synchronization' => 1
  826. ]);
  827. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  828. if ($orders && count($orders)) {
  829. foreach ($orders as $order) {
  830. $lines = [];
  831. foreach ($order->productOrder as $productOrder) {
  832. $lines[] = [
  833. 'name' => $productOrder->product->name,
  834. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  835. 'tax' => $productOrder->taxRate->value * 100,
  836. 'date' => $strDate,
  837. 'quantity' => $productOrder->quantity
  838. ];
  839. }
  840. $typePaymentTiller = '';
  841. if ($order->mean_payment == MeanPayment::MONEY
  842. || $order->mean_payment == MeanPayment::CREDIT
  843. || $order->mean_payment == MeanPayment::TRANSFER
  844. || $order->mean_payment == MeanPayment::OTHER) {
  845. $typePaymentTiller = 'CASH';
  846. }
  847. if ($order->mean_payment == MeanPayment::CREDIT_CARD) {
  848. $typePaymentTiller = 'CARD';
  849. }
  850. if ($order->mean_payment == MeanPayment::CHEQUE) {
  851. $typePaymentTiller = 'BANK_CHECK';
  852. }
  853. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  854. $typePaymentTiller = 'CASH';
  855. }
  856. $return[] = $tiller->postOrder([
  857. 'externalId' => $order->id,
  858. 'type' => 1,
  859. 'status' => "CLOSED",
  860. 'openDate' => $strDate,
  861. 'closeDate' => $strDate,
  862. 'lines' => $lines,
  863. 'payments' => [[
  864. 'type' => $typePaymentTiller,
  865. 'amount' => $order->getAmountWithTax(Order::AMOUNT_TOTAL) * 100,
  866. 'status' => 'ACCEPTED',
  867. 'date' => $strDate
  868. ]]
  869. ]);
  870. }
  871. }
  872. }
  873. }
  874. return $return ;
  875. }
  876. public function actionAjaxValidateDeliveryNotes($idOrders)
  877. {
  878. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  879. if (strlen($idOrders)) {
  880. $idOrders = json_decode($idOrders, true);
  881. if (is_array($idOrders) && count($idOrders) > 0) {
  882. foreach($idOrders as $idOrder) {
  883. $order = Order::searchOne([
  884. 'id' => (int)$idOrder
  885. ]);
  886. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  887. $deliveryNote = DeliveryNote::searchOne([
  888. 'id' => (int) $order->id_delivery_note
  889. ]) ;
  890. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  891. $deliveryNote->changeStatus(Document::STATUS_VALID);
  892. $deliveryNote->save();
  893. }
  894. }
  895. }
  896. return [
  897. 'return' => 'success',
  898. 'alert' => [
  899. 'type' => 'success',
  900. 'message' => 'Bon(s) de livraison validé(s)'
  901. ]
  902. ] ;
  903. }
  904. }
  905. return [
  906. 'return' => 'error',
  907. 'alert' => [
  908. 'type' => 'danger',
  909. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  910. ]
  911. ];
  912. }
  913. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  914. {
  915. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  916. if (strlen($idOrders)) {
  917. $idOrders = json_decode($idOrders, true);
  918. if (is_array($idOrders) && count($idOrders) > 0) {
  919. foreach ($idOrders as $idOrder) {
  920. $order = Order::searchOne([
  921. 'id' => (int)$idOrder
  922. ]);
  923. if($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  924. $deliveryNote = null ;
  925. $idDeliveryNote = $order->id_delivery_note ;
  926. if($idDeliveryNote) {
  927. $deliveryNote = DeliveryNote::searchOne([
  928. 'id' => (int) $idDeliveryNote
  929. ]);
  930. }
  931. // on regénére le document si c'est un brouillon
  932. if($deliveryNote && $deliveryNote->isStatusDraft()) {
  933. $deliveryNote->delete() ;
  934. $deliveryNote = null ;
  935. }
  936. if(!$deliveryNote) {
  937. $deliveryNote = new DeliveryNote() ;
  938. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  939. $deliveryNote->id_user = $order->id_user;
  940. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date('d/m/Y', strtotime($order->distribution->date)) . ')';
  941. $deliveryNote->address = $order->user->getFullAddress() ;
  942. $deliveryNote->save();
  943. }
  944. if($deliveryNote) {
  945. $order->id_delivery_note = $deliveryNote->id;
  946. $order->save();
  947. }
  948. }
  949. }
  950. }
  951. return [
  952. 'return' => 'success',
  953. 'alert' => [
  954. 'type' => 'success',
  955. 'message' => 'Bon(s) de livraison généré(s)'
  956. ]
  957. ] ;
  958. }
  959. return [
  960. 'return' => 'error',
  961. 'alert' => [
  962. 'type' => 'danger',
  963. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  964. ]
  965. ];
  966. }
  967. public function actionAjaxGenerateDeliveryNote($idOrders)
  968. {
  969. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  970. if (strlen($idOrders)) {
  971. $idOrders = json_decode($idOrders, true);
  972. if (is_array($idOrders) && count($idOrders) > 0) {
  973. // récupération première commande pour obtenir des infos
  974. reset($idOrders) ;
  975. $firstOrder = Order::searchOne([
  976. 'id' => (int)$idOrders[key($idOrders)]
  977. ]);
  978. // deliveryNote existant
  979. $deliveryNote = null ;
  980. $isUpdate = false ;
  981. $i = 0 ;
  982. $ordersArray = Order::searchAll([
  983. 'id' => $idOrders,
  984. ]) ;
  985. do {
  986. $order = $ordersArray[$i] ;
  987. if($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
  988. $deliveryNote = DeliveryNote::searchOne([
  989. 'id' => $order->id_delivery_note
  990. ]) ;
  991. $isUpdate = true ;
  992. }
  993. $i ++ ;
  994. } while($deliveryNote == null && isset($ordersArray[$i])) ;
  995. if($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  996. return [
  997. 'return' => 'error',
  998. 'alert' => [
  999. 'type' => 'danger',
  1000. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1001. ]
  1002. ] ;
  1003. }
  1004. if ($firstOrder) {
  1005. // génération du BL
  1006. if(!$deliveryNote) {
  1007. $deliveryNote = new DeliveryNote;
  1008. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date('d/m/Y', strtotime($firstOrder->distribution->date)) . ')';
  1009. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1010. if($firstOrder->pointSale->id_user) {
  1011. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1012. }
  1013. else {
  1014. $user = new User ;
  1015. $user->type = User::TYPE_LEGAL_PERSON ;
  1016. $user->name_legal_person = $firstOrder->pointSale->name ;
  1017. $user->address = $firstOrder->pointSale->address ;
  1018. $user->id_producer = 0 ;
  1019. $user->setPassword(Password::generate());
  1020. $user->generateAuthKey();
  1021. $user->email = '' ;
  1022. if (!strlen($user->email)) {
  1023. $user->username = 'inconnu@opendistrib.net';
  1024. }
  1025. $user->save() ;
  1026. $userProducer = new UserProducer;
  1027. $userProducer->id_user = $user->id;
  1028. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1029. $userProducer->credit = 0;
  1030. $userProducer->active = 1;
  1031. $userProducer->save();
  1032. $firstOrder->pointSale->id_user = $user->id ;
  1033. $firstOrder->pointSale->save() ;
  1034. $deliveryNote->id_user = $user->id;
  1035. }
  1036. if(!isset($user)) {
  1037. $user = User::searchOne([
  1038. 'id' => $deliveryNote->id_user
  1039. ]) ;
  1040. }
  1041. $deliveryNote->address = $user->getFullAddress() ;
  1042. $deliveryNote->save();
  1043. }
  1044. else {
  1045. // réinitialisation des order.id_delivery_order
  1046. Order::updateAll([
  1047. 'id_delivery_note' => null
  1048. ], [
  1049. 'id_delivery_note' => $deliveryNote->id
  1050. ]) ;
  1051. }
  1052. // affectation du BL aux commandes
  1053. foreach ($idOrders as $idOrder) {
  1054. $order = Order::searchOne([
  1055. 'id' => (int)$idOrder
  1056. ]);
  1057. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1058. $order->id_delivery_note = $deliveryNote->id;
  1059. $order->save();
  1060. }
  1061. }
  1062. return [
  1063. 'return' => 'success',
  1064. 'alert' => [
  1065. 'type' => 'success',
  1066. 'message' => 'Bon de livraison '.($isUpdate ? 'modifié' : 'généré')
  1067. ]
  1068. ] ;
  1069. }
  1070. }
  1071. }
  1072. return [
  1073. 'return' => 'error',
  1074. 'alert' => [
  1075. 'type' => 'danger',
  1076. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1077. ]
  1078. ];
  1079. }
  1080. }