|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296 |
- <?php
-
- /**
- * Copyright Souke (2018)
- *
- * contact@souke.fr
- *
- * 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\helpers\CSV;
- use common\helpers\GlobalParam;
- use common\helpers\MeanPayment;
- use common\helpers\Price;
- use domain\Order\Order\OrderRepositoryQuery;
- use domain\Order\OrderStatus\OrderStatus;
- use backend\forms\ReportPaymentsForm;
- use Yii;
- use yii\filters\AccessControl;
-
- class ReportController extends BackendController
- {
- var $enableCsrfValidation = false;
-
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::class,
- 'rules' => [
- [
- 'allow' => true,
- 'roles' => ['@'],
- 'matchCallback' => function ($rule, $action) {
- return $this->getUserModule()
- ->getAuthorizationChecker()
- ->isGrantedAsProducer($this->getUserCurrent());
- }
- ]
- ],
- ],
- ];
- }
-
- public function actionIndex()
- {
- $this->checkProductsPointsSale();
- return $this->render('index');
- }
-
- public function actionAjaxInit()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $userModule = $this->getUserModule();
- $pointSaleModule = $this->getPointSaleModule();
- $distributionModule = $this-> getDistributionModule();
-
- $usersArray = $userModule->findUsers();
- foreach($usersArray as $key => $user) {
- $usersArray[$key]['username'] = $userModule->getSolver()->getUsernameFromArray($user, true);
- }
- $pointsSaleArray = $pointSaleModule->findPointSales();
- $firstDistribution = $distributionModule->findOneFirstDistribution();
- $lastDistribution = $distributionModule->findOneLastDistribution();
- $firstYear = date('Y', strtotime($firstDistribution->date));
- $lastYear = date('Y', strtotime($lastDistribution->date));
-
- $distributionYearsArray = [];
- for ($year = $firstYear; $year <= $lastYear; $year++) {
- $distributionYearsArray[] = $year;
- }
-
- $distributionsByMonthArray = [];
- $distributionsArray = $distributionModule->findDistributionsWithOrders();
- foreach ($distributionsArray as $distribution) {
- $month = date('Y-m', strtotime($distribution->date));
- if (!isset($distributionsByMonthArray[$month])) {
- $distributionsByMonthArray[$month] = [
- 'display' => 0,
- 'year' => date('Y', strtotime($distribution->date)),
- 'month' => strftime('%B', strtotime($distribution->date)),
- 'distributions' => []
- ];
- }
- $distribution->date = strftime('%A %d %B %Y', strtotime($distribution->date));
- $distributionsByMonthArray[$month]['distributions'][] = $distribution;
- }
-
- return [
- 'usersArray' => $usersArray,
- 'pointsSaleArray' => $pointsSaleArray,
- 'distributionYearsArray' => $distributionYearsArray,
- 'distributionsByMonthArray' => $distributionsByMonthArray
- ];
- }
-
- public function actionAjaxReport()
- {
- $posts = Yii::$app->request->post();
- $isDownload = $posts['isDownload'] == 1;
- $resArray = [];
- $conditionUsers = $this->_generateConditionSqlReport($posts, 'users', 'id_user');
- $conditionPointsSale = $this->_generateConditionSqlReport($posts, 'pointsSale', 'id_point_sale');
- $conditionDistributions = $this->_generateConditionSqlReport($posts, 'distributions', 'id_distribution');
-
- $res = Yii::$app->db->createCommand("SELECT product.name, SUM(product_order.quantity) AS quantity, SUM(product_order.price * product_order.quantity) AS total
- FROM `order`, product_order, product
- WHERE `order`.id = product_order.id_order
- AND product.id_producer = " . ((int)GlobalParam::getCurrentProducerId()) . "
- AND product_order.id_product = product.id
- AND ".OrderRepositoryQuery::getSqlFilterIsValid()."
- " . $conditionUsers . "
- " . $conditionPointsSale . "
- " . $conditionDistributions . "
- GROUP BY product.id
- ORDER BY product.order ASC
- ")
- ->queryAll();
-
- $totalGlobal = 0;
- foreach ($res as $line) {
- $roundedTotal = round($line['total'], 2);
- $total = $isDownload ? $roundedTotal : Price::format($roundedTotal);
-
- $quantity = $line['quantity'];
- if((int) $quantity != $quantity) {
- $quantity = round($quantity, 3);
- }
-
- if ($line['quantity'] > 0) {
- $resArray[] = [
- 'name' => $line['name'],
- 'quantity' => $quantity,
- 'total' => $total,
- ];
- $totalGlobal += $line['total'];
- }
- }
-
- $roundedTotalGlobal = round($totalGlobal, 2);
- $totalGlobalFormat = $isDownload ? $roundedTotalGlobal : Price::format($roundedTotalGlobal).' HT';
-
- $resArray[] = [
- 'name' => '',
- 'quantity' => '',
- 'total' => $totalGlobalFormat,
- ];
-
- if($isDownload) {
- CSV::send('rapport.csv', $resArray);
- }
- else {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- return $resArray;
- }
- }
-
- public function _generateConditionSqlReport($posts, $name, $fieldOrder)
- {
- $condition = '';
- if (isset($posts[$name]) && strlen($posts[$name])) {
- $idsArray = explode(',', $posts[$name]);
- for ($i = 0; $i < count($idsArray); $i++) {
- $idsArray[$i] = (int)$idsArray[$i];
- }
- $condition = 'AND `order`.' . $fieldOrder . ' IN (' . implode(',', $idsArray) . ') ';
- }
- return $condition;
- }
-
- public function actionPayments()
- {
- $dateStart = $dateEnd = null;
- $reportPaymentsForm = new ReportPaymentsForm();
- if($reportPaymentsForm->load(Yii::$app->request->post()) && $reportPaymentsForm->validate()) {
- $dateStart = date('Y-m-d', strtotime(str_replace('/', '-', $reportPaymentsForm->date_start)));
- $dateEnd = date('Y-m-d', strtotime(str_replace('/', '-', $reportPaymentsForm->date_end)));
- }
-
- if($dateStart && $dateEnd) {
- $orderModule = $this->getOrderModule();
- $ordersArray = $orderModule->getRepository()
- ->findOrdersByPeriod(
- new \DateTime($dateStart),
- new \DateTime($dateEnd)
- );
-
- $datas = [
- [
- 'Date',
- 'Client',
- 'Montant',
- 'Facture',
- 'Crédit',
- 'Espèce',
- 'Chèque',
- 'Virement',
- 'Carte bancaire',
- 'Total'
- ]
- ];
-
- $sumAmountTotalSpentByCredit = 0;
- $sumAmountTotalSpentByMoney = 0;
- $sumAmountTotalSpentByCheque = 0;
- $sumAmountTotalSpentByTransfer = 0;
- $sumAmountTotalSpentByCreditCard = 0;
-
- foreach($ordersArray as $order) {
- $orderModule->getBuilder()->initOrder($order);
-
- $hasInvoice = false;
- $referenceInvoice = 'Non';
- if($order->invoice) {
- $hasInvoice = true;
- $referenceInvoice = $order->invoice->reference."";
- }
-
- $amountTotalSpentByCredit = $orderModule->getSolver()->getAmountTotalSpentByMeanPayment($order, MeanPayment::CREDIT);
- $sumAmountTotalSpentByCredit += $amountTotalSpentByCredit;
- $amountTotalSpentByMoney = $orderModule->getSolver()->getAmountTotalSpentByMeanPayment($order, MeanPayment::MONEY);
- $sumAmountTotalSpentByMoney += $amountTotalSpentByMoney;
- $amountTotalSpentByCheque = $orderModule->getSolver()->getAmountTotalSpentByMeanPayment($order, MeanPayment::CHEQUE);
- $sumAmountTotalSpentByCheque += $amountTotalSpentByCheque;
- $amountTotalSpentByTransfer = $orderModule->getSolver()->getAmountTotalSpentByMeanPayment($order, MeanPayment::TRANSFER);
- $sumAmountTotalSpentByTransfer += $amountTotalSpentByTransfer;
- $amountTotalSpentByCreditCard = $orderModule->getSolver()->getAmountTotalSpentByMeanPayment($order, MeanPayment::CREDIT_CARD);
- $sumAmountTotalSpentByCreditCard += $amountTotalSpentByCreditCard;
-
- $datas[] = [
- $order->distribution->date,
- $orderModule->getSolver()->getOrderUsername($order),
- CSV::formatNumber($orderModule->getSolver()->getOrderAmountWithTax($order)),
- $referenceInvoice,
- $hasInvoice ? '' : CSV::formatNumber($amountTotalSpentByCredit),
- $hasInvoice ? '' : CSV::formatNumber($amountTotalSpentByMoney),
- $hasInvoice ? '' : CSV::formatNumber($amountTotalSpentByCheque),
- $hasInvoice ? '' : CSV::formatNumber($amountTotalSpentByTransfer),
- $hasInvoice ? '' : CSV::formatNumber($amountTotalSpentByCreditCard)
- ];
- }
-
- $datas[] = [
- '',
- '',
- '',
- 'Totaux paiements',
- CSV::formatNumber($sumAmountTotalSpentByCredit),
- CSV::formatNumber($sumAmountTotalSpentByMoney),
- CSV::formatNumber($sumAmountTotalSpentByCheque),
- CSV::formatNumber($sumAmountTotalSpentByTransfer),
- CSV::formatNumber($sumAmountTotalSpentByCreditCard),
- CSV::formatNumber($sumAmountTotalSpentByCredit + $sumAmountTotalSpentByMoney + $sumAmountTotalSpentByCheque +
- $sumAmountTotalSpentByTransfer + $sumAmountTotalSpentByCreditCard)
- ];
-
- CSV::send('commandes.csv', $datas);
- }
-
- return $this->render('payments', [
- 'reportPaymentsForm' => $reportPaymentsForm
- ]);
- }
-
- }
|