Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

OrderController.php 41KB

8 лет назад
6 лет назад
6 лет назад
6 лет назад
8 лет назад
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 лет назад
8 лет назад
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 лет назад
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 лет назад
8 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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, $meanPayment = '', $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->mean_payment = $meanPayment ;
  708. $order->id_distribution = $distribution->id;
  709. $order->origin = Order::ORIGIN_ADMIN;
  710. $order->comment = $comment;
  711. if ($idUser) {
  712. $order->id_user = $idUser;
  713. // commentaire du point de vente
  714. $userPointSale = UserPointSale::searchOne([
  715. 'id_point_sale' => $idPointSale,
  716. 'id_user' => $idUser
  717. ]) ;
  718. if ($userPointSale && strlen($userPointSale->comment)) {
  719. $order->comment_point_sale = $userPointSale->comment;
  720. }
  721. } else {
  722. $order->username = $username;
  723. $order->id_user = 0;
  724. }
  725. $order->save();
  726. foreach ($products as $key => $dataProductOrder) {
  727. $product = Product::findOne($key);
  728. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'] ;
  729. if ($product && $quantity) {
  730. $productOrder = new ProductOrder;
  731. $productOrder->id_order = $order->id;
  732. $productOrder->id_product = $key;
  733. $productOrder->quantity = $quantity;
  734. $productOrder->unit = $product->unit;
  735. $productOrder->step = $product->step;
  736. $productOrder->price = $product->price;
  737. $productOrder->save();
  738. }
  739. }
  740. $order = Order::searchOne(['id' => $order->id]) ;
  741. if($order && $processCredit) {
  742. $order->processCredit() ;
  743. }
  744. // lien utilisateur / point de vente
  745. if($idUser && $pointSale) {
  746. $pointSale->linkUser($idUser) ;
  747. }
  748. }
  749. return ['success'] ;
  750. }
  751. /**
  752. * Met à jour une commande via une requête AJAX.
  753. *
  754. * @param integer $idOrder
  755. * @param array $products
  756. * @param string $date
  757. * @param string $comment
  758. */
  759. public function actionAjaxUpdate(
  760. $date, $idOrder, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment = '', $processCredit = 0)
  761. {
  762. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  763. $order = Order::searchOne(['id' => $idOrder]) ;
  764. if ($order &&
  765. $order->distribution->id_producer == Producer::getId()) {
  766. $products = json_decode($products);
  767. foreach ($products as $key => $dataProductOrder) {
  768. $productOrder = ProductOrder::findOne([
  769. 'id_order' => $idOrder,
  770. 'id_product' => $key
  771. ]);
  772. $quantity = $dataProductOrder->quantity
  773. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'] ;
  774. if ($quantity) {
  775. if ($productOrder) {
  776. $productOrder->quantity = $quantity;
  777. } else {
  778. $product = Product::findOne($key);
  779. if ($product) {
  780. $productOrder = new ProductOrder;
  781. $productOrder->id_order = $idOrder;
  782. $productOrder->id_product = $key;
  783. $productOrder->quantity = $quantity;
  784. $productOrder->unit = $product->unit;
  785. $productOrder->step = $product->step;
  786. $productOrder->price = $product->price;
  787. }
  788. }
  789. $productOrder->save();
  790. } else {
  791. if ($productOrder) {
  792. $productOrder->delete();
  793. }
  794. }
  795. }
  796. $order->id_point_sale = $idPointSale;
  797. $order->date_update = date('Y-m-d H:i:s');
  798. $order->mean_payment = $meanPayment;
  799. $order->comment = $comment;
  800. if ($idUser) {
  801. $order->username = '' ;
  802. $order->id_user = $idUser;
  803. // commentaire du point de vente
  804. $userPointSale = UserPointSale::searchOne([
  805. 'id_point_sale' => $order->id_point_sale,
  806. 'id_user' => $idUser
  807. ]) ;
  808. if ($userPointSale && strlen($userPointSale->comment)) {
  809. $order->comment_point_sale = $userPointSale->comment;
  810. }
  811. } else {
  812. $order->username = $username;
  813. $order->id_user = 0;
  814. }
  815. $order->save();
  816. $order = Order::searchOne(['id' => $order->id]) ;
  817. if($order && $processCredit) {
  818. $order->processCredit() ;
  819. }
  820. }
  821. }
  822. /**
  823. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  824. *
  825. * @param integer $idOrder
  826. */
  827. public function actionPaymentStatus($idOrder)
  828. {
  829. $order = Order::searchOne(['id' => $idOrder]) ;
  830. if ($order) {
  831. $html = '';
  832. if ($order->id_user) {
  833. $userProducer = UserProducer::find()
  834. ->where([
  835. 'id_user' => $order->id_user,
  836. 'id_producer' => $order->distribution->id_producer
  837. ])
  838. ->one();
  839. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  840. if (abs($order->amount - $amountPaid) < 0.0001) {
  841. $html .= '<span class="label label-success">Payé</span>';
  842. $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']);
  843. } elseif ($order->amount > $amountPaid) {
  844. $amountToPay = $order->amount - $amountPaid;
  845. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  846. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  847. } elseif ($order->amount < $amountPaid) {
  848. $amountToRefund = $amountPaid - $order->amount;
  849. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  850. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  851. }
  852. $html .= '<span class="buttons-credit">'
  853. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  854. . $buttonsCredit
  855. . '</span>';
  856. // historique
  857. $history = CreditHistory::find()
  858. ->with('userAction')
  859. ->where(['id_order' => $idOrder])
  860. ->all();
  861. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  862. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  863. . '<tbody>';
  864. if ($history && is_array($history) && count($history)) {
  865. foreach ($history as $h) {
  866. $html .= '<tr>'
  867. . '<td>' . date('d/m/Y H:i:s', strtotime($h->date)) . '</td>'
  868. . '<td>' . Html::encode($h->strUserAction()) . '</td>'
  869. . '<td>' . $h->getStrWording() . '</td>'
  870. . '<td>' . ($h->isTypeDebit() ? '- '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  871. . '<td>' . ($h->isTypeCredit() ? '+ '.$h->getAmount(Order::AMOUNT_TOTAL,true) : '') . '</td>'
  872. . '</tr>';
  873. }
  874. } else {
  875. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  876. }
  877. $html .= '</tbody></table>';
  878. } else {
  879. $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>';
  880. }
  881. echo json_encode([
  882. 'html_payment_status' => $html,
  883. 'json_order' => $order->getDataJson()
  884. ]);
  885. }
  886. die();
  887. }
  888. /**
  889. * Effectue le paiement/remboursement d'une commande.
  890. *
  891. * @param integer $idOrder
  892. * @param string $type
  893. * @param float $amount
  894. * @return string
  895. */
  896. public function actionAjaxPayment($idOrder, $type, $amount)
  897. {
  898. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  899. $order = Order::searchOne([
  900. 'id' => $idOrder
  901. ]) ;
  902. if ($order) {
  903. $order->saveCreditHistory(
  904. $type,
  905. $amount,
  906. Producer::getId(),
  907. $order->id_user,
  908. User::getCurrentId()
  909. );
  910. }
  911. return ['success'];
  912. }
  913. /**
  914. * Modifie l'état de la synchronisation Tiller d'une commande.
  915. *
  916. * @param int $idOrder
  917. * @param boolean $boolSynchroTiller
  918. * @return array
  919. */
  920. public function actionAjaxChangeSynchroTiller($idOrder, $boolSynchroTiller)
  921. {
  922. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  923. $order = Order::searchOne([
  924. 'id' => (int) $idOrder
  925. ]) ;
  926. if($order) {
  927. $order->tiller_synchronization = (int) $boolSynchroTiller ;
  928. $res = $order->save() ;
  929. return ['success'];
  930. }
  931. return ['error'];
  932. }
  933. }