Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

DistributionController.php 71KB

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