Browse Source

Refactoring services #885

refactoring
Guillaume 1 year ago
parent
commit
a8422dcf1b
8 changed files with 95 additions and 50 deletions
  1. +0
    -1
      common/logic/Config/TaxRate/TaxRateRepository.php
  2. +33
    -19
      common/logic/Order/Order/OrderBuilder.php
  3. +45
    -8
      common/logic/Order/Order/OrderManager.php
  4. +5
    -2
      common/logic/Order/Order/OrderRepository.php
  5. +0
    -5
      frontend/controllers/SiteController.php
  6. +1
    -1
      producer/controllers/CreditController.php
  7. +9
    -11
      producer/controllers/OrderController.php
  8. +2
    -3
      producer/controllers/SubscriptionController.php

+ 0
- 1
common/logic/Config/TaxRate/TaxRateRepository.php View File



class TaxRateRepository extends BaseService implements RepositoryInterface class TaxRateRepository extends BaseService implements RepositoryInterface
{ {

public function defaultOptionsSearch(): array public function defaultOptionsSearch(): array
{ {
return [ return [

+ 33
- 19
common/logic/Order/Order/OrderBuilder.php View File

use common\logic\User\UserProducer\UserProducerRepository; use common\logic\User\UserProducer\UserProducerRepository;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;


/**
*
*/

class OrderBuilder extends BaseService implements BuilderInterface class OrderBuilder extends BaseService implements BuilderInterface
{ {
protected UserSolver $userSolver; protected UserSolver $userSolver;
* Ajoute l'abonnement' pour une date donnée. * Ajoute l'abonnement' pour une date donnée.
*/ */
// add // add
public function createOrderFromSubscription(Subscription $subscription, string $date, $force = false)
public function createOrderFromSubscription(Subscription $subscription, string $date, bool $force = false): ?Order
{ {
$now = date('Y-m-d'); $now = date('Y-m-d');
$distributionDate = date('Y-m-d', strtotime($date)); $distributionDate = date('Y-m-d', strtotime($date));


$order = $this->createOrder($distribution); $order = $this->createOrder($distribution);
$this->updateOrderFromSubscription($order, $subscription); $this->updateOrderFromSubscription($order, $subscription);

return $order;
} }

return null;
} }


/** /**
*/ */
// addAll // addAll
// createAllFromSubscriptions // createAllFromSubscriptions
public function createAllOrdersFromSubscriptions(string $date, $force = false): void
public function createAllOrdersFromSubscriptions(string $date, bool $force = false): array
{ {
$orderArray = [];
$distribution = $this->distributionRepository->getOneByDate(date('Y-m-d', strtotime($date))); $distribution = $this->distributionRepository->getOneByDate(date('Y-m-d', strtotime($date)));


if ($distribution) { if ($distribution) {
$subscriptionArray = $this->subscriptionRepository->getByDate($date); $subscriptionArray = $this->subscriptionRepository->getByDate($date);
foreach ($subscriptionArray as $subscription) { foreach ($subscriptionArray as $subscription) {
if (!$this->subscriptionSolver->hasOrderAlreadyExist($subscription, $orderArray)) { if (!$this->subscriptionSolver->hasOrderAlreadyExist($subscription, $orderArray)) {
$this->createFromSubscription($subscription, $date, $force);
$this->createOrderFromSubscription($subscription, $date, $force);
} }
} }
} }

return $orderArray;
} }


// updateIncomingDistributions // updateIncomingDistributions
public function updateOrdersIncomingDistributionsFromSubscription(Subscription $subscription, $update = false): void
public function updateOrdersIncomingDistributionsFromSubscription(Subscription $subscription, $update = false): array
{ {
$orderArray = [];
$matchedDistributionsArray = $this->distributionRepository->searchMatchedIncomingDistributions($subscription); $matchedDistributionsArray = $this->distributionRepository->searchMatchedIncomingDistributions($subscription);


if ($update) { if ($update) {
$this->deleteOrdersIncomingDistributions($subscription);
$this->deleteOrdersIncomingDistributionsFromSubscription($subscription);
} }


if (count($matchedDistributionsArray)) { if (count($matchedDistributionsArray)) {
foreach ($matchedDistributionsArray as $distribution) { foreach ($matchedDistributionsArray as $distribution) {
$this->createOrderFromSubscription($subscription, $distribution->date);
$orderArray[] = $this->createOrderFromSubscription($subscription, $distribution->date);
} }
} }

return $orderArray;
} }


public function deleteOrdersIncomingDistributionsFromSubscription(Subscription $subscription, $deleteAfterDateEnd = false)
public function deleteOrdersIncomingDistributionsFromSubscription(Subscription $subscription, bool $deleteAfterDateEnd = false): int
{ {
$dateStart = $subscription->date_begin; $dateStart = $subscription->date_begin;
$comparatorDateStart = '>='; $comparatorDateStart = '>=';
); );
} }


$this->delete($order, true);
$this->deleteOrder($order, true);


$countOrdersDeleted ++; $countOrdersDeleted ++;
} }
return $countOrdersDeleted; return $countOrdersDeleted;
} }


public function addProductOrdersFromSubscription(Order $order, Subscription $subscription): void
public function addProductOrdersFromSubscription(Order $order, Subscription $subscription): bool
{ {
$productsAdd = false; $productsAdd = false;
$user = $subscription->user ?? null; $user = $subscription->user ?? null;
} }


if(!$productsAdd) { if(!$productsAdd) {
$order->delete();
$this->deleteOrder($order);
} }

return $productsAdd;
} }


// updateFromSubscription // updateFromSubscription
* Initialise le montant total, le montant déjà payé et le poids de la commande. * Initialise le montant total, le montant déjà payé et le poids de la commande.
*/ */
// init // init
public function initOrder(Order $order, $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public function initOrder(Order $order, string $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT): void
{ {
$this->initOrderAmount($order, $taxCalculationMethod); $this->initOrderAmount($order, $taxCalculationMethod);
$this->initOrderPaidAmount($order); $this->initOrderPaidAmount($order);

return $this;
} }


/** /**
* Initialise le montant de la commande. * Initialise le montant de la commande.
*/ */
// initAmount // initAmount
public function initOrderAmount(Order $order, $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public function initOrderAmount(Order $order, string $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT): void
{ {
$order->amount = 0; $order->amount = 0;
$order->amount_with_tax = 0; $order->amount_with_tax = 0;
} }


// delete // delete
public function deleteOrder(Order $order, $force = false)
public function deleteOrder(Order $order, bool $force = false): bool
{ {
// remboursement si l'utilisateur a payé pour cette commande // remboursement si l'utilisateur a payé pour cette commande
$amountPaid = $this->orderSolver->getAmount($order, Order::AMOUNT_PAID); $amountPaid = $this->orderSolver->getAmount($order, Order::AMOUNT_PAID);


return $order->save(); return $order->save();
} }

return false;
} }


/** /**


// setTillerSynchronization // setTillerSynchronization
// updateTillerSynchronization // updateTillerSynchronization
public function updateOrderTillerSynchronization(Order $order)
public function updateOrderTillerSynchronization(Order $order): void
{ {
$paymentStatus = $order->getPaymentStatus(); $paymentStatus = $order->getPaymentStatus();


} }


$order->save(); $order->save();

return $order;
} }


/** /**


// initReference // initReference
// generateReference // generateReference
public function generateOrderReference(Order $order)
public function generateOrderReference(Order $order): void
{ {
$producer = $order->producer; $producer = $order->producer;



+ 45
- 8
common/logic/Order/Order/OrderManager.php View File

namespace common\logic\Order\Order; namespace common\logic\Order\Order;


use common\logic\BaseManager; use common\logic\BaseManager;
use common\logic\Config\TaxRate\TaxRate;
use common\logic\Distribution\Distribution\Distribution;
use common\logic\Document\Document\Document;
use common\logic\Order\ProductOrder\ProductOrder;
use common\logic\Producer\Producer\Producer;
use common\logic\Product\Product\Product; use common\logic\Product\Product\Product;
use common\logic\Subscription\Subscription\Subscription;
use common\logic\User\User\User; use common\logic\User\User\User;
use yii\db\Query;


/** /**
* > Solver
* Solver :
* @method string getFieldNameAmount($typeTotal = Order::AMOUNT_TOTAL, string $typeField = '') * @method string getFieldNameAmount($typeTotal = Order::AMOUNT_TOTAL, string $typeField = '')
* @method float getOrderTotalVat(Order $order, string $typeTotal = Order::AMOUNT_TOTAL) * @method float getOrderTotalVat(Order $order, string $typeTotal = Order::AMOUNT_TOTAL)
* @method ?string getPaymentStatus(Order $order)
* @method string|null getPaymentStatus(Order $order)
* @method string getPointSaleSummary(Order $order) * @method string getPointSaleSummary(Order $order)
* @method string getOrderUsername(Order $order) * @method string getOrderUsername(Order $order)
* @method bool isLinkedToValidDocument(Order $order) * @method bool isLinkedToValidDocument(Order $order)
* @method string getCommentReport(Order $order) * @method string getCommentReport(Order $order)
* @method string getDateAsHtml(Order $order) * @method string getDateAsHtml(Order $order)
* @method countProducts(Order $order): int
* @method int countProducts(Order $order)
* @method int getProductQuantityPieces(Product $product, array $orders) * @method int getProductQuantityPieces(Product $product, array $orders)
* @method int getProductQuantity(Product $product, array $orders, bool $ignoreCancel = false, string $unit = null) * @method int getProductQuantity(Product $product, array $orders, bool $ignoreCancel = false, string $unit = null)
* @method string getHistoryClass(Order $order) * @method string getHistoryClass(Order $order)
* @method bool isOrderBelongsToUser(Order $order, User $user = null) * @method bool isOrderBelongsToUser(Order $order, User $user = null)
* @method string getDataJson(Order $order) * @method string getDataJson(Order $order)
* *
* Repository
*
* Builder
*
* Utils
* Repository :
* @method array defaultOptionsSearch()
* @method Order|null findOneById(int $id)
* @method array findBy(array $params = [], array $options = [])
* @method array findByDistribution(Distribution $distribution, string $conditionAppend = '')
* @method Order|null findOneLastOfYear(Producer $producer)
* @method Query queryHistory(Producer $producer, User $user, string $type = 'incoming')
* @method string getCartSummary(Order $order, $htmlFormat = true)
* @method string getAmountSummary(Order $order)
* @method string getState(Order $order)
* *
* Builder :
* @method Order instanciateOrder(Distribution $distribution)
* @method Order createOrder(Distribution $distribution)
* @method Order|null createOrderFromSubscription(Subscription $subscription, string $date, bool $force = false)
* @method array createAllOrdersFromSubscriptions(string $date, bool $force = false)
* @method array updateOrdersIncomingDistributionsFromSubscription(Subscription $subscription, bool $update = false)
* @method int deleteOrdersIncomingDistributionsFromSubscription(Subscription $subscription, bool $deleteAfterDateEnd = false)
* @method bool addProductOrdersFromSubscription(Order $order, Subscription $subscription)
* @method void updateOrderFromSubscription(Order $order, Subscription $subscription)
* @method void initOrderBaseFromSubscription(Order $order, Subscription $subscription)
* @method void initOrderAutoPaymentFromSubscription(Order $order, Subscription $subscription)
* @method void createUserPointSale(Order $order)
* @method void initOrderCommentPointSale(Order $order)
* @method void initOrder(Order $order, string $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
* @method void initOrderAmount(Order $order, string $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
* @method void addProductOrderWeight(Order $order, ProductOrder $productOrder)
* @method void addProductOrderAmount(Order $order, string $typeTotal, ProductOrder $productOrder, string $taxCalculationMethod)
* @method void addProductOrderVat(Order $order, string $typeTotal, float $priceTotalWithoutTax, TaxRate $taxRate, string $taxCalculationMethod)
* @method void initOrderPaidAmount(Order $order)
* @method void deleteOrder(Order $order, bool $force = false): bool
* @method void processCredit(Order $order)
* @method void updateOrderTillerSynchronization(Order $order)
* @method void updateOrderStatus(Order $order, string $newStatus, string $origin)
* @method void generateOrderReference(Order $order)
* @method void updateOrderInvoicePrices(Order $order, array $params = [])
*/ */
class OrderManager extends BaseManager class OrderManager extends BaseManager
{ {

+ 5
- 2
common/logic/Order/Order/OrderRepository.php View File

* Recherche et initialise des commandes. * Recherche et initialise des commandes.
*/ */
// searchBy // searchBy
public function findBy($params = [], $options = [])
public function findBy(array $params = [], array $options = []): array
{ {
$orders = Order::searchBy($params, $options); $orders = Order::searchBy($params, $options);




/** /**
* Retourne le résumé du panier au format HTML. * Retourne le résumé du panier au format HTML.
* @TODO : à déplacer dans OrderSolver
*/ */
public function getCartSummary(Order $order, $htmlFormat = true): string public function getCartSummary(Order $order, $htmlFormat = true): string
{ {


/** /**
* Retourne le résumé du paiement (montant, statut). * Retourne le résumé du paiement (montant, statut).
* @TODO : à déplacer dans OrderSolver
*/ */
public function getAmountSummary(Order $order): string public function getAmountSummary(Order $order): string
{ {


/** /**
* Retourne l'état de la commande (livrée, modifiable ou en préparation. * Retourne l'état de la commande (livrée, modifiable ou en préparation.
* @TODO : à déplacer dans OrderSolver
*/ */
public function getState(Order $order): string public function getState(Order $order): string
{ {
return Order::STATE_PREPARATION; return Order::STATE_PREPARATION;
} }


public function getOneLastOfYear(Producer $producer)
public function findOneLastOfYear(Producer $producer)
{ {
return Order::find()->innerJoinWith('distribution', true) return Order::find()->innerJoinWith('distribution', true)
->where(['>=', 'distribution.date', date('Y') . '-01-01']) ->where(['>=', 'distribution.date', date('Y') . '-01-01'])

+ 0
- 5
frontend/controllers/SiteController.php View File

*/ */
public function actionIndex() public function actionIndex()
{ {
$distribution = $this->getDistributionContainer()->getRepository()->getOneById(1);
$orderManager = $this->getOrderManager();
$order = $orderManager->instanciateOrder($distribution);
$orderManager->getOrderTotalVat($order);

return $this->render('index', [ return $this->render('index', [
'producerDemoAccount' => $this->getLogic()->getProducerContainer() 'producerDemoAccount' => $this->getLogic()->getProducerContainer()
->getRepository()->getOneDemoAccount(), ->getRepository()->getOneDemoAccount(),

+ 1
- 1
producer/controllers/CreditController.php View File

$idProducer = $paymentIntentMetadata->producer_id; $idProducer = $paymentIntentMetadata->producer_id;


if (isset($paymentIntentMetadata->order_id)) { if (isset($paymentIntentMetadata->order_id)) {
$order = $this->getLogic()->getOrderContainer()->getRepository()->getOneById($paymentIntentMetadata->order_id);
$order = $this->getOrderManager()->findOneById($paymentIntentMetadata->order_id);
$pointSale = $this->getLogic()->getPointSaleContainer()->getRepostory()->getOneById($order->id_point_sale); $pointSale = $this->getLogic()->getPointSaleContainer()->getRepostory()->getOneById($order->id_point_sale);
$distribution = $this->getLogic()->getDistributionContainer()->getRepository()->getOneById($order->id_distribution); $distribution = $this->getLogic()->getDistributionContainer()->getRepository()->getOneById($order->id_distribution);
} }

+ 9
- 11
producer/controllers/OrderController.php View File

); );
} }


$order = $this->getOrderContainer()->getRepository()->getOneById($id);
if ($order && $this->getOrderContainer()->getSolver()->isStateOpen($order)) {
$order = $this->getOrderManager()->findOneById($id);
if ($order && $this->getOrderManager()->isOrderStateOpen($order)) {
$params['order'] = $order; $params['order'] = $order;
} }


*/ */
public function actionHistory($type = 'incoming') public function actionHistory($type = 'incoming')
{ {
$queryHistoryArray = $this->getOrderContainer()->getRepository()
$queryHistoryArray = $this->getOrderManager()
->queryHistory($this->getProducer(), $this->getUserCurrent(), $type); ->queryHistory($this->getProducer(), $this->getUserCurrent(), $type);
$queryHistoryIncoming = $queryHistoryArray['incoming']; $queryHistoryIncoming = $queryHistoryArray['incoming'];
$queryHistoryPassed = $queryHistoryArray['passed']; $queryHistoryPassed = $queryHistoryArray['passed'];
*/ */
public function actionCancel(int $id) public function actionCancel(int $id)
{ {
$orderContainer = $this->getOrderContainer();
$order = $orderContainer->getRepository()->getOneById($id);
$order = $this->getOrderManager()->findOneById($id);


if (!$order) { if (!$order) {
throw new \yii\web\NotFoundHttpException('Commande introuvable'); throw new \yii\web\NotFoundHttpException('Commande introuvable');
} }


if ($orderContainer->getSolver()->isStateOpen($order)) {
if ($this->getOrderManager()->isOrderStateOpen($order)) {
throw new UserException('Vous ne pouvez plus annuler cette commande.'); throw new UserException('Vous ne pouvez plus annuler cette commande.');
} }


if ($orderContainer->getSolver()->belongsToUser($order, GlobalParam::getCurrentUser())) {
if ($this->getOrderManager()->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
$orderContainer->getBuilder()->delete($order); $orderContainer->getBuilder()->delete($order);
\Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.'); \Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
} }
*/ */
public function actionConfirm(int $idOrder, string $returnPayment = '') public function actionConfirm(int $idOrder, string $returnPayment = '')
{ {
$orderContainer = $this->getOrderContainer();
$order = $orderContainer->getRepository()->getOneById($idOrder);
$order = $this->getOrderManager()->findOneById($idOrder);
$producer = $this->getProducer(); $producer = $this->getProducer();


if (!$order || (!$orderContainer->getSolver()->belongsToUser($order, GlobalParam::getCurrentUser()) && !$producer->option_allow_order_guest)) {
if (!$order || (!$this->getOrderManager()->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()) && !$producer->option_allow_order_guest)) {
throw new \yii\base\UserException('Commande introuvable.'); throw new \yii\base\UserException('Commande introuvable.');
} }


Order $order = null Order $order = null
) )
{ {
$ordersArray = $this->getOrderContainer()->getRepository()->getByDistribution($distribution);
$ordersArray = $this->getOrderManager()->findByDistribution($distribution);


$productsArray = Product::find() $productsArray = Product::find()
->where([ ->where([

+ 2
- 3
producer/controllers/SubscriptionController.php View File

if ($model->load($posts) && $model->validate() && $model->save()) { if ($model->load($posts) && $model->validate() && $model->save()) {


$subscription = $subscriptionRepository->getOneById($model->id); $subscription = $subscriptionRepository->getOneById($model->id);
$this->getOrderContainer()->getBuilder()
->updateIncomingDistributions($subscription, $isUpdate);
$this->getOrderManager()->updateOrdersIncomingDistributionsFromSubscription($subscription, $isUpdate);


if ($isUpdate) { if ($isUpdate) {
$this->setFlash('success', 'Abonnement modifié'); $this->setFlash('success', 'Abonnement modifié');
$subscriptionContainer->getBuilder()->delete($subscription); $subscriptionContainer->getBuilder()->delete($subscription);


// @TODO : gérer via événements // @TODO : gérer via événements
$this->getOrderContainer()->getBuilder()->deleteOrdersIncomingDistributions($subscription);
$this->getOrderManager()->deleteOrdersIncomingDistributionsFromSubscription($subscription);


$this->setFlash('success', 'Abonnement supprimé'); $this->setFlash('success', 'Abonnement supprimé');



Loading…
Cancel
Save