No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

DistributionController.php 73KB

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