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

1317 lines
48KB

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