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

DistributionController.php 71KB

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