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

OrderController.php 41KB

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