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

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