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 72KB

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