選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

OrderController.php 41KB

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