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

OrderController.php 54KB

8 лет назад
6 лет назад
8 лет назад
6 лет назад
6 лет назад
6 лет назад
8 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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. if($dataProductOrder->price) {
  744. $productOrder->price = number_format(Price::getPrice($dataProductOrder->price, $product->taxRate->value), 3) ;
  745. }
  746. else {
  747. $productOrder->price = $product->price;
  748. }
  749. $productOrder->id_tax_rate = $product->taxRate->id;
  750. $productOrder->save();
  751. }
  752. }
  753. $order = Order::searchOne(['id' => $order->id]);
  754. if ($order && $processCredit) {
  755. $order->processCredit();
  756. }
  757. $order->setTillerSynchronization() ;
  758. // lien utilisateur / point de vente
  759. if ($idUser && $pointSale) {
  760. $pointSale->linkUser($idUser);
  761. }
  762. }
  763. return ['success'];
  764. }
  765. /**
  766. * Met à jour une commande via une requête AJAX.
  767. *
  768. * @param integer $idOrder
  769. * @param array $products
  770. * @param string $date
  771. * @param string $comment
  772. */
  773. public function actionAjaxUpdate()
  774. {
  775. $request = Yii::$app->request ;
  776. $date = $request->post('date') ;
  777. $idOrder = $request->post('idOrder') ;
  778. $idPointSale = $request->post('idPointSale') ;
  779. $idUser = $request->post('idUser') ;
  780. $username = $request->post('username') ;
  781. $meanPayment = $request->post('meanPayment') ;
  782. $products = $request->post('products') ;
  783. $comment = $request->post('comment') ;
  784. $processCredit = $request->post('processCredit') ;
  785. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  786. $order = Order::searchOne(['id' => $idOrder]);
  787. if ($order &&
  788. $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  789. $products = json_decode($products);
  790. foreach ($products as $key => $dataProductOrder) {
  791. $productOrder = ProductOrder::findOne([
  792. 'id_order' => $idOrder,
  793. 'id_product' => $key
  794. ]);
  795. $quantity = $dataProductOrder->quantity
  796. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  797. if ($quantity) {
  798. if ($productOrder) {
  799. $productOrder->quantity = $quantity;
  800. } else {
  801. $product = Product::findOne($key);
  802. if ($product) {
  803. $productOrder = new ProductOrder;
  804. $productOrder->id_order = $idOrder;
  805. $productOrder->id_product = $key;
  806. $productOrder->quantity = $quantity;
  807. $productOrder->unit = $product->unit;
  808. $productOrder->step = $product->step;
  809. if($dataProductOrder->price) {
  810. $productOrder->price = number_format(Price::getPrice($dataProductOrder->price, $product->taxRate->value), 3) ;
  811. }
  812. else {
  813. $productOrder->price = $product->price;
  814. }
  815. $productOrder->id_tax_rate = $product->taxRate->id;
  816. }
  817. }
  818. $productOrder->save();
  819. } else {
  820. if ($productOrder) {
  821. $productOrder->delete();
  822. }
  823. }
  824. }
  825. $order->id_point_sale = $idPointSale;
  826. $order->date_update = date('Y-m-d H:i:s');
  827. $order->mean_payment = $meanPayment;
  828. $order->comment = $comment;
  829. if ($idUser) {
  830. $order->username = '';
  831. $order->id_user = $idUser;
  832. // commentaire du point de vente
  833. $userPointSale = UserPointSale::searchOne([
  834. 'id_point_sale' => $order->id_point_sale,
  835. 'id_user' => $idUser
  836. ]);
  837. if ($userPointSale && strlen($userPointSale->comment)) {
  838. $order->comment_point_sale = $userPointSale->comment;
  839. }
  840. } else {
  841. $order->username = $username;
  842. $order->id_user = 0;
  843. }
  844. $order->save();
  845. $order = Order::searchOne(['id' => $order->id]);
  846. if ($order && $processCredit) {
  847. $order->processCredit();
  848. }
  849. }
  850. }
  851. /**
  852. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  853. *
  854. * @param integer $idOrder
  855. */
  856. public function actionPaymentStatus($idOrder)
  857. {
  858. $order = Order::searchOne(['id' => $idOrder]);
  859. if ($order) {
  860. $html = '';
  861. if ($order->id_user) {
  862. $userProducer = UserProducer::find()
  863. ->where([
  864. 'id_user' => $order->id_user,
  865. 'id_producer' => $order->distribution->id_producer
  866. ])
  867. ->one();
  868. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  869. if (abs($order->amount - $amountPaid) < 0.0001) {
  870. $html .= '<span class="label label-success">Payé</span>';
  871. $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']);
  872. } elseif ($order->amount > $amountPaid) {
  873. $amountToPay = $order->amount - $amountPaid;
  874. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  875. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  876. } elseif ($order->amount < $amountPaid) {
  877. $amountToRefund = $amountPaid - $order->amount;
  878. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  879. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  880. }
  881. $html .= '<span class="buttons-credit">'
  882. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  883. . $buttonsCredit
  884. . '</span>';
  885. // historique
  886. $history = CreditHistory::find()
  887. ->with('userAction')
  888. ->where(['id_order' => $idOrder])
  889. ->all();
  890. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  891. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  892. . '<tbody>';
  893. if ($history && is_array($history) && count($history)) {
  894. foreach ($history as $h) {
  895. $html .= '<tr>'
  896. . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
  897. . '<td>' . Html::encode($h->strUserAction()) . '</td>'
  898. . '<td>' . $h->getStrWording() . '</td>'
  899. . '<td>' . ($h->isTypeDebit() ? '- ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
  900. . '<td>' . ($h->isTypeCredit() ? '+ ' . $h->getAmountWithTax(Order::AMOUNT_TOTAL, true) : '') . '</td>'
  901. . '</tr>';
  902. }
  903. } else {
  904. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  905. }
  906. $html .= '</tbody></table>';
  907. } else {
  908. $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>';
  909. }
  910. echo json_encode([
  911. 'html_payment_status' => $html,
  912. 'json_order' => $order->getDataJson()
  913. ]);
  914. }
  915. die();
  916. }
  917. /**
  918. * Effectue le paiement/remboursement d'une commande.
  919. *
  920. * @param integer $idOrder
  921. * @param string $type
  922. * @param float $amount
  923. * @return string
  924. */
  925. public function actionAjaxPayment($idOrder, $type, $amount)
  926. {
  927. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  928. $order = Order::searchOne([
  929. 'id' => $idOrder
  930. ]);
  931. if ($order) {
  932. $order->saveCreditHistory(
  933. $type,
  934. $amount,
  935. GlobalParam::getCurrentProducerId(),
  936. $order->id_user,
  937. User::getCurrentId()
  938. );
  939. }
  940. return ['success'];
  941. }
  942. /**
  943. * Modifie l'état de la synchronisation Tiller d'une commande.
  944. *
  945. * @param int $idOrder
  946. * @param boolean $boolSynchroTiller
  947. * @return array
  948. */
  949. public function actionAjaxChangeSynchroTiller($idOrder, $boolSynchroTiller)
  950. {
  951. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  952. $order = Order::searchOne([
  953. 'id' => (int)$idOrder
  954. ]);
  955. if ($order) {
  956. $order->tiller_synchronization = (int)$boolSynchroTiller;
  957. $res = $order->save();
  958. return ['success'];
  959. }
  960. return ['error'];
  961. }
  962. }