Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

OrderController.php 46KB

vor 8 Jahren
vor 8 Jahren
vor 8 Jahren
vor 8 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use common\forms\SubscriptionForm;
  39. use common\helpers\CSV;
  40. use common\helpers\GlobalParam;
  41. use common\helpers\MeanPayment;
  42. use common\helpers\Price;
  43. use common\logic\Distribution\Distribution\Model\Distribution;
  44. use common\logic\Distribution\PointSaleDistribution\Model\PointSaleDistribution;
  45. use common\logic\Distribution\ProductDistribution\Model\ProductDistribution;
  46. use common\logic\Order\Order\Model\Order;
  47. use common\logic\Order\ProductOrder\Model\ProductOrder;
  48. use common\logic\PointSale\PointSale\Model\PointSale;
  49. use common\logic\Product\Product\Model\Product;
  50. use common\logic\User\CreditHistory\Model\CreditHistory;
  51. use common\logic\User\User\Model\User;
  52. use common\logic\User\UserProducer\Model\UserProducer;
  53. use yii\filters\AccessControl;
  54. use yii\helpers\Html;
  55. class OrderController extends BackendController
  56. {
  57. var $enableCsrfValidation = false;
  58. public function behaviors()
  59. {
  60. return [
  61. 'access' => [
  62. 'class' => AccessControl::class,
  63. 'rules' => [
  64. [
  65. 'allow' => true,
  66. 'roles' => ['@'],
  67. 'matchCallback' => function ($rule, $action) {
  68. return $this->getUserManager()->isCurrentProducer()
  69. || $this->getUserManager()->isCurrentAdmin();
  70. }
  71. ]
  72. ],
  73. ],
  74. ];
  75. }
  76. /**
  77. * Traite le formulaire d'ajout/modification de commande.
  78. */
  79. public function processOrderForm(
  80. Distribution $distribution,
  81. string $date,
  82. array $pointsSale,
  83. array $products,
  84. array $users
  85. )
  86. {
  87. $orderManager = $this->getOrderManager();
  88. $pointSaleManager = $this->getPointSaleManager();
  89. if ($date != '') {
  90. $orders = $orderManager->findOrdersByDistribution($distribution);
  91. foreach ($pointsSale as $point) {
  92. $orderManager->initPointSaleOrders($point, $orders);
  93. if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
  94. // modifs
  95. foreach ($point->orders as $order) {
  96. // suppression des product_order
  97. ProductOrder::deleteAll(['id_order' => $order->id]);
  98. // création des commande_produit modifiés
  99. foreach ($products as $product) {
  100. $quantity = \Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
  101. if ($quantity) {
  102. $productOrder = new ProductOrder;
  103. $productOrder->id_order = $order->id;
  104. $productOrder->id_product = $product->id;
  105. $productOrder->quantity = $quantity;
  106. $productOrder->price = $p->price;
  107. $productOrder->unit = $p->unit;
  108. $productOrder->step = $p->step;
  109. $productOrder->id_tax_rate = $p->taxRate->id;
  110. $productOrder->save();
  111. }
  112. }
  113. }
  114. $username = \Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
  115. $date = \Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
  116. $oneProduct = false;
  117. foreach ($products as $product) {
  118. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  119. if ($quantity) {
  120. $oneProduct = true;
  121. }
  122. }
  123. if (strlen($username) && $date && $oneProduct) {
  124. $order = new Order();
  125. $order->id_point_sale = $point->id;
  126. $order->id_production = $distribution->id;
  127. $order->id_user = 0;
  128. $order->username = $username;
  129. $arrayDate = explode('/', $date);
  130. $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
  131. $order->save();
  132. foreach ($products as $product) {
  133. $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
  134. if ($quantity) {
  135. $productOrder = new ProductOrder();
  136. $productOrder->id_order = $order->id;
  137. $productOrder->id_product = $product->id;
  138. $productOrder->quantity = $quantity;
  139. $productOrder->price = $p->price;
  140. $productOrder->unit = $p->unit;
  141. $productOrder->step = $p->step;
  142. $productOrder->id_tax_rate = $p->taxRate->id;
  143. $productOrder->save();
  144. }
  145. }
  146. $orderManager->generateOrderReference($order);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. /**
  153. * Page principale de la gestion des commandes.
  154. */
  155. public function actionIndex($date = '', $returnData = false)
  156. {
  157. $distributionManager = $this->getDistributionManager();
  158. $productManager = $this->getProductManager();
  159. $pointSaleManager = $this->getPointSaleManager();
  160. $orderManager = $this->getOrderManager();
  161. $productDistributionManager = $this->getProductDistributionManager();
  162. if (!Product::searchCount() || !PointSale::searchCount()) {
  163. $this->redirect(['site/index', 'error_products_points_sale' => 1]);
  164. }
  165. $orders = [];
  166. // users
  167. $arrayUsers = [0 => '--'];
  168. $users = User::searchAll([], ['orderby' => 'lastname, name ASC']);
  169. foreach ($users as $user) {
  170. $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
  171. }
  172. $distribution = $distributionManager->createDistributionIfNotExist($date);
  173. if ($distribution) {
  174. $arrayPointsSale = PointSale::find()
  175. ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
  176. $q->where(['id_distribution' => $distribution->id]);
  177. }])
  178. ->where([
  179. 'id_producer' => GlobalParam::getCurrentProducerId(),
  180. ])
  181. ->all();
  182. } else {
  183. $arrayPointsSale = $pointSaleManager->findPointSales();
  184. }
  185. $arrayProducts = $productManager->findProducts();
  186. $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
  187. // commandes
  188. $arrayOrders = $orderManager->findOrdersByDistribution($distribution);
  189. $revenues = 0;
  190. $weight = 0;
  191. $revenuesDelivered = 0;
  192. if ($arrayOrders) {
  193. foreach ($arrayOrders as $order) {
  194. if (is_null($order->date_delete)) {
  195. $revenues += $order->amount;
  196. if ($order->id_point_sale != 1) {
  197. $revenuesDelivered += $order->amount;
  198. }
  199. $weight += $order->weight;
  200. }
  201. }
  202. }
  203. $revenues = number_format($revenues, 2);
  204. // init commandes point de vente
  205. foreach ($arrayPointsSale as $pointSale) {
  206. $orderManager->initPointSaleOrders($pointSale, $arrayOrders);
  207. $dataSelectOrders = [];
  208. $dataOptionsOrders = [];
  209. foreach ($pointSale->orders as $order) {
  210. if ($order->user) {
  211. $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
  212. } else {
  213. $dataSelectOrders[$order->id] = $order->username;
  214. }
  215. $dataOptionsOrders[$order->id] = [];
  216. $arrayOptions = [];
  217. $arrayOptions[$order->id]['amount'] = $order->amount;
  218. $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
  219. $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
  220. $arrayOptions[$order->id]['products'] = [];
  221. $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
  222. foreach ($order->productOrder as $productOrder) {
  223. $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
  224. }
  225. $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
  226. $dataOptionsOrders[$order->id]['value'] = $order->id;
  227. }
  228. $pointSale->data_select_orders = $dataSelectOrders;
  229. $pointSale->data_options_orders = $dataOptionsOrders;
  230. }
  231. // gestion produits selec
  232. if (isset($_POST['valider_produit_selec'])) {
  233. if (isset($_POST['Product'])) {
  234. foreach ($arrayProducts as $product) {
  235. $productDistribution = $productDistributionManager->findOneProductDistribution($distribution, $product);
  236. if (!$productDistribution) {
  237. $productDistribution = new ProductDistribution();
  238. $productDistribution->id_distribution = $distribution->id;
  239. $productDistribution->id_product = $product->id;
  240. $productDistribution->active = 0;
  241. if (isset($product->quantity_max)) {
  242. $productDistribution->quantity_max = $product->quantity_max;
  243. } else {
  244. $productDistribution->quantity_max = null;
  245. }
  246. $productDistributionManager->saveCreate($productDistribution);
  247. }
  248. if (isset($_POST['Product'][$product->id]['active'])) {
  249. $productDistribution->active = 1;
  250. } else {
  251. $productDistribution->active = 0;
  252. }
  253. if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
  254. $productDistribution->quantity_max = (int)$_POST['Product'][$product->id]['quantity_max'];
  255. } else {
  256. $productDistribution->quantity_max = null;
  257. }
  258. $productDistributionManager->saveUpdate($productDistribution);
  259. }
  260. }
  261. }
  262. $arrayProductsSelected = [];
  263. if ($distribution) {
  264. $arrayProductsSelected = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  265. $arrayProducts = $productManager->findProductsByDistribution($distribution);
  266. }
  267. // poids total de la production et CA potentiel
  268. $potentialTurnover = 0;
  269. $totalWeight = 0;
  270. foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
  271. if ($selectedProduct['active']) {
  272. foreach ($arrayProducts as $product) {
  273. if ($product->id == $idSelectedProduct) {
  274. $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
  275. $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
  276. }
  277. }
  278. }
  279. }
  280. $arrayDistributionDays = $distributionManager->findDistributionsActive();
  281. // commandes auto
  282. $subscriptionForm = new SubscriptionForm();
  283. // productions point vente
  284. $pointSaleDistribution = new PointSaleDistribution();
  285. $oointsSaleDistribution = [];
  286. if ($distribution) {
  287. $pointsSaleDistribution = PointSaleDistribution::searchAll([
  288. 'id_distribution' => $distribution->id
  289. ]);
  290. }
  291. $arrayPointsSaleDistribution = [];
  292. if (isset($pointsSaleDistribution)) {
  293. foreach ($pointsSaleDistribution as $pointSaleDistrib) {
  294. $key = $pointSaleDistrib->id_distribution . '-' . $pointSaleDistrib->id_point_sale;
  295. if ($pointSaleDistrib->delivery == 1) {
  296. $pointSaleDistribution->points_sale_distribution[] = $key;
  297. }
  298. if (isset($pointSaleDistrib->pointSale) && strlen($pointSaleDistrib->pointSale->name)) {
  299. $arrayPointsSaleDistribution[$key] = Html::encode($pointSaleDistrib->pointSale->name);
  300. }
  301. }
  302. }
  303. // une production de la semaine activée ou non
  304. $oneDistributionWeekActive = false;
  305. $week = sprintf('%02d', date('W', strtotime($date)));
  306. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  307. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  308. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  309. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  310. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  311. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  312. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  313. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  314. $weekDistribution = Distribution::find()
  315. ->andWhere([
  316. 'id_producer' => GlobalParam::getCurrentProducerId(),
  317. 'active' => 1,
  318. ])
  319. ->andWhere(['or',
  320. ['date' => $dateMonday],
  321. ['date' => $dateTuesday],
  322. ['date' => $dateWednesday],
  323. ['date' => $dateThursday],
  324. ['date' => $dateFriday],
  325. ['date' => $dateSaturday],
  326. ['date' => $dateSunday],
  327. ])
  328. ->one();
  329. if ($weekDistribution) {
  330. $oneDistributionWeekActive = true;
  331. }
  332. $datas = [
  333. 'arrayProducts' => $arrayProducts,
  334. 'arrayPointsSale' => $arrayPointsSale,
  335. 'arrayOrders' => $arrayOrders,
  336. 'date' => $date,
  337. 'distribution' => $distribution,
  338. 'arrayDistributionDays' => $arrayDistributionDays,
  339. 'selectedProducts' => $arrayProductsSelected,
  340. 'users' => $arrayUsers,
  341. 'revenues' => $revenues,
  342. 'revenuesDelivered' => $revenuesDelivered,
  343. 'weight' => $weight,
  344. 'potentialTurnover' => $potentialTurnover,
  345. 'totalWeight' => $totalWeight,
  346. 'subscriptionForm' => $subscriptionForm,
  347. 'pointSaleDistribution' => $pointSaleDistribution,
  348. 'arrayPointsSaleDistribution' => $arrayPointsSaleDistribution,
  349. 'oneDistributionWeekActive' => $oneDistributionWeekActive
  350. ];
  351. if ($returnData) {
  352. return $datas;
  353. } else {
  354. return $this->render('index', $datas);
  355. }
  356. }
  357. /**
  358. * Génère un fichier d'export des commandes au format CSV.
  359. *
  360. * @param string $date
  361. * @param integer $id_point_vente
  362. * @param boolean $global
  363. */
  364. public function actionDownload($date = '', $idPointSale = 0, $global = 0)
  365. {
  366. $orderManager = $this->getOrderManager();
  367. $distributionManager = $this->getDistributionManager();
  368. $pointSaleManager = $this->getPointSaleManager();
  369. $productManager = $this->getProductManager();
  370. $productDistributionManager = $this->getProductDistributionManager();
  371. $distribution = $distributionManager->findOneDistributionByDate($date);
  372. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  373. $productsArray = $productManager->findProducts();
  374. $ordersArray = $orderManager->findOrdersByDate($date);
  375. $pointsSaleArray = $pointSaleManager->findPointSales();
  376. foreach ($pointsSaleArray as $pointSale) {
  377. $pointSaleManager->initOrders($pointSale, $ordersArray);
  378. }
  379. /*
  380. * export global
  381. */
  382. if ($global) {
  383. $data = [];
  384. $filename = 'export_' . $date . '_global';
  385. $dayWeek = date('w', strtotime($date));
  386. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  387. $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  388. // par point de vente
  389. foreach ($pointsSaleArray as $pointSale) {
  390. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  391. $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
  392. $data[] = $line;
  393. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
  394. foreach ($res['data'] as $line) {
  395. $data[] = $line;
  396. }
  397. }
  398. if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
  399. $line = ['Total'];
  400. $strProducts = '';
  401. foreach ($productsArray as $product) {
  402. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  403. $quantity = $orderManager->getProductQuantity($product, $pointSale->orders);
  404. $strQuantity = '';
  405. if ($quantity) {
  406. $strQuantity = $quantity;
  407. $strProducts .= $strQuantity . ', ';
  408. }
  409. }
  410. }
  411. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  412. $line[] = number_format($pointSale->revenues, 2) . ' €';
  413. $data[] = $line;
  414. $data[] = [];
  415. }
  416. }
  417. $line = ['Total'];
  418. $strProducts = '';
  419. foreach ($productsArray as $product) {
  420. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  421. $quantity = $orderManager->getProductQuantity($product, $ordersArray);
  422. $strQuantity = '';
  423. if ($quantity) {
  424. $strQuantity = $quantity;
  425. $strQuantity .= $strQuantity . ', ';
  426. }
  427. }
  428. }
  429. $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
  430. $data[] = $line;
  431. $infos = $this->actionIndex($date, true);
  432. CSV::downloadSendHeaders($filename . '.csv');
  433. echo CSV::array2csv($data);
  434. die();
  435. } /*
  436. * export individuel
  437. */
  438. else {
  439. if ($ordersArray && count($ordersArray)) {
  440. $data = [];
  441. // par point de vente
  442. if ($idPointSale) {
  443. $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
  444. $data = $res['data'];
  445. $filename = $res['filename'];
  446. } // récapitulatif
  447. else {
  448. $res = $this->contentRecapCSV($date, $productsArray, $pointsSaleArray, $ordersArray);
  449. $filename = 'summary_' . $date;
  450. $data = $res['data'];
  451. }
  452. CSV::downloadSendHeaders($filename . '.csv');
  453. echo CSV::array2csv($data);
  454. die();
  455. }
  456. }
  457. }
  458. /**
  459. * Génère le contenu nécessaire aux exports au format CSV.
  460. *
  461. * @param string $date
  462. * @param array $products
  463. * @param array $pointsSale
  464. * @param array $orders
  465. * @return array
  466. * @see OrderController::actionDownload()
  467. */
  468. public function contentRecapCSV(string $date, array $products, array $pointsSale, array $orders)
  469. {
  470. $orderManager = $this->getOrderManager();
  471. $distributionManager = $this->getDistributionManager();
  472. $productDistributionManager = $this->getProductDistributionManager();
  473. $data = [];
  474. $filename = 'summary_' . $date;
  475. $distribution = $distributionManager->findOneDistributionByDate($date);
  476. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  477. // head
  478. $data[0] = ['Lieu'];
  479. foreach ($products as $product) {
  480. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  481. $data[0][] = $product->description;
  482. }
  483. }
  484. $dayWeek = date('w', strtotime($date));
  485. $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
  486. $fieldHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
  487. // datas
  488. foreach ($pointsSale as $pointSale) {
  489. if (count($pointSale->orders) && strlen($pointSale->$fieldHoursPointSale)) {
  490. $dataAdd = [$pointSale->name];
  491. foreach ($products as $product) {
  492. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  493. $dataAdd[] = $orderManager->getProductQuantity($product, $pointSale->orders);
  494. }
  495. }
  496. $data[] = $dataAdd;
  497. }
  498. }
  499. $dataAdd = ['Total'];
  500. foreach ($products as $product) {
  501. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  502. $dataAdd[] = $orderManager->getProductQuantity($product, $orders);
  503. }
  504. }
  505. $data[] = $dataAdd;
  506. return [
  507. 'data' => $data,
  508. 'filename' => $filename
  509. ];
  510. }
  511. /**
  512. * Génère le contenu relatif aux points de vente nécessaires aux exports au
  513. * format CSV.
  514. *
  515. * @param string $date
  516. * @param array $produits
  517. * @param array $points_vente
  518. * @param integer $id_point_vente
  519. * @return array
  520. */
  521. public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
  522. {
  523. $distributionManager = $this->getDistributionManager();
  524. $productDistributionManager = $this->getProductDistributionManager();
  525. $data = [];
  526. $distribution = $distributionManager->findOneDistributionByDate($date);
  527. $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
  528. // datas
  529. foreach ($pointsSale as $pointSale) {
  530. if ($pointSale->id == $idPointSale) {
  531. $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
  532. foreach ($pointSale->orders as $order) {
  533. $strUser = '';
  534. // username
  535. if ($order->user) {
  536. $strUser = $order->user->name . " " . $order->user->lastname;
  537. } else {
  538. $strUser = $order->username;
  539. }
  540. // téléphone
  541. if (isset($order->user) && strlen($order->user->phone)) {
  542. $strUser .= ' (' . $order->user->phone . ')';
  543. }
  544. $dataAdd = [$strUser];
  545. // produits
  546. $strProducts = '';
  547. foreach ($products as $product) {
  548. if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
  549. $add = false;
  550. foreach ($product->productOrder as $productOrder) {
  551. if ($product->id == $productOrder->id_product) {
  552. $strProducts .= $productOrder->quantity;
  553. $add = true;
  554. }
  555. }
  556. }
  557. }
  558. $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
  559. $dataAdd[] = number_format($order->amount, 2) . ' €';
  560. $dataAdd[] = $order->comment;
  561. $data[] = $dataAdd;
  562. }
  563. }
  564. }
  565. return [
  566. 'data' => $data,
  567. 'filename' => $filename
  568. ];
  569. }
  570. /**
  571. * Change l'état d'un jour de distribution (activé, désactivé).
  572. */
  573. public function actionChangeState(string $date, bool $active, bool $redirect = true)
  574. {
  575. $distributionManager = $this->getDistributionManager();
  576. $distribution = $distributionManager->createDistributionIfNotExist($date);
  577. $distributionManager->activeDistribution($distribution, $active);
  578. if ($redirect) {
  579. $this->redirect(['index', 'date' => $date]);
  580. }
  581. }
  582. /**
  583. * Change l'état d'une semaine de production (activé, désactivé).
  584. */
  585. public function actionChangeStateWeek(string $date, bool $active)
  586. {
  587. $pointSaleManager = $this->getPointSaleManager();
  588. $pointsSaleArray = $pointSaleManager->findPointSales();
  589. $week = sprintf('%02d', date('W', strtotime($date)));
  590. $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
  591. $dateMonday = date('Y-m-d', strtotime('Monday', $start));
  592. $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
  593. $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
  594. $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
  595. $dateFriday = date('Y-m-d', strtotime('Friday', $start));
  596. $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
  597. $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
  598. $activeMonday = false;
  599. $activeTuesday = false;
  600. $activeWednesday = false;
  601. $activeThursday = false;
  602. $activeFriday = false;
  603. $activeSaturday = false;
  604. $activeSunday = false;
  605. foreach ($pointsSaleArray as $pointSale) {
  606. if ($pointSale->delivery_monday) $activeMonday = true;
  607. if ($pointSale->delivery_tuesday) $activeTuesday = true;
  608. if ($pointSale->delivery_wednesday) $activeWednesday = true;
  609. if ($pointSale->delivery_thursday) $activeThursday = true;
  610. if ($pointSale->delivery_friday) $activeFriday = true;
  611. if ($pointSale->delivery_saturday) $activeSaturday = true;
  612. if ($pointSale->delivery_sunday) $activeSunday = true;
  613. }
  614. if ($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false);
  615. if ($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false);
  616. if ($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false);
  617. if ($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false);
  618. if ($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false);
  619. if ($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false);
  620. if ($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false);
  621. $this->redirect(['index', 'date' => $date]);
  622. }
  623. /**
  624. * Supprime une commande via une requête AJAX.
  625. */
  626. public function actionAjaxDelete(int $idOrder)
  627. {
  628. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  629. $orderManager = $this->getOrderManager();
  630. $order = $orderManager->findOneOrderById($idOrder);
  631. if ($order) {
  632. $orderManager->deleteOrder($order);
  633. }
  634. return ['success'];
  635. }
  636. /**
  637. * Supprime une commande.
  638. */
  639. public function actionDelete(string $date, int $idOrder)
  640. {
  641. $orderManager = $this->getOrderManager();
  642. $order = $orderManager->findOneOrderById($idOrder);
  643. if ($order) {
  644. $orderManager->deleteOrder($order);
  645. }
  646. $this->redirect(['index', 'date' => $date]);
  647. }
  648. /**
  649. * Crée une commande via une requête AJAX.
  650. *
  651. * @param string $date
  652. * @param integer $idPointSale
  653. * @param integer $idUser
  654. * @param string $username
  655. * @param array $produits
  656. * @param string $commentaire
  657. */
  658. public function actionAjaxCreate(
  659. $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment)
  660. {
  661. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  662. $distributionManager = $this->getDistributionManager();
  663. $pointSaleManager = $this->getPointSaleManager();
  664. $userPointSaleManager = $this->getUserPointSaleManager();
  665. $userManager = $this->getUserManager();
  666. $userProducerManager = $this->getUserProducerManager();
  667. $producerManager = $this->getProducerManager();
  668. $productManager = $this->getProductManager();
  669. $orderManager = $this->getOrderManager();
  670. $products = json_decode($products);
  671. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  672. $distribution = $distributionManager->findOneDistributionByDate($date);
  673. $producerCurrent = $this->getProducerCurrent();
  674. if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
  675. && ($idUser || strlen($username))
  676. && $pointSale
  677. && count(get_object_vars($products))
  678. && $distribution) {
  679. $order = new Order;
  680. $order->date = date('Y-m-d H:i:s');
  681. $order->id_point_sale = $idPointSale;
  682. $order->mean_payment = $meanPayment;
  683. $order->id_distribution = $distribution->id;
  684. $order->origin = Order::ORIGIN_ADMIN;
  685. $order->comment = $comment;
  686. $order->status = 'tmp-order';
  687. if ($idUser) {
  688. $order->id_user = $idUser;
  689. // commentaire du point de vente
  690. $userPointSale = $userPointSaleManager->findOneUserPointSale($userManager->findOneUserById($idUser), $pointSale);
  691. if ($userPointSale && strlen($userPointSale->comment)) {
  692. $order->comment_point_sale = $userPointSale->comment;
  693. }
  694. } else {
  695. $order->username = $username;
  696. $order->id_user = 0;
  697. }
  698. $order->save();
  699. $user = false;
  700. $userProducer = false;
  701. if (isset($order->user) && $order->user) {
  702. $user = $order->user;
  703. $userProducer = $userProducerManager->findOneUserProducer(
  704. $user,
  705. $producerManager->findOneProducerById($order->distribution->id_producer)
  706. );
  707. }
  708. foreach ($products as $key => $dataProductOrder) {
  709. $product = $productManager->findOneProductById($key);
  710. $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  711. if ($product && $quantity) {
  712. $productOrder = new ProductOrder;
  713. $productOrder->id_order = $order->id;
  714. $productOrder->id_product = $key;
  715. $productOrder->quantity = $quantity;
  716. $productOrder->unit = $product->unit;
  717. $productOrder->step = $product->step;
  718. if ($dataProductOrder->price) {
  719. $productOrder->price = $dataProductOrder->price;
  720. } else {
  721. $productOrder->price = $productManager->getPrice($product, [
  722. 'user' => $user,
  723. 'user_producer' => $userProducer,
  724. 'point_sale' => $order->pointSale,
  725. 'quantity' => $productOrder->quantity
  726. ]);
  727. }
  728. $productOrder->id_tax_rate = $product->taxRate->id;
  729. $productOrder->save();
  730. }
  731. }
  732. $order = $orderManager->findOneOrderById($order->id);
  733. $orderManager->initOrder($order);
  734. if ($order && $orderManager->isCreditAutoPayment($order)) {
  735. $orderManager->processCredit($order);
  736. }
  737. $order = $orderManager->findOneOrderById($order->id);
  738. $orderManager->initOrder($order);
  739. if ($order) {
  740. $orderManager->generateOrderReference($order);
  741. $orderManager->updateOrderTillerSynchronization($order);
  742. }
  743. // lien utilisateur / point de vente
  744. if ($idUser && $pointSale) {
  745. $pointSaleManager->addUser($user, $pointSale);
  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. {
  760. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  761. $orderManager = $this->getOrderManager();
  762. $userManager = $this->getUserManager();
  763. $pointSaleManager = $this->getPointSaleManager();
  764. $userPointSaleManager = $this->getUserPointSaleManager();
  765. $creditHistoryManager = $this->getCreditHistoryManager();
  766. $request = \Yii::$app->request;
  767. $date = $request->post('date');
  768. $idOrder = $request->post('idOrder');
  769. $idPointSale = $request->post('idPointSale');
  770. $idUser = $request->post('idUser');
  771. $username = $request->post('username');
  772. $meanPayment = $request->post('meanPayment');
  773. $products = $request->post('products');
  774. $comment = $request->post('comment');
  775. $order = $orderManager->findOneOrderById($idOrder);
  776. $user = $userManager->findOneUserById($idUser);
  777. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  778. if ($order
  779. && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
  780. $oldIdUser = $order->id_user;
  781. $oldUser = $userManager->findOneUserById($oldIdUser);
  782. if ($idUser) {
  783. $order->username = '';
  784. $order->id_user = $idUser;
  785. // commentaire du point de vente
  786. $userPointSale = $userPointSaleManager->findOneUserPointSale($user, $pointSale);
  787. if ($userPointSale && strlen($userPointSale->comment)) {
  788. $order->comment_point_sale = $userPointSale->comment;
  789. }
  790. } else {
  791. $order->username = $username;
  792. $order->id_user = 0;
  793. }
  794. $user = User::searchOne(['id' => $order->id_user]);
  795. $userProducer = false;
  796. if ($user) {
  797. $userProducer = UserProducer::searchOne([
  798. 'id_user' => $user->id,
  799. 'id_producer' => $order->distribution->id_producer
  800. ]);
  801. }
  802. $products = json_decode($products);
  803. foreach ($products as $key => $dataProductOrder) {
  804. $productOrder = ProductOrder::findOne([
  805. 'id_order' => $idOrder,
  806. 'id_product' => $key
  807. ]);
  808. $quantity = $dataProductOrder->quantity
  809. / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
  810. if ($quantity) {
  811. if ($productOrder) {
  812. $productOrder->quantity = $quantity;
  813. $productOrder->price = $dataProductOrder->price;
  814. if($dataProductOrder->invoice_price && $dataProductOrder->invoice_price != $dataProductOrder->price) {
  815. //die('invoice price : '.$dataProductOrder->invoice_price);
  816. $productOrder->invoice_price = $dataProductOrder->invoice_price;
  817. }
  818. } else {
  819. $product = Product::findOne($key);
  820. if ($product) {
  821. $productOrder = new ProductOrder;
  822. $productOrder->id_order = $idOrder;
  823. $productOrder->id_product = $key;
  824. $productOrder->quantity = $quantity;
  825. $productOrder->unit = $product->unit;
  826. $productOrder->step = $product->step;
  827. $productOrder->id_tax_rate = $product->taxRate->id;
  828. if ($dataProductOrder->price) {
  829. $productOrder->price = $dataProductOrder->price;
  830. } else {
  831. $productOrder->price = $product->getPrice([
  832. 'user' => $user,
  833. 'user_producer' => $userProducer,
  834. 'point_sale' => $order->pointSale,
  835. 'quantity' => $productOrder->quantity
  836. ]);
  837. }
  838. }
  839. }
  840. $productOrder->save();
  841. } else {
  842. if ($productOrder) {
  843. $productOrder->delete();
  844. }
  845. }
  846. }
  847. $order->id_point_sale = $idPointSale;
  848. $order->date_update = date('Y-m-d H:i:s');
  849. $order->mean_payment = $meanPayment;
  850. $order->comment = $comment;
  851. $order->save();
  852. $order = Order::searchOne(['id' => $order->id]);
  853. $orderManager->initOrder($order);
  854. if ($order && $orderManager->isCreditAutoPayment($order)) {
  855. // Si changement d'user : on rembourse l'ancien user
  856. $amountPaid = $orderManager->getOrderAmount($order, Order::AMOUNT_PAID);
  857. if ($oldIdUser != $idUser && $amountPaid > 0) {
  858. $creditHistoryManager->createCreditHistory(
  859. CreditHistory::TYPE_REFUND,
  860. $amountPaid,
  861. $this->getProducerCurrent(),
  862. $oldUser,
  863. $this->getUserCurrent()
  864. );
  865. $order = Order::searchOne(['id' => $order->id]);
  866. $orderManager->initOrder($order);
  867. }
  868. $orderManager->processCredit($order);
  869. }
  870. }
  871. }
  872. /**
  873. * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
  874. */
  875. public function actionPaymentStatus(int $idOrder)
  876. {
  877. $orderManager = $this->getOrderManager();
  878. $creditHistoryManager = $this->getCreditHistoryManager();
  879. $order = $orderManager->findOneOrderById($idOrder);
  880. if ($order) {
  881. $html = '';
  882. if ($order->id_user) {
  883. $userProducer = UserProducer::find()
  884. ->where([
  885. 'id_user' => $order->id_user,
  886. 'id_producer' => $order->distribution->id_producer
  887. ])
  888. ->one();
  889. $amountPaid = $orderManager->getOrderAmount($order, Order::AMOUNT_PAID);
  890. if (abs($order->amount - $amountPaid) < 0.0001) {
  891. $html .= '<span class="label label-success">Payé</span>';
  892. $buttonsCredit = Html::a('Rembourser ' . $orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
  893. } elseif ($order->amount > $amountPaid) {
  894. $amountToPay = $order->amount - $amountPaid;
  895. $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
  896. $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
  897. } elseif ($order->amount < $amountPaid) {
  898. $amountToRefund = $amountPaid - $order->amount;
  899. $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
  900. $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
  901. }
  902. $html .= '<span class="buttons-credit">'
  903. . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
  904. . $buttonsCredit
  905. . '</span>';
  906. // historique
  907. $history = CreditHistory::find()
  908. ->with('userAction')
  909. ->where(['id_order' => $idOrder])
  910. ->all();
  911. $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
  912. . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
  913. . '<tbody>';
  914. if ($history && is_array($history) && count($history)) {
  915. foreach ($history as $creditHistory) {
  916. $html .= '<tr>'
  917. . '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryManager->getDate($creditHistory))) . '</td>'
  918. . '<td>' . Html::encode($creditHistoryManager->getStrUserAction($creditHistory)) . '</td>'
  919. . '<td>' . $creditHistoryManager->getStrWording($creditHistory) . '</td>'
  920. . '<td>' . ($creditHistoryManager->isTypeDebit($creditHistory) ? '- ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
  921. . '<td>' . ($creditHistoryManager->isTypeCredit($creditHistory) ? '+ ' . Price::getPriceWithTax($creditHistory->amount) : '') . '</td>'
  922. . '</tr>';
  923. }
  924. } else {
  925. $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
  926. }
  927. $html .= '</tbody></table>';
  928. } else {
  929. $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>';
  930. }
  931. echo json_encode([
  932. 'html_payment_status' => $html,
  933. 'json_order' => $order->getDataJson()
  934. ]);
  935. }
  936. die();
  937. }
  938. /**
  939. * Effectue le paiement/remboursement d'une commande.
  940. */
  941. public function actionAjaxPayment(int $idOrder, string $type, float $amount): array
  942. {
  943. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  944. $orderManager = $this->getOrderManager();
  945. $creditHistoryManager = $this->getCreditHistoryManager();
  946. $order = $orderManager->findOneOrderById($idOrder);
  947. if ($order) {
  948. $creditHistoryManager->createCreditHistory(
  949. $type,
  950. $amount,
  951. GlobalParam::getCurrentProducer(),
  952. $order->user,
  953. GlobalParam::getCurrentUser(),
  954. MeanPayment::CREDIT,
  955. $order
  956. );
  957. }
  958. return ['success'];
  959. }
  960. /**
  961. * Modifie l'état de la synchronisation Tiller d'une commande.
  962. */
  963. public function actionAjaxChangeSynchroTiller(int $idOrder, bool $boolSynchroTiller): array
  964. {
  965. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  966. $orderManager = $this->getOrderManager();
  967. $order = $orderManager->findOneOrderById($idOrder);
  968. if ($order) {
  969. $orderManager->updateOrderTillerSynchronization($order, (int) $boolSynchroTiller);
  970. return ['success'];
  971. }
  972. return ['error'];
  973. }
  974. }