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

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