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

DistributionController.php 73KB

преди 6 години
преди 5 години
преди 3 години
преди 6 години
преди 6 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 3 години
преди 4 години
преди 3 години
преди 6 години
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use backend\controllers\BackendController;
  39. use common\helpers\GlobalParam;
  40. use common\models\DeliveryNote;
  41. use common\models\Distribution;
  42. use common\models\Document;
  43. use common\models\PointSale;
  44. use common\models\Product;
  45. use common\models\Producer;
  46. use common\models\Order;
  47. use common\models\ProductCategory;
  48. use common\models\User;
  49. use common\models\Subscription;
  50. use common\helpers\Price;
  51. use common\models\PointSaleDistribution;
  52. use common\models\UserProducer;
  53. use DateTime;
  54. class DistributionController extends BackendController
  55. {
  56. public function behaviors()
  57. {
  58. return [
  59. 'access' => [
  60. 'class' => AccessControl::className(),
  61. 'rules' => [
  62. [
  63. 'actions' => ['report-cron', 'report-terredepains'],
  64. 'allow' => true,
  65. 'roles' => ['?']
  66. ],
  67. [
  68. 'allow' => true,
  69. 'roles' => ['@'],
  70. 'matchCallback' => function ($rule, $action) {
  71. return User::getCurrentStatus() == USER::STATUS_ADMIN
  72. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  73. }
  74. ]
  75. ],
  76. ],
  77. ];
  78. }
  79. public function actionIndex($date = '')
  80. {
  81. $this->checkProductsPointsSale();
  82. $format = 'Y-m-d';
  83. $theDate = '';
  84. $dateObject = DateTime::createFromFormat($format, $date);
  85. if ($dateObject && $dateObject->format($format) === $date) {
  86. $theDate = $date;
  87. }
  88. return $this->render('index', [
  89. 'date' => $theDate
  90. ]);
  91. }
  92. public function actionAjaxInfos($date = '')
  93. {
  94. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  95. $json = [
  96. 'distribution' => [],
  97. 'products' => []
  98. ];
  99. $format = 'Y-m-d';
  100. $dateObject = DateTime::createFromFormat($format, $date);
  101. $producer = GlobalParam::getCurrentProducer();
  102. $json['producer'] = [
  103. 'credit' => $producer->credit,
  104. 'tiller' => $producer->tiller,
  105. 'option_display_export_grid' => $producer->option_display_export_grid
  106. ];
  107. $json['means_payment'] = MeanPayment::getAll();
  108. $distributionsArray = Distribution::searchAll([
  109. 'active' => 1
  110. ], [
  111. 'conditions' => [
  112. 'date > :date_begin',
  113. 'date < :date_end'
  114. ],
  115. 'params' => [
  116. ':date_begin' => date(
  117. 'Y-m-d',
  118. strtotime('-1 month')
  119. ),
  120. ':date_end' => date(
  121. 'Y-m-d',
  122. strtotime('+3 month')
  123. ),
  124. ],
  125. ]);
  126. $json['distributions'] = $distributionsArray;
  127. if ($dateObject && $dateObject->format($format) === $date) {
  128. // distribution
  129. $distribution = Distribution::initDistribution($date);
  130. $json['distribution'] = [
  131. 'id' => $distribution->id,
  132. 'active' => $distribution->active,
  133. 'url_report' => Yii::$app->urlManagerBackend->createUrl(
  134. ['distribution/report', 'date' => $distribution->date]
  135. ),
  136. 'url_report_grid' => Yii::$app->urlManagerBackend->createUrl(
  137. ['distribution/report-grid', 'date' => $distribution->date]
  138. ),
  139. ];
  140. // commandes
  141. $ordersArray = Order::searchAll([
  142. 'distribution.id' => $distribution->id,
  143. ], [
  144. 'orderby' => 'user.lastname ASC, user.name ASC'
  145. ]);
  146. // montant et poids des commandes
  147. $revenues = 0;
  148. $weight = 0;
  149. if ($ordersArray) {
  150. foreach ($ordersArray as $order) {
  151. if (is_null($order->date_delete)) {
  152. $revenues += $order->getAmountWithTax();
  153. $weight += $order->weight;
  154. }
  155. }
  156. }
  157. $json['distribution']['revenues'] = Price::format($revenues);
  158. $json['distribution']['weight'] = number_format($weight, 2);
  159. // products
  160. $productsArray = Product::find()
  161. ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
  162. ->joinWith([
  163. 'taxRate',
  164. 'productDistribution' => function ($query) use ($distribution) {
  165. $query->andOnCondition(
  166. 'product_distribution.id_distribution = ' . $distribution->id
  167. );
  168. }
  169. ])
  170. ->orderBy('product_distribution.active DESC, order ASC')
  171. ->asArray()
  172. ->all();
  173. $potentialRevenues = 0;
  174. $potentialWeight = 0;
  175. foreach ($productsArray as &$theProduct) {
  176. $quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray);
  177. $theProduct['quantity_ordered'] = $quantityOrder;
  178. if (!isset($theProduct['productDistribution'][0])) {
  179. $theProductObject = (object)$theProduct;
  180. $theProduct['productDistribution'][0] = $distribution->linkProduct($theProductObject);
  181. }
  182. if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
  183. $theProduct['quantity_remaining'] = null;
  184. } else {
  185. $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
  186. }
  187. $theProduct['quantity_form'] = 0;
  188. if ($theProduct['productDistribution'][0]['active'] && $theProduct['productDistribution'][0]['quantity_max']) {
  189. $potentialRevenues += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['price'];
  190. $potentialWeight += $theProduct['productDistribution'][0]['quantity_max'] * $theProduct['weight'] / 1000;
  191. }
  192. if (!isset($theProduct['taxRate'])) {
  193. $theProduct['taxRate'] = $producer->taxRate;
  194. }
  195. }
  196. $json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
  197. $json['distribution']['potential_weight'] = number_format($potentialWeight, 2);
  198. $json['products'] = $productsArray;
  199. // orders as array
  200. $ordersArrayObject = $ordersArray;
  201. if ($ordersArray) {
  202. foreach ($ordersArray as &$order) {
  203. $productOrderArray = [];
  204. foreach ($order->productOrder as $productOrder) {
  205. $productOrderArray[$productOrder->id_product] = [
  206. 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
  207. 'unit' => $productOrder->unit,
  208. 'price' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value)
  209. ];
  210. }
  211. foreach ($productsArray as $product) {
  212. if (!isset($productOrderArray[$product['id']])) {
  213. $productOrderArray[$product['id']] = [
  214. 'quantity' => 0,
  215. 'unit' => $product['unit'],
  216. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  217. ];
  218. }
  219. }
  220. $creditHistoryArray = [];
  221. foreach ($order->creditHistory as $creditHistory) {
  222. $creditHistoryArray[] = [
  223. 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
  224. 'user_action' => $creditHistory->strUserAction(),
  225. 'wording' => $creditHistory->getStrWording(),
  226. 'debit' => ($creditHistory->isTypeDebit() ? '-&nbsp;' . $creditHistory->getAmount(
  227. Order::AMOUNT_TOTAL,
  228. true
  229. ) : ''),
  230. 'credit' => ($creditHistory->isTypeCredit() ? '+&nbsp;' . $creditHistory->getAmount(
  231. Order::AMOUNT_TOTAL,
  232. true
  233. ) : '')
  234. ];
  235. }
  236. $arrayCreditUser = [];
  237. if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
  238. $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
  239. }
  240. $oneProductUnactivated = false;
  241. foreach ($order->productOrder as $productOrder) {
  242. foreach ($productsArray as $product) {
  243. if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
  244. $oneProductUnactivated = true;
  245. }
  246. }
  247. }
  248. $order = array_merge($order->getAttributes(), [
  249. 'selected' => false,
  250. 'amount' => Price::numberTwoDecimals($order->getAmountWithTax(Order::AMOUNT_TOTAL)),
  251. 'amount_paid' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_PAID)),
  252. 'amount_remaining' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_REMAINING)),
  253. 'amount_surplus' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_SURPLUS)),
  254. 'user' => (isset($order->user)) ? array_merge(
  255. $order->user->getAttributes(),
  256. $arrayCreditUser
  257. ) : null,
  258. 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
  259. 'productOrder' => $productOrderArray,
  260. 'creditHistory' => $creditHistoryArray,
  261. 'oneProductUnactivated' => $oneProductUnactivated
  262. ]);
  263. }
  264. }
  265. $json['orders'] = $ordersArray;
  266. // points de vente
  267. $pointsSaleArray = PointSale::find()
  268. ->joinWith([
  269. 'pointSaleDistribution' => function ($q) use ($distribution) {
  270. $q->where(['id_distribution' => $distribution->id]);
  271. }
  272. ])
  273. ->where([
  274. 'id_producer' => GlobalParam::getCurrentProducerId(),
  275. ])
  276. ->asArray()
  277. ->all();
  278. $idPointSaleDefault = 0;
  279. foreach ($pointsSaleArray as $pointSale) {
  280. if ($pointSale['default']) {
  281. $idPointSaleDefault = $pointSale['id'];
  282. }
  283. }
  284. $json['points_sale'] = $pointsSaleArray;
  285. // bons de livraison
  286. $deliveryNotesArray = DeliveryNote::searchAll([
  287. 'distribution.date' => $date,
  288. ]);
  289. $deliveryNotesByPointSaleArray = [];
  290. foreach ($deliveryNotesArray as $deliveryNote) {
  291. if (isset($deliveryNote->orders[0])) {
  292. $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
  293. $deliveryNote->getAttributes();
  294. }
  295. }
  296. $json['delivery_notes'] = $deliveryNotesByPointSaleArray;
  297. // order create
  298. $productOrderArray = [];
  299. foreach ($productsArray as $product) {
  300. $productOrderArray[$product['id']] = [
  301. 'quantity' => 0,
  302. 'unit' => $product['unit'],
  303. 'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
  304. ];
  305. }
  306. $json['order_create'] = [
  307. 'id_point_sale' => $idPointSaleDefault,
  308. 'id_user' => 0,
  309. 'username' => '',
  310. 'comment' => '',
  311. 'productOrder' => $productOrderArray
  312. ];
  313. // utilisateurs
  314. $usersArray = User::findBy()->all();
  315. $json['users'] = $usersArray;
  316. // une production de la semaine activée ou non
  317. $oneDistributionWeekActive = false;
  318. $week = sprintf('%02d', date('W', strtotime($date)));
  319. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  320. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  321. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  322. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  323. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  324. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  325. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  326. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  327. $weekDistribution = Distribution::find()
  328. ->andWhere([
  329. 'id_producer' => GlobalParam::getCurrentProducerId(),
  330. 'active' => 1,
  331. ])
  332. ->andWhere([
  333. 'or',
  334. ['date' => $dateMonday],
  335. ['date' => $dateTuesday],
  336. ['date' => $dateWednesday],
  337. ['date' => $dateThursday],
  338. ['date' => $dateFriday],
  339. ['date' => $dateSaturday],
  340. ['date' => $dateSunday],
  341. ])
  342. ->one();
  343. if ($weekDistribution) {
  344. $oneDistributionWeekActive = true;
  345. }
  346. $json['one_distribution_week_active'] = $oneDistributionWeekActive;
  347. // tiller
  348. if ($producer->tiller) {
  349. $tiller = new Tiller();
  350. $json['tiller_is_synchro'] = (int)$tiller->isSynchro($date);
  351. }
  352. // abonnements manquants
  353. $arraySubscriptions = Subscription::searchByDate($date);
  354. $json['missing_subscriptions'] = [];
  355. if ($distribution->active) {
  356. foreach ($arraySubscriptions as $subscription) {
  357. if (!$subscription->hasOrderAlreadyExist($ordersArrayObject)
  358. && $subscription->productSubscription && count($subscription->productSubscription)
  359. && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
  360. $json['missing_subscriptions'][] = [
  361. 'username' => $subscription->getUsername()
  362. ];
  363. }
  364. }
  365. }
  366. }
  367. return $json;
  368. }
  369. public function actionAjaxPointSaleFavorite($idUser)
  370. {
  371. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  372. $user = User::findOne(['id' => $idUser]);
  373. $favoritePointSale = $user->getFavoritePointSale();
  374. $idFavoritePointSale = 0;
  375. if ($favoritePointSale) {
  376. $idFavoritePointSale = $favoritePointSale->id;
  377. }
  378. return [
  379. 'id_favorite_point_sale' => $idFavoritePointSale
  380. ];
  381. }
  382. public function actionAjaxUpdateProductOrder(
  383. $idDistribution,
  384. $idUser = false,
  385. $idPointSale = false,
  386. $idOrder = false
  387. ) {
  388. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  389. $distribution = Distribution::findOne($idDistribution);
  390. $user = User::findOne($idUser);
  391. $pointSale = PointSale::findOne($idPointSale);
  392. $productsArray = Product::find()
  393. ->where([
  394. 'id_producer' => GlobalParam::getCurrentProducerId(),
  395. 'product.active' => 1,
  396. ])->joinWith([
  397. 'productPrice',
  398. 'productDistribution' => function ($q) use ($distribution) {
  399. $q->where(['id_distribution' => $distribution->id]);
  400. }
  401. ])->all();
  402. $productOrderArray = [];
  403. foreach ($productsArray as $product) {
  404. $priceArray = $product->getPriceArray($user, $pointSale);
  405. $productOrderArray[$product['id']] = [
  406. 'quantity' => 0,
  407. 'unit' => $product->unit,
  408. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  409. 'prices' => $priceArray,
  410. 'active' => $product->productDistribution[0]->active
  411. && (!$pointSale || $product->isAvailableOnPointSale($pointSale))
  412. ];
  413. }
  414. return $productOrderArray;
  415. }
  416. /**
  417. * Génére un PDF récapitulatif des des commandes d'un producteur pour une
  418. * date donnée (Méthode appelable via CRON)
  419. *
  420. * @param string $date
  421. * @param boolean $save
  422. * @param integer $idProducer
  423. * @param string $key
  424. * @return PDF|null
  425. */
  426. public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
  427. {
  428. if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
  429. $this->actionReport($date, $save, $idProducer);
  430. }
  431. }
  432. /**
  433. * Génére un PDF récapitulatif des commandes d'un producteur pour une
  434. * date donnée.
  435. *
  436. * @param string $date
  437. * @param boolean $save
  438. * @param integer $idProducer
  439. * @return PDF|null
  440. */
  441. public function actionReport($date = '', $save = false, $idProducer = 0, $type = "pdf")
  442. {
  443. if (!Yii::$app->user->isGuest) {
  444. $idProducer = GlobalParam::getCurrentProducerId();
  445. }
  446. $ordersArray = Order::searchAll(
  447. [
  448. 'distribution.date' => $date,
  449. 'distribution.id_producer' => $idProducer
  450. ],
  451. [
  452. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  453. 'conditions' => 'date_delete IS NULL'
  454. ]
  455. );
  456. $distribution = Distribution::searchOne([
  457. 'id_producer' => $idProducer
  458. ], [
  459. 'conditions' => 'date LIKE :date',
  460. 'params' => [':date' => $date]
  461. ]);
  462. if ($distribution) {
  463. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  464. $pointsSaleArray = PointSale::searchAll([
  465. 'point_sale.id_producer' => $idProducer
  466. ]);
  467. foreach ($pointsSaleArray as $pointSale) {
  468. $pointSale->initOrders($ordersArray);
  469. }
  470. // produits
  471. $productsArray = Product::find()
  472. ->joinWith([
  473. 'productDistribution' => function ($q) use ($distribution) {
  474. $q->where(['id_distribution' => $distribution->id]);
  475. }
  476. ])
  477. ->where([
  478. 'id_producer' => $idProducer,
  479. ])
  480. ->orderBy('order ASC')
  481. ->all();
  482. if ($type == 'pdf') {
  483. $viewPdf = 'report';
  484. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  485. $producer = GlobalParam::getCurrentProducer();
  486. if ($producer->slug == 'bourlinguepacotille') {
  487. $viewPdf = 'report-bourlingue';
  488. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  489. }
  490. // get your HTML raw content without any layouts or scripts
  491. $content = $this->renderPartial($viewPdf, [
  492. 'date' => $date,
  493. 'distribution' => $distribution,
  494. 'selectedProductsArray' => $selectedProductsArray,
  495. 'pointsSaleArray' => $pointsSaleArray,
  496. 'productsArray' => $productsArray,
  497. 'ordersArray' => $ordersArray,
  498. 'producer' => Producer::searchOne(['id' => $idProducer])
  499. ]);
  500. $dateStr = date('d/m/Y', strtotime($date));
  501. if ($save) {
  502. $destination = Pdf::DEST_FILE;
  503. } else {
  504. $destination = Pdf::DEST_BROWSER;
  505. }
  506. $pdf = new Pdf([
  507. // set to use core fonts only
  508. 'mode' => Pdf::MODE_UTF8,
  509. // A4 paper format
  510. 'format' => Pdf::FORMAT_A4,
  511. // portrait orientation
  512. 'orientation' => $orientationPdf,
  513. // stream to browser inline
  514. 'destination' => $destination,
  515. 'filename' => Yii::getAlias(
  516. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  517. ),
  518. // your html content input
  519. 'content' => $content,
  520. // format content from your own css file if needed or use the
  521. // enhanced bootstrap css built by Krajee for mPDF formatting
  522. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  523. // any css to be embedded if required
  524. 'cssInline' => '
  525. table {
  526. border-spacing : 0px ;
  527. border-collapse : collapse ;
  528. width: 100% ;
  529. }
  530. table tr th,
  531. table tr td {
  532. padding: 0px ;
  533. margin: 0px ;
  534. border: solid 1px #e0e0e0 ;
  535. padding: 3px 8px ;
  536. vertical-align : top;
  537. page-break-inside: avoid !important;
  538. color: black;
  539. }
  540. table tr th {
  541. font-size: 13px ;
  542. }
  543. table tr td {
  544. font-size: 13px ;
  545. }
  546. ',
  547. // set mPDF properties on the fly
  548. //'options' => ['title' => 'Krajee Report Title'],
  549. // call mPDF methods on the fly
  550. 'methods' => [
  551. 'SetHeader' => ['Commandes du ' . $dateStr],
  552. 'SetFooter' => ['{PAGENO}'],
  553. ]
  554. ]);
  555. // return the pdf output as per the destination setting
  556. return $pdf->render();
  557. } elseif ($type == 'csv') {
  558. $datas = [];
  559. $optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products');
  560. $optionCsvExportByPiece = Producer::getConfig('option_csv_export_by_piece');
  561. // produits en colonne
  562. $productsNameArray = ['', 'Commentaire'];
  563. $productsIndexArray = [];
  564. $productsHasQuantity = [];
  565. $cpt = 2;
  566. foreach ($productsArray as $product) {
  567. $productsHasQuantity[$product->id] = 0;
  568. foreach (Product::$unitsArray as $unit => $dataUnit) {
  569. $quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
  570. if ($quantity) {
  571. $productsHasQuantity[$product->id] += $quantity;
  572. }
  573. }
  574. if ($productsHasQuantity[$product->id] > 0 || $optionCsvExportAllProducts) {
  575. $productName = $product->getNameExport();
  576. if ($optionCsvExportByPiece) {
  577. $productUnit = 'piece';
  578. } else {
  579. $productUnit = $product->unit;
  580. }
  581. $productName .= ' (' . Product::strUnit($productUnit, 'wording_short', true) . ')';
  582. $productsNameArray[] = $productName;
  583. $productsIndexArray[$product->id] = $cpt++;
  584. }
  585. }
  586. $datas[] = $productsNameArray;
  587. // points de vente
  588. foreach ($pointsSaleArray as $pointSale) {
  589. if (count($pointSale->orders)) {
  590. // listing commandes
  591. $datas[] = ['> ' . $pointSale->name];
  592. foreach ($pointSale->orders as $order) {
  593. $orderLine = [$order->getStrUser(), $order->getCommentReport()];
  594. if ($optionCsvExportByPiece) {
  595. foreach ($order->productOrder as $productOrder) {
  596. $orderLine[$productsIndexArray[$productOrder->id_product]] = Order::getProductQuantityPieces(
  597. $productOrder->id_product,
  598. [$order]
  599. );
  600. }
  601. } else {
  602. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  603. $orderLine[$indexProduct] = '';
  604. }
  605. foreach ($order->productOrder as $productOrder) {
  606. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  607. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  608. }
  609. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  610. if ($productOrder->product->unit != $productOrder->unit) {
  611. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit(
  612. $productOrder->unit,
  613. 'wording_short',
  614. true
  615. );
  616. }
  617. }
  618. }
  619. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt);
  620. }
  621. // total point de vente
  622. if ($optionCsvExportByPiece) {
  623. $totalsPointSaleArray = $this->_totalReportPiecesCSV(
  624. 'Total',
  625. $pointSale->orders,
  626. $productsArray,
  627. $productsIndexArray
  628. );
  629. } else {
  630. $totalsPointSaleArray = $this->_totalReportCSV(
  631. 'Total',
  632. $pointSale->orders,
  633. $productsArray,
  634. $productsIndexArray
  635. );
  636. }
  637. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt);
  638. $datas[] = [];
  639. }
  640. }
  641. // global
  642. if ($optionCsvExportByPiece) {
  643. $totalsGlobalArray = $this->_totalReportPiecesCSV(
  644. '> Totaux',
  645. $ordersArray,
  646. $productsArray,
  647. $productsIndexArray
  648. );
  649. } else {
  650. $totalsGlobalArray = $this->_totalReportCSV(
  651. '> Totaux',
  652. $ordersArray,
  653. $productsArray,
  654. $productsIndexArray
  655. );
  656. }
  657. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt);
  658. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  659. echo CSV::array2csv($datas);
  660. die();
  661. }
  662. }
  663. return null;
  664. }
  665. public function actionReportGrid($date = '', $save = false, $idProducer = 0, $type = "pdf")
  666. {
  667. if (!Yii::$app->user->isGuest) {
  668. $idProducer = GlobalParam::getCurrentProducerId();
  669. }
  670. $distribution = Distribution::searchOne([
  671. 'id_producer' => $idProducer
  672. ], [
  673. 'conditions' => 'date LIKE :date',
  674. 'params' => [':date' => $date]
  675. ]);
  676. if ($distribution) {
  677. $ordersArray = Order::searchAll(
  678. [
  679. 'distribution.date' => $date,
  680. 'distribution.id_producer' => $idProducer
  681. ],
  682. [
  683. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  684. 'conditions' => 'date_delete IS NULL'
  685. ]
  686. );
  687. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  688. $pointsSaleArray = PointSale::searchAll([
  689. 'point_sale.id_producer' => $idProducer
  690. ]);
  691. foreach ($pointsSaleArray as $pointSale) {
  692. $pointSale->initOrders($ordersArray);
  693. }
  694. $ordersByPage = 22;
  695. $nbPages = ceil(count($ordersArray) / $ordersByPage);
  696. $ordersArrayPaged = [];
  697. foreach ($pointsSaleArray as $pointSale) {
  698. $index = 0;
  699. $indexPage = 0;
  700. foreach ($pointSale->orders as $order) {
  701. if (!isset($ordersArrayPaged[$pointSale->id])) {
  702. $ordersArrayPaged[$pointSale->id] = [];
  703. }
  704. if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
  705. $ordersArrayPaged[$pointSale->id][$indexPage] = [];
  706. }
  707. $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;
  708. $index++;
  709. if ($index == $ordersByPage) {
  710. $index = 0;
  711. $indexPage++;
  712. }
  713. }
  714. }
  715. // catégories
  716. $categoriesArray = ProductCategory::searchAll(
  717. ['id_producer' => $idProducer],
  718. ['orderby' => 'product_category.position ASC']
  719. );
  720. array_unshift($categoriesArray, null);
  721. // produits
  722. $productsArray = Product::find()
  723. ->joinWith([
  724. 'productDistribution' => function ($q) use ($distribution) {
  725. $q->where(['id_distribution' => $distribution->id]);
  726. }
  727. ])
  728. ->where([
  729. 'id_producer' => $idProducer,
  730. ])
  731. ->orderBy('order ASC')
  732. ->all();
  733. $viewPdf = 'report-grid';
  734. $orientationPdf = Pdf::ORIENT_PORTRAIT;
  735. $producer = GlobalParam::getCurrentProducer();
  736. if ($producer->slug == 'bourlinguepacotille') {
  737. $viewPdf = 'report-bourlingue';
  738. $orientationPdf = Pdf::ORIENT_LANDSCAPE;
  739. }
  740. // get your HTML raw content without any layouts or scripts
  741. $content = $this->renderPartial($viewPdf, [
  742. 'date' => $date,
  743. 'distribution' => $distribution,
  744. 'selectedProductsArray' => $selectedProductsArray,
  745. 'pointsSaleArray' => $pointsSaleArray,
  746. 'categoriesArray' => $categoriesArray,
  747. 'productsArray' => $productsArray,
  748. 'ordersArray' => $ordersArrayPaged,
  749. 'producer' => Producer::searchOne(['id' => $idProducer])
  750. ]);
  751. $dateStr = date('d/m/Y', strtotime($date));
  752. if ($save) {
  753. $destination = Pdf::DEST_FILE;
  754. } else {
  755. $destination = Pdf::DEST_BROWSER;
  756. }
  757. $pdf = new Pdf([
  758. // set to use core fonts only
  759. 'mode' => Pdf::MODE_UTF8,
  760. // A4 paper format
  761. 'format' => Pdf::FORMAT_A4,
  762. // portrait orientation
  763. 'orientation' => $orientationPdf,
  764. // stream to browser inline
  765. 'destination' => $destination,
  766. 'filename' => Yii::getAlias(
  767. '@app/web/pdf/Commandes-' . $date . '-' . $idProducer . '.pdf'
  768. ),
  769. // your html content input
  770. 'content' => $content,
  771. // format content from your own css file if needed or use the
  772. // enhanced bootstrap css built by Krajee for mPDF formatting
  773. //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
  774. // any css to be embedded if required
  775. 'cssInline' => '
  776. table {
  777. border-spacing : 0px ;
  778. border-collapse : collapse ;
  779. width: 100% ;
  780. }
  781. table tr th,
  782. table tr td {
  783. padding: 0px ;
  784. margin: 0px ;
  785. border: solid 1px #e0e0e0 ;
  786. padding: 3px ;
  787. vertical-align : top;
  788. page-break-inside: avoid !important;
  789. }
  790. table tr th {
  791. font-size: 10px ;
  792. }
  793. table tr td {
  794. font-size: 10px ;
  795. }
  796. table thead tr {
  797. line-height: 220px;
  798. text-align:left;
  799. }
  800. .th-user,
  801. .td-nb-products {
  802. /* width: 35px ; */
  803. text-align: center ;
  804. }
  805. .th-user {
  806. padding: 10px ;
  807. }
  808. .category-name {
  809. font-weight: bold ;
  810. }
  811. ',
  812. // set mPDF properties on the fly
  813. //'options' => ['title' => 'Krajee Report Title'],
  814. // call mPDF methods on the fly
  815. 'methods' => [
  816. 'SetHeader' => ['Commandes du ' . $dateStr],
  817. 'SetFooter' => ['{PAGENO}'],
  818. ]
  819. ]);
  820. // return the pdf output as per the destination setting
  821. return $pdf->render();
  822. }
  823. }
  824. /**
  825. * Génère un export des commandes au format CSV à destination du Google Drive
  826. * de Terre de pains.
  827. *
  828. * @param type $date
  829. * @return CSV
  830. */
  831. public function actionReportTerredepains($date, $key)
  832. {
  833. if ($key == 'ef572cc148c001f0180c4a624189ed30') {
  834. $producer = Producer::searchOne([
  835. 'producer.slug' => 'terredepains'
  836. ]);
  837. $idProducer = $producer->id;
  838. $ordersArray = Order::searchAll(
  839. [
  840. 'distribution.date' => $date,
  841. 'distribution.id_producer' => $idProducer
  842. ],
  843. [
  844. 'orderby' => 'user.lastname ASC, user.name ASC, comment_point_sale ASC',
  845. 'conditions' => 'date_delete IS NULL'
  846. ]
  847. );
  848. $distribution = Distribution::searchOne([
  849. 'distribution.id_producer' => $idProducer
  850. ], [
  851. 'conditions' => 'date LIKE :date',
  852. 'params' => [
  853. ':date' => $date,
  854. ]
  855. ]);
  856. if ($distribution) {
  857. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  858. $pointsSaleArray = PointSale::searchAll([
  859. 'point_sale.id_producer' => $idProducer
  860. ]);
  861. foreach ($pointsSaleArray as $pointSale) {
  862. $pointSale->initOrders($ordersArray);
  863. }
  864. // produits
  865. $productsArray = Product::find()
  866. ->joinWith([
  867. 'productDistribution' => function ($q) use ($distribution) {
  868. $q->where(['id_distribution' => $distribution->id]);
  869. }
  870. ])
  871. ->where([
  872. 'id_producer' => $idProducer,
  873. ])
  874. ->orderBy('order ASC')
  875. ->all();
  876. $datas = [];
  877. // produits en colonne
  878. $productsNameArray = [''];
  879. $productsIndexArray = [];
  880. $productsHasQuantity = [];
  881. $cpt = 1;
  882. foreach ($productsArray as $product) {
  883. $theUnit = Product::strUnit($product->unit, 'wording_short', true);
  884. $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
  885. $productsNameArray[] = $product->name . $theUnit;
  886. $productsIndexArray[$product->id] = $cpt++;
  887. }
  888. $productsNameArray[] = 'Total';
  889. $datas[] = $productsNameArray;
  890. // global
  891. $totalsGlobalArray = $this->_totalReportCSV(
  892. '> Totaux',
  893. $ordersArray,
  894. $productsArray,
  895. $productsIndexArray
  896. );
  897. $datas[] = $this->_lineOrderReportCSV($totalsGlobalArray, $cpt - 1, true);
  898. $datas[] = [];
  899. // points de vente
  900. foreach ($pointsSaleArray as $pointSale) {
  901. if (count($pointSale->orders)) {
  902. // listing commandes
  903. /*foreach ($pointSale->orders as $order) {
  904. $orderLine = [$order->getStrUser()];
  905. foreach ($productsIndexArray as $idProduct => $indexProduct) {
  906. $orderLine[$indexProduct] = '';
  907. }
  908. foreach ($order->productOrder as $productOrder) {
  909. if (strlen($orderLine[$productsIndexArray[$productOrder->id_product]])) {
  910. $orderLine[$productsIndexArray[$productOrder->id_product]] .= ' + ';
  911. }
  912. $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
  913. if ($productOrder->product->unit != $productOrder->unit) {
  914. $orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
  915. }
  916. }
  917. $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
  918. }*/
  919. // total point de vente
  920. $totalsPointSaleArray = $this->_totalReportCSV(
  921. '> ' . $pointSale->name,
  922. $pointSale->orders,
  923. $productsArray,
  924. $productsIndexArray
  925. );
  926. $datas[] = $this->_lineOrderReportCSV($totalsPointSaleArray, $cpt - 1, true);
  927. }
  928. }
  929. CSV::downloadSendHeaders('Commandes_' . $date . '.csv');
  930. echo CSV::array2csv($datas);
  931. die();
  932. }
  933. return null;
  934. }
  935. }
  936. public function _totalReportCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  937. {
  938. $totalsPointSaleArray = [$label];
  939. foreach ($productsArray as $product) {
  940. foreach (Product::$unitsArray as $unit => $dataUnit) {
  941. $quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  942. if ($quantity) {
  943. $index = $productsIndexArray[$product->id];
  944. if (!isset($totalsPointSaleArray[$index])) {
  945. $totalsPointSaleArray[$index] = '';
  946. }
  947. if (strlen($totalsPointSaleArray[$index])) {
  948. $totalsPointSaleArray[$index] .= ' + ';
  949. }
  950. $totalsPointSaleArray[$index] .= $quantity;
  951. if ($product->unit != $unit) {
  952. $totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
  953. }
  954. }
  955. }
  956. }
  957. return $totalsPointSaleArray;
  958. }
  959. public function _totalReportPiecesCSV($label, $ordersArray, $productsArray, $productsIndexArray)
  960. {
  961. $totalsPointSaleArray = [$label];
  962. foreach ($productsArray as $product) {
  963. $quantity = 0;
  964. foreach (Product::$unitsArray as $unit => $dataUnit) {
  965. $quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
  966. if ($unit == 'piece') {
  967. $quantity += $quantityProduct;
  968. } else {
  969. if ($product->weight > 0) {
  970. $quantity += ($quantityProduct * $dataUnit['coefficient']) / $product->weight;
  971. }
  972. }
  973. }
  974. if ($quantity) {
  975. $index = $productsIndexArray[$product->id];
  976. $totalsPointSaleArray[$index] = $quantity;
  977. }
  978. }
  979. return $totalsPointSaleArray;
  980. }
  981. public function _lineOrderReportCSV($orderLine, $cptMax, $showTotal = false)
  982. {
  983. $line = [];
  984. $cptTotal = 0;
  985. for ($i = 0; $i <= $cptMax; $i++) {
  986. if (isset($orderLine[$i]) && $orderLine[$i]) {
  987. $line[] = $orderLine[$i];
  988. if (is_numeric($orderLine[$i])) {
  989. $cptTotal += $orderLine[$i];
  990. }
  991. } else {
  992. $line[] = '';
  993. }
  994. }
  995. if ($cptTotal > 0 && $showTotal) {
  996. $line[] = $cptTotal;
  997. }
  998. return $line;
  999. }
  1000. public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
  1001. {
  1002. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1003. $productDistribution = ProductDistribution::searchOne([
  1004. 'id_distribution' => $idDistribution,
  1005. 'id_product' => $idProduct,
  1006. ]);
  1007. $productDistribution->quantity_max = (!$quantityMax) ? null : (float)$quantityMax;
  1008. $productDistribution->save();
  1009. return ['success'];
  1010. }
  1011. public function actionAjaxProcessActiveProduct($idDistribution, $idProduct, $active)
  1012. {
  1013. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1014. $productDistribution = ProductDistribution::searchOne([
  1015. 'id_distribution' => $idDistribution,
  1016. 'id_product' => $idProduct,
  1017. ]);
  1018. $productDistribution->active = $active;
  1019. $productDistribution->save();
  1020. return ['success'];
  1021. }
  1022. public function actionAjaxProcessActivePointSale($idDistribution, $idPointSale, $delivery)
  1023. {
  1024. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1025. $pointSaleDistribution = PointSaleDistribution::searchOne([
  1026. 'id_distribution' => $idDistribution,
  1027. 'id_point_sale' => $idPointSale,
  1028. ]);
  1029. $pointSaleDistribution->delivery = $delivery;
  1030. $pointSaleDistribution->save();
  1031. return ['success'];
  1032. }
  1033. /**
  1034. * Active/désactive un jour de distribution.
  1035. *
  1036. * @param integer $idDistribution
  1037. * @param string $date
  1038. * @param boolean $active
  1039. * @return array
  1040. */
  1041. public function actionAjaxProcessActiveDistribution($idDistribution = 0, $date = '', $active)
  1042. {
  1043. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1044. if ($idDistribution) {
  1045. $distribution = Distribution::searchOne([
  1046. 'id' => $idDistribution
  1047. ]);
  1048. }
  1049. $format = 'Y-m-d';
  1050. $dateObject = DateTime::createFromFormat($format, $date);
  1051. if ($dateObject && $dateObject->format($format) === $date) {
  1052. $distribution = Distribution::initDistribution($date);
  1053. }
  1054. if ($distribution) {
  1055. $distribution->active($active);
  1056. return ['success'];
  1057. }
  1058. return ['error'];
  1059. }
  1060. /**
  1061. * Change l'état d'une semaine de production (activé, désactivé).
  1062. *
  1063. * @param string $date
  1064. * @param integer $active
  1065. */
  1066. public function actionAjaxProcessActiveWeekDistribution($date, $active)
  1067. {
  1068. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1069. $week = sprintf('%02d', date('W', strtotime($date)));
  1070. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  1071. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  1072. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  1073. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  1074. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  1075. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  1076. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  1077. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  1078. $pointsSaleArray = PointSale::searchAll();
  1079. $activeMonday = false;
  1080. $activeTuesday = false;
  1081. $activeWednesday = false;
  1082. $activeThursday = false;
  1083. $activeFriday = false;
  1084. $activeSaturday = false;
  1085. $activeSunday = false;
  1086. foreach ($pointsSaleArray as $pointSale) {
  1087. if ($pointSale->delivery_monday) {
  1088. $activeMonday = true;
  1089. }
  1090. if ($pointSale->delivery_tuesday) {
  1091. $activeTuesday = true;
  1092. }
  1093. if ($pointSale->delivery_wednesday) {
  1094. $activeWednesday = true;
  1095. }
  1096. if ($pointSale->delivery_thursday) {
  1097. $activeThursday = true;
  1098. }
  1099. if ($pointSale->delivery_friday) {
  1100. $activeFriday = true;
  1101. }
  1102. if ($pointSale->delivery_saturday) {
  1103. $activeSaturday = true;
  1104. }
  1105. if ($pointSale->delivery_sunday) {
  1106. $activeSunday = true;
  1107. }
  1108. }
  1109. if ($activeMonday || !$active) {
  1110. $this->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
  1111. }
  1112. if ($activeTuesday || !$active) {
  1113. $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
  1114. }
  1115. if ($activeWednesday || !$active) {
  1116. $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
  1117. }
  1118. if ($activeThursday || !$active) {
  1119. $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
  1120. }
  1121. if ($activeFriday || !$active) {
  1122. $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
  1123. }
  1124. if ($activeSaturday || !$active) {
  1125. $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
  1126. }
  1127. if ($activeSunday || !$active) {
  1128. $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
  1129. }
  1130. return ['success'];
  1131. }
  1132. /**
  1133. * Ajoute les commandes récurrentes pour une date donnée.
  1134. *
  1135. * @param string $date
  1136. */
  1137. public function actionAjaxProcessAddSubscriptions($date)
  1138. {
  1139. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1140. Subscription::addAll($date, true);
  1141. return ['success'];
  1142. }
  1143. /**
  1144. * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
  1145. *
  1146. * @param string $date
  1147. */
  1148. public function actionAjaxProcessSynchroTiller($date)
  1149. {
  1150. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1151. $return = [];
  1152. $producerTiller = Producer::getConfig('tiller');
  1153. if ($producerTiller) {
  1154. $tiller = new Tiller();
  1155. $isSynchro = $tiller->isSynchro($date);
  1156. if (!$isSynchro) {
  1157. $orders = Order::searchAll([
  1158. 'distribution.date' => $date,
  1159. 'order.tiller_synchronization' => 1
  1160. ], [
  1161. 'conditions' => 'date_delete IS NULL'
  1162. ]);
  1163. $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
  1164. if ($orders && count($orders)) {
  1165. foreach ($orders as $order) {
  1166. $lines = [];
  1167. foreach ($order->productOrder as $productOrder) {
  1168. $lines[] = [
  1169. 'name' => $productOrder->product->name,
  1170. 'price' => $productOrder->getPriceWithTax() * 100 * $productOrder->quantity,
  1171. 'tax' => $productOrder->taxRate->value * 100,
  1172. 'date' => $strDate,
  1173. 'quantity' => $productOrder->quantity
  1174. ];
  1175. }
  1176. $typePaymentTiller = '';
  1177. if ($order->mean_payment == MeanPayment::MONEY) {
  1178. $typePaymentTiller = 'CASH';
  1179. }
  1180. if ($order->mean_payment == MeanPayment::CREDIT_CARD
  1181. || $order->mean_payment == MeanPayment::CREDIT
  1182. || $order->mean_payment == MeanPayment::TRANSFER
  1183. || $order->mean_payment == MeanPayment::OTHER) {
  1184. $typePaymentTiller = 'CARD';
  1185. }
  1186. if ($order->mean_payment == MeanPayment::CHEQUE) {
  1187. $typePaymentTiller = 'BANK_CHECK';
  1188. }
  1189. if (!strlen($typePaymentTiller) || !$order->mean_payment) {
  1190. $typePaymentTiller = 'CASH';
  1191. }
  1192. $returnTiller = $tiller->postOrder([
  1193. 'externalId' => $order->id,
  1194. 'type' => 1,
  1195. 'status' => 'IN_PROGRESS',
  1196. 'openDate' => $strDate,
  1197. 'closeDate' => $strDate,
  1198. 'lines' => $lines,
  1199. 'payments' => [
  1200. [
  1201. 'type' => $typePaymentTiller,
  1202. 'amount' => $order->getAmountWithTax(
  1203. Order::AMOUNT_TOTAL
  1204. ) * 100,
  1205. 'status' => 'ACCEPTED',
  1206. 'date' => $strDate
  1207. ]
  1208. ]
  1209. ]);
  1210. $returnTillerObject = json_decode($returnTiller);
  1211. $order->tiller_external_id = '' . $returnTillerObject->id;
  1212. $order->save();
  1213. $return[] = $returnTiller;
  1214. }
  1215. }
  1216. }
  1217. }
  1218. return $return;
  1219. }
  1220. public function actionAjaxValidateDeliveryNotes($idOrders)
  1221. {
  1222. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1223. if (strlen($idOrders)) {
  1224. $idOrders = json_decode($idOrders, true);
  1225. if (is_array($idOrders) && count($idOrders) > 0) {
  1226. foreach ($idOrders as $idOrder) {
  1227. $order = Order::searchOne([
  1228. 'id' => (int)$idOrder
  1229. ]);
  1230. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1231. $deliveryNote = DeliveryNote::searchOne([
  1232. 'id' => (int)$order->id_delivery_note
  1233. ]);
  1234. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1235. $deliveryNote->changeStatus(Document::STATUS_VALID);
  1236. $deliveryNote->save();
  1237. }
  1238. }
  1239. }
  1240. return [
  1241. 'return' => 'success',
  1242. 'alert' => [
  1243. 'type' => 'success',
  1244. 'message' => 'Bon(s) de livraison validé(s)'
  1245. ]
  1246. ];
  1247. }
  1248. }
  1249. return [
  1250. 'return' => 'error',
  1251. 'alert' => [
  1252. 'type' => 'danger',
  1253. 'message' => 'Une erreur est survenue lors de la validation des bons de livraison'
  1254. ]
  1255. ];
  1256. }
  1257. public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
  1258. {
  1259. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1260. if (strlen($idOrders)) {
  1261. $idOrders = json_decode($idOrders, true);
  1262. if (is_array($idOrders) && count($idOrders) > 0) {
  1263. foreach ($idOrders as $idOrder) {
  1264. $order = Order::searchOne([
  1265. 'id' => (int)$idOrder
  1266. ]);
  1267. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId(
  1268. ) && $order->id_user) {
  1269. $deliveryNote = null;
  1270. $idDeliveryNote = $order->id_delivery_note;
  1271. if ($idDeliveryNote) {
  1272. $deliveryNote = DeliveryNote::searchOne([
  1273. 'id' => (int)$idDeliveryNote
  1274. ]);
  1275. }
  1276. // on regénére le document si c'est un brouillon
  1277. if ($deliveryNote && $deliveryNote->isStatusDraft()) {
  1278. $deliveryNote->delete();
  1279. $deliveryNote = null;
  1280. }
  1281. if (!$deliveryNote) {
  1282. $deliveryNote = new DeliveryNote();
  1283. $deliveryNote->initTaxCalculationMethod();
  1284. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1285. $deliveryNote->id_user = $order->id_user;
  1286. $deliveryNote->name = 'Bon de livraison ' . $order->getUsername() . ' (' . date(
  1287. 'd/m/Y',
  1288. strtotime(
  1289. $order->distribution->date
  1290. )
  1291. ) . ')';
  1292. $deliveryNote->address = $order->user->getFullAddress();
  1293. $deliveryNote->save();
  1294. }
  1295. if ($deliveryNote) {
  1296. $order->id_delivery_note = $deliveryNote->id;
  1297. $order->save();
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return [
  1303. 'return' => 'success',
  1304. 'alert' => [
  1305. 'type' => 'success',
  1306. 'message' => 'Bon(s) de livraison généré(s)'
  1307. ]
  1308. ];
  1309. }
  1310. return [
  1311. 'return' => 'error',
  1312. 'alert' => [
  1313. 'type' => 'danger',
  1314. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1315. ]
  1316. ];
  1317. }
  1318. public function actionAjaxGenerateDeliveryNote($idOrders)
  1319. {
  1320. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  1321. if (strlen($idOrders)) {
  1322. $idOrders = json_decode($idOrders, true);
  1323. if (is_array($idOrders) && count($idOrders) > 0) {
  1324. // récupération première commande pour obtenir des infos
  1325. reset($idOrders);
  1326. $firstOrder = Order::searchOne([
  1327. 'id' => (int)$idOrders[key($idOrders)]
  1328. ]);
  1329. // deliveryNote existant
  1330. $deliveryNote = null;
  1331. $isUpdate = false;
  1332. $i = 0;
  1333. $ordersArray = Order::searchAll([
  1334. 'id' => $idOrders,
  1335. ]);
  1336. do {
  1337. $order = $ordersArray[$i];
  1338. if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId(
  1339. ) && $order->id_delivery_note > 0) {
  1340. $deliveryNote = DeliveryNote::searchOne([
  1341. 'id' => $order->id_delivery_note
  1342. ]);
  1343. $isUpdate = true;
  1344. }
  1345. $i++;
  1346. } while ($deliveryNote == null && isset($ordersArray[$i]));
  1347. if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
  1348. return [
  1349. 'return' => 'error',
  1350. 'alert' => [
  1351. 'type' => 'danger',
  1352. 'message' => 'Vous ne pouvez pas modifier un bon de livraison déjà validé.'
  1353. ]
  1354. ];
  1355. }
  1356. if ($firstOrder) {
  1357. // génération du BL
  1358. if (!$deliveryNote) {
  1359. $deliveryNote = new DeliveryNote;
  1360. $deliveryNote->initTaxCalculationMethod();
  1361. $deliveryNote->name = 'Bon de livraison ' . $firstOrder->pointSale->name . ' (' . date(
  1362. 'd/m/Y',
  1363. strtotime(
  1364. $firstOrder->distribution->date
  1365. )
  1366. ) . ')';
  1367. $deliveryNote->id_producer = GlobalParam::getCurrentProducerId();
  1368. if ($firstOrder->pointSale->id_user) {
  1369. $deliveryNote->id_user = $firstOrder->pointSale->id_user;
  1370. $user = User::searchOne([
  1371. 'id' => $deliveryNote->id_user
  1372. ]);
  1373. $userProducer = UserProducer::searchOne([
  1374. 'id_user' => $deliveryNote->id_user,
  1375. 'id_producer' => GlobalParam::getCurrentProducerId(
  1376. )
  1377. ]);
  1378. } else {
  1379. $user = new User;
  1380. $user->type = User::TYPE_LEGAL_PERSON;
  1381. $user->name_legal_person = $firstOrder->pointSale->name;
  1382. $user->address = $firstOrder->pointSale->address;
  1383. $user->id_producer = 0;
  1384. $user->setPassword(Password::generate());
  1385. $user->generateAuthKey();
  1386. $user->email = '';
  1387. if (!strlen($user->email)) {
  1388. $user->username = 'inconnu@opendistrib.net';
  1389. }
  1390. $user->save();
  1391. $userProducer = new UserProducer;
  1392. $userProducer->id_user = $user->id;
  1393. $userProducer->id_producer = GlobalParam::getCurrentProducerId();
  1394. $userProducer->credit = 0;
  1395. $userProducer->active = 1;
  1396. $userProducer->save();
  1397. $firstOrder->pointSale->id_user = $user->id;
  1398. $firstOrder->pointSale->save();
  1399. $deliveryNote->id_user = $user->id;
  1400. }
  1401. $deliveryNote->address = $user->getFullAddress();
  1402. $deliveryNote->save();
  1403. } else {
  1404. // réinitialisation des order.id_delivery_note
  1405. Order::updateAll([
  1406. 'id_delivery_note' => null
  1407. ], [
  1408. 'id_delivery_note' => $deliveryNote->id
  1409. ]);
  1410. }
  1411. if (!isset($user) || !$user) {
  1412. $user = User::searchOne([
  1413. 'id' => $deliveryNote->id_user
  1414. ]);
  1415. $userProducer = UserProducer::searchOne([
  1416. 'id_user' => $deliveryNote->id_user,
  1417. 'id_producer' => GlobalParam::getCurrentProducerId(
  1418. )
  1419. ]);
  1420. }
  1421. // affectation du BL aux commandes
  1422. foreach ($idOrders as $idOrder) {
  1423. $order = Order::searchOne([
  1424. 'id' => (int)$idOrder
  1425. ]);
  1426. if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  1427. $order->id_delivery_note = $deliveryNote->id;
  1428. $order->save();
  1429. }
  1430. // init invoice price
  1431. $order = Order::searchOne(['id' => $idOrder]);
  1432. if ($order) {
  1433. $order->initInvoicePrices([
  1434. 'user' => $user,
  1435. 'user_producer' => $userProducer,
  1436. 'point_sale' => $firstOrder->pointSale
  1437. ]);
  1438. }
  1439. }
  1440. return [
  1441. 'return' => 'success',
  1442. 'alert' => [
  1443. 'type' => 'success',
  1444. 'message' => 'Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré')
  1445. ]
  1446. ];
  1447. }
  1448. }
  1449. }
  1450. return [
  1451. 'return' => 'error',
  1452. 'alert' => [
  1453. 'type' => 'danger',
  1454. 'message' => 'Une erreur est survenue lors de la génération du bon de livraison.'
  1455. ]
  1456. ];
  1457. }
  1458. }