您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1131 行
46KB

  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\Price;
  42. use common\logic\Distribution\Distribution\Model\Distribution;
  43. use common\logic\Distribution\PointSaleDistribution\Model\PointSaleDistribution;
  44. use common\logic\Distribution\ProductDistribution\Model\ProductDistribution;
  45. use common\logic\Order\Order\Model\Order;
  46. use common\logic\Order\ProductOrder\Model\ProductOrder;
  47. use common\logic\PointSale\PointSale\Model\PointSale;
  48. use common\logic\Product\Product\Model\Product;
  49. use common\logic\Payment\Model\Payment;
  50. use common\logic\User\User\Model\User;
  51. use common\logic\User\UserProducer\Model\UserProducer;
  52. use yii\filters\AccessControl;
  53. use yii\helpers\Html;
  54. class OrderController extends BackendController
  55. {
  56. var $enableCsrfValidation = false;
  57. public function behaviors()
  58. {
  59. return [
  60. 'access' => [
  61. 'class' => AccessControl::class,
  62. 'rules' => [
  63. [
  64. 'allow' => true,
  65. 'roles' => ['@'],
  66. 'matchCallback' => function ($rule, $action) {
  67. return $this->getUserManager()->isCurrentProducer()
  68. || $this->getUserManager()->isCurrentAdmin();
  69. }
  70. ]
  71. ],
  72. ],
  73. ];
  74. }
  75. /**
  76. * Traite le formulaire d'ajout/modification de commande.
  77. */
  78. public function processOrderForm(
  79. Distribution $distribution,
  80. string $date,
  81. array $pointsSale,
  82. array $products,
  83. array $users
  84. )
  85. {
  86. $orderManager = $this->getOrderManager();
  87. $pointSaleManager = $this->getPointSaleManager();
  88. if ($date != '') {
  89. $orders = $orderManager->findOrdersByDistribution($distribution);
  90. foreach ($pointsSale as $point) {
  91. $orderManager->initPointSaleOrders($point, $orders);
  92. if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
  93. // modifs
  94. foreach ($point->orders as $order) {
  95. // suppression des product_order
  96. ProductOrder::deleteAll(['id_order' => $order->id]);
  97. // création des commande_produit modifiés
  98. foreach ($products as $product) {
  99. $quantity = \Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
  100. if ($quantity) {
  101. $productOrder = new ProductOrder;
  102. $productOrder->id_order = $order->id;
  103. $productOrder->id_product = $product->id;
  104. $productOrder->quantity = $quantity;
  105. $productOrder->price = $p->price;
  106. $productOrder->unit = $p->unit;
  107. $productOrder->step = $p->step;
  108. $productOrder->id_tax_rate = $p->taxRate->id;
  109. $productOrder->save();
  110. }
  111. }
  112. }
  113. $username = \Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
  114. $date = \Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
  115. $oneProduct = false;
  116. foreach ($products as $product) {
  117. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  118. if ($quantity) {
  119. $oneProduct = true;
  120. }
  121. }
  122. if (strlen($username) && $date && $oneProduct) {
  123. $order = new Order();
  124. $order->id_point_sale = $point->id;
  125. $order->id_production = $distribution->id;
  126. $order->id_user = 0;
  127. $order->username = $username;
  128. $arrayDate = explode('/', $date);
  129. $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
  130. $order->save();
  131. foreach ($products as $product) {
  132. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  133. if ($quantity) {
  134. $productOrder = new ProductOrder();
  135. $productOrder->id_order = $order->id;
  136. $productOrder->id_product = $product->id;
  137. $productOrder->quantity = $quantity;
  138. $productOrder->price = $p->price;
  139. $productOrder->unit = $p->unit;
  140. $productOrder->step = $p->step;
  141. $productOrder->id_tax_rate = $p->taxRate->id;
  142. $productOrder->save();
  143. }
  144. }
  145. $orderManager->generateOrderReference($order);
  146. }
  147. }
  148. }
  149. }
  150. }
  151. /**
  152. * Page principale de la gestion des commandes.
  153. */
  154. public function actionIndex($date = '', $returnData = false)
  155. {
  156. $distributionManager = $this->getDistributionManager();
  157. $productManager = $this->getProductManager();
  158. $pointSaleManager = $this->getPointSaleManager();
  159. $orderManager = $this->getOrderManager();
  160. $productDistributionManager = $this->getProductDistributionManager();
  161. if (!Product::searchCount() || !PointSale::searchCount()) {
  162. $this->redirect(['dashboard/index', 'error_products_points_sale' => 1]);
  163. }
  164. $orders = [];
  165. // users
  166. $arrayUsers = [0 => '--'];
  167. $users = User::searchAll([], ['orderby' => 'lastname, name ASC']);
  168. foreach ($users as $user) {
  169. $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
  170. }
  171. $distribution = $distributionManager->createDistributionIfNotExist($date);
  172. if ($distribution) {
  173. $arrayPointsSale = PointSale::find()
  174. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  175. $q->where(['id_distribution' => $distribution->id]);
  176. }])
  177. ->where([
  178. 'id_producer' => GlobalParam::getCurrentProducerId(),
  179. ])
  180. ->all();
  181. } else {
  182. $arrayPointsSale = $pointSaleManager->findPointSales();
  183. }
  184. $arrayProducts = $productManager->findProducts();
  185. $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
  186. // commandes
  187. $arrayOrders = $orderManager->findOrdersByDistribution($distribution);
  188. $revenues = 0;
  189. $weight = 0;
  190. $revenuesDelivered = 0;
  191. if ($arrayOrders) {
  192. foreach ($arrayOrders as $order) {
  193. if (is_null($order->date_delete)) {
  194. $revenues += $order->amount;
  195. if ($order->id_point_sale != 1) {
  196. $revenuesDelivered += $order->amount;
  197. }
  198. $weight += $order->weight;
  199. }
  200. }
  201. }
  202. $revenues = number_format($revenues, 2);
  203. // init commandes point de vente
  204. foreach ($arrayPointsSale as $pointSale) {
  205. $orderManager->initPointSaleOrders($pointSale, $arrayOrders);
  206. $dataSelectOrders = [];
  207. $dataOptionsOrders = [];
  208. foreach ($pointSale->orders as $order) {
  209. if ($order->user) {
  210. $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
  211. } else {
  212. $dataSelectOrders[$order->id] = $order->username;
  213. }
  214. $dataOptionsOrders[$order->id] = [];
  215. $arrayOptions = [];
  216. $arrayOptions[$order->id]['amount'] = $order->amount;
  217. $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
  218. $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
  219. $arrayOptions[$order->id]['products'] = [];
  220. $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
  221. foreach ($order->productOrder as $productOrder) {
  222. $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
  223. }
  224. $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
  225. $dataOptionsOrders[$order->id]['value'] = $order->id;
  226. }
  227. $pointSale->data_select_orders = $dataSelectOrders;
  228. $pointSale->data_options_orders = $dataOptionsOrders;
  229. }
  230. // gestion produits selec
  231. if (isset($_POST['valider_produit_selec'])) {
  232. if (isset($_POST['Product'])) {
  233. foreach ($arrayProducts as $product) {
  234. $productDistribution = $productDistributionManager->findOneProductDistribution($distribution, $product);
  235. if (!$productDistribution) {
  236. $productDistribution = new ProductDistribution();
  237. $productDistribution->id_distribution = $distribution->id;
  238. $productDistribution->id_product = $product->id;
  239. $productDistribution->active = 0;
  240. if (isset($product->quantity_max)) {
  241. $productDistribution->quantity_max = $product->quantity_max;
  242. } else {
  243. $productDistribution->quantity_max = null;
  244. }
  245. $productDistributionManager->saveCreate($productDistribution);
  246. }
  247. if (isset($_POST['Product'][$product->id]['active'])) {
  248. $productDistribution->active = 1;
  249. } else {
  250. $productDistribution->active = 0;
  251. }
  252. if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
  253. $productDistribution->quantity_max = (int)$_POST['Product'][$product->id]['quantity_max'];
  254. } else {
  255. $productDistribution->quantity_max = null;
  256. }
  257. $productDistributionManager->saveUpdate($productDistribution);
  258. }
  259. }
  260. }
  261. $arrayProductsSelected = [];
  262. if ($distribution) {
  263. $arrayProductsSelected = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  264. $arrayProducts = $productManager->findProductsByDistribution($distribution);
  265. }
  266. // poids total de la production et CA potentiel
  267. $potentialTurnover = 0;
  268. $totalWeight = 0;
  269. foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
  270. if ($selectedProduct['active']) {
  271. foreach ($arrayProducts as $product) {
  272. if ($product->id == $idSelectedProduct) {
  273. $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
  274. $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
  275. }
  276. }
  277. }
  278. }
  279. $arrayDistributionDays = $distributionManager->findDistributionsActive();
  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' => GlobalParam::getCurrentProducerId(),
  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. $orderManager = $this->getOrderManager();
  366. $distributionManager = $this->getDistributionManager();
  367. $pointSaleManager = $this->getPointSaleManager();
  368. $productManager = $this->getProductManager();
  369. $productDistributionManager = $this->getProductDistributionManager();
  370. $distribution = $distributionManager->findOneDistribution($date);
  371. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  372. $productsArray = $productManager->findProducts();
  373. $ordersArray = $orderManager->findOrdersByDistributionDate($date);
  374. $pointsSaleArray = $pointSaleManager->findPointSales();
  375. foreach ($pointsSaleArray as $pointSale) {
  376. $pointSaleManager->initOrders($pointSale, $ordersArray);
  377. }
  378. /*
  379. * export global
  380. */
  381. if ($global) {
  382. $data = [];
  383. $filename = 'export_' . $date . '_global';
  384. $dayWeek = date('w', strtotime($date));
  385. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  386. $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  387. // par point de vente
  388. foreach ($pointsSaleArray as $pointSale) {
  389. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  390. $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
  391. $data[] = $line;
  392. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
  393. foreach ($res['data'] as $line) {
  394. $data[] = $line;
  395. }
  396. }
  397. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  398. $line = ['Total'];
  399. $strProducts = '';
  400. foreach ($productsArray as $product) {
  401. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  402. $quantity = $orderManager->getProductQuantity($product, $pointSale->orders);
  403. $strQuantity = '';
  404. if ($quantity) {
  405. $strQuantity = $quantity;
  406. $strProducts .= $strQuantity . ', ';
  407. }
  408. }
  409. }
  410. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  411. $line[] = number_format($pointSale->revenues, 2) . ' €';
  412. $data[] = $line;
  413. $data[] = [];
  414. }
  415. }
  416. $line = ['Total'];
  417. $strProducts = '';
  418. foreach ($productsArray as $product) {
  419. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  420. $quantity = $orderManager->getProductQuantity($product, $ordersArray);
  421. $strQuantity = '';
  422. if ($quantity) {
  423. $strQuantity = $quantity;
  424. $strQuantity .= $strQuantity . ', ';
  425. }
  426. }
  427. }
  428. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  429. $data[] = $line;
  430. $infos = $this->actionIndex($date, true);
  431. CSV::downloadSendHeaders($filename . '.csv');
  432. echo CSV::array2csv($data);
  433. die();
  434. } /*
  435. * export individuel
  436. */
  437. else {
  438. if ($ordersArray && count($ordersArray)) {
  439. $data = [];
  440. // par point de vente
  441. if ($idPointSale) {
  442. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
  443. $data = $res['data'];
  444. $filename = $res['filename'];
  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. * @param string $date
  461. * @param array $products
  462. * @param array $pointsSale
  463. * @param array $orders
  464. * @return array
  465. * @see OrderController::actionDownload()
  466. */
  467. public function contentRecapCSV(string $date, array $products, array $pointsSale, array $orders)
  468. {
  469. $orderManager = $this->getOrderManager();
  470. $distributionManager = $this->getDistributionManager();
  471. $productDistributionManager = $this->getProductDistributionManager();
  472. $data = [];
  473. $filename = 'summary_' . $date;
  474. $distribution = $distributionManager->findOneDistribution($date);
  475. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  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[] = $orderManager->getProductQuantity($product, $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[] = $orderManager->getProductQuantity($product, $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. $distributionManager = $this->getDistributionManager();
  523. $productDistributionManager = $this->getProductDistributionManager();
  524. $data = [];
  525. $distribution = $distributionManager->findOneDistribution($date);
  526. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  527. // datas
  528. foreach ($pointsSale as $pointSale) {
  529. if ($pointSale->id == $idPointSale) {
  530. $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
  531. foreach ($pointSale->orders as $order) {
  532. $strUser = '';
  533. // username
  534. if ($order->user) {
  535. $strUser = $order->user->name . " " . $order->user->lastname;
  536. } else {
  537. $strUser = $order->username;
  538. }
  539. // téléphone
  540. if (isset($order->user) && strlen($order->user->phone)) {
  541. $strUser .= ' (' . $order->user->phone . ')';
  542. }
  543. $dataAdd = [$strUser];
  544. // produits
  545. $strProducts = '';
  546. foreach ($products as $product) {
  547. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  548. $add = false;
  549. foreach ($product->productOrder as $productOrder) {
  550. if ($product->id == $productOrder->id_product) {
  551. $strProducts .= $productOrder->quantity;
  552. $add = true;
  553. }
  554. }
  555. }
  556. }
  557. $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
  558. $dataAdd[] = number_format($order->amount, 2) . ' €';
  559. $dataAdd[] = $order->comment;
  560. $data[] = $dataAdd;
  561. }
  562. }
  563. }
  564. return [
  565. 'data' => $data,
  566. 'filename' => $filename
  567. ];
  568. }
  569. /**
  570. * Change l'état d'un jour de distribution (activé, désactivé).
  571. */
  572. public function actionChangeState(string $date, bool $active, bool $redirect = true)
  573. {
  574. $distributionManager = $this->getDistributionManager();
  575. $distribution = $distributionManager->createDistributionIfNotExist($date);
  576. $distributionManager->activeDistribution($distribution, $active);
  577. if ($redirect) {
  578. $this->redirect(['index', 'date' => $date]);
  579. }
  580. }
  581. /**
  582. * Change l'état d'une semaine de production (activé, désactivé).
  583. */
  584. public function actionChangeStateWeek(string $date, bool $active)
  585. {
  586. $pointSaleManager = $this->getPointSaleManager();
  587. $pointsSaleArray = $pointSaleManager->findPointSales();
  588. $week = sprintf('%02d', date('W', strtotime($date)));
  589. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  590. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  591. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  592. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  593. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  594. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  595. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  596. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  597. $activeMonday = false;
  598. $activeTuesday = false;
  599. $activeWednesday = false;
  600. $activeThursday = false;
  601. $activeFriday = false;
  602. $activeSaturday = false;
  603. $activeSunday = false;
  604. foreach ($pointsSaleArray as $pointSale) {
  605. if ($pointSale->delivery_monday) $activeMonday = true;
  606. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  607. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  608. if ($pointSale->delivery_thursday) $activeThursday = true;
  609. if ($pointSale->delivery_friday) $activeFriday = true;
  610. if ($pointSale->delivery_saturday) $activeSaturday = true;
  611. if ($pointSale->delivery_sunday) $activeSunday = true;
  612. }
  613. if ($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false);
  614. if ($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false);
  615. if ($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false);
  616. if ($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false);
  617. if ($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false);
  618. if ($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false);
  619. if ($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false);
  620. $this->redirect(['index', 'date' => $date]);
  621. }
  622. /**
  623. * Supprime une commande via une requête AJAX.
  624. */
  625. public function actionAjaxDelete(int $idOrder)
  626. {
  627. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  628. $orderManager = $this->getOrderManager();
  629. $order = $orderManager->findOneOrderById($idOrder);
  630. if ($order) {
  631. $orderManager->deleteOrder($order);
  632. }
  633. return ['success'];
  634. }
  635. /**
  636. * Supprime une commande.
  637. */
  638. public function actionDelete(string $date, int $idOrder)
  639. {
  640. $orderManager = $this->getOrderManager();
  641. $order = $orderManager->findOneOrderById($idOrder);
  642. if ($order) {
  643. $orderManager->deleteOrder($order);
  644. }
  645. $this->redirect(['index', 'date' => $date]);
  646. }
  647. /**
  648. * Crée une commande via une requête AJAX.
  649. *
  650. * @param string $date
  651. * @param integer $idPointSale
  652. * @param integer $idUser
  653. * @param string $username
  654. * @param array $produits
  655. * @param string $commentaire
  656. */
  657. public function actionAjaxCreate(
  658. $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment)
  659. {
  660. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  661. $distributionManager = $this->getDistributionManager();
  662. $pointSaleManager = $this->getPointSaleManager();
  663. $userPointSaleManager = $this->getUserPointSaleManager();
  664. $userManager = $this->getUserManager();
  665. $userProducerManager = $this->getUserProducerManager();
  666. $producerManager = $this->getProducerManager();
  667. $productManager = $this->getProductManager();
  668. $orderManager = $this->getOrderManager();
  669. $products = json_decode($products);
  670. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  671. $distribution = $distributionManager->findOneDistribution($date);
  672. $producerCurrent = $this->getProducerCurrent();
  673. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
  674. && ($idUser || strlen($username))
  675. && $pointSale
  676. && count(get_object_vars($products))
  677. && $distribution) {
  678. $order = new Order;
  679. $order->date = date('Y-m-d H:i:s');
  680. $order->id_point_sale = $idPointSale;
  681. $order->mean_payment = $meanPayment;
  682. $order->id_distribution = $distribution->id;
  683. $order->origin = Order::ORIGIN_ADMIN;
  684. $order->comment = $comment;
  685. $order->status = 'tmp-order';
  686. if ($idUser) {
  687. $order->id_user = $idUser;
  688. // commentaire du point de vente
  689. $userPointSale = $userPointSaleManager->findOneUserPointSale($userManager->findOneUserById($idUser), $pointSale);
  690. if ($userPointSale && strlen($userPointSale->comment)) {
  691. $order->comment_point_sale = $userPointSale->comment;
  692. }
  693. } else {
  694. $order->username = $username;
  695. $order->id_user = 0;
  696. }
  697. $order->save();
  698. $user = false;
  699. $userProducer = false;
  700. if (isset($order->user) && $order->user) {
  701. $user = $order->user;
  702. $userProducer = $userProducerManager->findOneUserProducer($user);
  703. }
  704. foreach ($products as $key => $dataProductOrder) {
  705. $product = $productManager->findOneProductById($key);
  706. if(isset(Product::$unitsArray[$dataProductOrder->unit]) && Product::$unitsArray[$dataProductOrder->unit]['coefficient']) {
  707. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  708. if ($product && $quantity) {
  709. $productOrder = new ProductOrder;
  710. $productOrder->id_order = $order->id;
  711. $productOrder->id_product = $key;
  712. $productOrder->quantity = $quantity;
  713. $productOrder->unit = $product->unit;
  714. $productOrder->step = $product->step;
  715. if ($dataProductOrder->price) {
  716. $productOrder->price = $dataProductOrder->price;
  717. } else {
  718. $productOrder->price = $productManager->getPrice($product, [
  719. 'user' => $user,
  720. 'user_producer' => $userProducer,
  721. 'point_sale' => $order->pointSale,
  722. 'quantity' => $productOrder->quantity
  723. ]);
  724. }
  725. $productOrder->id_tax_rate = $product->taxRate->id;
  726. $productOrder->save();
  727. }
  728. }
  729. }
  730. $order = $orderManager->findOneOrderById($order->id);
  731. $orderManager->initOrder($order);
  732. if ($order && $orderManager->isCreditAutoPayment($order)) {
  733. $orderManager->processCredit($order);
  734. }
  735. $order = $orderManager->findOneOrderById($order->id);
  736. $orderManager->initOrder($order);
  737. if ($order) {
  738. $orderManager->generateOrderReference($order);
  739. $orderManager->updateOrderTillerSynchronization($order);
  740. }
  741. // lien utilisateur / point de vente
  742. if ($idUser && $pointSale) {
  743. $pointSaleManager->addUser($user, $pointSale);
  744. }
  745. }
  746. return ['success'];
  747. }
  748. /**
  749. * Met à jour une commande via une requête AJAX.
  750. *
  751. * @param integer $idOrder
  752. * @param array $products
  753. * @param string $date
  754. * @param string $comment
  755. */
  756. public function actionAjaxUpdate()
  757. {
  758. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  759. $orderManager = $this->getOrderManager();
  760. $userManager = $this->getUserManager();
  761. $pointSaleManager = $this->getPointSaleManager();
  762. $userPointSaleManager = $this->getUserPointSaleManager();
  763. $paymentManager = $this->getPaymentManager();
  764. $productManager = $this->getProductManager();
  765. $request = \Yii::$app->request;
  766. $date = $request->post('date');
  767. $idOrder = $request->post('idOrder');
  768. $idPointSale = $request->post('idPointSale');
  769. $idUser = $request->post('idUser');
  770. $username = $request->post('username');
  771. $meanPayment = $request->post('meanPayment');
  772. $products = $request->post('products');
  773. $comment = $request->post('comment');
  774. $order = $orderManager->findOneOrderById($idOrder);
  775. $orderManager->initOrder($order);
  776. $user = $userManager->findOneUserById($idUser);
  777. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  778. if ($order
  779. && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  780. // Si changement d'user : on rembourse l'ancien user
  781. $oldIdUser = $order->id_user;
  782. $amountPaid = $orderManager->getOrderAmountWithTax($order, Order::AMOUNT_PAID);
  783. if ($oldIdUser != $idUser && $amountPaid > 0) {
  784. $paymentManager->refundOrderCredit($order, $this->getUserCurrent());
  785. $order = $orderManager->findOneOrderById($idOrder);
  786. $orderManager->initOrder($order);
  787. }
  788. if ($idUser) {
  789. $order->username = '';
  790. $order->id_user = $idUser;
  791. // commentaire du point de vente
  792. $userPointSale = $userPointSaleManager->findOneUserPointSale($user, $pointSale);
  793. if ($userPointSale && strlen($userPointSale->comment)) {
  794. $order->comment_point_sale = $userPointSale->comment;
  795. }
  796. } else {
  797. $order->username = $username;
  798. $order->id_user = 0;
  799. }
  800. $user = User::searchOne(['id' => $order->id_user]);
  801. $userProducer = false;
  802. if ($user) {
  803. $userProducer = UserProducer::searchOne([
  804. 'id_user' => $user->id,
  805. 'id_producer' => $order->distribution->id_producer
  806. ]);
  807. }
  808. $products = json_decode($products);
  809. foreach ($products as $key => $dataProductOrder) {
  810. $productOrder = ProductOrder::findOne([
  811. 'id_order' => $idOrder,
  812. 'id_product' => $key
  813. ]);
  814. $quantity = $dataProductOrder->quantity
  815. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  816. if ($quantity) {
  817. if ($productOrder) {
  818. $productOrder->quantity = $quantity;
  819. $productOrder->price = $dataProductOrder->price;
  820. if(isset($dataProductOrder->invoice_price)
  821. && $dataProductOrder->invoice_price
  822. && $dataProductOrder->invoice_price != $dataProductOrder->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. $paymentManager = $this->getPaymentManager();
  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('Recréditer ' . $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> à débiter';
  890. $buttonsCredit = Html::a('Débiter ' . 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> à recréditer';
  894. $buttonsCredit = Html::a('Recréditer ' . 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 = Payment::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($paymentManager->getDate($creditHistory))) . '</td>'
  912. . '<td>' . Html::encode($paymentManager->getStrUserAction($creditHistory)) . '</td>'
  913. . '<td>' . $paymentManager->getStrWording($creditHistory) . '</td>'
  914. . '<td>' . ($paymentManager->isTypeDebit($creditHistory) ? '- ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
  915. . '<td>' . ($paymentManager->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, string $meanPayment): array
  936. {
  937. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  938. $orderManager = $this->getOrderManager();
  939. $paymentManager = $this->getPaymentManager();
  940. $order = $orderManager->findOneOrderById($idOrder);
  941. $orderManager->initOrder($order);
  942. if ($order) {
  943. $paymentManager->payOrRefundOrder($type, $order, $meanPayment, $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. }