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.

OrderController.php 41KB

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