Browse Source

Commandes : système de statut de commande

feature/rotating_product
Guillaume Bourgeois 5 months ago
parent
commit
61215ec178
34 changed files with 690 additions and 152 deletions
  1. +5
    -6
      backend/controllers/CronController.php
  2. +1
    -1
      backend/controllers/DistributionController.php
  3. +5
    -1
      backend/controllers/DocumentController.php
  4. +10
    -7
      backend/controllers/OrderController.php
  5. +4
    -2
      backend/controllers/PointSaleController.php
  6. +4
    -2
      backend/controllers/ProducerAdminController.php
  7. +3
    -1
      backend/controllers/ReportController.php
  8. +8
    -5
      backend/controllers/SubscriptionController.php
  9. +3
    -1
      backend/views/user/index.php
  10. +1
    -1
      backend/web/js/vuejs/distribution-index.js
  11. +2
    -0
      common/components/BusinessLogic.php
  12. +12
    -0
      common/components/BusinessLogicTrait.php
  13. +46
    -0
      console/migrations/m240527_083421_create_table_order_status_history.php
  14. +42
    -3
      domain/Order/Order/Order.php
  15. +13
    -60
      domain/Order/Order/OrderBuilder.php
  16. +113
    -1
      domain/Order/Order/OrderManager.php
  17. +4
    -2
      domain/Order/Order/OrderRepository.php
  18. +7
    -1
      domain/Order/Order/OrderRepositoryQuery.php
  19. +45
    -5
      domain/Order/Order/OrderSolver.php
  20. +5
    -6
      domain/Order/Order/TillerManager.php
  21. +35
    -0
      domain/Order/OrderStatus/OrderStatus.php
  22. +18
    -0
      domain/Order/OrderStatus/OrderStatusBuilder.php
  23. +28
    -0
      domain/Order/OrderStatus/OrderStatusDefinition.php
  24. +22
    -0
      domain/Order/OrderStatus/OrderStatusModule.php
  25. +36
    -0
      domain/Order/OrderStatus/OrderStatusRepository.php
  26. +107
    -0
      domain/Order/OrderStatusHistory/OrderStatusHistory.php
  27. +28
    -0
      domain/Order/OrderStatusHistory/OrderStatusHistoryBuilder.php
  28. +13
    -0
      domain/Order/OrderStatusHistory/OrderStatusHistoryDefinition.php
  29. +30
    -0
      domain/Order/OrderStatusHistory/OrderStatusHistoryManager.php
  30. +22
    -0
      domain/Order/OrderStatusHistory/OrderStatusHistoryModule.php
  31. +3
    -1
      domain/Producer/Producer/ProducerRepository.php
  32. +0
    -37
      domain/Subscription/Subscription/OrderManager.php
  33. +10
    -5
      producer/controllers/OrderController.php
  34. +5
    -4
      producer/controllers/SubscriptionController.php

+ 5
- 6
backend/controllers/CronController.php View File

use common\helpers\MeanPayment; use common\helpers\MeanPayment;
use domain\Distribution\Distribution\ExportManager; use domain\Distribution\Distribution\ExportManager;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\User\User\User; use domain\User\User\User;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
*/ */
$arrayOrders = Order::searchAll([ $arrayOrders = Order::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $producer->id
], [
'conditions' => 'date_delete IS NULL'
'distribution.id_producer' => $producer->id,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]); ]);


$configCredit = $producerModule->getConfig('credit'); $configCredit = $producerModule->getConfig('credit');
if (!strlen($forceDate) && $producerModule->getConfig('option_notify_producer_order_summary')) { if (!strlen($forceDate) && $producerModule->getConfig('option_notify_producer_order_summary')) {
$arrayOrders = Order::searchAll([ $arrayOrders = Order::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $producer->id
], [
'conditions' => 'date_delete IS NULL'
'distribution.id_producer' => $producer->id,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]); ]);


$mail = Yii::$app->mailerService->getMailer()->compose( $mail = Yii::$app->mailerService->getMailer()->compose(

+ 1
- 1
backend/controllers/DistributionController.php View File

if ($ordersArray) { if ($ordersArray) {
foreach ($ordersArray as $order) { foreach ($ordersArray as $order) {
$orderModule->initOrder($order); $orderModule->initOrder($order);
if (is_null($order->date_delete)) {
if($orderModule->getSolver()->isOrderStatusValid($order)) {
$revenues += $orderModule->getOrderAmount($order); $revenues += $orderModule->getOrderAmount($order);
$revenuesWithTax += $orderModule->getOrderAmountWithTax($order); $revenuesWithTax += $orderModule->getOrderAmountWithTax($order);
$weight += $order->weight; $weight += $order->weight;

+ 5
- 1
backend/controllers/DocumentController.php View File

use domain\Document\Invoice\Invoice; use domain\Document\Invoice\Invoice;
use domain\Document\Quotation\Quotation; use domain\Document\Quotation\Quotation;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\ProductOrder\ProductOrder; use domain\Order\ProductOrder\ProductOrder;
use domain\Payment\Payment; use domain\Payment\Payment;
use kartik\mpdf\Pdf; use kartik\mpdf\Pdf;


public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price) public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price)
{ {
$orderModule = $this->getOrderModule();
$documentModule = $this->getDocumentModule(); $documentModule = $this->getDocumentModule();
$productModule = $this->getProductModule(); $productModule = $this->getProductModule();
$userCurrent = $this->getUserCurrent();


if ($documentModule->isValidClass($classDocument)) { if ($documentModule->isValidClass($classDocument)) {
$document = $this->findModel($idDocument, $classDocument); $document = $this->findModel($idDocument, $classDocument);
$order->id_user = $document->id_user; $order->id_user = $document->id_user;
$order->id_point_sale = null; $order->id_point_sale = null;
$order->id_distribution = null; $order->id_distribution = null;
$order->status = 'tmp-order';
$order->origin = Order::ORIGIN_ADMIN; $order->origin = Order::ORIGIN_ADMIN;
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
$fieldIdDocument = 'id_' . $classDocumentComplete::tableName(); $fieldIdDocument = 'id_' . $classDocumentComplete::tableName();
$order->$fieldIdDocument = $document->id; $order->$fieldIdDocument = $document->id;
$order->save(); $order->save();
$orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $userCurrent);

} else { } else {
$order = $document->orders[0]; $order = $document->orders[0];
} }

+ 10
- 7
backend/controllers/OrderController.php View File

use domain\Distribution\PointSaleDistribution\PointSaleDistribution; use domain\Distribution\PointSaleDistribution\PointSaleDistribution;
use domain\Distribution\ProductDistribution\ProductDistribution; use domain\Distribution\ProductDistribution\ProductDistribution;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\ProductOrder\ProductOrder; use domain\Order\ProductOrder\ProductOrder;
use domain\Payment\Payment; use domain\Payment\Payment;
use domain\PointSale\PointSale\PointSale; use domain\PointSale\PointSale\PointSale;
/** /**
* Traite le formulaire d'ajout/modification de commande. * Traite le formulaire d'ajout/modification de commande.
*/ */
public function processOrderForm(
/*public function processOrderForm(
Distribution $distribution, Distribution $distribution,
string $date, string $date,
array $pointsSale, array $pointsSale,
} }
} }
} }
}
}*/


/** /**
* Page principale de la gestion des commandes. * Page principale de la gestion des commandes.
*/ */
public function actionIndex($date = '', $returnData = false)
/*public function actionIndex($date = '', $returnData = false)
{ {
$distributionModule = $this-> getDistributionModule(); $distributionModule = $this-> getDistributionModule();
$productModule = $this->getProductModule(); $productModule = $this->getProductModule();
} else { } else {
return $this->render('index', $datas); return $this->render('index', $datas);
} }
}
}*/


/** /**
* Génère un fichier d'export des commandes au format CSV. * Génère un fichier d'export des commandes au format CSV.


$order = $orderModule->findOneOrderById($idOrder); $order = $orderModule->findOneOrderById($idOrder);
if ($order) { if ($order) {
$orderModule->deleteOrder($order);
$orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
} }


return ['success']; return ['success'];
$orderModule = $this->getOrderModule(); $orderModule = $this->getOrderModule();
$order = $orderModule->findOneOrderById($idOrder); $order = $orderModule->findOneOrderById($idOrder);
if ($order) { if ($order) {
$orderModule->deleteOrder($order);
$orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
} }


$this->redirect(['index', 'date' => $date]); $this->redirect(['index', 'date' => $date]);
$pointSale = $pointSaleModule->findOnePointSaleById($idPointSale); $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
$distribution = $distributionModule->findOneDistribution($date); $distribution = $distributionModule->findOneDistribution($date);
$producerCurrent = $this->getProducerCurrent(); $producerCurrent = $this->getProducerCurrent();
$userCurrent = $this->getUserCurrent();


if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date) if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)
&& ($idUser || strlen($username)) && ($idUser || strlen($username))
$order->id_distribution = $distribution->id; $order->id_distribution = $distribution->id;
$order->origin = Order::ORIGIN_ADMIN; $order->origin = Order::ORIGIN_ADMIN;
$order->comment = $comment; $order->comment = $comment;
$order->status = 'tmp-order';


if ($idUser) { if ($idUser) {
$order->id_user = $idUser; $order->id_user = $idUser;


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


$orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $userCurrent);

$user = false; $user = false;
$userProducer = false; $userProducer = false;
if (isset($order->user) && $order->user) { if (isset($order->user) && $order->user) {

+ 4
- 2
backend/controllers/PointSaleController.php View File

use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use domain\Distribution\PointSaleDistribution\PointSaleDistribution; use domain\Distribution\PointSaleDistribution\PointSaleDistribution;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\PointSale\PointSale\PointSale; use domain\PointSale\PointSale\PointSale;
use domain\PointSale\PointSale\PointSaleSearch; use domain\PointSale\PointSale\PointSaleSearch;
use domain\PointSale\UserPointSale\UserPointSale; use domain\PointSale\UserPointSale\UserPointSale;
$ordersArray = Order::searchAll( $ordersArray = Order::searchAll(
[ [
'id_point_sale' => $id, 'id_point_sale' => $id,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
], ],
[ [
'conditions' => 'date_delete IS NULL AND distribution.date > :today',
'conditions' => 'distribution.date > :today',
'params' => [':today' => date('Y-m-d')] 'params' => [':today' => date('Y-m-d')]
] ]
); );


if ($ordersArray) { if ($ordersArray) {
foreach ($ordersArray as $order) { foreach ($ordersArray as $order) {
$orderModule->deleteOrder($order, true);
$orderModule->getManager()->deleteOrder($order, $this->getUserCurrent(), true);
} }
} }



+ 4
- 2
backend/controllers/ProducerAdminController.php View File

use common\helpers\Ajax; use common\helpers\Ajax;
use common\helpers\Alwaysdata; use common\helpers\Alwaysdata;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\Producer\Producer\Producer; use domain\Producer\Producer\Producer;
use domain\Product\Product\Product; use domain\Product\Product\Product;
use Yii; use Yii;
if ($withOrders) { if ($withOrders) {
$countOrders = Order::searchCount([ $countOrders = Order::searchCount([
'id_user' => $idUser, 'id_user' => $idUser,
'distribution.id_producer' => $fromProducerId
], ['conditions' => 'date_delete IS NULL']);
'distribution.id_producer' => $fromProducerId,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]);
} }


if (($withOrders && $countOrders) || !$withOrders) { if (($withOrders && $countOrders) || !$withOrders) {

+ 3
- 1
backend/controllers/ReportController.php View File

use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\MeanPayment; use common\helpers\MeanPayment;
use common\helpers\Price; use common\helpers\Price;
use domain\Order\Order\OrderRepositoryQuery;
use domain\Order\OrderStatus\OrderStatus;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;


WHERE `order`.id = product_order.id_order WHERE `order`.id = product_order.id_order
AND product.id_producer = " . ((int)GlobalParam::getCurrentProducerId()) . " AND product.id_producer = " . ((int)GlobalParam::getCurrentProducerId()) . "
AND product_order.id_product = product.id AND product_order.id_product = product.id
AND `order`.date_delete IS NULL
AND ".OrderRepositoryQuery::getSqlFilterIsValid()."
" . $conditionUsers . " " . $conditionUsers . "
" . $conditionPointsSale . " " . $conditionPointsSale . "
" . $conditionDistributions . " " . $conditionDistributions . "

+ 8
- 5
backend/controllers/SubscriptionController.php View File

*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$orderModule = $this->getOrderModule();
$subscriptionModule = $this->getSubscriptionModule(); $subscriptionModule = $this->getSubscriptionModule();
$productSubscriptionModule = $this->getProductSubscriptionModule(); $productSubscriptionModule = $this->getProductSubscriptionModule();
$productModule = $this->getProductModule(); $productModule = $this->getProductModule();
$messageOrdersDeleted = ''; $messageOrdersDeleted = '';


if ($model->date_end) { if ($model->date_end) {
$countOrdersDeleted = $subscriptionModule->getOrderManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription, true);
$countOrdersDeleted = $orderModule->getManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent(), true);
if ($countOrdersDeleted) { if ($countOrdersDeleted) {
$messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées'; $messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées';
} }
*/ */
public function actionDelete(int $id) public function actionDelete(int $id)
{ {
$orderModule = $this->getOrderModule();
$subscriptionModule = $this->getSubscriptionModule(); $subscriptionModule = $this->getSubscriptionModule();


$subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($id); $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($id);


if($subscription) { if($subscription) {
$subscriptionModule->getOrderManager()->deleteOrdersIncomingDistributionsFromSubscription($subscription);
$orderModule->getManager()->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());
$subscriptionModule->deleteSubscription($subscription); $subscriptionModule->deleteSubscription($subscription);
$this->setFlash('success', 'Abonnement supprimé'); $this->setFlash('success', 'Abonnement supprimé');
} }


public function actionUpdateDistributions(int $idSubscription, bool $generate = false, bool $update = false) public function actionUpdateDistributions(int $idSubscription, bool $generate = false, bool $update = false)
{ {
$orderModule = $this->getOrderModule();
$subscriptionModule = $this->getSubscriptionModule(); $subscriptionModule = $this->getSubscriptionModule();
$distributionModule = $this-> getDistributionModule(); $distributionModule = $this-> getDistributionModule();
$subscription = $subscriptionModule->findOneSubscriptionById($idSubscription); $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);


if ($generate) { if ($generate) {
if ($update) { if ($update) {
$subscriptionModule->getOrderManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription);
$orderModule->getManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());
} }
foreach ($matchedDistributionsArray as $distribution) { foreach ($matchedDistributionsArray as $distribution) {
$subscriptionModule->createOrderFromSubscription($subscription, $distribution->date); $subscriptionModule->createOrderFromSubscription($subscription, $distribution->date);

+ 3
- 1
backend/views/user/index.php View File

use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Price; use common\helpers\Price;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\Producer\Producer\ProducerModule; use domain\Producer\Producer\ProducerModule;
use domain\User\User\UserModule; use domain\User\User\UserModule;
use domain\User\UserProducer\UserProducer; use domain\User\UserProducer\UserProducer;
$url = Yii::$app->urlManager->createUrl(['user/orders', 'id' => $model['id']]); $url = Yii::$app->urlManager->createUrl(['user/orders', 'id' => $model['id']]);
$countOrders = Order::searchCount([ $countOrders = Order::searchCount([
'id_user' => $model['id'], 'id_user' => $model['id'],
], ['conditions' => 'date_delete IS NULL']);
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]);


$html = ''; $html = '';
if ($countOrders) { if ($countOrders) {

+ 1
- 1
backend/web/js/vuejs/distribution-index.js View File

app.ordersUpdate = JSON.parse(JSON.stringify(response.data.orders)); app.ordersUpdate = JSON.parse(JSON.stringify(response.data.orders));


for (i = 0; i < app.orders.length; i++) { for (i = 0; i < app.orders.length; i++) {
if (!app.orders[i].date_delete) {
if (!app.orders[i].order_status_alias == 'ordered') {
app.countOrders++; app.countOrders++;
} }
} }

+ 2
- 0
common/components/BusinessLogic.php View File

$this->getPointSaleModule(), $this->getPointSaleModule(),
$this->getProductModule(), $this->getProductModule(),
$this->getProductOrderModule(), $this->getProductOrderModule(),
$this->getOrderStatusModule(),
$this->getOrderStatusHistoryModule(),
$this->getQuotationModule(), $this->getQuotationModule(),
$this->getInvoiceModule(), $this->getInvoiceModule(),
$this->getDeliveryNoteModule(), $this->getDeliveryNoteModule(),

+ 12
- 0
common/components/BusinessLogicTrait.php View File

use domain\Feature\FeatureProducer\FeatureProducerModule; use domain\Feature\FeatureProducer\FeatureProducerModule;
use domain\Opinion\OpinionModule; use domain\Opinion\OpinionModule;
use domain\Order\Order\OrderModule; use domain\Order\Order\OrderModule;
use domain\Order\OrderStatus\OrderStatusModule;
use domain\Order\OrderStatusHistory\OrderStatusHistoryModule;
use domain\Order\ProductOrder\ProductOrderModule; use domain\Order\ProductOrder\ProductOrderModule;
use domain\Payment\PaymentModule; use domain\Payment\PaymentModule;
use domain\PointSale\PointSale\PointSaleModule; use domain\PointSale\PointSale\PointSaleModule;


trait BusinessLogicTrait trait BusinessLogicTrait
{ {
public function getOrderStatusModule(): OrderStatusModule
{
return OrderStatusModule::getInstance();
}

public function getOrderStatusHistoryModule(): OrderStatusHistoryModule
{
return OrderStatusHistoryModule::getInstance();
}

public function getUnitModule(): UnitModule public function getUnitModule(): UnitModule
{ {
return UnitModule::getInstance(); return UnitModule::getInstance();

+ 46
- 0
console/migrations/m240527_083421_create_table_order_status_history.php View File

<?php

use yii\db\Migration;
use yii\db\Schema;

/**
* Class m240527_083421_create_table_order_status_history
*/
class m240527_083421_create_table_order_status_history extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->dropColumn('order', 'status');
$this->addColumn('order', 'order_status_alias', Schema::TYPE_STRING);
$this->dropTable('order_status_history');
$this->createTable('order_status_history', [
'id' => 'pk',
'id_order' => Schema::TYPE_INTEGER,
'order_status_alias' => Schema::TYPE_STRING,
'date' => Schema::TYPE_DATETIME,
'id_user' => Schema::TYPE_INTEGER
]);
$this->createIndex('id_order', 'order_status_history', 'id_order');
$this->createIndex('id_user', 'order_status_history', 'id_user');
$this->addForeignKey('fk_id_order', 'order_status_history', 'id_order', 'order', 'id');
$this->addForeignKey('fk_id_user', 'order_status_history', 'id_user', 'user', 'id');
}

/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropColumn('order', 'order_status_alias');
$this->addColumn('order', 'status', Schema::TYPE_STRING);

$this->dropIndex('id_order', 'order_status_history');
$this->dropIndex('id_user', 'order_status_history');
$this->dropForeignKey('fk_id_order', 'order_status_history');
$this->dropForeignKey('fk_id_user', 'order_status_history');
$this->dropTable('order_status_history');
}
}

+ 42
- 3
domain/Order/Order/Order.php View File

use domain\Document\DeliveryNote\DeliveryNote; use domain\Document\DeliveryNote\DeliveryNote;
use domain\Document\Invoice\Invoice; use domain\Document\Invoice\Invoice;
use domain\Document\Quotation\Quotation; use domain\Document\Quotation\Quotation;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\OrderStatusHistory\OrderStatusHistory;
use domain\Order\ProductOrder\ProductOrder; use domain\Order\ProductOrder\ProductOrder;
use domain\Payment\Payment; use domain\Payment\Payment;
use domain\PointSale\PointSale\PointSale; use domain\PointSale\PointSale\PointSale;


class Order extends ActiveRecordCommon class Order extends ActiveRecordCommon
{ {
protected OrderStatus $orderStatusObject;

const EVENT_DELETE = 'order.event.delete'; const EVENT_DELETE = 'order.event.delete';


var $amount = 0; var $amount = 0;
const STATE_PREPARATION = 'preparation'; const STATE_PREPARATION = 'preparation';
const STATE_DELIVERED = 'delivered'; const STATE_DELIVERED = 'delivered';



public function getOrderStatusAlias(): ?string
{
return $this->order_status_alias;
}

public function setOrderStatusAlias(string $orderStatusAlias): self
{
$this->order_status_alias = $orderStatusAlias;
return $this;
}

public function getOrderStatus(): OrderStatus
{
return $this->orderStatusObject;
}

public function setOrderStatus(OrderStatus $orderStatus): self
{
$this->setOrderStatusAlias($orderStatus->getAlias());
$this->orderStatusObject = $orderStatus;
return $this;
}

public function getOrderStatusHistory(): array
{
return $this->orderStatusHistoryRelation;
}

/** /**
* @inheritdoc * @inheritdoc
*/ */
public function rules() public function rules()
{ {
return [ return [
[['id_user', 'date', 'status'], 'required', 'message' => ''],
[['id_user', 'date'], 'required', 'message' => ''],
[ [
[ [
'id_user', 'id_user',
'integer' 'integer'
], ],
[['auto_payment', 'tiller_synchronization', 'delivery_home', 'ignore_when_invoicing'], 'boolean'], [['auto_payment', 'tiller_synchronization', 'delivery_home', 'ignore_when_invoicing'], 'boolean'],
[['status', 'reference', 'delivery_address', 'online_payment_url', 'tiller_external_id'], 'string'],
[['order_status_alias', 'reference', 'delivery_address', 'online_payment_url', 'tiller_external_id'], 'string'],
[['date', 'date_update', 'comment', 'comment_point_sale', 'mean_payment', 'tiller_external_id'], 'safe'] [['date', 'date_update', 'comment', 'comment_point_sale', 'mean_payment', 'tiller_external_id'], 'safe']
]; ];
} }
'id_user' => 'Id User', 'id_user' => 'Id User',
'date' => 'Date', 'date' => 'Date',
'date_update' => 'Date de modification', 'date_update' => 'Date de modification',
'order_status_alias' => 'Statut',
'id_point_sale' => 'Point de vente', 'id_point_sale' => 'Point de vente',
'id_distribution' => 'Date de distribution', 'id_distribution' => 'Date de distribution',
'id_subscription' => 'Abonnement', 'id_subscription' => 'Abonnement',
'status' => 'Statut',
'id_invoice' => 'Facture', 'id_invoice' => 'Facture',
'id_quotation' => 'Devis', 'id_quotation' => 'Devis',
'id_delivery_note' => 'Bon de livraison', 'id_delivery_note' => 'Bon de livraison',
{ {
$this->populateFieldObject('id_delivery_note', 'deliveryNote', $deliveryNote); $this->populateFieldObject('id_delivery_note', 'deliveryNote', $deliveryNote);
} }

public function getOrderStatusHistoryRelation()
{
return $this->hasMany(OrderStatusHistory::class, ['id_order' => 'id'])
->orderBy(['order_status.id' => SORT_DESC]);
}
} }

+ 13
- 60
domain/Order/Order/OrderBuilder.php View File

use domain\Document\Document\DocumentSolver; use domain\Document\Document\DocumentSolver;
use domain\Document\Invoice\Invoice; use domain\Document\Invoice\Invoice;
use domain\Order\Order\Event\OrderDeleteEvent; use domain\Order\Order\Event\OrderDeleteEvent;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\OrderStatus\OrderStatusRepository;
use domain\Order\ProductOrder\ProductOrder; use domain\Order\ProductOrder\ProductOrder;
use domain\Order\ProductOrder\ProductOrderBuilder; use domain\Order\ProductOrder\ProductOrderBuilder;
use domain\Order\ProductOrder\ProductOrderSolver; use domain\Order\ProductOrder\ProductOrderSolver;
protected DeliveryNoteBuilder $deliveryNoteBuilder; protected DeliveryNoteBuilder $deliveryNoteBuilder;
protected DocumentSolver $documentSolver; protected DocumentSolver $documentSolver;
protected ProducerSolver $producerSolver; protected ProducerSolver $producerSolver;
protected OrderStatusRepository $orderStatusRepository;


public function loadDependencies(): void public function loadDependencies(): void
{ {
$this->deliveryNoteBuilder = $this->loadService(DeliveryNoteBuilder::class); $this->deliveryNoteBuilder = $this->loadService(DeliveryNoteBuilder::class);
$this->documentSolver = $this->loadService(DocumentSolver::class); $this->documentSolver = $this->loadService(DocumentSolver::class);
$this->producerSolver = $this->loadService(ProducerSolver::class); $this->producerSolver = $this->loadService(ProducerSolver::class);
$this->orderStatusRepository = $this->loadService(OrderStatusRepository::class);
} }


public function instanciateOrder(Distribution $distribution): Order public function instanciateOrder(Distribution $distribution): Order
$taxCalculationMethod = $this->getProducerContext()->option_tax_calculation_method; $taxCalculationMethod = $this->getProducerContext()->option_tax_calculation_method;
$this->initOrderAmount($order, $taxCalculationMethod); $this->initOrderAmount($order, $taxCalculationMethod);
$this->initOrderPaidAmount($order); $this->initOrderPaidAmount($order);
$this->initOrderStatus($order);
}

public function initOrderStatus(Order $order)
{
$orderStatusAlias = $order->getOrderStatusAlias() ?: OrderStatus::ALIAS_ORDERED;
$orderStatus = $this->orderStatusRepository->getOrderStatusByAlias($orderStatusAlias);
$order->setOrderStatus($orderStatus);
} }


/** /**
} }
} }


public function deleteOrder(Order $order, bool $force = false): bool
{
$return = false;
$this->initOrder($order);

// delete
if ($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_DELETE ||
($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS && strlen($order->date_delete))
|| $force) {

$this->productOrderBuilder->deleteProductOrdersByOrder($order);

$return = $this->delete($order);
}
// status 'delete'
elseif ($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS) {
$order->date_delete = date('Y-m-d H:i:s');
$return = $this->update($order);
}

if($return) {
$orderDeleteEvent = new OrderDeleteEvent();
$orderDeleteEvent->order = $order;
$order->trigger(Order::EVENT_DELETE, $orderDeleteEvent);
}

return $return;
}

/** /**
* Ajuste le crédit pour que la commande soit payée. * Ajuste le crédit pour que la commande soit payée.
*/ */
$this->saveUpdate($order); $this->saveUpdate($order);
} }


/**
* Changement de statut d'une commande.
*/
public function updateOrderStatus(Order $order, string $newStatus, string $origin): void
{
$orderStatusArray = GlobalParam::get('orderStatus');
$userCurrent = $this->userSolver->getCurrent();

switch ($newStatus) {
case 'new-order' :
$order->status = $newStatus;
$order->save();
break;
case 'waiting-paiement-on-delivery':
case 'waiting-paiement-by-credit':
case 'paid-by-credit':
case 'waiting-delevery' :
case 'delivered':
case 'refunded':
case 'cancel':
if (in_array($newStatus, $orderStatusArray[$order->status]['nextStatusAllow'])) {
$order->status = $newStatus;
$order->save();
}
break;
default:
throw new NotFoundHttpException('Statut de commande inconnu.');
}
}

// initReference // initReference
// generateReference // generateReference
public function generateOrderReference(Order $order): void public function generateOrderReference(Order $order): void
if ($pointSale->id == $order->id_point_sale) { if ($pointSale->id == $order->id_point_sale) {
$pointSale->orders[] = $order; $pointSale->orders[] = $order;


if (is_null($order->date_delete)) {
if($this->orderSolver->isOrderStatusValid($order)) {
$pointSale->revenues += (float)$order->amount; $pointSale->revenues += (float)$order->amount;
$pointSale->revenues_with_tax += (float)$order->amount_with_tax; $pointSale->revenues_with_tax += (float)$order->amount_with_tax;
} }

+ 113
- 1
domain/Order/Order/OrderManager.php View File



use domain\_\AbstractService; use domain\_\AbstractService;
use domain\_\ManagerInterface; use domain\_\ManagerInterface;
use domain\Distribution\Distribution\DistributionRepository;
use domain\Distribution\Distribution\DistributionSolver;
use domain\Order\Order\Event\OrderDeleteEvent;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\OrderStatus\OrderStatusRepository;
use domain\Order\OrderStatusHistory\OrderStatusHistoryManager;
use domain\Producer\Producer\Producer;
use domain\Producer\Producer\ProducerSolver;
use domain\Subscription\Subscription\Subscription;
use domain\User\User\User;


class OrderManager extends AbstractService implements ManagerInterface class OrderManager extends AbstractService implements ManagerInterface
{ {
protected ProducerSolver $producerSolver;
protected OrderBuilder $orderBuilder;
protected OrderStatusRepository $orderStatusRepository;
protected OrderStatusHistoryManager $orderStatusHistoryManager;
protected DistributionRepository $distributionRepository;
protected \domain\Subscription\Subscription\OrderManager $subscriptionOrderManager;
protected OrderRepository $orderRepository;
protected DistributionSolver $distributionSolver;
protected OrderSolver $orderSolver;

public function loadDependencies(): void
{
$this->producerSolver = $this->loadService(ProducerSolver::class);
$this->orderBuilder = $this->loadService(OrderBuilder::class);
$this->orderStatusRepository = $this->loadService(OrderStatusRepository::class);
$this->orderStatusHistoryManager = $this->loadService(OrderStatusHistoryManager::class);
$this->distributionRepository = $this->loadService(DistributionRepository::class);
$this->subscriptionOrderManager = $this->loadService(\domain\Subscription\Subscription\OrderManager::class);
$this->orderRepository = $this->loadService(OrderRepository::class);
$this->distributionSolver = $this->loadService(DistributionSolver::class);
$this->orderSolver = $this->loadService(OrderSolver::class);
}

public function changeOrderStatus(Order $order, string $orderStatusAlias, User $user)
{
$orderStatus = $this->orderStatusRepository->getOrderStatusByAlias($orderStatusAlias);

$order->setOrderStatus($orderStatus);
$this->orderBuilder->update($order);

$this->orderStatusHistoryManager->create(
$order,
$orderStatus,
new \DateTime(),
$user
);
}

public function deleteOrder(Order $order, User $user, bool $force = false): bool
{
$return = false;
$this->orderBuilder->initOrder($order);

// delete
if ($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_DELETE ||
($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS
&& $this->orderSolver->isOrderStatusCanceled($order))
|| $force) {

$this->changeOrderStatus($order, OrderStatus::ALIAS_DELETED, $user);

}
// cancel
elseif ($this->producerSolver->getConfig('option_behavior_cancel_order') == Producer::BEHAVIOR_DELETE_ORDER_STATUS) {
$this->changeOrderStatus($order, OrderStatus::ALIAS_CANCELED, $user);
$this->orderBuilder->update($order);
}

if($return) {
$orderDeleteEvent = new OrderDeleteEvent();
$orderDeleteEvent->order = $order;
$order->trigger(Order::EVENT_DELETE, $orderDeleteEvent);
}

return $return;
}

public function updateOrdersIncomingDistributionsFromSubscription(Subscription $subscription, User $userAction, $update = false): array
{
$orderArray = [];
$matchedDistributionsArray = $this->distributionRepository->findDistributionsIncomingMatchWithSubscrtiption($subscription, true);

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

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

return $orderArray;
}

public function deleteOrdersIncomingDistributionsFromSubscription(Subscription $subscription, User $userAction, bool $deleteAfterDateEnd = false): int
{
$ordersArray = $this->orderRepository->findOrdersIncomingBySubscription($subscription, !$deleteAfterDateEnd);
$countOrdersDeleted = 0;

if ($ordersArray && count($ordersArray)) {
foreach ($ordersArray as $order) {
if ($this->distributionSolver->isDistributionAvailable($order->distribution)) {
$theOrder = $this->orderRepository->findOneOrderById($order->id);
$this->orderBuilder->initOrder($theOrder);
$this->deleteOrder($order, $userAction, true);
$countOrdersDeleted++;
}
}
}

return $countOrdersDeleted;
}
} }

+ 4
- 2
domain/Order/Order/OrderRepository.php View File

use domain\Document\Invoice\Invoice; use domain\Document\Invoice\Invoice;
use domain\Document\Invoice\InvoiceRepository; use domain\Document\Invoice\InvoiceRepository;
use domain\Document\Invoice\InvoiceSolver; use domain\Document\Invoice\InvoiceSolver;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\ProductOrder\ProductOrderRepository; use domain\Order\ProductOrder\ProductOrderRepository;
use domain\Payment\Payment; use domain\Payment\Payment;
use domain\Payment\PaymentSolver; use domain\Payment\PaymentSolver;


$ordersArray = Order::searchAll([], [ $ordersArray = Order::searchAll([], [
'orderby' => 'IF(ISNULL(date_update), `order`.`date`, `order`.`date_update`) DESC', 'orderby' => 'IF(ISNULL(date_update), `order`.`date`, `order`.`date_update`) DESC',
'conditions' => $conditionsOrders . ' AND (origin = \'' . Order::ORIGIN_USER . '\' OR origin = \'' . Order::ORIGIN_ADMIN . '\' OR (origin = \'' . Order::ORIGIN_AUTO . '\' AND (date_update IS NOT NULL OR date_delete IS NOT NULL)))',
'conditions' => $conditionsOrders . ' AND (origin = \'' . Order::ORIGIN_USER . '\' OR origin = \'' . Order::ORIGIN_ADMIN . '\' OR (origin = \'' . Order::ORIGIN_AUTO . '\' AND (date_update IS NOT NULL OR order_status_alias LIKE \''.OrderStatus::ALIAS_CANCELED.'\')))',
'params' => $paramsOrders, 'params' => $paramsOrders,
]); ]);


{ {
return Order::searchCount([ return Order::searchCount([
'id_user' => $user->id, 'id_user' => $user->id,
], ['conditions' => 'date_delete IS NULL']);
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]);
} }


public function getTotalAmountSpent(User $user): float public function getTotalAmountSpent(User $user): float

+ 7
- 1
domain/Order/Order/OrderRepositoryQuery.php View File



use domain\Document\DeliveryNote\DeliveryNote; use domain\Document\DeliveryNote\DeliveryNote;
use domain\Document\Invoice\Invoice; use domain\Document\Invoice\Invoice;
use domain\Order\OrderStatus\OrderStatus;
use domain\User\User\User; use domain\User\User\User;
use domain\_\AbstractRepositoryQuery; use domain\_\AbstractRepositoryQuery;


return $this; return $this;
} }


public static function getSqlFilterIsValid(): string
{
return "`order`.order_status_alias LIKE '".OrderStatus::ALIAS_ORDERED."'";
}

public function filterIsValid(): self public function filterIsValid(): self
{ {
$this->andWhere('date_delete IS NULL');
$this->andWhere(['order_status_alias' => OrderStatus::ALIAS_ORDERED]);


return $this; return $this;
} }

+ 45
- 5
domain/Order/Order/OrderSolver.php View File

use common\helpers\Price; use common\helpers\Price;
use domain\Document\Document\Document; use domain\Document\Document\Document;
use domain\Document\Document\DocumentSolver; use domain\Document\Document\DocumentSolver;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\OrderStatusHistory\OrderStatusHistory;
use domain\Order\ProductOrder\ProductOrderSolver; use domain\Order\ProductOrder\ProductOrderSolver;
use domain\Payment\Payment; use domain\Payment\Payment;
use domain\Payment\PaymentSolver; use domain\Payment\PaymentSolver;


if (count($ordersArray)) { if (count($ordersArray)) {
foreach ($ordersArray as $order) { foreach ($ordersArray as $order) {
if (is_null($order->date_delete)) {
if($this->isOrderStatusValid($order)) {
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
if ($productOrder->id_product == $product->id) { if ($productOrder->id_product == $product->id) {
$quantity += $this->productOrderSolver->getQuantityPieces($productOrder); $quantity += $this->productOrderSolver->getQuantityPieces($productOrder);


if (count($ordersArray)) { if (count($ordersArray)) {
foreach ($ordersArray as $order) { foreach ($ordersArray as $order) {
if (is_null($order->date_delete) || $ignoreCancel) {
if ($this->isOrderStatusValid($order) || $ignoreCancel) {
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
if ($productOrder->id_product == $product->id && if ($productOrder->id_product == $product->id &&
((is_null($unit) && $productOrder->product->unit == $productOrder->unit) ((is_null($unit) && $productOrder->product->unit == $productOrder->unit)
// getClassHistory // getClassHistory
public function getHistoryClass(Order $order): string public function getHistoryClass(Order $order): string
{ {
if (!is_null($order->date_delete)) {
if($this->isOrderStatusCanceled($order)) {
return 'commande-delete'; return 'commande-delete';
} }


'date' => $order->date_update 'date' => $order->date_update
]; ];
} }
if (!is_null($order->date_delete)) {
if ($this->isOrderStatusCanceled($order)) {
$arr = [ $arr = [
'class' => 'delete', 'class' => 'delete',
'glyphicon' => 'remove', 'glyphicon' => 'remove',
'str' => 'Annulée', 'str' => 'Annulée',
'date' => $order->date_delete
'date' => $this->getOrderStatusHistoryByOrderStatusAlias($order,OrderStatus::ALIAS_CANCELED)
->getDate()->format('Y-m-d H:i:s')
]; ];
} }




return $amount; return $amount;
} }

public function getOrderStatusHistoryByOrderStatusAlias(Order $order, string $orderStatusAlias): ?OrderStatusHistory
{
foreach($order->getOrderStatusHistory() as $orderStatusHistory) {
if($orderStatusHistory->getOrderStatusAlias() == $orderStatusAlias) {
return $orderStatusHistory;
}
}

return null;
}

public function isOrderStatusValid(Order $order): bool
{
return $this->isOrderStatusOrdered($order);
}

public function isOrderStatusCanceledOrDeleted(Order $order): bool
{
return $this->isOrderStatusCanceled($order)
|| $this->isOrderStatusDeleted($order);
}

public function isOrderStatusOrdered(Order $order): bool
{
return $order->getOrderStatusAlias() == OrderStatus::ALIAS_ORDERED;
}

public function isOrderStatusCanceled(Order $order): bool
{
return $order->getOrderStatusAlias() == OrderStatus::ALIAS_CANCELED;
}

public function isOrderStatusDeleted(Order $order): bool
{
return $order->getOrderStatusAlias() == OrderStatus::ALIAS_DELETED;
}
} }

+ 5
- 6
domain/Order/Order/TillerManager.php View File

use common\components\Tiller\TillerClientV2; use common\components\Tiller\TillerClientV2;
use common\components\Tiller\TillerClientV3; use common\components\Tiller\TillerClientV3;
use common\helpers\MeanPayment; use common\helpers\MeanPayment;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\ProductOrder\ProductOrderSolver; use domain\Order\ProductOrder\ProductOrderSolver;
use domain\Producer\Producer\ProducerSolver; use domain\Producer\Producer\ProducerSolver;
use domain\_\AbstractManager; use domain\_\AbstractManager;
if (!$isSynchro) { if (!$isSynchro) {
$orders = Order::searchAll([ $orders = Order::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'order.tiller_synchronization' => 1
], [
'conditions' => 'date_delete IS NULL'
'order.tiller_synchronization' => 1,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]); ]);


$strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1); $strDate = date('Y-m-d\T12:i:s+0000', strtotime($date) + 1);


$ordersOpendistrib = Order::searchAll([ $ordersOpendistrib = Order::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'order.tiller_synchronization' => 1
], [
'conditions' => 'date_delete IS NULL'
'order.tiller_synchronization' => 1,
'order_status_alias' => OrderStatus::ALIAS_ORDERED
]); ]);


$ordersOpendistribSynchro = []; $ordersOpendistribSynchro = [];

+ 35
- 0
domain/Order/OrderStatus/OrderStatus.php View File

<?php

namespace domain\Order\OrderStatus;

class OrderStatus
{
const ALIAS_ORDERED = 'ordered';
const ALIAS_CANCELED = 'canceled';
const ALIAS_DELETED = 'deleted';

public string $alias;
public string $name;

public function getAlias(): string
{
return $this->alias;
}

public function setAlias(string $alias): self
{
$this->alias = $alias;
return $this;
}

public function getName(): string
{
return $this->name;
}

public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}

+ 18
- 0
domain/Order/OrderStatus/OrderStatusBuilder.php View File

<?php

namespace domain\Order\OrderStatus;

use domain\_\AbstractBuilder;

class OrderStatusBuilder extends AbstractBuilder
{
public function instanciateOrderStatus(string $alias, string $name): OrderStatus
{
$orderStatus = new OrderStatus();

$orderStatus->setAlias($alias);
$orderStatus->setName($name);

return $orderStatus;
}
}

+ 28
- 0
domain/Order/OrderStatus/OrderStatusDefinition.php View File

<?php

namespace domain\Order\OrderStatus;

use domain\_\AbstractDefinition;

class OrderStatusDefinition extends AbstractDefinition
{
public function getEntityFqcn(): string
{
return OrderStatus::class;
}

public function getOrderStatusList(): array
{
return [
OrderStatus::ALIAS_ORDERED => [
'name' => 'Commandée'
],
OrderStatus::ALIAS_CANCELED => [
'name' => 'Annulée'
],
OrderStatus::ALIAS_DELETED => [
'name' => 'Supprimée'
]
];
}
}

+ 22
- 0
domain/Order/OrderStatus/OrderStatusModule.php View File

<?php

namespace domain\Order\OrderStatus;

use domain\_\AbstractModule;

class OrderStatusModule extends AbstractModule
{
public function getDefinition(): OrderStatusDefinition
{
return OrderStatusDefinition::getInstance();
}

public function getServices(): array
{
return [
OrderStatusDefinition::class,
OrderStatusRepository::class,
OrderStatusBuilder::class,
];
}
}

+ 36
- 0
domain/Order/OrderStatus/OrderStatusRepository.php View File

<?php

namespace domain\Order\OrderStatus;

use domain\_\AbstractRepository;
use yii\base\ErrorException;

class OrderStatusRepository extends AbstractRepository
{
protected OrderStatusDefinition $orderStatusDefinition;

public function loadDependencies(): void
{
$this->orderStatusDefinition = $this->loadService(OrderStatusDefinition::class);
}

public function getDefaultOptionsSearch(): array
{
return [];
}

public function getOrderStatusByAlias(string $alias): OrderStatus
{
$orderStatusArray = $this->orderStatusDefinition->getOrderStatusList();

if(isset($orderStatusArray[$alias])) {
return OrderStatusBuilder::getInstance()->instanciateOrderStatus(
$alias,
$orderStatusArray[$alias]['name']
);
}
else {
throw new ErrorException('Statut de commande introuvable : '.$alias);
}
}
}

+ 107
- 0
domain/Order/OrderStatusHistory/OrderStatusHistory.php View File

<?php

namespace domain\Order\OrderStatusHistory;

use common\components\ActiveRecordCommon;
use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\User\User\User;

class OrderStatusHistory extends ActiveRecordCommon
{
protected OrderStatus $orderStatusObject;

public function getOrder(): Order
{
return $this->orderRelation;
}

public function setOrder(Order $order): self
{
$this->populateFieldObject('id_order', 'orderRelation', $order);
return $this;
}

public function getUser(): User
{
return $this->userRelation;
}

public function setUser(User $user): self
{
$this->populateFieldObject('id_user', 'userRelation', $user);
return $this;
}

public function getDate(): \DateTime
{
return new \DateTime(strtotime($this->date));
}

public function setDate(\DateTime $date): self
{
$this->date = $date->format('Y-m-d H:i:s');
return $this;
}

public function getOrderStatusAlias(): string
{
return $this->order_status_alias;
}

public function setOrderStatusAlias(string $orderStatusAlias): self
{
$this->order_status_alias = $orderStatusAlias;
return $this;
}

public function getOrderStatus(): OrderStatus
{
return $this->orderStatusObject;
}

public function setOrderStatus(OrderStatus $orderStatus): self
{
$this->orderStatusObject = $orderStatus;
$this->setOrderStatusAlias($orderStatus->getAlias());
return $this;
}

public static function tableName()
{
return 'order_status_history';
}

public function rules()
{
return [
[['id_order', 'order_status_alias', 'date', 'id_user'], 'required'],
[['id_order', 'id_user'], 'integer'],
[['order_status_alias'], 'string'],
[['date'], 'safe'],
];
}

public function attributeLabels()
{
return [
'id' => 'ID',
'id_order' => 'Commande',
'order_status_alias' => 'Statut',
'date' => 'Date',
'id_user' => 'Utilisateur'
];
}

/* Relations */

private function getOrderRelation()
{
return $this->hasOne(Order::class, ['id' => 'id_order']);
}

private function getUserRelation()
{
return $this->hasOne(User::class, ['id' => 'id_user']);
}
}

+ 28
- 0
domain/Order/OrderStatusHistory/OrderStatusHistoryBuilder.php View File

<?php

namespace domain\Order\OrderStatusHistory;

use domain\_\AbstractBuilder;
use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\User\User\User;

class OrderStatusHistoryBuilder extends AbstractBuilder
{
public function instanciateOrderStatusHistory(
Order $order,
OrderStatus $orderStatus,
\DateTime $date,
User $user
): OrderStatusHistory
{
$orderStatusHistory = new OrderStatusHistory();

$orderStatusHistory->setOrder($order);
$orderStatusHistory->setOrderStatus($orderStatus);
$orderStatusHistory->setDate($date);
$orderStatusHistory->setUser($user);

return $orderStatusHistory;
}
}

+ 13
- 0
domain/Order/OrderStatusHistory/OrderStatusHistoryDefinition.php View File

<?php

namespace domain\Order\OrderStatusHistory;

use domain\_\AbstractDefinition;

class OrderStatusHistoryDefinition extends AbstractDefinition
{
public function getEntityFqcn(): string
{
return OrderStatusHistory::class;
}
}

+ 30
- 0
domain/Order/OrderStatusHistory/OrderStatusHistoryManager.php View File

<?php

namespace domain\Order\OrderStatusHistory;

use domain\_\AbstractManager;
use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\User\User\User;

class OrderStatusHistoryManager extends AbstractManager
{
protected OrderStatusHistoryBuilder $orderStatusHistoryBuilder;

public function loadDependencies(): void
{
$this->orderStatusHistoryBuilder = $this->loadService(OrderStatusHistoryBuilder::class);
}

public function create(
Order $order,
OrderStatus $orderStatus,
\DateTime $date,
User $user
): OrderStatusHistory
{
$orderStatusHistory = $this->orderStatusHistoryBuilder->instanciateOrderStatusHistory($order, $orderStatus, $date, $user);
$this->orderStatusHistoryBuilder->create($orderStatusHistory);
return $orderStatusHistory;
}
}

+ 22
- 0
domain/Order/OrderStatusHistory/OrderStatusHistoryModule.php View File

<?php

namespace domain\Order\OrderStatusHistory;

use domain\_\AbstractModule;

class OrderStatusHistoryModule extends AbstractModule
{
public function getDefinition(): OrderStatusHistoryDefinition
{
return OrderStatusHistoryDefinition::getInstance();
}

public function getServices(): array
{
return [
OrderStatusHistoryDefinition::class,
OrderStatusHistoryBuilder::class,
OrderStatusHistoryManager::class,
];
}
}

+ 3
- 1
domain/Producer/Producer/ProducerRepository.php View File

use common\helpers\Price; use common\helpers\Price;
use domain\Document\Document\DocumentInterface; use domain\Document\Document\DocumentInterface;
use domain\Document\Document\DocumentSolver; use domain\Document\Document\DocumentSolver;
use domain\Order\Order\OrderRepositoryQuery;
use domain\Order\OrderStatus\OrderStatus;
use domain\PointSale\PointSale\PointSale; use domain\PointSale\PointSale\PointSale;
use domain\Producer\ProducerPriceRange\ProducerPriceRangeRepository; use domain\Producer\ProducerPriceRange\ProducerPriceRangeRepository;
use domain\User\User\User; use domain\User\User\User;
SELECT SUM('.$selectSum.') AS turnover SELECT SUM('.$selectSum.') AS turnover
FROM `order`, product_order, distribution, tax_rate FROM `order`, product_order, distribution, tax_rate
WHERE `order`.id = product_order.id_order WHERE `order`.id = product_order.id_order
AND `order`.date_delete IS NULL
AND '.OrderRepositoryQuery::getSqlFilterIsValid().'
AND distribution.id_producer = :id_producer AND distribution.id_producer = :id_producer
AND `order`.id_distribution = distribution.id AND `order`.id_distribution = distribution.id
AND distribution.date > :date_start AND distribution.date > :date_start

+ 0
- 37
domain/Subscription/Subscription/OrderManager.php View File



return $ordersSubscriptionsArray; return $ordersSubscriptionsArray;
} }

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

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

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

return $orderArray;
}

public function deleteOrdersIncomingDistributionsFromSubscription(Subscription $subscription, bool $deleteAfterDateEnd = false): int
{
$ordersArray = $this->orderRepository->findOrdersIncomingBySubscription($subscription, !$deleteAfterDateEnd);
$countOrdersDeleted = 0;

if ($ordersArray && count($ordersArray)) {
foreach ($ordersArray as $order) {
if ($this->distributionSolver->isDistributionAvailable($order->distribution)) {
$theOrder = $this->orderRepository->findOneOrderById($order->id);
$this->orderBuilder->initOrder($theOrder);
$this->orderBuilder->deleteOrder($order, true);
$countOrdersDeleted++;
}
}
}

return $countOrdersDeleted;
}
} }

+ 10
- 5
producer/controllers/OrderController.php View File

use domain\Config\Unit\UnitDefinition; use domain\Config\Unit\UnitDefinition;
use domain\Distribution\Distribution\Distribution; use domain\Distribution\Distribution\Distribution;
use domain\Order\Order\Order; use domain\Order\Order\Order;
use domain\Order\OrderStatus\OrderStatus;
use domain\Order\ProductOrder\ProductOrder; use domain\Order\ProductOrder\ProductOrder;
use domain\PointSale\PointSale\PointSale; use domain\PointSale\PointSale\PointSale;
use domain\Producer\Producer\Producer; use domain\Producer\Producer\Producer;
$order = new Order; $order = new Order;
$order->load(\Yii::$app->request->post()); $order->load(\Yii::$app->request->post());
$order->id_user = $user ? $user->id : null; $order->id_user = $user ? $user->id : null;
$order->status = 'tmp-order';
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
$order->origin = Order::ORIGIN_USER; $order->origin = Order::ORIGIN_USER;
} }


$order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ? $order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ?
$pointSaleModule->getComment($pointSale) : ''; $pointSaleModule->getComment($pointSale) : '';
$order->date_delete = null; // la commande est automatiquement réactivée lors d'une modification

// une commande annulée est automatiquement réactivée lors d'une modification
if($orderModule->getSolver()->isOrderStatusCanceled($order)) {
$orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $this->getUserCurrent());
}

$order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false; $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
$order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null; $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;


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


$orderModule->generateOrderReference($order); $orderModule->generateOrderReference($order);
$orderModule->updateOrderStatus($order, 'new-order', 'user');
$orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
$producerModule->addUser($user, $producer); $producerModule->addUser($user, $producer);


// suppression de tous les enregistrements ProductOrder // suppression de tous les enregistrements ProductOrder
throw new \yii\web\NotFoundHttpException('Commande introuvable'); throw new \yii\web\NotFoundHttpException('Commande introuvable');
} }


$orderModule->initOrder($order);
$orderModule->getBuilder()->initOrder($order);


if (!$orderModule->isOrderStateOpen($order)) { if (!$orderModule->isOrderStateOpen($order)) {
throw new UserException('Vous ne pouvez plus annuler cette commande.'); throw new UserException('Vous ne pouvez plus annuler cette commande.');
} }


if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) { if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
$orderModule->deleteOrder($order);
$orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
$this->setFlash('success', 'Votre commande a bien été annulée.'); $this->setFlash('success', 'Votre commande a bien été annulée.');
} }



+ 5
- 4
producer/controllers/SubscriptionController.php View File



public function actionAjaxProcess() public function actionAjaxProcess()
{ {
$orderModule = $this->getOrderModule();
$subscriptionModule = $this->getSubscriptionModule(); $subscriptionModule = $this->getSubscriptionModule();
$model = new SubscriptionForm(); $model = new SubscriptionForm();
$model->id_producer = GlobalParam::getCurrentProducerId(); $model->id_producer = GlobalParam::getCurrentProducerId();
if ($model->load($posts) && $model->validate() && $model->save()) { if ($model->load($posts) && $model->validate() && $model->save()) {


$subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($model->id); $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($model->id);
$subscriptionModule->getOrderManager()
->updateOrdersIncomingDistributionsFromSubscription($subscription, $isUpdate);
$orderModule->getManager()
->updateOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent(), $isUpdate);


if ($isUpdate) { if ($isUpdate) {
$this->setFlash('success', "L'abonnement a bien été modifié"); $this->setFlash('success', "L'abonnement a bien été modifié");
if($subscription) { if($subscription) {
$subscriptionModule->getBuilder()->deleteSubscription($subscription); $subscriptionModule->getBuilder()->deleteSubscription($subscription);
// @TODO : gérer via événements // @TODO : gérer via événements
$this->getSubscriptionModule()->getOrderManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription);
$this->getOrderModule()->getManager()
->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());


$this->setFlash('success', "L'abonnement a bien été modifié"); $this->setFlash('success', "L'abonnement a bien été modifié");
} }

Loading…
Cancel
Save