|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128 |
- <?php
-
- /**
- * Copyright distrib (2018)
- *
- * contact@opendistrib.net
- *
- * Ce logiciel est un programme informatique servant à aider les producteurs
- * à distribuer leur production en circuits courts.
- *
- * Ce logiciel est régi par la licence CeCILL soumise au droit français et
- * respectant les principes de diffusion des logiciels libres. Vous pouvez
- * utiliser, modifier et/ou redistribuer ce programme sous les conditions
- * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
- * sur le site "http://www.cecill.info".
- *
- * En contrepartie de l'accessibilité au code source et des droits de copie,
- * de modification et de redistribution accordés par cette licence, il n'est
- * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
- * seule une responsabilité restreinte pèse sur l'auteur du programme, le
- * titulaire des droits patrimoniaux et les concédants successifs.
- *
- * A cet égard l'attention de l'utilisateur est attirée sur les risques
- * associés au chargement, à l'utilisation, à la modification et/ou au
- * développement et à la reproduction du logiciel par l'utilisateur étant
- * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
- * manipuler et qui le réserve donc à des développeurs et des professionnels
- * avertis possédant des connaissances informatiques approfondies. Les
- * utilisateurs sont donc invités à charger et tester l'adéquation du
- * logiciel à leurs besoins dans des conditions permettant d'assurer la
- * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
- * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
- *
- * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
- * pris connaissance de la licence CeCILL, et que vous en avez accepté les
- * termes.
- */
-
- namespace backend\controllers;
-
- use common\forms\SubscriptionForm;
- use common\helpers\CSV;
- use common\helpers\GlobalParam;
- use common\logic\Distribution\Distribution\Distribution;
- use common\logic\Distribution\PointSaleDistribution\PointSaleDistribution;
- use common\logic\Distribution\ProductDistribution\ProductDistribution;
- use common\logic\Order\Order\Order;
- use common\logic\Order\ProductOrder\ProductOrder;
- use common\logic\PointSale\PointSale\PointSale;
- use common\logic\Product\Product\Product;
- use common\logic\User\CreditHistory\CreditHistory;
- use common\logic\User\User\User;
- use common\logic\User\UserProducer\UserProducer;
- use yii\filters\AccessControl;
- use yii\helpers\Html;
-
- class OrderController extends BackendController
- {
- var $enableCsrfValidation = false;
-
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::class,
- 'rules' => [
- [
- 'allow' => true,
- 'roles' => ['@'],
- 'matchCallback' => function ($rule, $action) {
- return $this->getUserManager()->isCurrentProducer()
- || $this->getUserManager()->isCurrentAdmin();
- }
- ]
- ],
- ],
- ];
- }
-
- /**
- * Traite le formulaire d'ajout/modification de commande.
- */
- public function processOrderForm(
- Distribution $distribution,
- string $date,
- array $pointsSale,
- array $products,
- array $users
- )
- {
- $orderManager = $this->getOrderManager();
- $pointSaleManager = $this->getPointSaleManager();
-
- if ($date != '') {
- $orders = $orderManager->findOrdersByDistribution($distribution);
-
- foreach ($pointsSale as $point) {
- $pointSaleManager->initPointSaleOrders($point, $orders);
-
- if (isset($_POST['submit_pv']) && $_POST['submit_pv']) {
- // modifs
- foreach ($point->orders as $order) {
-
- // suppression des product_order
- ProductOrder::deleteAll(['id_order' => $order->id]);
-
- // création des commande_produit modifiés
- foreach ($products as $product) {
- $quantity = \Yii::$app->getRequest()->post('product_' . $point->id . '_' . $product->id, 0);
- if ($quantity) {
- $productOrder = new ProductOrder;
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $product->id;
- $productOrder->quantity = $quantity;
- $productOrder->price = $p->price;
- $productOrder->unit = $p->unit;
- $productOrder->step = $p->step;
- $productOrder->id_tax_rate = $p->taxRate->id;
- $productOrder->save();
- }
- }
- }
-
- $username = \Yii::$app->getRequest()->post('username_point_sale_' . $point->id, 0);
- $date = \Yii::$app->getRequest()->post('date_order_point_sale_' . $point->id, 0);
- $oneProduct = false;
- foreach ($products as $product) {
- $quantity = Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
- if ($quantity) {
- $oneProduct = true;
- }
- }
-
- if (strlen($username) && $date && $oneProduct) {
- $order = new Order();
- $order->id_point_sale = $point->id;
- $order->id_production = $distribution->id;
- $order->id_user = 0;
- $order->username = $username;
- $arrayDate = explode('/', $date);
- $order->date = $arrayDate[2] . '-' . $arrayDate[1] . '-' . $arrayDate[0] . ' 00:00:00';
- $order->save();
-
- foreach ($products as $product) {
- $quantity = \Yii::$app->getRequest()->post('product_point_sale_' . $point->id . '_' . $product->id, 0);
- if ($quantity) {
- $productOrder = new ProductOrder;
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $product->id;
- $productOrder->quantity = $quantity;
- $productOrder->price = $p->price;
- $productOrder->unit = $p->unit;
- $productOrder->step = $p->step;
- $productOrder->id_tax_rate = $p->taxRate->id;
- $productOrder->save();
- }
- }
-
- $orderManager->generateOrderReference($order);
- }
- }
- }
- }
- }
-
- /**
- * Page principale de la gestion des commandes.
- */
- public function actionIndex($date = '', $returnData = false)
- {
- $distributionManager = $this->getDistributionManager();
- $productManager = $this->getProductManager();
- $pointSaleManager = $this->getPointSaleManager();
- $orderManager = $this->getOrderManager();
- $productDistributionManager = $this->getProductDistributionManager();
-
- if (!Product::searchCount() || !PointSale::searchCount()) {
- $this->redirect(['site/index', 'error_products_points_sale' => 1]);
- }
-
- $orders = [];
-
- // users
- $arrayUsers = [0 => '--'];
- $users = User::searchAll([], ['orderby' => 'lastname, name ASC']);
-
- foreach ($users as $user) {
- $arrayUsers[$user->id] = $user->name . ' ' . $user->lastname;
- }
-
- $distribution = $distributionManager->createDistributionIfNotExist($this->getProducerCurrent(), $date);
-
- if ($distribution) {
- $arrayPointsSale = PointSale::find()
- ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
- $q->where(['id_distribution' => $distribution->id]);
- }])
- ->where([
- 'id_producer' => GlobalParam::getCurrentProducerId(),
- ])
- ->all();
- } else {
- $arrayPointsSale = $pointSaleManager->findPointSales();
- }
-
- $arrayProducts = $productManager->findProducts();
-
- $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);
-
- // commandes
- $arrayOrders = $orderManager->findOrdersByDistribution($distribution);
- $revenues = 0;
- $weight = 0;
- $revenuesDelivered = 0;
-
- if ($arrayOrders) {
- foreach ($arrayOrders as $order) {
- if (is_null($order->date_delete)) {
- $revenues += $order->amount;
- if ($order->id_point_sale != 1) {
- $revenuesDelivered += $order->amount;
- }
- $weight += $order->weight;
- }
- }
- }
-
- $revenues = number_format($revenues, 2);
-
- // init commandes point de vente
- foreach ($arrayPointsSale as $pointSale) {
- $pointSaleManager->initPointSaleOrders($pointSale, $arrayOrders);
-
- $dataSelectOrders = [];
- $dataOptionsOrders = [];
- foreach ($pointSale->orders as $order) {
- if ($order->user) {
- $dataSelectOrders[$order->id] = $order->user->name . ' ' . $order->user->lastname;
- } else {
- $dataSelectOrders[$order->id] = $order->username;
- }
-
- $dataOptionsOrders[$order->id] = [];
- $arrayOptions = [];
- $arrayOptions[$order->id]['amount'] = $order->amount;
- $arrayOptions[$order->id]['str_amount'] = number_format($order->amount, 2, ',', '') . ' €';
- $arrayOptions[$order->id]['paid_amount'] = $order->paid_amount;
- $arrayOptions[$order->id]['products'] = [];
- $arrayOptions[$order->id]['comment'] = Html::encode($order->comment);
- foreach ($order->productOrder as $productOrder) {
- $arrayOptions[$order->id]['products'][$productOrder->id_product] = $productOrder->quantity;
- }
-
- $dataOptionsOrders[$order->id]['data-order'] = json_encode($arrayOptions[$order->id]);
- $dataOptionsOrders[$order->id]['value'] = $order->id;
- }
- $pointSale->data_select_orders = $dataSelectOrders;
- $pointSale->data_options_orders = $dataOptionsOrders;
- }
-
- // gestion produits selec
- if (isset($_POST['valider_produit_selec'])) {
-
- if (isset($_POST['Product'])) {
-
- foreach ($arrayProducts as $product) {
-
- $productDistribution = $productDistributionManager->findOneProductDistribution($distribution, $product);
-
- if (!$productDistribution) {
- $productDistribution = new ProductDistribution();
- $productDistribution->id_distribution = $distribution->id;
- $productDistribution->id_product = $product->id;
- $productDistribution->active = 0;
-
- if (isset($product->quantity_max)) {
- $productDistribution->quantity_max = $product->quantity_max;
- } else {
- $productDistribution->quantity_max = null;
- }
-
- $productDistributionManager->saveCreate($productDistribution);
- }
-
- if (isset($_POST['Product'][$product->id]['active'])) {
- $productDistribution->active = 1;
- } else {
- $productDistribution->active = 0;
- }
-
- if ((isset($_POST['Product'][$product->id]['quantity_max']) && $_POST['Product'][$product->id]['quantity_max'] != '')) {
- $productDistribution->quantity_max = (int)$_POST['Product'][$product->id]['quantity_max'];
- } else {
- $productDistribution->quantity_max = null;
- }
-
- $productDistributionManager->saveUpdate($productDistribution);
- }
- }
- }
-
- $arrayProductsSelected = [];
- if ($distribution) {
- $arrayProductsSelected = $productDistributionManager->findProductDistributionsByDistribution($distribution);
- $arrayProducts = $productManager->findProductsByDistribution($distribution);
- }
-
- // poids total de la production et CA potentiel
- $potentialTurnover = 0;
- $totalWeight = 0;
- foreach ($arrayProductsSelected as $idSelectedProduct => $selectedProduct) {
- if ($selectedProduct['active']) {
- foreach ($arrayProducts as $product) {
- if ($product->id == $idSelectedProduct) {
- $potentialTurnover += $selectedProduct['quantity_max'] * $product->price;
- $totalWeight += $selectedProduct['quantity_max'] * $product->weight / 1000;
- }
- }
- }
- }
-
- $arrayDistributionDays = $distributionManager->findDistributionsActive();
-
- // commandes auto
- $subscriptionForm = new SubscriptionForm();
-
- // productions point vente
- $pointSaleDistribution = new PointSaleDistribution();
- $oointsSaleDistribution = [];
-
- if ($distribution) {
- $pointsSaleDistribution = PointSaleDistribution::searchAll([
- 'id_distribution' => $distribution->id
- ]);
- }
-
- $arrayPointsSaleDistribution = [];
-
- if (isset($pointsSaleDistribution)) {
- foreach ($pointsSaleDistribution as $pointSaleDistrib) {
- $key = $pointSaleDistrib->id_distribution . '-' . $pointSaleDistrib->id_point_sale;
- if ($pointSaleDistrib->delivery == 1) {
- $pointSaleDistribution->points_sale_distribution[] = $key;
- }
- if (isset($pointSaleDistrib->pointSale) && strlen($pointSaleDistrib->pointSale->name)) {
- $arrayPointsSaleDistribution[$key] = Html::encode($pointSaleDistrib->pointSale->name);
- }
- }
- }
-
- // une production de la semaine activée ou non
- $oneDistributionWeekActive = false;
- $week = sprintf('%02d', date('W', strtotime($date)));
- $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
- $dateMonday = date('Y-m-d', strtotime('Monday', $start));
- $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
- $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
- $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
- $dateFriday = date('Y-m-d', strtotime('Friday', $start));
- $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
- $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
-
- $weekDistribution = Distribution::find()
- ->andWhere([
- 'id_producer' => GlobalParam::getCurrentProducerId(),
- 'active' => 1,
- ])
- ->andWhere(['or',
- ['date' => $dateMonday],
- ['date' => $dateTuesday],
- ['date' => $dateWednesday],
- ['date' => $dateThursday],
- ['date' => $dateFriday],
- ['date' => $dateSaturday],
- ['date' => $dateSunday],
- ])
- ->one();
- if ($weekDistribution) {
- $oneDistributionWeekActive = true;
- }
-
- $datas = [
- 'arrayProducts' => $arrayProducts,
- 'arrayPointsSale' => $arrayPointsSale,
- 'arrayOrders' => $arrayOrders,
- 'date' => $date,
- 'distribution' => $distribution,
- 'arrayDistributionDays' => $arrayDistributionDays,
- 'selectedProducts' => $arrayProductsSelected,
- 'users' => $arrayUsers,
- 'revenues' => $revenues,
- 'revenuesDelivered' => $revenuesDelivered,
- 'weight' => $weight,
- 'potentialTurnover' => $potentialTurnover,
- 'totalWeight' => $totalWeight,
- 'subscriptionForm' => $subscriptionForm,
- 'pointSaleDistribution' => $pointSaleDistribution,
- 'arrayPointsSaleDistribution' => $arrayPointsSaleDistribution,
- 'oneDistributionWeekActive' => $oneDistributionWeekActive
- ];
-
- if ($returnData) {
- return $datas;
- } else {
- return $this->render('index', $datas);
- }
- }
-
- /**
- * Génère un fichier d'export des commandes au format CSV.
- *
- * @param string $date
- * @param integer $id_point_vente
- * @param boolean $global
- */
- public function actionDownload($date = '', $idPointSale = 0, $global = 0)
- {
- $orderManager = $this->getOrderManager();
- $distributionManager = $this->getDistributionManager();
- $pointSaleManager = $this->getPointSaleManager();
- $productManager = $this->getProductManager();
- $productDistributionManager = $this->getProductDistributionManager();
-
- $distribution = $distributionManager->findOneDistributionByDate($date);
- $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
- $productsArray = $productManager->findProducts();
- $ordersArray = $orderManager->findOrdersByDate($date);
-
- $pointsSaleArray = $pointSaleManager->findPointSales();
- foreach ($pointsSaleArray as $pointSale) {
- $pointSaleManager->initOrders($pointSale, $ordersArray);
- }
-
- /*
- * export global
- */
- if ($global) {
-
- $data = [];
- $filename = 'export_' . $date . '_global';
-
- $dayWeek = date('w', strtotime($date));
- $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
- $fieldsHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
-
- // par point de vente
- foreach ($pointsSaleArray as $pointSale) {
- if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
-
- $line = [$pointSale->name, 'Produits', 'Montant', 'Commentaire'];
-
- $data[] = $line;
-
- $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $pointSale->id);
- foreach ($res['data'] as $line) {
- $data[] = $line;
- }
- }
-
- if (count($pointSale->orders) && strlen($pointSale->$fieldsHoursPointSale)) {
-
- $line = ['Total'];
- $strProducts = '';
- foreach ($productsArray as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $quantity = $orderManager->getProductQuantity($product, $pointSale->orders);
- $strQuantity = '';
- if ($quantity) {
- $strQuantity = $quantity;
- $strProducts .= $strQuantity . ', ';
- }
- }
- }
- $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
- $line[] = number_format($pointSale->revenues, 2) . ' €';
- $data[] = $line;
-
- $data[] = [];
- }
- }
-
- $line = ['Total'];
- $strProducts = '';
- foreach ($productsArray as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $quantity = $orderManager->getProductQuantity($product, $ordersArray);
- $strQuantity = '';
- if ($quantity) {
- $strQuantity = $quantity;
- $strQuantity .= $strQuantity . ', ';
- }
- }
- }
- $line[] = substr($strProducts, 0, strlen($strProducts) - 2);
-
- $data[] = $line;
-
-
- $infos = $this->actionIndex($date, true);
-
- CSV::downloadSendHeaders($filename . '.csv');
- echo CSV::array2csv($data);
- die();
- } /*
- * export individuel
- */
- else {
- if ($ordersArray && count($ordersArray)) {
-
- $data = [];
-
- // par point de vente
- if ($idPointSale) {
- $res = $this->contentPointSaleCSV($date, $productsArray, $pointsSaleArray, $idPointSale);
- $data = $res['data'];
- $filename = $res['filename'];
- } // récapitulatif
- else {
- $res = $this->contentRecapCSV($date, $productsArray, $pointsSaleArray, $ordersArray);
- $filename = 'summary_' . $date;
- $data = $res['data'];
- }
-
- CSV::downloadSendHeaders($filename . '.csv');
- echo CSV::array2csv($data);
- die();
- }
- }
- }
-
- /**
- * Génère le contenu nécessaire aux exports au format CSV.
- *
- * @param string $date
- * @param array $products
- * @param array $pointsSale
- * @param array $orders
- * @return array
- * @see OrderController::actionDownload()
- */
- public function contentRecapCSV(string $date, array $products, array $pointsSale, array $orders)
- {
- $orderManager = $this->getOrderManager();
- $distributionManager = $this->getDistributionManager();
- $productDistributionManager = $this->getProductDistributionManager();
-
- $data = [];
- $filename = 'summary_' . $date;
-
- $distribution = $distributionManager->findOneDistributionByDate($date);
- $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
-
- // head
- $data[0] = ['Lieu'];
- foreach ($products as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $data[0][] = $product->description;
- }
- }
-
- $dayWeek = date('w', strtotime($date));
- $dayWeekArray = [0 => 'sunday', 1 => 'monday', 2 => 'tuesday', 3 => 'wednesday', 4 => 'thursday', 5 => 'friday', 6 => 'saturday'];
- $fieldHoursPointSale = 'infos_' . $dayWeekArray[$dayWeek];
-
-
- // datas
- foreach ($pointsSale as $pointSale) {
- if (count($pointSale->orders) && strlen($pointSale->$fieldHoursPointSale)) {
- $dataAdd = [$pointSale->name];
- foreach ($products as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $dataAdd[] = $orderManager->getProductQuantity($product, $pointSale->orders);
- }
- }
- $data[] = $dataAdd;
- }
- }
-
- $dataAdd = ['Total'];
- foreach ($products as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $dataAdd[] = $orderManager->getProductQuantity($product, $orders);
- }
- }
- $data[] = $dataAdd;
-
- return [
- 'data' => $data,
- 'filename' => $filename
- ];
- }
-
- /**
- * Génère le contenu relatif aux points de vente nécessaires aux exports au
- * format CSV.
- *
- * @param string $date
- * @param array $produits
- * @param array $points_vente
- * @param integer $id_point_vente
- * @return array
- */
- public function contentPointSaleCSV($date, $products, $pointsSale, $idPointSale)
- {
- $distributionManager = $this->getDistributionManager();
- $productDistributionManager = $this->getProductDistributionManager();
-
- $data = [];
- $distribution = $distributionManager->findOneDistributionByDate($date);
- $selectedProductsArray = $productDistributionManager->findProductDistributionsByDistribution($distribution);
-
- // datas
- foreach ($pointsSale as $pointSale) {
- if ($pointSale->id == $idPointSale) {
-
- $filename = 'export_' . $date . '_' . strtolower(str_replace(' ', '-', $pointSale->name));
-
- foreach ($pointSale->orders as $order) {
- $strUser = '';
- // username
- if ($order->user) {
- $strUser = $order->user->name . " " . $order->user->lastname;
- } else {
- $strUser = $order->username;
- }
-
- // téléphone
- if (isset($order->user) && strlen($order->user->phone)) {
- $strUser .= ' (' . $order->user->phone . ')';
- }
-
- $dataAdd = [$strUser];
-
- // produits
- $strProducts = '';
- foreach ($products as $product) {
- if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
- $add = false;
- foreach ($product->productOrder as $productOrder) {
- if ($product->id == $productOrder->id_product) {
- $strProducts .= $productOrder->quantity;
- $add = true;
- }
- }
- }
- }
-
- $dataAdd[] = substr($strProducts, 0, strlen($strProducts) - 2);
- $dataAdd[] = number_format($order->amount, 2) . ' €';
- $dataAdd[] = $order->comment;
-
- $data[] = $dataAdd;
- }
- }
- }
-
- return [
- 'data' => $data,
- 'filename' => $filename
- ];
- }
-
- /**
- * Change l'état d'un jour de distribution (activé, désactivé).
- */
- public function actionChangeState(string $date, bool $active, bool $redirect = true)
- {
- $distributionManager = $this->getDistributionManager();
- $distribution = $distributionManager->createDistributionIfNotExist($this->getProducerCurrent(), $date);
- $distributionManager->activeDistribution($distribution, $active);
-
- if ($redirect) {
- $this->redirect(['index', 'date' => $date]);
- }
- }
-
- /**
- * Change l'état d'une semaine de production (activé, désactivé).
- */
- public function actionChangeStateWeek(string $date, bool $active)
- {
- $pointSaleManager = $this->getPointSaleManager();
-
- $pointsSaleArray = $pointSaleManager->findPointSales();
-
- $week = sprintf('%02d', date('W', strtotime($date)));
- $start = strtotime(date('Y', strtotime($date)) . 'W' . $week);
- $dateMonday = date('Y-m-d', strtotime('Monday', $start));
- $dateTuesday = date('Y-m-d', strtotime('Tuesday', $start));
- $dateWednesday = date('Y-m-d', strtotime('Wednesday', $start));
- $dateThursday = date('Y-m-d', strtotime('Thursday', $start));
- $dateFriday = date('Y-m-d', strtotime('Friday', $start));
- $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
- $dateSunday = date('Y-m-d', strtotime('Sunday', $start));
-
- $activeMonday = false;
- $activeTuesday = false;
- $activeWednesday = false;
- $activeThursday = false;
- $activeFriday = false;
- $activeSaturday = false;
- $activeSunday = false;
-
- foreach ($pointsSaleArray as $pointSale) {
- if ($pointSale->delivery_monday) $activeMonday = true;
- if ($pointSale->delivery_tuesday) $activeTuesday = true;
- if ($pointSale->delivery_wednesday) $activeWednesday = true;
- if ($pointSale->delivery_thursday) $activeThursday = true;
- if ($pointSale->delivery_friday) $activeFriday = true;
- if ($pointSale->delivery_saturday) $activeSaturday = true;
- if ($pointSale->delivery_sunday) $activeSunday = true;
- }
-
- if ($activeMonday || !$active) $this->actionChangeState($dateMonday, $active, false);
- if ($activeTuesday || !$active) $this->actionChangeState($activeTuesday, $active, false);
- if ($activeWednesday || !$active) $this->actionChangeState($activeWednesday, $active, false);
- if ($activeThursday || !$active) $this->actionChangeState($activeThursday, $active, false);
- if ($activeFriday || !$active) $this->actionChangeState($activeFriday, $active, false);
- if ($activeSaturday || !$active) $this->actionChangeState($activeSaturday, $active, false);
- if ($activeSunday || !$active) $this->actionChangeState($activeSunday, $active, false);
-
- $this->redirect(['index', 'date' => $date]);
- }
-
- /**
- * Supprime une commande via une requête AJAX.
- */
- public function actionAjaxDelete(int $idOrder)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $orderManager = $this->getOrderManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
- if ($order) {
- $orderManager->deleteOrder($order);
- }
-
- return ['success'];
- }
-
-
- /**
- * Supprime une commande.
- */
- public function actionDelete(string $date, int $idOrder)
- {
- $orderManager = $this->getOrderManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
- if ($order) {
- $orderManager->deleteOrder($order);
- }
-
- $this->redirect(['index', 'date' => $date]);
- }
-
- /**
- * Crée une commande via une requête AJAX.
- *
- * @param string $date
- * @param integer $idPointSale
- * @param integer $idUser
- * @param string $username
- * @param array $produits
- * @param string $commentaire
- * @param string $processCredit
- */
- public function actionAjaxCreate(
- $date, $idPointSale, $idUser, $username, $meanPayment = '', $products, $comment, $processCredit = 0)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $distributionManager = $this->getDistributionManager();
- $pointSaleManager = $this->getPointSaleManager();
- $userPointSaleManager = $this->getUserPointSaleManager();
- $userManager = $this->getUserManager();
- $userProducerManager = $this->getUserProducerManager();
- $producerManager = $this->getProducerManager();
- $productManager = $this->getProductManager();
- $orderManager = $this->getOrderManager();
-
- $products = json_decode($products);
- $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
- $distribution = $distributionManager->findOneDistributionByDate($date);
-
- if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
- && ($idUser || strlen($username))
- && $pointSale
- && count(get_object_vars($products))
- && $distribution) {
-
- $order = new Order;
- $order->date = date('Y-m-d H:i:s');
- $order->id_point_sale = $idPointSale;
- $order->mean_payment = $meanPayment;
- $order->id_distribution = $distribution->id;
- $order->origin = Order::ORIGIN_ADMIN;
- $order->comment = $comment;
- $order->status = 'tmp-order';
-
- if ($idUser) {
- $order->id_user = $idUser;
-
- // commentaire du point de vente
- $userPointSale = $userPointSaleManager->findOneUserPointSale($userManager->findOneUserById($idUser), $pointSale);
-
- if ($userPointSale && strlen($userPointSale->comment)) {
- $order->comment_point_sale = $userPointSale->comment;
- }
- } else {
- $order->username = $username;
- $order->id_user = 0;
- }
-
- $order->save();
-
- $user = false;
- $userProducer = false;
- if (isset($order->user) && $order->user) {
- $user = $order->user;
-
- $userProducer = $userProducerManager->findOneUserProducer(
- $user,
- $producerManager->findOneProducerById($order->distribution->id_producer)
- );
- }
-
- foreach ($products as $key => $dataProductOrder) {
- $product = $productManager->findOneProductById($key);
- $quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
- if ($product && $quantity) {
- $productOrder = new ProductOrder;
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $key;
- $productOrder->quantity = $quantity;
- $productOrder->unit = $product->unit;
- $productOrder->step = $product->step;
- if ($dataProductOrder->price) {
- $productOrder->price = $dataProductOrder->price;
- } else {
- $productOrder->price = $productManager->getPrice($product, [
- 'user' => $user,
- 'user_producer' => $userProducer,
- 'point_sale' => $order->pointSale,
- 'quantity' => $productOrder->quantity
- ]);
- }
- $productOrder->id_tax_rate = $product->taxRate->id;
- $productOrder->save();
- }
- }
-
- $order = $orderManager->findOneOrderById($order);
- if ($order && $processCredit) {
- $orderManager->processCredit($order);
- }
-
- if ($order) {
- $orderManager->generateOrderReference($order);
- $orderManager->updateOrderTillerSynchronization($order);
- }
-
- // lien utilisateur / point de vente
- if ($idUser && $pointSale) {
- $pointSaleManager->addUser($pointSale, $user);
- }
- }
-
- return ['success'];
- }
-
- /**
- * Met à jour une commande via une requête AJAX.
- *
- * @param integer $idOrder
- * @param array $products
- * @param string $date
- * @param string $comment
- */
- public function actionAjaxUpdate()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $orderManager = $this->getOrderManager();
- $userManager = $this->getUserManager();
- $pointSaleManager = $this->getPointSaleManager();
- $userPointSaleManager = $this->getUserPointSaleManager();
-
- $request = \Yii::$app->request;
- $date = $request->post('date');
- $idOrder = $request->post('idOrder');
- $idPointSale = $request->post('idPointSale');
- $idUser = $request->post('idUser');
- $username = $request->post('username');
- $meanPayment = $request->post('meanPayment');
- $products = $request->post('products');
- $comment = $request->post('comment');
- $processCredit = $request->post('processCredit');
-
- $order = $orderManager->findOneOrderById($idOrder);
- $user = $userManager->findOneUserById($idUser);
- $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
-
- if ($order
- && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
-
- $oldIdUser = $order->id_user;
- if ($idUser) {
- $order->username = '';
- $order->id_user = $idUser;
-
- // commentaire du point de vente
- $userPointSale = $userPointSaleManager->findOneUserPointSale($user, $pointSale);
- if ($userPointSale && strlen($userPointSale->comment)) {
- $order->comment_point_sale = $userPointSale->comment;
- }
- } else {
- $order->username = $username;
- $order->id_user = 0;
- }
-
- $user = User::searchOne(['id' => $order->id_user]);
- $userProducer = false;
- if ($user) {
- $userProducer = UserProducer::searchOne([
- 'id_user' => $user->id,
- 'id_producer' => $order->distribution->id_producer
- ]);
- }
-
- $products = json_decode($products);
- foreach ($products as $key => $dataProductOrder) {
- $productOrder = ProductOrder::findOne([
- 'id_order' => $idOrder,
- 'id_product' => $key
- ]);
-
- $quantity = $dataProductOrder->quantity
- / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
-
- if ($quantity) {
- if ($productOrder) {
- $productOrder->quantity = $quantity;
- $productOrder->price = $dataProductOrder->price;
- } else {
- $product = Product::findOne($key);
-
- if ($product) {
- $productOrder = new ProductOrder;
- $productOrder->id_order = $idOrder;
- $productOrder->id_product = $key;
- $productOrder->quantity = $quantity;
- $productOrder->unit = $product->unit;
- $productOrder->step = $product->step;
- $productOrder->id_tax_rate = $product->taxRate->id;
-
- if ($dataProductOrder->price) {
- $productOrder->price = $dataProductOrder->price;
- } else {
- $productOrder->price = $product->getPrice([
- 'user' => $user,
- 'user_producer' => $userProducer,
- 'point_sale' => $order->pointSale,
- 'quantity' => $productOrder->quantity
- ]);
- }
- }
- }
-
- $productOrder->save();
- } else {
- if ($productOrder) {
- $productOrder->delete();
- }
- }
- }
-
- $order->id_point_sale = $idPointSale;
- $order->date_update = date('Y-m-d H:i:s');
- $order->mean_payment = $meanPayment;
- $order->comment = $comment;
-
- $order->save();
-
- $order = Order::searchOne(['id' => $order->id]);
- if ($order && $processCredit) {
- // Si changement d'user : on rembourse l'ancien user
- $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
- if ($oldIdUser != $idUser && $amountPaid > 0) {
- $order->saveCreditHistory(
- CreditHistory::TYPE_REFUND,
- $amountPaid,
- GlobalParam::getCurrentProducerId(),
- $oldIdUser,
- GlobalParam::getCurrentUserId()
- );
- $order = Order::searchOne(['id' => $order->id]);
- }
-
- $order->processCredit();
- }
- }
- }
-
-
- /**
- * Retourne l'état du paiement (historique, crédit) d'une commande donnée.
- */
- public function actionPaymentStatus(int $idOrder)
- {
- $creditHistoryManager = $this->getCreditHistoryManager();
- $order = Order::searchOne(['id' => $idOrder]);
-
- if ($order) {
- $html = '';
-
- if ($order->id_user) {
- $userProducer = UserProducer::find()
- ->where([
- 'id_user' => $order->id_user,
- 'id_producer' => $order->distribution->id_producer
- ])
- ->one();
-
- $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
-
- if (abs($order->amount - $amountPaid) < 0.0001) {
- $html .= '<span class="label label-success">Payé</span>';
- $buttonsCredit = Html::a('Rembourser ' . $order->getAmountWithTax(Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
- } elseif ($order->amount > $amountPaid) {
- $amountToPay = $order->amount - $amountPaid;
- $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
- $buttonsCredit = Html::a('Payer ' . number_format($amountToPay, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs payer', 'data-montant' => $amountToPay, 'data-type' => 'payment']);
- } elseif ($order->amount < $amountPaid) {
- $amountToRefund = $amountPaid - $order->amount;
- $html .= ' <span class="label label-success">Payé</span> <strong>' . number_format($amountToRefund, 2) . ' €</strong> à rembourser';
- $buttonsCredit = Html::a('Rembourser ' . number_format($amountToRefund, 2) . ' €', 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $amountToRefund, 'data-type' => 'refund']);
- }
-
- $html .= '<span class="buttons-credit">'
- . 'Crédit : <strong>' . number_format($userProducer->credit, 2) . ' €</strong><br />'
- . $buttonsCredit
- . '</span>';
-
- // historique
- $history = CreditHistory::find()
- ->with('userAction')
- ->where(['id_order' => $idOrder])
- ->all();
-
- $html .= '<br /><br /><strong>Historique</strong><br /><table class="table table-condensed table-bordered">'
- . '<thead><tr><th>Date</th><th>Utilisateur</th><th>Action</th><th>- Débit</th><th>+ Crédit</th></tr></thead>'
- . '<tbody>';
-
- if ($history && is_array($history) && count($history)) {
- foreach ($history as $creditHistory) {
- $html .= '<tr>'
- . '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryManager->getDate($creditHistory))) . '</td>'
- . '<td>' . Html::encode($creditHistoryManager->getStrUserAction($creditHistory)) . '</td>'
- . '<td>' . $creditHistoryManager->getStrWording($creditHistory) . '</td>'
- . '<td>' . ($creditHistoryManager->isTypeDebit($creditHistory) ? '- ' . $creditHistoryManager->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
- . '<td>' . ($creditHistoryManager->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryManager->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
- . '</tr>';
- }
- } else {
- $html .= '<tr><td colspan="4">Aucun résultat</td></tr>';
- }
-
- $html .= '</tbody></table>';
- } else {
- $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>';
- }
-
- echo json_encode([
- 'html_payment_status' => $html,
- 'json_order' => $order->getDataJson()
- ]);
- }
-
- die();
- }
-
- /**
- * Effectue le paiement/remboursement d'une commande.
- */
- public function actionAjaxPayment(int $idOrder, string $type, float $amount): array
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $orderManager = $this->getOrderManager();
- $creditHistoryManager = $this->getCreditHistoryManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
-
- if ($order) {
- $creditHistoryManager->createCreditHistory(
- $type,
- $amount,
- GlobalParam::getCurrentProducer(),
- $order->user,
- GlobalParam::getCurrentUser()
- );
- }
-
- return ['success'];
- }
-
- /**
- * Modifie l'état de la synchronisation Tiller d'une commande.
- */
- public function actionAjaxChangeSynchroTiller(int $idOrder, bool $boolSynchroTiller): array
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $orderManager = $this->getOrderManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
- if ($order) {
- $orderManager->updateOrderTillerSynchronization($order, (int) $boolSynchroTiller);
- return ['success'];
- }
-
- return ['error'];
- }
-
- }
-
|