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

DistributionController.php 69KB

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