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.

OrderController.php 53KB

8 jaren geleden
8 jaren geleden
8 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use common\helpers\GlobalParam;
  39. use common\models\Order;
  40. use common\models\ProductOrder;
  41. use common\models\Product;
  42. use common\models\User;
  43. use common\models\ProductDistribution;
  44. use common\models\Distribution;
  45. use common\models\Producer;
  46. class OrderController extends BackendController
  47. {
  48. var $enableCsrfValidation = false;
  49. public function behaviors()
  50. {
  51. return [
  52. 'access' => [
  53. 'class' => AccessControl::className(),
  54. 'rules' => [
  55. [
  56. 'allow' => true,
  57. 'roles' => ['@'],
  58. 'matchCallback' => function ($rule, $action) {
  59. return User::getCurrentStatus() == USER::STATUS_ADMIN
  60. || User::getCurrentStatus() == USER::STATUS_PRODUCER;
  61. }
  62. ]
  63. ],
  64. ],
  65. ];
  66. }
  67. /**
  68. * Traite le formulaire d'ajout/modification de commande.
  69. *
  70. * @param Distribution $distribution
  71. * @param string $date
  72. * @param array $points_vente
  73. * @param array $produits
  74. * @param array $users
  75. */
  76. public function processOrderForm(
  77. $distribution, $date, $pointsSale, $products, $users)
  78. {
  79. if ($date != '') {
  80. // commandes
  81. $orders = Order::searchAll([
  82. 'distribution.date' => $date
  83. ]);
  84. foreach ($pointsSale as $point) {
  85. $point->initOrders($orders);
  86. if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
  87. // modifs
  88. foreach ($point->orders as $order) {
  89. // suppression des product_order
  90. ProductOrder::deleteAll(['id_order' => $order->id]);
  91. // création des commande_produit modifiés
  92. foreach ($products as $product) {
  93. $quantity = Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
  94. if ($quantity) {
  95. $productOrder = new ProductOrder;
  96. $productOrder->id_order = $order->id;
  97. $productOrder->id_product = $product->id;
  98. $productOrder->quantity = $quantity;
  99. $productOrder->price = $p->price;
  100. $productOrder->unit = $p->unit;
  101. $productOrder->step = $p->step;
  102. $productOrder->id_tax_rate = $p->taxRate->id ;
  103. $productOrder->save();
  104. }
  105. }
  106. }
  107. $username = Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
  108. $date = Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
  109. $oneProduct = false;
  110. foreach ($products as $product) {
  111. $quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  112. if ($quantity) {
  113. $oneProduct = true;
  114. }
  115. }
  116. if (strlen($username) && $date && $oneProduct) {
  117. $order = new Order;
  118. $order->id_point_sale = $point->id;
  119. $order->id_production = $distribution->id;
  120. $order->id_user = 0;
  121. $order->username = $username;
  122. $arrayDate = explode('/', $date);
  123. $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
  124. $order->save();
  125. foreach ($products as $product) {
  126. $quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  127. if ($quantity) {
  128. $productOrder = new ProductOrder;
  129. $productOrder->id_order = $order->id;
  130. $productOrder->id_product = $product->id;
  131. $productOrder->quantity = $quantity;
  132. $productOrder->price = $p->price;
  133. $productOrder->unit = $p->unit;
  134. $productOrder->step = $p->step;
  135. $productOrder->id_tax_rate = $p->taxRate->id ;
  136. $productOrder->save();
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. }
  144. /**
  145. * Page principale de la gestion des commandes.
  146. *
  147. * @param string $date
  148. * @param boolean $returnData
  149. * @return string
  150. */
  151. public function actionIndex($date = '', $returnData = false)
  152. {
  153. if (!Product::searchCount() || !PointSale::searchCount()) {
  154. $this->redirect(['site/index', 'error_products_points_sale' => 1]);
  155. }
  156. $orders = [];
  157. // users
  158. $arrayUsers = [0 => '--'];
  159. $users = User::searchAll([], ['orderby' => 'lastname, name ASC']);
  160. foreach ($users as $user) {
  161. $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
  162. }
  163. // création du jour de distribution
  164. $distribution = Distribution::initDistribution($date);
  165. // points de vente
  166. if ($distribution) {
  167. $arrayPointsSale = PointSale::find()
  168. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  169. $q->where(['id_distribution' => $distribution->id]);
  170. }])
  171. ->where([
  172. 'id_producer' => GlobalParam::getCurrentProducerId(),
  173. ])
  174. ->all();
  175. } else {
  176. $arrayPointsSale = PointSale::searchAll();
  177. }
  178. // produits
  179. $arrayProducts = Product::searchAll();
  180. // gestion des commandes
  181. $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
  182. // commandes
  183. $arrayOrders = Order::searchAll([
  184. 'distribution.date' => $date,
  185. ]);
  186. $revenues = 0;
  187. $weight = 0;
  188. $revenuesDelivered = 0;
  189. if ($arrayOrders) {
  190. foreach ($arrayOrders as $order) {
  191. if (is_null($order->date_delete)) {
  192. $revenues += $order->amount;
  193. if ($order->id_point_sale != 1) {
  194. $revenuesDelivered += $order->amount;
  195. }
  196. $weight += $order->weight;
  197. }
  198. }
  199. }
  200. $revenues = number_format($revenues, 2);
  201. // init commandes point de vente
  202. foreach ($arrayPointsSale as $pointSale) {
  203. $pointSale->initOrders($arrayOrders);
  204. $dataSelectOrders = [];
  205. $dataOptionsOrders = [];
  206. foreach ($pointSale->orders as $order) {
  207. if ($order->user) {
  208. $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
  209. } else {
  210. $dataSelectOrders[$order->id] = $order->username;
  211. }
  212. $dataOptionsOrders[$order->id] = [];
  213. $arrayOptions = [];
  214. $arrayOptions[$order->id]['amount'] = $order->amount;
  215. $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
  216. $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
  217. $arrayOptions[$order->id]['products'] = [];
  218. $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
  219. foreach ($order->productOrder as $productOrder) {
  220. $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
  221. }
  222. $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
  223. $dataOptionsOrders[$order->id]['value'] = $order->id;
  224. }
  225. $pointSale->data_select_orders = $dataSelectOrders;
  226. $pointSale->data_options_orders = $dataOptionsOrders;
  227. }
  228. // gestion produits selec
  229. if (isset($_POST['valider_produit_selec'])) {
  230. if (isset($_POST['Product'])) {
  231. foreach ($arrayProducts as $product) {
  232. $productDistribution = ProductDistribution::searchOne([
  233. 'id_distribution' => $distribution->id,
  234. 'id_product' => $product->id
  235. ]);
  236. if (!$productDistribution) {
  237. $productDistribution = new ProductDistribution();
  238. $productDistribution->id_distribution = $distribution->id;
  239. $productDistribution->id_product = $product->id;
  240. $productDistribution->active = 0;
  241. if (isset($product->quantity_max)) {
  242. $productDistribution->quantity_max = $product->quantity_max;
  243. } else {
  244. $productDistribution->quantity_max = null;
  245. }
  246. $productDistribution->save();
  247. }
  248. if (isset($_POST['Product'][$product->id]['active'])) {
  249. $productDistribution->active = 1;
  250. } else {
  251. $productDistribution->active = 0;
  252. }
  253. if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
  254. $productDistribution->quantity_max = (int)$_POST['Product'][$product->id]['quantity_max'];
  255. } else {
  256. $productDistribution->quantity_max = null;
  257. }
  258. $productDistribution->save();
  259. }
  260. }
  261. }
  262. $arrayProductsSelected = [];
  263. if ($distribution) {
  264. // produits selec pour production
  265. $arrayProductsSelected = ProductDistribution::searchByDistribution($distribution->id);
  266. }
  267. // produits
  268. if ($distribution) {
  269. $arrayProducts = Product::searchByDistribution($distribution->id);
  270. }
  271. // poids total de la production et CA potentiel
  272. $potentialTurnover = 0;
  273. $totalWeight = 0;
  274. foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
  275. if ($selectedProduct['active']) {
  276. foreach ($arrayProducts as $product) {
  277. if ($product->id == $idSelectedProduct) {
  278. $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
  279. $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
  280. }
  281. }
  282. }
  283. }
  284. // jours de distribution
  285. $arrayDistributionDays = Distribution::searchAll([
  286. 'active' => 1
  287. ]);
  288. // commandes auto
  289. $subscriptionForm = new SubscriptionForm;
  290. // productions point vente
  291. $pointSaleDistribution = new PointSaleDistribution;
  292. $oointsSaleDistribution = [];
  293. if ($distribution) {
  294. $pointsSaleDistribution = PointSaleDistribution::searchAll([
  295. 'id_distribution' => $distribution->id
  296. ]);
  297. }
  298. $arrayPointsSaleDistribution = [];
  299. if (isset($pointsSaleDistribution)) {
  300. foreach ($pointsSaleDistribution as $pointSaleDistrib) {
  301. $key = $pointSaleDistrib->id_distribution . '-' . $pointSaleDistrib->id_point_sale;
  302. if ($pointSaleDistrib->delivery == 1) {
  303. $pointSaleDistribution->points_sale_distribution[] = $key;
  304. }
  305. if (isset($pointSaleDistrib->pointSale) && strlen($pointSaleDistrib->pointSale->name)) {
  306. $arrayPointsSaleDistribution[$key] = Html::encode($pointSaleDistrib->pointSale->name);
  307. }
  308. }
  309. }
  310. // une production de la semaine activée ou non
  311. $oneDistributionWeekActive = false;
  312. $week = sprintf('%02d', date('W', strtotime($date)));
  313. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  314. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  315. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  316. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  317. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  318. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  319. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  320. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  321. $weekDistribution = Distribution::find()
  322. ->andWhere([
  323. 'id_producer' => GlobalParam::getCurrentProducerId(),
  324. 'active' => 1,
  325. ])
  326. ->andWhere(['or',
  327. ['date' => $dateMonday],
  328. ['date' => $dateTuesday],
  329. ['date' => $dateWednesday],
  330. ['date' => $dateThursday],
  331. ['date' => $dateFriday],
  332. ['date' => $dateSaturday],
  333. ['date' => $dateSunday],
  334. ])
  335. ->one();
  336. if ($weekDistribution) {
  337. $oneDistributionWeekActive = true;
  338. }
  339. $datas = [
  340. 'arrayProducts' => $arrayProducts,
  341. 'arrayPointsSale' => $arrayPointsSale,
  342. 'arrayOrders' => $arrayOrders,
  343. 'date' => $date,
  344. 'distribution' => $distribution,
  345. 'arrayDistributionDays' => $arrayDistributionDays,
  346. 'selectedProducts' => $arrayProductsSelected,
  347. 'users' => $arrayUsers,
  348. 'revenues' => $revenues,
  349. 'revenuesDelivered' => $revenuesDelivered,
  350. 'weight' => $weight,
  351. 'potentialTurnover' => $potentialTurnover,
  352. 'totalWeight' => $totalWeight,
  353. 'subscriptionForm' => $subscriptionForm,
  354. 'pointSaleDistribution' => $pointSaleDistribution,
  355. 'arrayPointsSaleDistribution' => $arrayPointsSaleDistribution,
  356. 'oneDistributionWeekActive' => $oneDistributionWeekActive
  357. ];
  358. if ($returnData) {
  359. return $datas;
  360. } else {
  361. return $this->render('index', $datas);
  362. }
  363. }
  364. /**
  365. * Génère un fichier d'export des commandes au format CSV.
  366. *
  367. * @param string $date
  368. * @param integer $id_point_vente
  369. * @param boolean $global
  370. */
  371. public function actionDownload($date = '', $idPointSale = 0, $global = 0)
  372. {
  373. // commandes
  374. $ordersArray = Order::searchAll([
  375. 'distribution.date' => $date
  376. ]);
  377. // points de vente
  378. $pointsSaleArray = PointSale::searchAll();
  379. foreach ($pointsSaleArray as $pointSale) {
  380. $pv->initOrders($ordersArray);
  381. }
  382. // produits
  383. $productsArray = Product::find()->orderBy('order ASC')->all();
  384. $distribution = Distribution::find()
  385. ->where('date LIKE \':date\'')
  386. ->params([':date' => $date])
  387. ->one();
  388. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  389. /*
  390. * export global
  391. */
  392. if ($global) {
  393. $data = [];
  394. $filename = 'export_' . $date . '_global';
  395. $dayWeek = date('w', strtotime($date));
  396. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  397. $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  398. // par point de vente
  399. foreach ($pointsSaleArray as $pointSale) {
  400. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  401. $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
  402. $data[] = $line;
  403. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
  404. foreach ($res['data'] as $line) {
  405. $data[] = $line;
  406. }
  407. }
  408. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  409. $line = ['Total'];
  410. $strProducts = '';
  411. foreach ($productsArray as $product) {
  412. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  413. $quantity = Order::getProductQuantity($product->id, $pointSale->orders);
  414. $strQuantity = '';
  415. if ($quantity) {
  416. $strQuantity = $quantity;
  417. $strProducts .= $strQuantity . ', ';
  418. }
  419. }
  420. }
  421. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  422. $line[] = number_format($pointSale->revenues, 2) . ' €';
  423. $data[] = $line;
  424. $data[] = [];
  425. }
  426. }
  427. $line = ['Total'];
  428. $strProducts = '';
  429. foreach ($productsArray as $product) {
  430. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  431. $quantity = Order::getProductQuantity($product->id, $ordersArray);
  432. $strQuantity = '';
  433. if ($quantity) {
  434. $strQuantity = $quantity;
  435. $strQuantity .= $strQuantity . ', ';
  436. }
  437. }
  438. }
  439. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  440. $data[] = $line;
  441. $infos = $this->actionIndex($date, true);
  442. CSV::downloadSendHeaders($filename . '.csv');
  443. echo CSV::array2csv($data);
  444. die();
  445. } /*
  446. * export individuel
  447. */
  448. else {
  449. if ($ordersArray && count($ordersArray)) {
  450. $data = [];
  451. // par point de vente
  452. if ($idPointSale) {
  453. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
  454. $data = $res['data'];
  455. $filename = $res['filename'];
  456. } // récapitulatif
  457. else {
  458. $res = $this->contentRecapCSV($date, $productsArray, $pointsSaleArray, $ordersArray);
  459. $filename = 'summary_' . $date;
  460. $data = $res['data'];
  461. }
  462. CSV::downloadSendHeaders($filename . '.csv');
  463. echo CSV::array2csv($data);
  464. die();
  465. }
  466. }
  467. }
  468. /**
  469. * Génère le contenu nécessaire aux exports au format CSV.
  470. *
  471. * @see OrderController::actionDownload()
  472. * @param string $date
  473. * @param array $products
  474. * @param array $pointsSale
  475. * @param array $orders
  476. * @return array
  477. */
  478. public function contentRecapCSV($date, $products, $pointsSale, $orders)
  479. {
  480. $data = [];
  481. $filename = 'summary_' . $date;
  482. $distribution = Distribution::find()
  483. ->where('date LIKE \':date\'')
  484. ->params([':date' => $date])
  485. ->one();
  486. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  487. // head
  488. $data[0] = ['Lieu'];
  489. foreach ($products as $product) {
  490. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  491. $data[0][] = $product->description;
  492. }
  493. }
  494. $dayWeek = date('w', strtotime($date));
  495. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  496. $fieldHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  497. // datas
  498. foreach ($pointsSale as $pointSale) {
  499. if (count($pointSale->orders) && strlen($pointSale->$fieldHoursPointSale)) {
  500. $dataAdd = [$pointSale->name];
  501. foreach ($products as $product) {
  502. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  503. $dataAdd[] = Order::getProductQuantity($product->id, $pointSale->orders);
  504. }
  505. }
  506. $data[] = $dataAdd;
  507. }
  508. }
  509. $dataAdd = ['Total'];
  510. foreach ($products as $product) {
  511. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  512. $dataAdd[] = Order::getProductQuantity($product->id, $orders);
  513. }
  514. }
  515. $data[] = $dataAdd;
  516. return [
  517. 'data' => $data,
  518. 'filename' => $filename
  519. ];
  520. }
  521. /**
  522. * Génère le contenu relatif aux points de vente nécessaires aux exports au
  523. * format CSV.
  524. *
  525. * @param string $date
  526. * @param array $produits
  527. * @param array $points_vente
  528. * @param integer $id_point_vente
  529. * @return array
  530. */
  531. public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
  532. {
  533. $data = [];
  534. $distribution = Distribution::find()->where('date LIKE \':date\'')->params([':date' => $date])->one();
  535. $selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
  536. // datas
  537. foreach ($pointsSale as $pointSale) {
  538. if ($pointSale->id == $idPointSale) {
  539. $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
  540. foreach ($pointSale->orders as $order) {
  541. $strUser = '';
  542. // username
  543. if ($order->user) {
  544. $strUser = $order->user->name . " " . $order->user->lastname;
  545. } else {
  546. $strUser = $order->username;
  547. }
  548. // téléphone
  549. if (isset($order->user) && strlen($order->user->phone)) {
  550. $strUser .= ' (' . $order->user->phone . ')';
  551. }
  552. $dataAdd = [$strUser];
  553. // produits
  554. $strProducts = '';
  555. foreach ($products as $product) {
  556. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  557. $add = false;
  558. foreach ($product->productOrder as $productOrder) {
  559. if ($product->id == $productOrder->id_product) {
  560. $strProducts .= $productOrder->quantity;
  561. $add = true;
  562. }
  563. }
  564. }
  565. }
  566. $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
  567. $dataAdd[] = number_format($order->amount, 2) . ' €';
  568. $dataAdd[] = $order->comment;
  569. $data[] = $dataAdd;
  570. }
  571. }
  572. }
  573. return [
  574. 'data' => $data,
  575. 'filename' => $filename
  576. ];
  577. }
  578. /**
  579. * Change l'état d'un jour de production (activé, désactivé).
  580. *
  581. * @param string $date
  582. * @param integer $actif
  583. * @param boolean $redirect
  584. */
  585. public function actionChangeState($date, $active, $redirect = true)
  586. {
  587. // changement état
  588. $distribution = Distribution::initDistribution($date);
  589. $distribution->active = $active;
  590. $distribution->save();
  591. if ($active) {
  592. // add commandes automatiques
  593. Subscription::addAll($date);
  594. }
  595. if ($redirect) {
  596. $this->redirect(['index', 'date' => $date]);
  597. }
  598. }
  599. /**
  600. * Change l'état d'une semaine de production (activé, désactivé).
  601. *
  602. * @param string $date
  603. * @param integer $actif
  604. */
  605. public function actionChangeStateWeek($date, $active)
  606. {
  607. $week = sprintf('%02d', date('W', strtotime($date)));
  608. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  609. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  610. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  611. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  612. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  613. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  614. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  615. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  616. $pointsSaleArray = PointSale::searchAll();
  617. $activeMonday = false;
  618. $activeTuesday = false;
  619. $activeWednesday = false;
  620. $activeThursday = false;
  621. $activeFriday = false;
  622. $activeSaturday = false;
  623. $activeSunday = false;
  624. foreach ($pointsSaleArray as $pointSale) {
  625. if ($pointSale->delivery_monday) $activeMonday = true;
  626. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  627. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  628. if ($pointSale->delivery_thursday) $activeThursday = true;
  629. if ($pointSale->delivery_friday) $activeFriday = true;
  630. if ($pointSale->delivery_saturday) $activeSaturday = true;
  631. if ($pointSale->delivery_sunday) $activeSunday = true;
  632. }
  633. if ($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false);
  634. if ($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false);
  635. if ($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false);
  636. if ($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false);
  637. if ($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false);
  638. if ($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false);
  639. if ($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false);
  640. $this->redirect(['index', 'date' => $date]);
  641. }
  642. /**
  643. * Supprime une commande via une requête AJAX.
  644. *
  645. * @param string $date
  646. * @param integer $idOrder
  647. */
  648. public function actionAjaxDelete($idOrder)
  649. {
  650. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  651. $order = Order::searchOne([
  652. 'id' => $idOrder
  653. ]);
  654. // delete
  655. if ($order) {
  656. $order->delete();
  657. }
  658. return ['success'];
  659. }
  660. /**
  661. * Supprime une commande.
  662. *
  663. * @param string $date
  664. * @param integer $idOrder
  665. */
  666. public function actionDelete($date, $idOrder)
  667. {
  668. $order = Order::searchOne(['id' => $idOrder]);
  669. if ($order) {
  670. // remboursement de la commande
  671. if ($order->id_user && $order->getAmount(Order::AMOUNT_PAID) && Producer::getConfig('credit')) {
  672. $order->saveCreditHistory(
  673. CreditHistory::TYPE_REFUND,
  674. $order->getAmount(Order::AMOUNT_PAID),
  675. $order->distribution->id_producer,
  676. $order->id_user,
  677. User::getCurrentId()
  678. );
  679. }
  680. $order->delete();
  681. ProductOrder::deleteAll(['id_order' => $idOrder]);
  682. }
  683. $this->redirect(['index', 'date' => $date]);
  684. }
  685. /**
  686. * Crée une commande via une requête AJAX.
  687. *
  688. * @param string $date
  689. * @param integer $idPointSale
  690. * @param integer $idUser
  691. * @param string $username
  692. * @param array $produits
  693. * @param string $commentaire
  694. * @param string $processCredit
  695. */
  696. public function actionAjaxCreate(
  697. $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment, $processCredit = 0)
  698. {
  699. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  700. $products = json_decode($products);
  701. $pointSale = PointSale::findOne($idPointSale);
  702. $distribution = Distribution::searchOne([
  703. 'date' => $date
  704. ]);
  705. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) &&
  706. ($idUser || strlen($username)) &&
  707. $pointSale &&
  708. count($products) &&
  709. $distribution) {
  710. $order = new Order;
  711. $order->date = date('Y-m-d H:i:s');
  712. $order->id_point_sale = $idPointSale;
  713. $order->mean_payment = $meanPayment;
  714. $order->id_distribution = $distribution->id;
  715. $order->origin = Order::ORIGIN_ADMIN;
  716. $order->comment = $comment;
  717. $order->status = 'tmp-order';
  718. if ($idUser) {
  719. $order->id_user = $idUser;
  720. // commentaire du point de vente
  721. $userPointSale = UserPointSale::searchOne([
  722. 'id_point_sale' => $idPointSale,
  723. 'id_user' => $idUser
  724. ]);
  725. if ($userPointSale && strlen($userPointSale->comment)) {
  726. $order->comment_point_sale = $userPointSale->comment;
  727. }
  728. } else {
  729. $order->username = $username;
  730. $order->id_user = 0;
  731. }
  732. $order->save();
  733. foreach ($products as $key => $dataProductOrder) {
  734. $product = Product::findOne($key);
  735. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  736. if ($product && $quantity) {
  737. $productOrder = new ProductOrder;
  738. $productOrder->id_order = $order->id;
  739. $productOrder->id_product = $key;
  740. $productOrder->quantity = $quantity;
  741. $productOrder->unit = $product->unit;
  742. $productOrder->step = $product->step;
  743. $productOrder->price = $product->price;
  744. $productOrder->id_tax_rate = $product->taxRate->id;
  745. $productOrder->save();
  746. }
  747. }
  748. $order = Order::searchOne(['id' => $order->id]);
  749. if ($order && $processCredit) {
  750. $order->processCredit();
  751. }
  752. $order->setTillerSynchronization() ;
  753. // lien utilisateur / point de vente
  754. if ($idUser && $pointSale) {
  755. $pointSale->linkUser($idUser);
  756. }
  757. }
  758. return ['success'];
  759. }
  760. /**
  761. * Met à jour une commande via une requête AJAX.
  762. *
  763. * @param integer $idOrder
  764. * @param array $products
  765. * @param string $date
  766. * @param string $comment
  767. */
  768. public function actionAjaxUpdate(
  769. $date, $idOrder, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment = '', $processCredit = 0)
  770. {
  771. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  772. $order = Order::searchOne(['id' => $idOrder]);
  773. if ($order &&
  774. $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  775. $products = json_decode($products);
  776. foreach ($products as $key => $dataProductOrder) {
  777. $productOrder = ProductOrder::findOne([
  778. 'id_order' => $idOrder,
  779. 'id_product' => $key
  780. ]);
  781. $quantity = $dataProductOrder->quantity
  782. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  783. if ($quantity) {
  784. if ($productOrder) {
  785. $productOrder->quantity = $quantity;
  786. } else {
  787. $product = Product::findOne($key);
  788. if ($product) {
  789. $productOrder = new ProductOrder;
  790. $productOrder->id_order = $idOrder;
  791. $productOrder->id_product = $key;
  792. $productOrder->quantity = $quantity;
  793. $productOrder->unit = $product->unit;
  794. $productOrder->step = $product->step;
  795. $productOrder->price = $product->price;
  796. $productOrder->id_tax_rate = $product->taxRate->id;
  797. }
  798. }
  799. $productOrder->save();
  800. } else {
  801. if ($productOrder) {
  802. $productOrder->delete();
  803. }
  804. }
  805. }
  806. $order->id_point_sale = $idPointSale;
  807. $order->date_update = date('Y-m-d H:i:s');
  808. $order->mean_payment = $meanPayment;
  809. $order->comment = $comment;
  810. if ($idUser) {
  811. $order->username = '';
  812. $order->id_user = $idUser;
  813. // commentaire du point de vente
  814. $userPointSale = UserPointSale::searchOne([
  815. 'id_point_sale' => $order->id_point_sale,
  816. 'id_user' => $idUser
  817. ]);
  818. if ($userPointSale && strlen($userPointSale->comment)) {
  819. $order->comment_point_sale = $userPointSale->comment;
  820. }
  821. } else {
  822. $order->username = $username;
  823. $order->id_user = 0;
  824. }
  825. $order->save();
  826. $order = Order::searchOne(['id' => $order->id]);
  827. if ($order && $processCredit) {
  828. $order->processCredit();
  829. }
  830. }
  831. }
  832. /**
  833. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  834. *
  835. * @param integer $idOrder
  836. */
  837. public function actionPaymentStatus($idOrder)
  838. {
  839. $order = Order::searchOne(['id' => $idOrder]);
  840. if ($order) {
  841. $html = '';
  842. if ($order->id_user) {
  843. $userProducer = UserProducer::find()
  844. ->where([
  845. 'id_user' => $order->id_user,
  846. 'id_producer' => $order->distribution->id_producer
  847. ])
  848. ->one();
  849. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  850. if (abs($order->amount - $amountPaid) < 0.0001) {
  851. $html .= '<span class="label label-success">Payé</span>';
  852. $buttonsCredit = Html::a('Rembourser ' . $order->getAmountWithTax(Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
  853. } elseif ($order->amount > $amountPaid) {
  854. $amountToPay = $order->amount - $amountPaid;
  855. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  856. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  857. } elseif ($order->amount < $amountPaid) {
  858. $amountToRefund = $amountPaid - $order->amount;
  859. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  860. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  861. }
  862. $html .= '<span class="buttons-credit">'
  863. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  864. . $buttonsCredit
  865. . '</span>';
  866. // historique
  867. $history = CreditHistory::find()
  868. ->with('userAction')
  869. ->where(['id_order' => $idOrder])
  870. ->all();
  871. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  872. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  873. . '<tbody>';
  874. if ($history && is_array($history) && count($history)) {
  875. foreach ($history as $h) {
  876. $html .= '<tr>'
  877. . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
  878. . '<td>' . Html::encode($h->strUserAction()) . '</td>'
  879. . '<td>' . $h->getStrWording() . '</td>'
  880. . '<td>' . ($h->isTypeDebit() ? '- ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
  881. . '<td>' . ($h->isTypeCredit() ? '+ ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
  882. . '</tr>';
  883. }
  884. } else {
  885. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  886. }
  887. $html .= '</tbody></table>';
  888. } else {
  889. $html .= '<div class="alert alert-warning">Pas de gestion de crédit pain pour cette commande car elle n\'est pas liée à un compte utilisateur.</div>';
  890. }
  891. echo json_encode([
  892. 'html_payment_status' => $html,
  893. 'json_order' => $order->getDataJson()
  894. ]);
  895. }
  896. die();
  897. }
  898. /**
  899. * Effectue le paiement/remboursement d'une commande.
  900. *
  901. * @param integer $idOrder
  902. * @param string $type
  903. * @param float $amount
  904. * @return string
  905. */
  906. public function actionAjaxPayment($idOrder, $type, $amount)
  907. {
  908. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  909. $order = Order::searchOne([
  910. 'id' => $idOrder
  911. ]);
  912. if ($order) {
  913. $order->saveCreditHistory(
  914. $type,
  915. $amount,
  916. GlobalParam::getCurrentProducerId(),
  917. $order->id_user,
  918. User::getCurrentId()
  919. );
  920. }
  921. return ['success'];
  922. }
  923. /**
  924. * Modifie l'état de la synchronisation Tiller d'une commande.
  925. *
  926. * @param int $idOrder
  927. * @param boolean $boolSynchroTiller
  928. * @return array
  929. */
  930. public function actionAjaxChangeSynchroTiller($idOrder, $boolSynchroTiller)
  931. {
  932. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  933. $order = Order::searchOne([
  934. 'id' => (int)$idOrder
  935. ]);
  936. if ($order) {
  937. $order->tiller_synchronization = (int)$boolSynchroTiller;
  938. $res = $order->save();
  939. return ['success'];
  940. }
  941. return ['error'];
  942. }
  943. }