Browse Source

[Technique] Administration : refactoring DistributionController #1173

feature/souke
Guillaume Bourgeois 1 year ago
parent
commit
863684274c
4 changed files with 292 additions and 251 deletions
  1. +230
    -248
      backend/controllers/DistributionController.php
  2. +1
    -0
      backend/views/distribution/index.php
  3. +37
    -0
      common/logic/Distribution/Distribution/Repository/DistributionRepository.php
  4. +24
    -3
      common/logic/PointSale/PointSale/Repository/PointSaleRepository.php

+ 230
- 248
backend/controllers/DistributionController.php View File

@@ -49,6 +49,7 @@ 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;
@@ -114,91 +115,28 @@ class DistributionController extends BackendController
$distributionManager = $this->getDistributionManager();
$orderManager = $this->getOrderManager();
$productManager = $this->getProductManager();
$creditHistoryManager = $this->getCreditHistoryManager();
$userManager = $this->getUserManager();
$subscriptionManager = $this->getSubscriptionManager();
$pointSaleManager = $this->getPointSaleManager();

$producer = $this->getProducerCurrent();

$json = [
'distribution' => [],
'products' => []
];

$format = 'Y-m-d';
$dateObject = DateTime::createFromFormat($format, $date);

$numberOfLoadedMonthes = '3 month';
if (is_object($dateObject)) {
$dateBegin = strtotime('-' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
$dateEnd = strtotime('+' . $numberOfLoadedMonthes, $dateObject->getTimestamp());
} else {
$dateBegin = strtotime('-' . $numberOfLoadedMonthes);
$dateEnd = strtotime('+' . $numberOfLoadedMonthes);
}

$json['producer'] = [
'credit' => $producer->credit,
'tiller' => $producer->tiller,
'option_display_export_grid' => $producer->option_display_export_grid
];

$json = ['distribution' => [], 'products' => []];
$json['means_payment'] = MeanPayment::getAll();

$distributionsArray = 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
),
],
]);
$json['distributions'] = $distributionsArray;
$json['producer'] = $this->buildAjaxInfosResponseProducer($producer);
$json['distributions'] = $this->buildAjaxInfosResponseDistributions($dateObject);

if ($dateObject && $dateObject->format($format) === $date) {
$distribution = $distributionManager->createDistributionIfNotExist($date);

$json['distribution'] = [
'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]
),
];

$distribution = $distributionManager->createDistributionIfNotExist($date);
$ordersArray = Order::searchAll([
'distribution.id' => $distribution->id,
], [
'orderby' => 'user.lastname ASC, user.name ASC'
]);
$ordersArrayObject = $ordersArray;

// 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;
}
}
}
$json['distribution']['revenues'] = Price::format($revenues);
$json['distribution']['weight'] = number_format($weight, 2);

// products
$productsQuery = Product::find()
@@ -223,7 +161,6 @@ class DistributionController extends BackendController
$theProduct['quantity_ordered'] = $quantityOrder;

if (!isset($theProduct['productDistribution'][0])) {
$theProductObject = (object)$theProduct;
$theProduct['productDistribution'][0] = $distributionManager->addProduct($distribution, $productObject);
}

@@ -245,212 +182,257 @@ class DistributionController extends BackendController
}
}

$json['products'] = $productsArray;

$json['distribution'] = $this->buildAjaxInfosResponseDistribution($distribution, $ordersArrayObject);
$json['distribution']['potential_revenues'] = Price::format($potentialRevenues);
$json['distribution']['potential_weight'] = number_format($potentialWeight, 2);

$json['products'] = $productsArray;
$json['orders'] = $this->buildAjaxInfosResponseOrders($ordersArray, $productsArray);
$json['points_sale'] = $pointSaleManager->findPointSalesByDistributionAsArray($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);
}

// orders as array
$ordersArrayObject = $ordersArray;
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),
];
}
return $json;
}

foreach ($productsArray as $product) {
if (!isset($productOrderArray[$product['id']])) {
$productOrderArray[$product['id']] = [
'quantity' => 0,
'unit' => $product['unit'],
'price' => number_format($product['price'], 3),
'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
];
}
}
public function buildAjaxInfosResponseProducer($producer)
{
return [
'credit' => $producer->credit,
'tiller' => $producer->tiller,
'option_display_export_grid' => $producer->option_display_export_grid
];
}

$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) ? '-&nbsp;' . $creditHistoryManager->getAmount(
$creditHistory,
Order::AMOUNT_TOTAL,
true
) : ''),
'credit' => ($creditHistoryManager->isTypeCredit($creditHistory) ? '+&nbsp;' . $creditHistoryManager->getAmount(
$creditHistory,
Order::AMOUNT_TOTAL,
true
) : '')
];
}
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);
}

$arrayCreditUser = [];
if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
$arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
}
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
]);
}

$oneProductUnactivated = false;
foreach ($order->productOrder as $productOrder) {
foreach ($productsArray as $product) {
if ($productOrder->id_product == $product['id'] && !$product['productDistribution'][0]['active']) {
$oneProductUnactivated = true;
}
}
}
public function buildAjaxInfosResponseDistribution(Distribution $distribution, array $ordersArray)
{
$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]
),
];

$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),
]);
// 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);

$json['orders'] = $ordersArray;
return $distributionJsonData;
}

$pointsSaleArray = PointSale::find()
->joinWith([
'pointSaleDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]);
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'], 3),
'price_with_tax' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
];
}
])
->where([
'id_producer' => $producer->id,
'status' => 1
])
->asArray()
->all();
}

$idPointSaleDefault = 0;
foreach ($pointsSaleArray as $pointSale) {
if ($pointSale['default']) {
$idPointSaleDefault = $pointSale['id'];
$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) ? '-&nbsp;' . $creditHistoryManager->getAmount(
$creditHistory,
Order::AMOUNT_TOTAL,
true
) : ''),
'credit' => ($creditHistoryManager->isTypeCredit($creditHistory) ? '+&nbsp;' . $creditHistoryManager->getAmount(
$creditHistory,
Order::AMOUNT_TOTAL,
true
) : '')
];
}
}
$json['points_sale'] = $pointsSaleArray;

// bons de livraison
$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();
$arrayCreditUser = [];
if (isset($order->user) && isset($order->user->userProducer) && isset($order->user->userProducer[0])) {
$arrayCreditUser['credit'] = $order->user->userProducer[0]->credit;
}
}
$json['delivery_notes'] = $deliveryNotesByPointSaleArray;

// order create
$productOrderArray = [];
foreach ($productsArray as $product) {
$productOrderArray[$product['id']] = [
'quantity' => 0,
'unit' => $product['unit'],
'price' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
];
}
$json['order_create'] = [
'id_point_sale' => $idPointSaleDefault,
'id_user' => 0,
'username' => '',
'comment' => '',
'productOrder' => $productOrderArray
];

// utilisateurs
$usersArray = $userManager->findUsers();

$json['users'] = $usersArray;

// 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;
$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),
]);
}
}

$json['one_distribution_week_active'] = $oneDistributionWeekActive;
return $ordersArray;
}

// tiller
if ($producer->tiller) {
$tiller = new Tiller();
$json['tiller_is_synchro'] = (int)$tiller->isSynchro($date);
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;
}

// abonnements manquants
$arraySubscriptions = $subscriptionManager->findSubscriptionsByDate($date);
$json['missing_subscriptions'] = [];
if ($distribution->active) {
foreach ($arraySubscriptions as $subscription) {
if (!$subscriptionManager->hasOrderAlreadyExist($subscription, $ordersArrayObject)
&& $subscription->productSubscription && count($subscription->productSubscription)
&& $subscription->id_point_sale && $subscription->id_point_sale > 0) {
$json['missing_subscriptions'][] = [
'username' => $subscriptionManager->getUsername($subscription)
];
}
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' => Price::getPriceWithTax($product['price'], $product['taxRate']['value']),
];
}
return [
'id_point_sale' => $pointSaleDefault ? $pointSaleDefault->id : false,
'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 $json;
return $missingSubscriptionsArray;
}

public function actionAjaxPointSaleFavorite($idUser)

+ 1
- 0
backend/views/distribution/index.php View File

@@ -303,6 +303,7 @@ $this->setPageTitle('Distributions') ;
</div>

<div class="alert alert-danger" v-if="distribution && !distribution.active && orders && orders.length > 0">
{{ distribution }}
Attention, ce jour de distribution n'est pas activé et vous avez quand même des commandes enregistrées.
</div>


+ 37
- 0
common/logic/Distribution/Distribution/Repository/DistributionRepository.php View File

@@ -2,6 +2,7 @@

namespace common\logic\Distribution\Distribution\Repository;

use common\helpers\GlobalParam;
use common\logic\AbstractRepository;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Distribution\Distribution\Service\DistributionSolver;
@@ -125,4 +126,40 @@ class DistributionRepository extends AbstractRepository
return false;
}

public function isOneDistributionWeekActive(string $date): bool
{
$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' => $this->getProducerContextId(),
'active' => 1,
])
->andWhere([
'or',
['date' => $dateMonday],
['date' => $dateTuesday],
['date' => $dateWednesday],
['date' => $dateThursday],
['date' => $dateFriday],
['date' => $dateSaturday],
['date' => $dateSunday],
])
->one();
if ($weekDistribution) {
$oneDistributionWeekActive = true;
}

return $oneDistributionWeekActive;
}
}

+ 24
- 3
common/logic/PointSale/PointSale/Repository/PointSaleRepository.php View File

@@ -50,14 +50,35 @@ class PointSaleRepository extends AbstractRepository
->fineOne();
}

public function findPointSalesByDistribution(Distribution $distribution)
public function queryPointSalesByDistribution(Distribution $distribution)
{
return $this->createDefaultQuery()
->filterIsOnline()
->with(['pointSaleDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]);
}])
->find();
}]);
}

public function findPointSalesByDistribution(Distribution $distribution)
{
return $this->queryPointSalesByDistribution($distribution)->find();
}

public function findPointSalesByDistributionAsArray(Distribution $distribution)
{
return $this->queryPointSalesByDistribution($distribution)->asArray()->find();
}

public function findOnePointSaleDefaultByDistribution(Distribution $distribution): ?PointSale
{
$pointSalesArray = $this->findPointSalesByDistribution($distribution);
foreach($pointSalesArray as $pointSale) {
if($pointSale->default) {
return $pointSale;
}
}

return null;
}

/**

Loading…
Cancel
Save