You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1131 line
54KB

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