[ '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(); $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); $json['units'] = Product::$unitsArray; if ($dateObject && $dateObject->format($format) === $date) { $distribution = $distributionManager->createDistributionIfNotExist($date); $ordersArray = $orderManager->findOrdersByDistribution($distribution); $ordersArrayObject = $ordersArray; $productsArray = $productManager->findProductsByDistribution($distribution, false); $json['products'] = $this->buildAjaxInfosResponseProducts($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) { $producerManager = $this->getProducerManager(); $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 ] ]; } $pointSaleArray['credit_functioning'] = $producerManager->getPointSaleCreditFunctioning($pointSale); } return $pointsSaleArray; } public function buildAjaxInfosResponseProducts(Distribution $distribution, array $productsArray, array $ordersArray) { $distributionManager = $this->getDistributionManager(); $orderManager = $this->getOrderManager(); $jsonProductsArray = []; foreach ($productsArray as $product) { $jsonProduct = $product->getAttributes(); $quantityOrder = $orderManager->getProductQuantity($product, $ordersArray); $jsonProduct['quantity_ordered'] = $quantityOrder; if (!isset($product->productDistribution[0])) { $productDistributionAdd = $distributionManager->addProduct($distribution, $product); if($productDistributionAdd) { $jsonProduct['productDistribution'][0] = $productDistributionAdd->getAttributes(); $product->populateRelation('productDistribution', [$productDistributionAdd]); } } else { foreach($product->productDistribution as $key => $productDistribution) { $jsonProduct['productDistribution'][$key] = $productDistribution->getAttributes(); } } if (!isset($product->productDistribution[0]) || !is_numeric($product->productDistribution[0]->quantity_max)) { $jsonProduct['quantity_remaining'] = null; } else { $jsonProduct['quantity_remaining'] = $product->productDistribution[0]->quantity_max - $quantityOrder; } $jsonProduct['quantity_form'] = 0; if ($product->taxRate) { $jsonProduct['taxRate'] = $product->taxRate->getAttributes(); } else { $jsonProduct['taxRate'] = $this->getProducerCurrent()->taxRate->getAttributes(); } $jsonProductsArray[] = $jsonProduct; } return $jsonProductsArray; } 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(); $paymentManager = $this->getPaymentManager(); 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']), ]; } } $paymentArray = []; foreach ($order->payment as $payment) { $paymentArray[] = [ 'type' => $payment->type, 'wording_type' => $paymentManager->getStrType($payment), 'mean_payment' => $payment->mean_payment, 'wording_mean_payment' => $paymentManager->getStrMeanPayment($payment), 'date' => date('d/m/Y H:i:s', strtotime($payment->date)), 'user' => $payment->getUserObject() ? $userManager->getUsername($payment->getUserObject()) : '', 'user_action' => $paymentManager->getStrUserAction($payment), 'wording' => $paymentManager->getStrWording($payment, $order), 'amount' => $paymentManager->getAmount($payment, Order::AMOUNT_TOTAL, true), ]; } $arrayCreditUser = []; if(isset($order->user)) { $arrayCreditUser['credit'] = $userManager->getCredit($order->user); $arrayCreditUser['credit_active'] = $userManager->getCreditActive($order->user); } $oneProductUnactivated = false; foreach ($order->productOrder as $productOrder) { foreach ($productsArray as $product) { if ($productOrder->id_product == $product['id'] && isset($product['productDistribution'][0]) && !$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, 'paymentsArray' => $paymentArray, 'oneProductUnactivated' => $oneProductUnactivated, 'isLinkedToValidDocument' => $orderManager->isLinkedToValidDocument($order), 'isCreditAutoPayment' => $orderManager->isCreditAutoPayment($order), 'isCreditContext' => $orderManager->isCreditContext($order), 'isPaid' => $orderManager->isOrderPaid($order), 'isPaidViaInvoice' => $orderManager->isOrderPaidViaInvoice($order), 'paymentLabelShort' => $orderManager->getPaymentLabelShort($order), 'isCreditFunctioningMandatory' => $orderManager->isOrderCreditFunctioningMandatory($order), 'isCreditFunctioningUser' => $orderManager->isOrderCreditFunctioningUser($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, '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'); } }