Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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