Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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