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

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