|
- <?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\helpers\Ajax;
- use common\helpers\CSV;
- use common\helpers\GlobalParam;
- use common\helpers\MeanPayment;
- use common\helpers\Password;
- use common\helpers\Price;
- use common\helpers\Tiller;
- use common\logic\Distribution\Distribution\Model\Distribution;
- use common\logic\Document\DeliveryNote\Model\DeliveryNote;
- use common\logic\Document\Document\Model\Document;
- use common\logic\Order\Order\Model\Order;
- use common\logic\PointSale\PointSale\Model\PointSale;
- use common\logic\Producer\Producer\Model\Producer;
- use common\logic\Product\Product\Model\Product;
- use common\logic\User\User\Model\User;
- use common\logic\User\UserProducer\Model\UserProducer;
- use DateTime;
- use kartik\mpdf\Pdf;
- use yii\filters\AccessControl;
-
- class DistributionController extends BackendController
- {
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::class,
- 'rules' => [
- [
- 'actions' => ['report-cron', 'report-terredepains'],
- 'allow' => true,
- 'roles' => ['?']
- ],
- [
- 'allow' => true,
- 'roles' => ['@'],
- 'matchCallback' => function ($rule, $action) {
- $userManager = $this->getUserManager();
- return $userManager->isCurrentAdmin() || $userManager->isCurrentProducer();
- }
- ]
- ],
- ],
- ];
- }
-
- public function actionIndex($date = '', $idOrderUpdate = 0)
- {
- $this->checkProductsPointsSale();
-
- $orderManager = $this->getOrderManager();
-
- $format = 'Y-m-d';
- $theDate = '';
- $dateObject = DateTime::createFromFormat($format, $date);
-
- if ($dateObject && $dateObject->format($format) === $date) {
- $theDate = $date;
- }
-
- $orderUpdate = null;
- if ($idOrderUpdate) {
- $orderUpdate = $orderManager->findOneOrderById($idOrderUpdate);
- }
-
- return $this->render('index', [
- 'date' => $theDate,
- 'orderUpdate' => $orderUpdate
- ]);
- }
-
- public function actionAjaxInfos($date = '')
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $distributionManager = $this->getDistributionManager();
- $orderManager = $this->getOrderManager();
- $productManager = $this->getProductManager();
- $userManager = $this->getUserManager();
- $pointSaleManager = $this->getPointSaleManager();
-
- $producer = $this->getProducerCurrent();
- $format = 'Y-m-d';
- $dateObject = DateTime::createFromFormat($format, $date);
-
- $json = ['distribution' => [], 'products' => []];
- $json['means_payment'] = MeanPayment::getAll();
- $json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
- $json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);
-
- if ($dateObject && $dateObject->format($format) === $date) {
- $distribution = $distributionManager->createDistributionIfNotExist($date);
- $ordersArray = $orderManager->findOrdersByDistribution($distribution);
- $ordersArrayObject = $ordersArray;
- $productsArray = $productManager->findProductsByDistributionAsArray($distribution);
-
- $json['products'] = $this->buildAjaxInfosResponseProducts($producer, $distribution, $productsArray, $ordersArray);
- $json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject, $productsArray);
- $json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
- $json['points_sale'] = $this->buildAjaxInfosResponsePointsSale($distribution);
- $json['delivery_notes'] = $this->buildAjaxInfosResponseDeliveryNotes($date);
- $json['order_create'] = $this->buildAjaxInfosResponseOrderCreate($distribution, $productsArray);
- $json['users'] = $userManager->findUsers();
- $json['one_distribution_week_active'] = $distributionManager->isOneDistributionWeekActive($date);
- $json['tiller_is_synchro'] = $this->buildAjaxInfosResponseTiller($producer, $date);
- $json['missing_subscriptions'] = $this->buildAjaxInfosResponseMissingSubscriptions($date, $distribution, $ordersArrayObject);
- }
-
- return $json;
- }
-
- public function buildAjaxInfosResponsePointsSale(Distribution $distribution)
- {
- $pointSaleManager = $this->getPointSaleManager();
- $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
-
- $pointsSaleArray = $pointSaleManager->findPointSalesByDistributionAsArray($distribution);
-
- // @TODO : à gérer autrement
- foreach($pointsSaleArray as &$pointSaleArray) {
- $idPointSale = $pointSaleArray['id'];
- $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
- if(!isset($pointSaleArray['pointSaleDistribution']) || !$pointSaleArray['pointSaleDistribution'] || !count($pointSaleArray['pointSaleDistribution'])) {
- $pointSaleDistribution = $pointSaleDistributionManager->createPointSaleDistributionIfNotExist($distribution, $pointSale);
- $pointSaleArray['pointSaleDistribution'] = [
- [
- 'id_distribution' => $pointSaleDistribution->id_distribution,
- 'id_point_sale' => $pointSaleDistribution->id_point_sale,
- 'delivery' => $pointSaleDistribution->delivery
- ]
- ];
- }
- }
-
- return $pointsSaleArray;
- }
-
- public function buildAjaxInfosResponseProducts(Producer $producer, Distribution $distribution, array &$productsArray, array $ordersArray)
- {
- $distributionManager = $this->getDistributionManager();
- $orderManager = $this->getOrderManager();
- $productManager = $this->getProductManager();
-
- foreach ($productsArray as &$theProduct) {
- $productObject = $productManager->findOneProductById($theProduct['id']);
- $quantityOrder = $orderManager->getProductQuantity($productObject, $ordersArray);
- $theProduct['quantity_ordered'] = $quantityOrder;
-
- if (!isset($theProduct['productDistribution'][0])) {
- $theProduct['productDistribution'][0] = $distributionManager->addProduct($distribution, $productObject);
- }
-
- if (!is_numeric($theProduct['productDistribution'][0]['quantity_max'])) {
- $theProduct['quantity_remaining'] = null;
- } else {
- $theProduct['quantity_remaining'] = $theProduct['productDistribution'][0]['quantity_max'] - $quantityOrder;
- }
-
- $theProduct['quantity_form'] = 0;
-
- if (!isset($theProduct['taxRate'])) {
- $theProduct['taxRate'] = $producer->taxRate;
- }
- }
-
- return $productsArray;
- }
-
- public function buildAjaxInfosResponseProducer($producer)
- {
- return [
- 'credit' => $producer->credit,
- 'tiller' => $producer->tiller,
- 'option_display_export_grid' => $producer->option_display_export_grid
- ];
- }
-
- public function buildAjaxInfosResponseDistributions($dateObject)
- {
- $numberOfLoadedMonthes = '3 month';
- if (is_object($dateObject)) {
- $dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
- $dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
- } else {
- $dateBegin = strtotime('-' . $numberOfLoadedMonthes);
- $dateEnd = strtotime('+' . $numberOfLoadedMonthes);
- }
-
- return Distribution::searchAll([
- 'active' => 1
- ], [
- 'conditions' => [
- 'date > :date_begin',
- 'date < :date_end'
- ],
- 'params' => [
- ':date_begin' => date(
- 'Y-m-d',
- $dateBegin
- ),
- ':date_end' => date(
- 'Y-m-d',
- $dateEnd
- ),
- ],
- 'as_array' => true
- ]);
- }
-
- public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray, array $productsArray)
- {
- $productManager = $this->getProductManager();
- $orderManager = $this->getOrderManager();
- $distributionJsonData = [
- 'id' => $distribution->id,
- 'active' => $distribution->active,
- 'url_report' => $this->getUrlManagerBackend()->createUrl(
- ['distribution/report', 'date' => $distribution->date]
- ),
- 'url_report_grid' => $this->getUrlManagerBackend()->createUrl(
- ['distribution/report-grid', 'date' => $distribution->date]
- ),
- ];
-
- // montant et poids des commandes
- $revenues = 0;
- $weight = 0;
- if ($ordersArray) {
- foreach ($ordersArray as $order) {
- $orderManager->initOrder($order);
- if (is_null($order->date_delete)) {
- $revenues += $orderManager->getOrderAmountWithTax($order);
- $weight += $order->weight;
- }
- }
- }
- $distributionJsonData['revenues'] = Price::format($revenues);
- $distributionJsonData['weight'] = number_format($weight, 2);
- $distributionJsonData['potential_revenues'] = Price::format($productManager->getProductDistributionPotentialRevenues($productsArray));
- $distributionJsonData['potential_weight'] = number_format($productManager->getProductDistributionPotentialWeight($productsArray), 2);
-
- return $distributionJsonData;
- }
-
- public function buildAjaxInfosResponseOrders(array $ordersArray, array $productsArray)
- {
- $userManager = $this->getUserManager();
- $orderManager = $this->getOrderManager();
- $creditHistoryManager = $this->getCreditHistoryManager();
-
- if ($ordersArray) {
- foreach ($ordersArray as &$order) {
-
- $orderManager->initOrder($order);
-
- $productOrderArray = [];
- foreach ($order->productOrder as $productOrder) {
- $productOrderArray[$productOrder->id_product] = [
- 'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
- 'unit' => $productOrder->unit,
- 'price' => number_format($productOrder->price, 5),
- 'invoice_price' => number_format($productOrder->invoice_price, 5),
- 'price_with_tax' => Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value),
- ];
- }
-
- foreach ($productsArray as $product) {
- if (!isset($productOrderArray[$product['id']])) {
- $productOrderArray[$product['id']] = [
- 'quantity' => 0,
- 'unit' => $product['unit'],
- 'price' => number_format($product['price'], 5),
- 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
- ];
- }
- }
-
- $creditHistoryArray = [];
-
- foreach ($order->creditHistory as $creditHistory) {
- $creditHistoryArray[] = [
- 'date' => date('d/m/Y H:i:s', strtotime($creditHistory->date)),
- 'user' => $userManager->getUsername($creditHistory->getUserObject()),
- 'user_action' => $creditHistoryManager->getStrUserAction($creditHistory),
- 'wording' => $creditHistoryManager->getStrWording($creditHistory),
- 'debit' => ($creditHistoryManager->isTypeDebit($creditHistory) ? '- ' . $creditHistoryManager->getAmount(
- $creditHistory,
- Order::AMOUNT_TOTAL,
- true
- ) : ''),
- 'credit' => ($creditHistoryManager->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryManager->getAmount(
- $creditHistory,
- Order::AMOUNT_TOTAL,
- true
- ) : '')
- ];
- }
-
- $arrayCreditUser = [];
- if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
- $arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
- }
-
- $oneProductUnactivated = false;
- foreach ($order->productOrder as $productOrder) {
- foreach ($productsArray as $product) {
- if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
- $oneProductUnactivated = true;
- }
- }
- }
-
- $order = array_merge($order->getAttributes(), [
- 'selected' => false,
- 'weight' => $order->weight,
- 'amount' => Price::numberTwoDecimals($orderManager->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL)),
- 'amount_paid' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_PAID)),
- 'amount_remaining' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_REMAINING)),
- 'amount_surplus' => Price::numberTwoDecimals($orderManager->getOrderAmount($order, Order::AMOUNT_SURPLUS)),
- 'user' => (isset($order->user)) ? array_merge(
- $order->user->getAttributes(),
- $arrayCreditUser
- ) : null,
- 'pointSale' => $order->pointSale ? ['id' => $order->pointSale->id, 'name' => $order->pointSale->name] : null,
- 'productOrder' => $productOrderArray,
- 'creditHistory' => $creditHistoryArray,
- 'oneProductUnactivated' => $oneProductUnactivated,
- 'isLinkedToValidDocument' => $orderManager->isLinkedToValidDocument($order),
- ]);
- }
- }
-
- return $ordersArray;
- }
-
- public function buildAjaxInfosResponseDeliveryNotes(string $date)
- {
- $deliveryNotesArray = DeliveryNote::searchAll([
- 'distribution.date' => $date,
- ], [
- 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
- ]);
- $deliveryNotesByPointSaleArray = [];
- foreach ($deliveryNotesArray as $deliveryNote) {
- if (isset($deliveryNote->orders[0])) {
- $deliveryNotesByPointSaleArray[$deliveryNote->orders[0]->id_point_sale] =
- $deliveryNote->getAttributes();
- }
- }
- return $deliveryNotesByPointSaleArray;
- }
-
- public function buildAjaxInfosResponseOrderCreate(Distribution $distribution, array $productsArray)
- {
- $pointSaleManager = $this->getPointSaleManager();
- $pointSaleDefault = $pointSaleManager->findOnePointSaleDefaultByDistribution($distribution);
-
- $productOrderArray = [];
- foreach ($productsArray as $product) {
- $productOrderArray[$product['id']] = [
- 'quantity' => 0,
- 'unit' => $product['unit'],
- 'price' => number_format($product['price'], 5),
- 'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
- ];
- }
- return [
- 'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : 0,
- 'id_user' => 0,
- 'username' => '',
- 'comment' => '',
- 'productOrder' => $productOrderArray
- ];
- }
-
- public function buildAjaxInfosResponseTiller(Producer $producer, string $date)
- {
- if ($producer->tiller) {
- $tiller = new Tiller();
- return (int) $tiller->isSynchro($date);
- }
-
- return false;
- }
-
- public function buildAjaxInfosResponseMissingSubscriptions(string $date, Distribution $distribution, array $ordersArray)
- {
- $subscriptionManager = $this->getSubscriptionManager();
- $missingSubscriptionsArray = [];
-
- $arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
- if ($distribution->active) {
- foreach ($arraySubscriptions as $subscription) {
- if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArray)
- && $subscription->productSubscription && count($subscription->productSubscription)
- && $subscription->id_point_sale && $subscription->id_point_sale > 0) {
- $missingSubscriptionsArray[] = [
- 'username' => $subscriptionManager->getUsername($subscription)
- ];
- }
- }
- }
-
- return $missingSubscriptionsArray;
- }
-
- public function actionAjaxPointSaleFavorite($idUser)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $userManager = $this->getUserManager();
- $orderManager = $this->getOrderManager();
-
- $user = $userManager->findOneUserById($idUser);
- $idFavoritePointSale = 0;
-
- if($user) {
- $favoritePointSale = $orderManager->getUserFavoritePointSale($user);
- if ($favoritePointSale) {
- $idFavoritePointSale = $favoritePointSale->id;
- }
- }
-
- return [
- 'id_favorite_point_sale' => $idFavoritePointSale
- ];
- }
-
- public function actionAjaxUpdateProductOrder(
- $idDistribution,
- $idUser = false,
- $idPointSale = false,
- $idOrder = false
- )
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $distributionManager = $this->getDistributionManager();
- $orderManager = $this->getOrderManager();
- $userManager = $this->getUserManager();
- $pointSaleManager = $this->getPointSaleManager();
- $productManager = $this->getProductManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
- $distribution = $distributionManager->findOneDistributionById($idDistribution);
- $user = $userManager->findOneUserById($idUser);
- $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
-
- $productsArray = Product::find()
- ->where([
- 'id_producer' => GlobalParam::getCurrentProducerId(),
- ])->joinWith([
- 'productPrice',
- 'productDistribution' => function ($q) use ($distribution) {
- $q->where(['id_distribution' => $distribution->id]);
- }
- ])->all();
-
- $productOrderArray = [];
- foreach ($productsArray as $product) {
- $priceArray = $productManager->getPriceArray($product, $user, $pointSale);
-
- $quantity = 0;
- $invoicePrice = null;
-
- if (isset($order->productOrder)) {
- foreach ($order->productOrder as $productOrder) {
- if ($productOrder->id_product == $product['id']) {
- if ($productOrder->invoice_price) {
- $invoicePrice = number_format($productOrder->invoice_price, 5);
- } else {
- $invoicePrice = number_format($productOrder->price, 5);
- }
- $quantity = $productOrder->quantity;
- }
- }
- }
-
- $productOrderArray[$product['id']] = [
- 'quantity' => $quantity,
- 'unit' => $product->unit,
- 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
- 'prices' => $priceArray,
- 'active' => $product->productDistribution[0]->active
- && (!$pointSale || $productManager->isAvailableOnPointSale($product, $pointSale)),
- 'invoice_price' => $invoicePrice
- ];
- }
-
- return $productOrderArray;
- }
-
- public function actionAjaxUpdateInvoicePrices($idOrder)
- {
- $orderManager = $this->getOrderManager();
- $userProducerManager = $this->getUserProducerManager();
- $productManager = $this->getProductManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
-
- if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
- $userProducer = null;
- if ($order->id_user) {
- $userProducer = $userProducerManager->findOneUserProducer($order->user);
- }
- foreach ($order->productOrder as $productOrder) {
- $invoicePrice = $productManager->getPrice($productOrder->product, [
- 'user' => $order->user ?: null,
- 'point_sale' => $order->pointSale,
- 'user_producer' => $userProducer,
- 'quantity' => $productOrder->quantity
- ]);
-
- if ($invoicePrice != $productOrder->price) {
- $productOrder->invoice_price = $invoicePrice;
- } else {
- $productOrder->invoice_price = null;
- }
- $productOrder->save();
- }
- }
- }
-
- /**
- * Génére un PDF récapitulatif des des commandes d'un producteur pour une
- * date donnée (Méthode appelable via CRON)
- *
- * @param string $date
- * @param boolean $save
- * @param integer $idProducer
- * @param string $key
- * @return Pdf|null
- */
- public function actionReportCron($date = '', $save = false, $idProducer = 0, $key = '')
- {
- if ($key == '64ac0bdab7e9f5e48c4d991ec5201d57') {
- $this->actionReport($date, $save, $idProducer);
- }
- }
-
- /**
- * Génére un PDF récapitulatif des commandes d'un producteur pour une
- * date donnée.
- */
- public function actionReport(string $date = '', bool $save = false, int $idProducer = 0, string $type = "pdf")
- {
- if (!$idProducer) {
- $idProducer = $this->getProducerCurrent()->id;
- }
-
- $distributionManager = $this->getDistributionManager();
- $producerManager = $this->getProducerManager();
- $producerCurrent = $producerManager->findOneProducerById($idProducer);
- $this->getLogic()->setProducerContext($producerCurrent);
- $distribution = $distributionManager->findOneDistribution($date);
-
- if ($distribution) {
- if ($type == 'pdf') {
- return $distributionManager->generateDistributionReportPdf($distribution, $save);
- }
- elseif ($type == 'csv') {
- $distributionManager->generateDistributionReportCsv($distribution);
- }
- }
- }
-
- public function actionReportGrid(string $date = '', bool $save = false, int $idProducer = 0)
- {
- if (!$idProducer) {
- $idProducer = $this->getProducerCurrent()->id;
- }
-
- $distributionManager = $this->getDistributionManager();
- $producerManager = $this->getProducerManager();
- $producerCurrent = $producerManager->findOneProducerById($idProducer);
- $this->getLogic()->setProducerContext($producerCurrent);
- $distribution = $distributionManager->findOneDistribution($date);
-
- if ($distribution) {
- return $distributionManager->generateDistributionReportGridPdf($distribution, $save);
- }
- }
-
- public function actionAjaxProcessProductQuantityMax($idDistribution, $idProduct, $quantityMax)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $productDistributionManager = $this->getProductDistributionManager();
- $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
- $productDistributionManager->updateProductDistributionQuantityMax($productDistribution, (float) $quantityMax);
- return ['success'];
- }
-
- public function actionAjaxProcessActiveProduct(int $idDistribution, int $idProduct, int $active)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $productDistributionManager = $this->getProductDistributionManager();
- $productDistribution = $this->getProductDistribution($idProduct, $idDistribution);
- $productDistributionManager->updateProductDistributionActive($productDistribution, $active);
- return ['success'];
- }
-
- public function actionAjaxProcessActivePointSale(int $idDistribution, int $idPointSale, int $delivery)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $distributionManager = $this->getDistributionManager();
- $pointSaleManager = $this->getPointSaleManager();
- $pointSaleDistributionManager = $this->getPointSaleDistributionManager();
-
- $pointSaleDistribution = $pointSaleDistributionManager->findOnePointSaleDistribution(
- $distributionManager->findOneDistributionById($idDistribution),
- $pointSaleManager->findOnePointSaleById($idPointSale)
- );
- $pointSaleDistribution->delivery = $delivery;
- $pointSaleDistributionManager->update($pointSaleDistribution);
-
- return ['success'];
- }
-
- public function getProductDistribution(int $idProduct, int $idDistribution)
- {
- $distributionManager = $this->getDistributionManager();
- $productManager = $this->getProductManager();
- $productDistributionManager = $this->getProductDistributionManager();
-
- return $productDistributionManager->findOneProductDistribution(
- $distributionManager->findOneDistributionById($idDistribution),
- $productManager->findOneProductById($idProduct)
- );
- }
-
- /**
- * Active/désactive un jour de distribution.
- *
- * @param integer $idDistribution
- * @param string $date
- * @param boolean $active
- * @return array
- */
- public function actionAjaxProcessActiveDistribution(int $idDistribution = 0, string $date = '', bool $active = false)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $distributionManager = $this->getDistributionManager();
-
- if ($idDistribution) {
- $distribution = $distributionManager->findOneDistributionById($idDistribution);
- }
-
- $format = 'Y-m-d';
- $dateObject = DateTime::createFromFormat($format, $date);
- if ($dateObject && $dateObject->format($format) === $date) {
- $distribution = $distributionManager->createDistributionIfNotExist($date);
- }
-
- if (isset($distribution) && $distribution) {
- $distributionManager->activeDistribution($distribution, $active);
- return ['success'];
- }
-
- return ['error'];
- }
-
- /**
- * Change l'état d'une semaine de production (activé, désactivé).
- *
- * @param string $date
- * @param integer $active
- */
- public function actionAjaxProcessActiveWeekDistribution($date, $active)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $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));
-
- $pointsSaleArray = PointSale::searchAll(['status' => 1]);
-
- $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->actionAjaxProcessActiveDistribution(0, $dateMonday, $active);
- }
- if ($activeTuesday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateTuesday, $active);
- }
- if ($activeWednesday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateWednesday, $active);
- }
- if ($activeThursday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateThursday, $active);
- }
- if ($activeFriday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateFriday, $active);
- }
- if ($activeSaturday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateSaturday, $active);
- }
- if ($activeSunday || !$active) {
- $this->actionAjaxProcessActiveDistribution(0, $dateSunday, $active);
- }
-
- return ['success'];
- }
-
- /**
- * Ajoute les commandes récurrentes pour une date donnée.
- *
- * @param string $date
- */
- public function actionAjaxProcessAddSubscriptions($date)
- {
- $ordersArray = $this->getOrderManager()->createAllOrdersFromSubscriptions($date, true);
-
- if($ordersArray && count($ordersArray)) {
- return Ajax::responseSuccess('Les abonnements ont bien été importés.');
- }
-
- return Ajax::responseError('Aucun abonnement à importer.');
- }
-
- /**
- * Synchronise les commandes avec la plateforme Tiller pour une date donnée.
- *
- * @param string $date
- */
- public function actionAjaxProcessSynchroTiller($date)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $producerManager = $this->getProducerManager();
- $productOrderManager = $this->getProductOrderManager();
- $orderManager = $this->getOrderManager();
-
- $return = [];
- $producerTiller = $producerManager->getConfig('tiller');
-
- if ($producerTiller) {
- $tiller = new Tiller();
- $isSynchro = $tiller->isSynchro($date);
-
- if (!$isSynchro) {
- $orders = Order::searchAll([
- 'distribution.date' => $date,
- 'order.tiller_synchronization' => 1
- ], [
- 'conditions' => 'date_delete IS NULL'
- ]);
-
- $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);
-
- if ($orders && count($orders)) {
- foreach ($orders as $order) {
- $orderManager->initOrder($order);
- $lines = [];
- foreach ($order->productOrder as $productOrder) {
- $lines[] = [
- 'name' => $productOrder->product->name,
- 'price' => $productOrderManager->getPriceWithTax($productOrder) * 100 * $productOrder->quantity,
- 'tax' => $productOrder->taxRate->value * 100,
- 'date' => $strDate,
- 'quantity' => $productOrder->quantity
- ];
- }
-
- $typePaymentTiller = '';
- if ($order->mean_payment == MeanPayment::MONEY) {
- $typePaymentTiller = 'CASH';
- }
- if ($order->mean_payment == MeanPayment::CREDIT_CARD
- || $order->mean_payment == MeanPayment::CREDIT
- || $order->mean_payment == MeanPayment::TRANSFER
- || $order->mean_payment == MeanPayment::OTHER) {
- $typePaymentTiller = 'CARD';
- }
- if ($order->mean_payment == MeanPayment::CHEQUE) {
- $typePaymentTiller = 'BANK_CHECK';
- }
- if (!strlen($typePaymentTiller) || !$order->mean_payment) {
- $typePaymentTiller = 'CASH';
- }
-
- $returnTiller = $tiller->postOrder([
- 'externalId' => $order->id,
- 'type' => 1,
- 'status' => 'IN_PROGRESS',
- 'openDate' => $strDate,
- 'closeDate' => $strDate,
- 'lines' => $lines,
- 'payments' => [
- [
- 'type' => $typePaymentTiller,
- 'amount' => $orderManager->getOrderAmountWithTax(
- $order,
- Order::AMOUNT_PAID
- ) * 100,
- 'status' => 'ACCEPTED',
- 'date' => $strDate
- ]
- ]
- ]);
-
- $returnTillerObject = json_decode($returnTiller);
- $order->tiller_external_id = '' . $returnTillerObject->id;
- $order->save();
-
- $return[] = $returnTiller;
- }
- }
- }
- }
-
- return $return;
- }
-
- public function actionAjaxGenerateDeliveryNote(int $idOrder)
- {
- $this->generateDeliveryNote($idOrder);
- return Ajax::responseSuccess('Bon de livraison généré');
- }
-
- public function actionAjaxGenerateDeliveryNotePointSale($idOrders)
- {
- $orderManager = $this->getOrderManager();
- $deliveryNoteManager = $this->getDeliveryNoteManager();
-
- if (strlen($idOrders)) {
- $idOrders = json_decode($idOrders, true);
-
- if (is_array($idOrders) && count($idOrders) > 0) {
- reset($idOrders);
- $firstOrder = $orderManager->findOneOrderById((int)$idOrders[key($idOrders)]);
- $ordersArray = Order::searchAll(['id' => $idOrders,]);
- $deliveryNote = $deliveryNoteManager->getOneDeliveryNoteExistingFromOrders($ordersArray);
- $isUpdate = (bool) $deliveryNote;
-
- if ($deliveryNote && $deliveryNoteManager->isStatusValid($deliveryNote)) {
- return Ajax::responseError('Vous ne pouvez pas modifier un bon de livraison déjà validé.');
- }
-
- if(!$deliveryNote && $firstOrder && !$firstOrder->pointSale->id_user) {
- return Ajax::responseError("Vous devez définir un contact de facturation pour ce point de vente.");
- }
-
- if ($firstOrder) {
- if (!$deliveryNote) {
- $deliveryNoteManager->createDeliveryNoteForPointSale(
- $firstOrder->pointSale,
- $firstOrder->distribution,
- $idOrders
- );
- }
-
- return Ajax::responseSuccess('Bon de livraison ' . ($isUpdate ? 'modifié' : 'généré'));
- }
- }
- }
-
- return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
- }
-
- public function actionAjaxGenerateDeliveryNoteEachUser($idOrders)
- {
- if (strlen($idOrders)) {
- $idOrders = json_decode($idOrders, true);
-
- if (is_array($idOrders) && count($idOrders) > 0) {
- foreach ($idOrders as $idOrder) {
- $this->generateDeliveryNote($idOrder);
- }
- }
-
- return Ajax::responseSuccess('Bon(s) de livraison généré(s)');
- }
-
- return Ajax::responseError('Une erreur est survenue lors de la génération du bon de livraison.');
- }
-
- public function generateDeliveryNote(int $idOrder)
- {
- $orderManager = $this->getOrderManager();
- $deliveryNoteManager = $this->getDeliveryNoteManager();
-
- $order = $orderManager->findOneOrderById($idOrder);
- if ($orderManager->isOrderFromProducer($order) && $order->id_user) {
- $deliveryNoteManager->createDeliveryNoteForOrder($order);
- }
- }
-
- public function actionAjaxValidateDeliveryNotes($idOrders)
- {
- $orderManager = $this->getOrderManager();
- $deliveryNoteManager = $this->getDeliveryNoteManager();
-
- if (strlen($idOrders)) {
- $idOrders = json_decode($idOrders, true);
- if (is_array($idOrders) && count($idOrders) > 0) {
- foreach ($idOrders as $idOrder) {
- $order = $orderManager->findOneOrderById($idOrder);
- if ($orderManager->isOrderFromProducer($order)) {
- $deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById((int) $order->id_delivery_note);
- if($deliveryNote) {
- $deliveryNoteManager->validateDocument($deliveryNote);
- }
- }
- }
-
- return Ajax::responseSuccess('Bon(s) de livraison validé(s)');
- }
- }
-
- return Ajax::responseError('Une erreur est survenue lors de la validation des bons de livraison');
- }
- }
|