Browse Source

Refactoring services #885

refactoring
Guillaume 1 year ago
parent
commit
1a70bb505f
100 changed files with 1233 additions and 653 deletions
  1. +1
    -1
      backend/controllers/AccessController.php
  2. +1
    -3
      backend/controllers/BackendController.php
  3. +1
    -1
      backend/controllers/CommunicateAdminController.php
  4. +3
    -6
      backend/controllers/CommunicateController.php
  5. +11
    -21
      backend/controllers/CronController.php
  6. +1
    -1
      backend/controllers/DeliveryNoteController.php
  7. +7
    -10
      backend/controllers/DevelopmentController.php
  8. +77
    -77
      backend/controllers/DistributionController.php
  9. +27
    -27
      backend/controllers/DocumentController.php
  10. +5
    -7
      backend/controllers/InvoiceController.php
  11. +60
    -60
      backend/controllers/OrderController.php
  12. +9
    -17
      backend/controllers/PointSaleController.php
  13. +9
    -9
      backend/controllers/ProducerAdminController.php
  14. +4
    -10
      backend/controllers/ProducerController.php
  15. +3
    -5
      backend/controllers/ProducerPriceRangeAdminController.php
  16. +2
    -14
      backend/controllers/ProductCategoryController.php
  17. +11
    -11
      backend/controllers/ProductController.php
  18. +2
    -2
      backend/controllers/QuotationController.php
  19. +4
    -6
      backend/controllers/ReportController.php
  20. +8
    -14
      backend/controllers/SiteController.php
  21. +1
    -4
      backend/controllers/StatsController.php
  22. +16
    -20
      backend/controllers/SubscriptionController.php
  23. +3
    -8
      backend/controllers/TaxRateAdminController.php
  24. +15
    -15
      backend/controllers/UserController.php
  25. +2
    -12
      backend/controllers/UserGroupController.php
  26. +3
    -3
      backend/models/MailForm.php
  27. +1
    -1
      backend/views/access/index.php
  28. +3
    -3
      backend/views/delivery-note/index.php
  29. +4
    -4
      backend/views/development/_form.php
  30. +8
    -8
      backend/views/development/development.php
  31. +11
    -11
      backend/views/distribution/report-bourlingue.php
  32. +2
    -2
      backend/views/distribution/report-grid.php
  33. +17
    -17
      backend/views/distribution/report.php
  34. +2
    -2
      backend/views/document/_download_product_line.php
  35. +2
    -2
      backend/views/document/_form.php
  36. +5
    -5
      backend/views/document/download.php
  37. +3
    -3
      backend/views/invoice/index.php
  38. +3
    -3
      backend/views/layouts/header.php
  39. +29
    -29
      backend/views/layouts/left.php
  40. +3
    -3
      backend/views/layouts/main-old.php
  41. +8
    -8
      backend/views/order/report.php
  42. +9
    -9
      backend/views/point-sale/_form.php
  43. +3
    -3
      backend/views/point-sale/index.php
  44. +2
    -2
      backend/views/producer-admin/_form.php
  45. +1
    -1
      backend/views/producer-admin/index.php
  46. +17
    -17
      backend/views/producer/update.php
  47. +5
    -5
      backend/views/product/_form.php
  48. +1
    -1
      backend/views/product/index.php
  49. +5
    -5
      backend/views/product/update/prices/_form.php
  50. +1
    -1
      backend/views/product/update/prices/list.php
  51. +2
    -2
      backend/views/quotation/index.php
  52. +1
    -1
      backend/views/site/index.php
  53. +4
    -4
      backend/views/subscription/_form.php
  54. +3
    -3
      backend/views/subscription/index.php
  55. +3
    -3
      backend/views/user/_form.php
  56. +3
    -3
      backend/views/user/credit.php
  57. +2
    -2
      backend/views/user/index.php
  58. +104
    -0
      common/components/BusinessLogic.php
  59. +6
    -6
      common/forms/SubscriptionForm.php
  60. +3
    -3
      common/helpers/Price.php
  61. +2
    -2
      common/helpers/Tiller.php
  62. +31
    -0
      common/logic/Config/TaxRate/TaxRateContainer.php
  63. +17
    -0
      common/logic/Config/TaxRate/TaxRateFactory.php
  64. +43
    -0
      common/logic/Config/TaxRate/TaxRateModel.php
  65. +37
    -0
      common/logic/Config/TaxRate/TaxRateRepository.php
  66. +4
    -5
      common/logic/Development/Development/DevelopmentModel.php
  67. +5
    -9
      common/logic/Development/DevelopmentPriority/DevelopmentPriorityModel.php
  68. +11
    -0
      common/logic/Distribution/Distribution/DistributionBuilder.php
  69. +43
    -0
      common/logic/Distribution/Distribution/DistributionContainer.php
  70. +16
    -0
      common/logic/Distribution/Distribution/DistributionFactory.php
  71. +18
    -20
      common/logic/Distribution/Distribution/DistributionModel.php
  72. +11
    -0
      common/logic/Distribution/Distribution/DistributionRepository.php
  73. +11
    -0
      common/logic/Distribution/Distribution/DistributionSolver.php
  74. +16
    -0
      common/logic/Distribution/PointSaleDistribution/PointSaleDistributionFactory.php
  75. +5
    -7
      common/logic/Distribution/PointSaleDistribution/PointSaleDistributionModel.php
  76. +16
    -0
      common/logic/Distribution/ProductDistribution/ProductDistributionFactory.php
  77. +7
    -7
      common/logic/Distribution/ProductDistribution/ProductDistributionModel.php
  78. +31
    -0
      common/logic/Document/DeliveryNote/DeliveryNoteContainer.php
  79. +16
    -0
      common/logic/Document/DeliveryNote/DeliveryNoteFactory.php
  80. +3
    -3
      common/logic/Document/DeliveryNote/DeliveryNoteModel.php
  81. +4
    -4
      common/logic/Document/DeliveryNote/DeliveryNoteSearch.php
  82. +11
    -0
      common/logic/Document/DeliveryNote/DeliveryNoteSolver.php
  83. +11
    -0
      common/logic/Document/Document/DocumentBuilder.php
  84. +37
    -0
      common/logic/Document/Document/DocumentContainer.php
  85. +10
    -10
      common/logic/Document/Document/DocumentModel.php
  86. +11
    -0
      common/logic/Document/Document/DocumentSolver.php
  87. +11
    -0
      common/logic/Document/Document/DocumentUtils.php
  88. +37
    -0
      common/logic/Document/Invoice/InvoiceContainer.php
  89. +16
    -0
      common/logic/Document/Invoice/InvoiceFactory.php
  90. +3
    -4
      common/logic/Document/Invoice/InvoiceModel.php
  91. +3
    -5
      common/logic/Document/Invoice/InvoiceSearch.php
  92. +39
    -0
      common/logic/Document/Quotation/QuotationContainer.php
  93. +16
    -0
      common/logic/Document/Quotation/QuotationFactory.php
  94. +3
    -3
      common/logic/Document/Quotation/QuotationModel.php
  95. +4
    -4
      common/logic/Document/Quotation/QuotationSearch.php
  96. +12
    -0
      common/logic/Order/Order/OrderBuilder.php
  97. +49
    -0
      common/logic/Order/Order/OrderContainer.php
  98. +16
    -0
      common/logic/Order/Order/OrderFactory.php
  99. +24
    -34
      common/logic/Order/Order/OrderModel.php
  100. +11
    -0
      common/logic/Order/Order/OrderRepository.php

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

]) ])
->all() ; ->all() ;
$producer = Producer::searchOne() ;
$producer = ProducerModel::searchOne() ;


return $this->render('index', [ return $this->render('index', [
'usersArray' => $usersArray, 'usersArray' => $usersArray,

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



namespace backend\controllers; namespace backend\controllers;


use common\models\Producer ;

class BackendController extends \common\controllers\CommonController class BackendController extends \common\controllers\CommonController
{ {
/** /**
*/ */
public function checkProductsPointsSale() public function checkProductsPointsSale()
{ {
if (!Product::searchCount() || !PointSale::searchCount()) {
if (!ProductModel::searchCount() || !PointSaleModel::searchCount()) {
$this->redirect(['site/index', 'error_products_points_sale' => 1]); $this->redirect(['site/index', 'error_products_points_sale' => 1]);
} }
} }

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

public function actionIndex($section = 'producers') public function actionIndex($section = 'producers')
{ {
if($section == 'producers') { if($section == 'producers') {
$producers = Producer::find()->where(['producer.active' => 1])->with(['contact'])->all() ;
$producers = ProducerModel::find()->where(['producer.active' => 1])->with(['contact'])->all() ;
$usersArray = []; $usersArray = [];
$users = [] ; $users = [] ;
foreach ($producers as $producer) { foreach ($producers as $producer) {

+ 3
- 6
backend/controllers/CommunicateController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\Producer ;
use common\models\UserModel ;

/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
*/ */
*/ */
public function actionIndex() public function actionIndex()
{ {
$producer = Producer::searchOne() ;
$pointsSaleArray = PointSale::searchAll() ;
$producer = ProducerModel::searchOne() ;
$pointsSaleArray = PointSaleModel::searchAll() ;
return $this->render('index', [ return $this->render('index', [
'producer' => $producer, 'producer' => $producer,
*/ */
public function actionInstructions() public function actionInstructions()
{ {
$producer = Producer::searchOne() ;
$producer = ProducerModel::searchOne() ;


// get your HTML raw content without any layouts or scripts // get your HTML raw content without any layouts or scripts
$content = $this->renderPartial('instructions_multi', [ $content = $this->renderPartial('instructions_multi', [

+ 11
- 21
backend/controllers/CronController.php View File

namespace backend\controllers; namespace backend\controllers;


use Yii; use Yii;
use common\models\UserModel;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use kartik\mpdf\Pdf;
use common\models\Producer;
use common\models\Order;
use common\models\Subscription;
use common\models\Distribution;
use common\models\CreditHistory;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
$dateTime = strtotime("+7 day"); $dateTime = strtotime("+7 day");
$dayStr = strtolower(date('l', $dateTime)); $dayStr = strtolower(date('l', $dateTime));
$fieldDeliveryDay = 'delivery_' . $dayStr; $fieldDeliveryDay = 'delivery_' . $dayStr;
$pointsSaleArray = PointSale::searchAll(['point_sale.id_producer' => $producer->id]);
$pointsSaleArray = PointSaleModel::searchAll(['point_sale.id_producer' => $producer->id]);
$activeDistribution = false; $activeDistribution = false;
foreach ($pointsSaleArray as $pointSale) { foreach ($pointsSaleArray as $pointSale) {
if ($pointSale->$fieldDeliveryDay) { if ($pointSale->$fieldDeliveryDay) {
} }


if ($activeDistribution) { if ($activeDistribution) {
$distribution = Distribution::initDistribution(date('Y-m-d', $dateTime), $producer->id);
$distribution = DistributionModel::initDistribution(date('Y-m-d', $dateTime), $producer->id);
$distribution->active(true); $distribution->active(true);
} }
} }
} }
} }


$arrayProducers = Producer::searchAll();
$arrayProducers = ProducerModel::searchAll();


foreach ($arrayProducers as $producer) { foreach ($arrayProducers as $producer) {
$countOrders = 0; $countOrders = 0;
$mailOrdersSend = false; $mailOrdersSend = false;


$distribution = Distribution::findOne([
$distribution = DistributionModel::findOne([
'date' => $date, 'date' => $date,
'active' => 1, 'active' => 1,
'id_producer' => $producer->id, 'id_producer' => $producer->id,
* Paiement des commandes (paiement automatique) * Paiement des commandes (paiement automatique)
*/ */


$arrayOrders = Order::searchAll([
$arrayOrders = OrderModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $producer->id 'distribution.id_producer' => $producer->id
], [ ], [
'conditions' => 'date_delete IS NULL' 'conditions' => 'date_delete IS NULL'
]); ]);


$configCredit = Producer::getConfig('credit', $producer->id);
$configCredit = ProducerModel::getConfig('credit', $producer->id);


if ($arrayOrders && is_array($arrayOrders)) { if ($arrayOrders && is_array($arrayOrders)) {
foreach ($arrayOrders as $order) { foreach ($arrayOrders as $order) {
if ($order->auto_payment && $configCredit) { if ($order->auto_payment && $configCredit) {
if ($order->getAmount(Order::AMOUNT_REMAINING) > 0) {
if ($order->getAmount(OrderModel::AMOUNT_REMAINING) > 0) {
$order->saveCreditHistory( $order->saveCreditHistory(
CreditHistory::TYPE_PAYMENT,
$order->getAmount(Order::AMOUNT_REMAINING),
CreditHistoryModel::TYPE_PAYMENT,
$order->getAmount(OrderModel::AMOUNT_REMAINING),
$order->distribution->id_producer, $order->distribution->id_producer,
$order->id_user, $order->id_user,
UserModel::ID_USER_SYSTEM UserModel::ID_USER_SYSTEM
* Envoi des commandes par email au producteur * Envoi des commandes par email au producteur
*/ */


if (!strlen($forceDate) && Producer::getConfig('option_notify_producer_order_summary', $producer->id)) {
$arrayOrders = Order::searchAll([
if (!strlen($forceDate) && ProducerModel::getConfig('option_notify_producer_order_summary', $producer->id)) {
$arrayOrders = OrderModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $producer->id 'distribution.id_producer' => $producer->id
], [ ], [

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

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return UserModel::hasAccessBackend();
} }
] ]
], ],

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



use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use Yii; use Yii;
use common\models\UserModel;
use common\models\Development;
use common\models\DevelopmentPriority;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
} }




public function actionDevelopment($status = Development::STATUS_OPEN)
public function actionDevelopment($status = DevelopmentModel::STATUS_OPEN)
{ {
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => Development::find()
'query' => DevelopmentModel::find()
->with(['developmentPriority', 'developmentPriorityCurrentProducer']) ->with(['developmentPriority', 'developmentPriorityCurrentProducer'])
->where(['status' => $status]) ->where(['status' => $status])
->orderBy('date DESC'), ->orderBy('date DESC'),
*/ */
public function actionPriority($idDevelopment, $priority = null) public function actionPriority($idDevelopment, $priority = null)
{ {
$develpmentPriority = DevelopmentPriority::searchOne([
$develpmentPriority = DevelopmentPriorityModel::searchOne([
'id_development' => $idDevelopment, 'id_development' => $idDevelopment,
]) ; ]) ;


if (in_array($priority, [DevelopmentPriority::PRIORITY_HIGH,
DevelopmentPriority::PRIORITY_NORMAL,
DevelopmentPriority::PRIORITY_LOW])) {
if (in_array($priority, [DevelopmentPriorityModel::PRIORITY_HIGH,
DevelopmentPriorityModel::PRIORITY_NORMAL,
DevelopmentPriorityModel::PRIORITY_LOW])) {


if ($develpmentPriority) { if ($develpmentPriority) {
$develpmentPriority->priority = $priority; $develpmentPriority->priority = $priority;
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = Development::findOne($id)) !== null) {
if (($model = DevelopmentModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

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



$orderUpdate = null; $orderUpdate = null;
if ($idOrderUpdate) { if ($idOrderUpdate) {
$orderUpdate = Order::searchOne(['id' => $idOrderUpdate]);
$orderUpdate = OrderModel::searchOne(['id' => $idOrderUpdate]);
} }


return $this->render('index', [ return $this->render('index', [


$json['means_payment'] = MeanPayment::getAll(); $json['means_payment'] = MeanPayment::getAll();


$distributionsArray = Distribution::searchAll([
$distributionsArray = DistributionModel::searchAll([
'active' => 1 'active' => 1
], [ ], [
'conditions' => [ 'conditions' => [


if ($dateObject && $dateObject->format($format) === $date) { if ($dateObject && $dateObject->format($format) === $date) {
// distribution // distribution
$distribution = Distribution::initDistribution($date);
$distribution = DistributionModel::initDistribution($date);
$json['distribution'] = [ $json['distribution'] = [
'id' => $distribution->id, 'id' => $distribution->id,
'active' => $distribution->active, 'active' => $distribution->active,
]; ];


// commandes // commandes
$ordersArray = Order::searchAll([
$ordersArray = OrderModel::searchAll([
'distribution.id' => $distribution->id, 'distribution.id' => $distribution->id,
], [ ], [
'orderby' => 'user.lastname ASC, user.name ASC' 'orderby' => 'user.lastname ASC, user.name ASC'
$json['distribution']['weight'] = number_format($weight, 2); $json['distribution']['weight'] = number_format($weight, 2);


// products // products
$productsQuery = Product::find()
$productsQuery = ProductModel::find()
->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),]) ->orWhere(['id_producer' => GlobalParam::getCurrentProducerId(),])
->joinWith([ ->joinWith([
'taxRate', 'taxRate',
$potentialWeight = 0; $potentialWeight = 0;


foreach ($productsArray as &$theProduct) { foreach ($productsArray as &$theProduct) {
$quantityOrder = Order::getProductQuantity($theProduct['id'], $ordersArray);
$quantityOrder = OrderModel::getProductQuantity($theProduct['id'], $ordersArray);
$theProduct['quantity_ordered'] = $quantityOrder; $theProduct['quantity_ordered'] = $quantityOrder;


if (!isset($theProduct['productDistribution'][0])) { if (!isset($theProduct['productDistribution'][0])) {
$productOrderArray = []; $productOrderArray = [];
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$productOrderArray[$productOrder->id_product] = [ $productOrderArray[$productOrder->id_product] = [
'quantity' => $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'],
'quantity' => $productOrder->quantity * ProductModel::$unitsArray[$productOrder->unit]['coefficient'],
'unit' => $productOrder->unit, 'unit' => $productOrder->unit,
'price' => number_format($productOrder->price, 3), 'price' => number_format($productOrder->price, 3),
'invoice_price' => number_format($productOrder->invoice_price, 2), 'invoice_price' => number_format($productOrder->invoice_price, 2),
'wording' => $creditHistoryService->getStrWording($creditHistory), 'wording' => $creditHistoryService->getStrWording($creditHistory),
'debit' => ($creditHistoryService->isTypeDebit($creditHistory) ? '- ' . $creditHistoryService->getAmount( 'debit' => ($creditHistoryService->isTypeDebit($creditHistory) ? '- ' . $creditHistoryService->getAmount(
$creditHistory, $creditHistory,
Order::AMOUNT_TOTAL,
OrderModel::AMOUNT_TOTAL,
true true
) : ''), ) : ''),
'credit' => ($creditHistoryService->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryService->getAmount( 'credit' => ($creditHistoryService->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryService->getAmount(
$creditHistory, $creditHistory,
Order::AMOUNT_TOTAL,
OrderModel::AMOUNT_TOTAL,
true true
) : '') ) : '')
]; ];
$order = array_merge($order->getAttributes(), [ $order = array_merge($order->getAttributes(), [
'selected' => false, 'selected' => false,
'weight' => $order->weight, 'weight' => $order->weight,
'amount' => Price::numberTwoDecimals($order->getAmountWithTax(Order::AMOUNT_TOTAL)),
'amount_paid' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_PAID)),
'amount_remaining' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_REMAINING)),
'amount_surplus' => Price::numberTwoDecimals($order->getAmount(Order::AMOUNT_SURPLUS)),
'amount' => Price::numberTwoDecimals($order->getAmountWithTax(OrderModel::AMOUNT_TOTAL)),
'amount_paid' => Price::numberTwoDecimals($order->getAmount(OrderModel::AMOUNT_PAID)),
'amount_remaining' => Price::numberTwoDecimals($order->getAmount(OrderModel::AMOUNT_REMAINING)),
'amount_surplus' => Price::numberTwoDecimals($order->getAmount(OrderModel::AMOUNT_SURPLUS)),
'user' => (isset($order->user)) ? array_merge( 'user' => (isset($order->user)) ? array_merge(
$order->user->getAttributes(), $order->user->getAttributes(),
$arrayCreditUser $arrayCreditUser
$json['orders'] = $ordersArray; $json['orders'] = $ordersArray;


// points de vente // points de vente
$pointsSaleArray = PointSale::find()
$pointsSaleArray = PointSaleModel::find()
->joinWith([ ->joinWith([
'pointSaleDistribution' => function ($q) use ($distribution) { 'pointSaleDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]); $q->where(['id_distribution' => $distribution->id]);
$json['points_sale'] = $pointsSaleArray; $json['points_sale'] = $pointsSaleArray;


// bons de livraison // bons de livraison
$deliveryNotesArray = DeliveryNote::searchAll([
$deliveryNotesArray = DeliveryNoteModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
], [ ], [
'join_with' => ['user AS user_delivery_note', 'orders', 'producer'] 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
$dateSaturday = date('Y-m-d', strtotime('Saturday', $start)); $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
$dateSunday = date('Y-m-d', strtotime('Sunday', $start)); $dateSunday = date('Y-m-d', strtotime('Sunday', $start));


$weekDistribution = Distribution::find()
$weekDistribution = DistributionModel::find()
->andWhere([ ->andWhere([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
'active' => 1, 'active' => 1,
} }


// abonnements manquants // abonnements manquants
$arraySubscriptions = Subscription::searchByDate($date);
$arraySubscriptions = SubscriptionModel::searchByDate($date);
$json['missing_subscriptions'] = []; $json['missing_subscriptions'] = [];
if ($distribution->active) { if ($distribution->active) {
foreach ($arraySubscriptions as $subscription) { foreach ($arraySubscriptions as $subscription) {
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne(['id' => $idOrder]);
$distribution = Distribution::findOne($idDistribution);
$order = OrderModel::searchOne(['id' => $idOrder]);
$distribution = DistributionModel::findOne($idDistribution);
$user = UserModel::findOne($idUser); $user = UserModel::findOne($idUser);
$pointSale = PointSale::findOne($idPointSale);
$pointSale = PointSaleModel::findOne($idPointSale);


$productsArray = Product::find()
$productsArray = ProductModel::find()
->where([ ->where([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
])->joinWith([ ])->joinWith([
$productOrderArray[$product['id']] = [ $productOrderArray[$product['id']] = [
'quantity' => $quantity, 'quantity' => $quantity,
'unit' => $product->unit, 'unit' => $product->unit,
'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
'unit_coefficient' => ProductModel::$unitsArray[$product->unit]['coefficient'],
'prices' => $priceArray, 'prices' => $priceArray,
'active' => $product->productDistribution[0]->active 'active' => $product->productDistribution[0]->active
&& (!$pointSale || $product->isAvailableOnPointSale($pointSale)), && (!$pointSale || $product->isAvailableOnPointSale($pointSale)),


public function actionAjaxUpdateInvoicePrices($idOrder) public function actionAjaxUpdateInvoicePrices($idOrder)
{ {
$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => (int)$idOrder 'id' => (int)$idOrder
]); ]);


$idProducer = GlobalParam::getCurrentProducerId(); $idProducer = GlobalParam::getCurrentProducerId();
} }


$ordersArray = Order::searchAll(
$ordersArray = OrderModel::searchAll(
[ [
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $idProducer 'distribution.id_producer' => $idProducer
] ]
); );


$distribution = Distribution::searchOne([
$distribution = DistributionModel::searchOne([
'id_producer' => $idProducer 'id_producer' => $idProducer
], [ ], [
'conditions' => 'date LIKE :date', 'conditions' => 'date LIKE :date',
]); ]);


if ($distribution) { if ($distribution) {
$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$pointsSaleArray = PointSale::searchAll([
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);
$pointsSaleArray = PointSaleModel::searchAll([
'point_sale.id_producer' => $idProducer 'point_sale.id_producer' => $idProducer
]); ]);


} }


// produits // produits
$productsArray = Product::find()
$productsArray = ProductModel::find()
->joinWith([ ->joinWith([
'productDistribution' => function ($q) use ($distribution) { 'productDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]); $q->where(['id_distribution' => $distribution->id]);
'pointsSaleArray' => $pointsSaleArray, 'pointsSaleArray' => $pointsSaleArray,
'productsArray' => $productsArray, 'productsArray' => $productsArray,
'ordersArray' => $ordersArray, 'ordersArray' => $ordersArray,
'producer' => Producer::searchOne(['id' => $idProducer])
'producer' => ProducerModel::searchOne(['id' => $idProducer])
]); ]);


$dateStr = date('d/m/Y', strtotime($date)); $dateStr = date('d/m/Y', strtotime($date));
} elseif ($type == 'csv') { } elseif ($type == 'csv') {
$datas = []; $datas = [];


$optionCsvExportAllProducts = Producer::getConfig('option_csv_export_all_products');
$optionCsvExportByPiece = Producer::getConfig('option_csv_export_by_piece');
$optionCsvExportAllProducts = ProducerModel::getConfig('option_csv_export_all_products');
$optionCsvExportByPiece = ProducerModel::getConfig('option_csv_export_by_piece');


// produits en colonne // produits en colonne
$productsNameArray = ['', 'Commentaire']; $productsNameArray = ['', 'Commentaire'];
$cpt = 2; $cpt = 2;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$productsHasQuantity[$product->id] = 0; $productsHasQuantity[$product->id] = 0;
foreach (Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $ordersArray, true, $unit);
foreach (ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray, true, $unit);
if ($quantity) { if ($quantity) {
$productsHasQuantity[$product->id] += $quantity; $productsHasQuantity[$product->id] += $quantity;
} }
$productUnit = $product->unit; $productUnit = $product->unit;
} }


$productName .= ' (' . Product::strUnit($productUnit, 'wording_short', true) . ')';
$productName .= ' (' . ProductModel::strUnit($productUnit, 'wording_short', true) . ')';


$productsNameArray[] = $productName; $productsNameArray[] = $productName;
$productsIndexArray[$product->id] = $cpt++; $productsIndexArray[$product->id] = $cpt++;


if ($optionCsvExportByPiece) { if ($optionCsvExportByPiece) {
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
$orderLine[$productsIndexArray[$productOrder->id_product]] = Order::getProductQuantityPieces(
$orderLine[$productsIndexArray[$productOrder->id_product]] = OrderModel::getProductQuantityPieces(
$productOrder->id_product, $productOrder->id_product,
[$order] [$order]
); );
} }
$orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity; $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
if ($productOrder->product->unit != $productOrder->unit) { if ($productOrder->product->unit != $productOrder->unit) {
$orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit(
$orderLine[$productsIndexArray[$productOrder->id_product]] .= ProductModel::strUnit(
$productOrder->unit, $productOrder->unit,
'wording_short', 'wording_short',
true true
$idProducer = GlobalParam::getCurrentProducerId(); $idProducer = GlobalParam::getCurrentProducerId();
} }


$distribution = Distribution::searchOne([
$distribution = DistributionModel::searchOne([
'id_producer' => $idProducer 'id_producer' => $idProducer
], [ ], [
'conditions' => 'date LIKE :date', 'conditions' => 'date LIKE :date',
]); ]);


if ($distribution) { if ($distribution) {
$ordersArray = Order::searchAll(
$ordersArray = OrderModel::searchAll(
[ [
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $idProducer 'distribution.id_producer' => $idProducer
] ]
); );


$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$pointsSaleArray = PointSale::searchAll([
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);
$pointsSaleArray = PointSaleModel::searchAll([
'point_sale.id_producer' => $idProducer 'point_sale.id_producer' => $idProducer
]); ]);


} }


// catégories // catégories
$categoriesArray = ProductCategory::searchAll(
$categoriesArray = ProductCategoryModel::searchAll(
['id_producer' => $idProducer], ['id_producer' => $idProducer],
['orderby' => 'product_category.position ASC'] ['orderby' => 'product_category.position ASC']
); );
array_unshift($categoriesArray, null); array_unshift($categoriesArray, null);


// produits // produits
$productsArray = Product::find()
$productsArray = ProductModel::find()
->joinWith([ ->joinWith([
'productDistribution' => function ($q) use ($distribution) { 'productDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]); $q->where(['id_distribution' => $distribution->id]);
'categoriesArray' => $categoriesArray, 'categoriesArray' => $categoriesArray,
'productsArray' => $productsArray, 'productsArray' => $productsArray,
'ordersArray' => $ordersArrayPaged, 'ordersArray' => $ordersArrayPaged,
'producer' => Producer::searchOne(['id' => $idProducer])
'producer' => ProducerModel::searchOne(['id' => $idProducer])
]); ]);


$dateStr = date('d/m/Y', strtotime($date)); $dateStr = date('d/m/Y', strtotime($date));
public function actionReportTerredepains($date, $key) public function actionReportTerredepains($date, $key)
{ {
if ($key == 'ef572cc148c001f0180c4a624189ed30') { if ($key == 'ef572cc148c001f0180c4a624189ed30') {
$producer = Producer::searchOne([
$producer = ProducerModel::searchOne([
'producer.slug' => 'terredepains' 'producer.slug' => 'terredepains'
]); ]);


$idProducer = $producer->id; $idProducer = $producer->id;


$ordersArray = Order::searchAll(
$ordersArray = OrderModel::searchAll(
[ [
'distribution.date' => $date, 'distribution.date' => $date,
'distribution.id_producer' => $idProducer 'distribution.id_producer' => $idProducer
] ]
); );


$distribution = Distribution::searchOne([
$distribution = DistributionModel::searchOne([
'distribution.id_producer' => $idProducer 'distribution.id_producer' => $idProducer
], [ ], [
'conditions' => 'date LIKE :date', 'conditions' => 'date LIKE :date',
]); ]);


if ($distribution) { if ($distribution) {
$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$pointsSaleArray = PointSale::searchAll([
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);
$pointsSaleArray = PointSaleModel::searchAll([
'point_sale.id_producer' => $idProducer 'point_sale.id_producer' => $idProducer
]); ]);


} }


// produits // produits
$productsArray = Product::find()
$productsArray = ProductModel::find()
->joinWith([ ->joinWith([
'productDistribution' => function ($q) use ($distribution) { 'productDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]); $q->where(['id_distribution' => $distribution->id]);
$productsHasQuantity = []; $productsHasQuantity = [];
$cpt = 1; $cpt = 1;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$theUnit = Product::strUnit($product->unit, 'wording_short', true);
$theUnit = ProductModel::strUnit($product->unit, 'wording_short', true);
$theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')'; $theUnit = ($theUnit == 'p.') ? '' : ' (' . $theUnit . ')';
$productsNameArray[] = $product->name . $theUnit; $productsNameArray[] = $product->name . $theUnit;
$productsIndexArray[$product->id] = $cpt++; $productsIndexArray[$product->id] = $cpt++;
} }
$orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity; $orderLine[$productsIndexArray[$productOrder->id_product]] .= $productOrder->quantity;
if ($productOrder->product->unit != $productOrder->unit) { if ($productOrder->product->unit != $productOrder->unit) {
$orderLine[$productsIndexArray[$productOrder->id_product]] .= Product::strUnit($productOrder->unit, 'wording_short', true);
$orderLine[$productsIndexArray[$productOrder->id_product]] .= ProductModel::strUnit($productOrder->unit, 'wording_short', true);
} }
} }
$datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true); $datas[] = $this->_lineOrderReportCSV($orderLine, $cpt - 1, true);
{ {
$totalsPointSaleArray = [$label]; $totalsPointSaleArray = [$label];
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach (Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
foreach (ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray, false, $unit);
if ($quantity) { if ($quantity) {
$index = $productsIndexArray[$product->id]; $index = $productsIndexArray[$product->id];
if (!isset($totalsPointSaleArray[$index])) { if (!isset($totalsPointSaleArray[$index])) {
$totalsPointSaleArray[$index] .= $quantity; $totalsPointSaleArray[$index] .= $quantity;


if ($product->unit != $unit) { if ($product->unit != $unit) {
$totalsPointSaleArray[$index] .= '' . Product::strUnit($unit, 'wording_short', true);
$totalsPointSaleArray[$index] .= '' . ProductModel::strUnit($unit, 'wording_short', true);
} }
} }
} }


foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$quantity = 0; $quantity = 0;
foreach (Product::$unitsArray as $unit => $dataUnit) {
$quantityProduct = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
foreach (ProductModel::$unitsArray as $unit => $dataUnit) {
$quantityProduct = OrderModel::getProductQuantity($product->id, $ordersArray, false, $unit);


if ($unit == 'piece') { if ($unit == 'piece') {
$quantity += $quantityProduct; $quantity += $quantityProduct;
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$productDistribution = ProductDistribution::searchOne([
$productDistribution = ProductDistributionModel::searchOne([
'id_distribution' => $idDistribution, 'id_distribution' => $idDistribution,
'id_product' => $idProduct, 'id_product' => $idProduct,
]); ]);
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$productDistribution = ProductDistribution::searchOne([
$productDistribution = ProductDistributionModel::searchOne([
'id_distribution' => $idDistribution, 'id_distribution' => $idDistribution,
'id_product' => $idProduct, 'id_product' => $idProduct,
]); ]);
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$pointSaleDistribution = PointSaleDistribution::searchOne([
$pointSaleDistribution = PointSaleDistributionModel::searchOne([
'id_distribution' => $idDistribution, 'id_distribution' => $idDistribution,
'id_point_sale' => $idPointSale, 'id_point_sale' => $idPointSale,
]); ]);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


if ($idDistribution) { if ($idDistribution) {
$distribution = Distribution::searchOne([
$distribution = DistributionModel::searchOne([
'id' => $idDistribution 'id' => $idDistribution
]); ]);
} }
$format = 'Y-m-d'; $format = 'Y-m-d';
$dateObject = DateTime::createFromFormat($format, $date); $dateObject = DateTime::createFromFormat($format, $date);
if ($dateObject && $dateObject->format($format) === $date) { if ($dateObject && $dateObject->format($format) === $date) {
$distribution = Distribution::initDistribution($date);
$distribution = DistributionModel::initDistribution($date);
} }


if ($distribution) { if ($distribution) {
$dateSaturday = date('Y-m-d', strtotime('Saturday', $start)); $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
$dateSunday = date('Y-m-d', strtotime('Sunday', $start)); $dateSunday = date('Y-m-d', strtotime('Sunday', $start));


$pointsSaleArray = PointSale::searchAll();
$pointsSaleArray = PointSaleModel::searchAll();


$activeMonday = false; $activeMonday = false;
$activeTuesday = false; $activeTuesday = false;
public function actionAjaxProcessAddSubscriptions($date) public function actionAjaxProcessAddSubscriptions($date)
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
Subscription::addAll($date, true);
SubscriptionModel::addAll($date, true);
return ['success']; return ['success'];
} }


{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$return = []; $return = [];
$producerTiller = Producer::getConfig('tiller');
$producerTiller = ProducerModel::getConfig('tiller');


if ($producerTiller) { if ($producerTiller) {
$tiller = new Tiller(); $tiller = new Tiller();
$isSynchro = $tiller->isSynchro($date); $isSynchro = $tiller->isSynchro($date);


if (!$isSynchro) { if (!$isSynchro) {
$orders = Order::searchAll([
$orders = OrderModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'order.tiller_synchronization' => 1 'order.tiller_synchronization' => 1
], [ ], [
[ [
'type' => $typePaymentTiller, 'type' => $typePaymentTiller,
'amount' => $order->getAmountWithTax( 'amount' => $order->getAmountWithTax(
Order::AMOUNT_TOTAL
OrderModel::AMOUNT_TOTAL
) * 100, ) * 100,
'status' => 'ACCEPTED', 'status' => 'ACCEPTED',
'date' => $strDate 'date' => $strDate


if (is_array($idOrders) && count($idOrders) > 0) { if (is_array($idOrders) && count($idOrders) > 0) {
foreach ($idOrders as $idOrder) { foreach ($idOrders as $idOrder) {
$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => (int)$idOrder 'id' => (int)$idOrder
]); ]);


if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) { if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
$deliveryNote = DeliveryNote::searchOne([
$deliveryNote = DeliveryNoteModel::searchOne([
'id' => (int)$order->id_delivery_note 'id' => (int)$order->id_delivery_note
]); ]);




if (is_array($idOrders) && count($idOrders) > 0) { if (is_array($idOrders) && count($idOrders) > 0) {
foreach ($idOrders as $idOrder) { foreach ($idOrders as $idOrder) {
$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => (int)$idOrder 'id' => (int)$idOrder
]); ]);


$deliveryNote = null; $deliveryNote = null;
$idDeliveryNote = $order->id_delivery_note; $idDeliveryNote = $order->id_delivery_note;
if ($idDeliveryNote) { if ($idDeliveryNote) {
$deliveryNote = DeliveryNote::searchOne([
$deliveryNote = DeliveryNoteModel::searchOne([
'id' => (int)$idDeliveryNote 'id' => (int)$idDeliveryNote
]); ]);
} }
if (is_array($idOrders) && count($idOrders) > 0) { if (is_array($idOrders) && count($idOrders) > 0) {
// récupération première commande pour obtenir des infos // récupération première commande pour obtenir des infos
reset($idOrders); reset($idOrders);
$firstOrder = Order::searchOne([
$firstOrder = OrderModel::searchOne([
'id' => (int)$idOrders[key($idOrders)] 'id' => (int)$idOrders[key($idOrders)]
]); ]);


$deliveryNote = null; $deliveryNote = null;
$isUpdate = false; $isUpdate = false;
$i = 0; $i = 0;
$ordersArray = Order::searchAll([
$ordersArray = OrderModel::searchAll([
'id' => $idOrders, 'id' => $idOrders,
]); ]);
do { do {
$order = $ordersArray[$i]; $order = $ordersArray[$i];
if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) { if ($order->distribution->id_producer == GlobalParam::getCurrentProducerId() && $order->id_delivery_note > 0) {
$deliveryNote = DeliveryNote::searchOne([
$deliveryNote = DeliveryNoteModel::searchOne([
'id' => $order->id_delivery_note 'id' => $order->id_delivery_note
]); ]);
$isUpdate = true; $isUpdate = true;
$i++; $i++;
} while ($deliveryNote == null && isset($ordersArray[$i])); } while ($deliveryNote == null && isset($ordersArray[$i]));


if ($deliveryNote && $deliveryNote->status == Document::STATUS_VALID) {
if ($deliveryNote && $deliveryNote->status == DocumentModel::STATUS_VALID) {
return [ return [
'return' => 'error', 'return' => 'error',
'alert' => [ 'alert' => [
$deliveryNote->save(); $deliveryNote->save();
} else { } else {
// réinitialisation des order.id_delivery_note // réinitialisation des order.id_delivery_note
Order::updateAll([
OrderModel::updateAll([
'id_delivery_note' => null 'id_delivery_note' => null
], [ ], [
'id_delivery_note' => $deliveryNote->id 'id_delivery_note' => $deliveryNote->id


// affectation du BL aux commandes // affectation du BL aux commandes
foreach ($idOrders as $idOrder) { foreach ($idOrders as $idOrder) {
$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => (int)$idOrder 'id' => (int)$idOrder
]); ]);
if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) { if ($order && $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
} }


// init invoice price // init invoice price
$order = Order::searchOne(['id' => $idOrder]);
$order = OrderModel::searchOne(['id' => $idOrder]);
if ($order) { if ($order) {
$order->initInvoicePrices([ $order->initInvoicePrices([
'user' => $user, 'user' => $user,

+ 27
- 27
backend/controllers/DocumentController.php View File

set_time_limit(0); set_time_limit(0);


$validatedDocumentsArray = array_merge( $validatedDocumentsArray = array_merge(
Quotation::find()->where(['status' => Document::STATUS_VALID])->all(),
DeliveryNote::find()->where(['status' => Document::STATUS_VALID])->all(),
Invoice::find()->where(['status' => Document::STATUS_VALID])->all()
QuotationModel::find()->where(['status' => DocumentModel::STATUS_VALID])->all(),
DeliveryNoteModel::find()->where(['status' => DocumentModel::STATUS_VALID])->all(),
InvoiceModel::find()->where(['status' => DocumentModel::STATUS_VALID])->all()
); );


foreach($validatedDocumentsArray as $document) { foreach($validatedDocumentsArray as $document) {
if ($model->getClass() == 'Invoice') { if ($model->getClass() == 'Invoice') {
if ($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) { if ($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) {
foreach ($model->deliveryNotes as $key => $idDeliveryNote) { foreach ($model->deliveryNotes as $key => $idDeliveryNote) {
Order::updateAll([
OrderModel::updateAll([
'id_invoice' => $model->id 'id_invoice' => $model->id
], [ ], [
'id_delivery_note' => $idDeliveryNote 'id_delivery_note' => $idDeliveryNote
$model->delete(); $model->delete();


if ($this->getClass() == 'DeliveryNote') { if ($this->getClass() == 'DeliveryNote') {
Order::updateAll([
OrderModel::updateAll([
'order.id_delivery_note' => null 'order.id_delivery_note' => null
], [ ], [
'order.id_delivery_note' => $id 'order.id_delivery_note' => $id
} }


if ($this->getClass() == 'Quotation') { if ($this->getClass() == 'Quotation') {
Order::updateAll([
OrderModel::updateAll([
'order.id_quotation' => null 'order.id_quotation' => null
], [ ], [
'order.id_quotation' => $id 'order.id_quotation' => $id
} }


if ($this->getClass() == 'Invoice') { if ($this->getClass() == 'Invoice') {
Order::updateAll([
OrderModel::updateAll([
'order.id_invoice' => null 'order.id_invoice' => null
], [ ], [
'order.id_invoice' => $id 'order.id_invoice' => $id
'', // Réf. '', // Réf.
$productOrder->product->name, // Désignation * $productOrder->product->name, // Désignation *
$productOrder->quantity, // Qté * $productOrder->quantity, // Qté *
'', // Product::strUnit($productOrder->unit, 'wording'), // Unité
'', // ProductModel::strUnit($productOrder->unit, 'wording'), // Unité
$price, // PU HT * $price, // PU HT *
'', // Remise '', // Remise
$productOrder->taxRate->value * 100, // TVA $productOrder->taxRate->value * 100, // TVA
'orderby' => 'distribution.date ASC', 'orderby' => 'distribution.date ASC',
'join_with' => ['user AS user_delivery_note', 'orders', 'producer'] 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
]; ];
$deliveryNotesCreateArray = DeliveryNote::searchAll([
$deliveryNotesCreateArray = DeliveryNoteModel::searchAll([
'id_user' => $user->id, 'id_user' => $user->id,
'status' => Document::STATUS_VALID
'status' => DocumentModel::STATUS_VALID
], $options); ], $options);
$deliveryNotesUpdateArray = DeliveryNote::searchAll([
$deliveryNotesUpdateArray = DeliveryNoteModel::searchAll([
'id_user' => $user->id, 'id_user' => $user->id,
'status' => Document::STATUS_VALID,
'status' => DocumentModel::STATUS_VALID,
'order.id_invoice' => $idDocument 'order.id_invoice' => $idDocument
], $options); ], $options);
$json['delivery_note_create_array'] = $this->initDeliveryNoteArray('create', $deliveryNotesCreateArray); $json['delivery_note_create_array'] = $this->initDeliveryNoteArray('create', $deliveryNotesCreateArray);
$deliveryNote->getAttributes(), $deliveryNote->getAttributes(),
[ [
'url' => Yii::$app->urlManager->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]), 'url' => Yii::$app->urlManager->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
'total' => $deliveryNote->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL)
'total' => $deliveryNote->getAmountWithTax(OrderModel::INVOICE_AMOUNT_TOTAL)
] ]
); );


{ {
$classDocument = $this->getClass(); $classDocument = $this->getClass();


if ($id > 0 && Document::isValidClass($classDocument)) {
if ($id > 0 && DocumentModel::isValidClass($classDocument)) {
$document = $classDocument::searchOne([ $document = $classDocument::searchOne([
'id' => $id 'id' => $id
]); ]);
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


if ($idDocument > 0 && Document::isValidClass($classDocument)) {
if ($idDocument > 0 && DocumentModel::isValidClass($classDocument)) {
$document = $classDocument::searchOne([ $document = $classDocument::searchOne([
'id' => $idDocument 'id' => $idDocument
]); ]);
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


if ($idDocument > 0 && Document::isValidClass($classDocument)) {
if ($idDocument > 0 && DocumentModel::isValidClass($classDocument)) {
$document = $classDocument::searchOne([ $document = $classDocument::searchOne([
'id' => $idDocument 'id' => $idDocument
]); ]);


if ($document) { if ($document) {
$productsArray = Product::searchAll([], [
$productsArray = ProductModel::searchAll([], [
'orderby' => 'product.order ASC' 'orderby' => 'product.order ASC'
]); ]);


'id_user' => $document->user->id, 'id_user' => $document->user->id,
'id_producer' => GlobalParam::getCurrentProducerId() 'id_producer' => GlobalParam::getCurrentProducerId()
]); ]);
$pointSale = PointSale::searchOne([
$pointSale = PointSaleModel::searchOne([
'id_user' => $document->user->id 'id_user' => $document->user->id
]); ]);


'order', 'order',
function ($product) use ($document, $userProducer, $pointSale) { function ($product) use ($document, $userProducer, $pointSale) {
return array_merge($product->getAttributes(), [ return array_merge($product->getAttributes(), [
'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
'unit_coefficient' => ProductModel::$unitsArray[$product->unit]['coefficient'],
'prices' => $product->getPriceArray($userProducer->user, $pointSale), 'prices' => $product->getPriceArray($userProducer->user, $pointSale),
'wording_unit' => $product->wording_unit, 'wording_unit' => $product->wording_unit,
'tax_rate' => $product->taxRate->value 'tax_rate' => $product->taxRate->value
'orders' => $ordersArray, 'orders' => $ordersArray,
'total' => ($document->getClass() == 'Invoice' || $document->getClass( 'total' => ($document->getClass() == 'Invoice' || $document->getClass(
) == 'DeliveryNote') ? $document->getAmount( ) == 'DeliveryNote') ? $document->getAmount(
Order::INVOICE_AMOUNT_TOTAL
) : $document->getAmount(Order::AMOUNT_TOTAL),
OrderModel::INVOICE_AMOUNT_TOTAL
) : $document->getAmount(OrderModel::AMOUNT_TOTAL),
'total_with_tax' => ($document->getClass() == 'Invoice' || $document->getClass( 'total_with_tax' => ($document->getClass() == 'Invoice' || $document->getClass(
) == 'DeliveryNote') ? $document->getAmountWithTax( ) == 'DeliveryNote') ? $document->getAmountWithTax(
Order::INVOICE_AMOUNT_TOTAL
) : $document->getAmountWithTax(Order::AMOUNT_TOTAL),
OrderModel::INVOICE_AMOUNT_TOTAL
) : $document->getAmountWithTax(OrderModel::AMOUNT_TOTAL),
'invoice_url' => ($document->getClass() == 'DeliveryNote' && $document->getInvoice()) ? Yii::$app->urlManager->createUrl(['invoice/update', 'id' => $document->getInvoice()->id]) : null 'invoice_url' => ($document->getClass() == 'DeliveryNote' && $document->getInvoice()) ? Yii::$app->urlManager->createUrl(['invoice/update', 'id' => $document->getInvoice()->id]) : null
]; ];
} }
$document = $classDocument::searchOne([ $document = $classDocument::searchOne([
'id' => $idDocument 'id' => $idDocument
]); ]);
$product = Product::searchOne([
$product = ProductModel::searchOne([
'id' => $idProduct 'id' => $idProduct
]); ]);


$order->id_point_sale = null; $order->id_point_sale = null;
$order->id_distribution = null; $order->id_distribution = null;
$order->status = 'tmp-order'; $order->status = 'tmp-order';
$order->origin = Order::ORIGIN_ADMIN;
$order->origin = OrderModel::ORIGIN_ADMIN;
$order->date = date('Y-m-d H:i:s'); $order->date = date('Y-m-d H:i:s');
$fieldIdDocument = 'id_' . $classDocument::tableName(); $fieldIdDocument = 'id_' . $classDocument::tableName();
$order->$fieldIdDocument = $document->id; $order->$fieldIdDocument = $document->id;
$productOrder = new ProductOrder; $productOrder = new ProductOrder;
$productOrder->id_order = $order->id; $productOrder->id_order = $order->id;
$productOrder->id_product = $idProduct; $productOrder->id_product = $idProduct;
$quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
$quantity = $quantity / ProductModel::$unitsArray[$product->unit]['coefficient'];
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
$productOrder->price = (float)$price; $productOrder->price = (float)$price;
$productOrder->unit = $product->unit; $productOrder->unit = $product->unit;
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$productOrder = ProductOrder::searchOne([
$productOrder = ProductOrderModel::searchOne([
'id' => $idProductOrder 'id' => $idProductOrder
]); ]);



+ 5
- 7
backend/controllers/InvoiceController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\Order;
use Yii; use Yii;



class InvoiceController extends DocumentController class InvoiceController extends DocumentController
{ {
/** /**
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$invoice = Invoice::searchOne(['id' => $idInvoice]);
$invoice = InvoiceModel::searchOne(['id' => $idInvoice]);


if($invoice && $invoice->isStatusDraft()) { if($invoice && $invoice->isStatusDraft()) {
Order::updateAll([
OrderModel::updateAll([
'id_invoice' => null 'id_invoice' => null
], [ ], [
'id_delivery_note' => $idDeliveryNote 'id_delivery_note' => $idDeliveryNote
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$invoice = Invoice::searchOne(['id' => $idInvoice]);
$deliveryNote = DeliveryNote::searchOne(['id' => $idDeliveryNote]);
$invoice = InvoiceModel::searchOne(['id' => $idInvoice]);
$deliveryNote = DeliveryNoteModel::searchOne(['id' => $idDeliveryNote]);


if($invoice && $invoice->isStatusDraft() && $deliveryNote) { if($invoice && $invoice->isStatusDraft() && $deliveryNote) {
Order::updateAll([
OrderModel::updateAll([
'id_invoice' => $idInvoice 'id_invoice' => $idInvoice
], [ ], [
'id_delivery_note' => $idDeliveryNote 'id_delivery_note' => $idDeliveryNote

+ 60
- 60
backend/controllers/OrderController.php View File

{ {
if ($date != '') { if ($date != '') {
// commandes // commandes
$orders = Order::searchAll([
$orders = OrderModel::searchAll([
'distribution.date' => $date 'distribution.date' => $date
]); ]);


foreach ($point->orders as $order) { foreach ($point->orders as $order) {


// suppression des product_order // suppression des product_order
ProductOrder::deleteAll(['id_order' => $order->id]);
ProductOrderModel::deleteAll(['id_order' => $order->id]);


// création des commande_produit modifiés // création des commande_produit modifiés
foreach ($products as $product) { foreach ($products as $product) {
*/ */
public function actionIndex($date = '', $returnData = false) public function actionIndex($date = '', $returnData = false)
{ {
if (!Product::searchCount() || !PointSale::searchCount()) {
if (!ProductModel::searchCount() || !PointSaleModel::searchCount()) {
$this->redirect(['site/index', 'error_products_points_sale' => 1]); $this->redirect(['site/index', 'error_products_points_sale' => 1]);
} }


} }


// création du jour de distribution // création du jour de distribution
$distribution = Distribution::initDistribution($date);
$distribution = DistributionModel::initDistribution($date);


// points de vente // points de vente
if ($distribution) { if ($distribution) {
$arrayPointsSale = PointSale::find()
$arrayPointsSale = PointSaleModel::find()
->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) { ->joinWith(['pointSaleDistribution' => function ($q) use ($distribution) {
$q->where(['id_distribution' => $distribution->id]); $q->where(['id_distribution' => $distribution->id]);
}]) }])
]) ])
->all(); ->all();
} else { } else {
$arrayPointsSale = PointSale::searchAll();
$arrayPointsSale = PointSaleModel::searchAll();
} }


// produits // produits
$arrayProducts = Product::searchAll();
$arrayProducts = ProductModel::searchAll();


// gestion des commandes // gestion des commandes
$this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users); $this->processOrderForm($distribution, $date, $arrayPointsSale, $arrayProducts, $users);


// commandes // commandes
$arrayOrders = Order::searchAll([
$arrayOrders = OrderModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
]); ]);


if (isset($_POST['Product'])) { if (isset($_POST['Product'])) {


foreach ($arrayProducts as $product) { foreach ($arrayProducts as $product) {
$productDistribution = ProductDistribution::searchOne([
$productDistribution = ProductDistributionModel::searchOne([
'id_distribution' => $distribution->id, 'id_distribution' => $distribution->id,
'id_product' => $product->id 'id_product' => $product->id
]); ]);
$arrayProductsSelected = []; $arrayProductsSelected = [];
if ($distribution) { if ($distribution) {
// produits selec pour production // produits selec pour production
$arrayProductsSelected = ProductDistribution::searchByDistribution($distribution->id);
$arrayProductsSelected = ProductDistributionModel::searchByDistribution($distribution->id);
} }


// produits // produits
if ($distribution) { if ($distribution) {
$arrayProducts = Product::searchByDistribution($distribution->id);
$arrayProducts = ProductModel::searchByDistribution($distribution->id);
} }


// poids total de la production et CA potentiel // poids total de la production et CA potentiel
} }


// jours de distribution // jours de distribution
$arrayDistributionDays = Distribution::searchAll([
$arrayDistributionDays = DistributionModel::searchAll([
'active' => 1 'active' => 1
]); ]);


$oointsSaleDistribution = []; $oointsSaleDistribution = [];


if ($distribution) { if ($distribution) {
$pointsSaleDistribution = PointSaleDistribution::searchAll([
$pointsSaleDistribution = PointSaleDistributionModel::searchAll([
'id_distribution' => $distribution->id 'id_distribution' => $distribution->id
]); ]);
} }
$dateSaturday = date('Y-m-d', strtotime('Saturday', $start)); $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
$dateSunday = date('Y-m-d', strtotime('Sunday', $start)); $dateSunday = date('Y-m-d', strtotime('Sunday', $start));


$weekDistribution = Distribution::find()
$weekDistribution = DistributionModel::find()
->andWhere([ ->andWhere([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
'active' => 1, 'active' => 1,
public function actionDownload($date = '', $idPointSale = 0, $global = 0) public function actionDownload($date = '', $idPointSale = 0, $global = 0)
{ {
// commandes // commandes
$ordersArray = Order::searchAll([
$ordersArray = OrderModel::searchAll([
'distribution.date' => $date 'distribution.date' => $date
]); ]);


// points de vente // points de vente
$pointsSaleArray = PointSale::searchAll();
$pointsSaleArray = PointSaleModel::searchAll();
foreach ($pointsSaleArray as $pointSale) { foreach ($pointsSaleArray as $pointSale) {
$pv->initOrders($ordersArray); $pv->initOrders($ordersArray);
} }


// produits // produits
$productsArray = Product::find()->orderBy('order ASC')->all();
$productsArray = ProductModel::find()->orderBy('order ASC')->all();


$distribution = Distribution::find()
$distribution = DistributionModel::find()
->where('date LIKE \':date\'') ->where('date LIKE \':date\'')
->params([':date' => $date]) ->params([':date' => $date])
->one(); ->one();


$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);


/* /*
* export global * export global
$strProducts = ''; $strProducts = '';
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) { if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders);
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders);
$strQuantity = ''; $strQuantity = '';
if ($quantity) { if ($quantity) {
$strQuantity = $quantity; $strQuantity = $quantity;
$strProducts = ''; $strProducts = '';
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) { if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
$quantity = Order::getProductQuantity($product->id, $ordersArray);
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray);
$strQuantity = ''; $strQuantity = '';
if ($quantity) { if ($quantity) {
$strQuantity = $quantity; $strQuantity = $quantity;
$data = []; $data = [];
$filename = 'summary_' . $date; $filename = 'summary_' . $date;


$distribution = Distribution::find()
$distribution = DistributionModel::find()
->where('date LIKE \':date\'') ->where('date LIKE \':date\'')
->params([':date' => $date]) ->params([':date' => $date])
->one(); ->one();


$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);


// head // head
$data[0] = ['Lieu']; $data[0] = ['Lieu'];
$dataAdd = [$pointSale->name]; $dataAdd = [$pointSale->name];
foreach ($products as $product) { foreach ($products as $product) {
if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) { if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
$dataAdd[] = Order::getProductQuantity($product->id, $pointSale->orders);
$dataAdd[] = OrderModel::getProductQuantity($product->id, $pointSale->orders);
} }
} }
$data[] = $dataAdd; $data[] = $dataAdd;
$dataAdd = ['Total']; $dataAdd = ['Total'];
foreach ($products as $product) { foreach ($products as $product) {
if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) { if (isset($selectedProductsArray[$product->id]['active']) && $selectedProductsArray[$product->id]['active']) {
$dataAdd[] = Order::getProductQuantity($product->id, $orders);
$dataAdd[] = OrderModel::getProductQuantity($product->id, $orders);
} }
} }
$data[] = $dataAdd; $data[] = $dataAdd;
{ {
$data = []; $data = [];


$distribution = Distribution::find()->where('date LIKE \':date\'')->params([':date' => $date])->one();
$selectedProductsArray = ProductDistribution::searchByDistribution($distribution->id);
$distribution = DistributionModel::find()->where('date LIKE \':date\'')->params([':date' => $date])->one();
$selectedProductsArray = ProductDistributionModel::searchByDistribution($distribution->id);


// datas // datas
foreach ($pointsSale as $pointSale) { foreach ($pointsSale as $pointSale) {
public function actionChangeState($date, $active, $redirect = true) public function actionChangeState($date, $active, $redirect = true)
{ {
// changement état // changement état
$distribution = Distribution::initDistribution($date);
$distribution = DistributionModel::initDistribution($date);
$distribution->active = $active; $distribution->active = $active;
$distribution->save(); $distribution->save();


if ($active) { if ($active) {
// add commandes automatiques // add commandes automatiques
Subscription::addAll($date);
SubscriptionModel::addAll($date);
} }


if ($redirect) { if ($redirect) {
$dateSaturday = date('Y-m-d', strtotime('Saturday', $start)); $dateSaturday = date('Y-m-d', strtotime('Saturday', $start));
$dateSunday = date('Y-m-d', strtotime('Sunday', $start)); $dateSunday = date('Y-m-d', strtotime('Sunday', $start));


$pointsSaleArray = PointSale::searchAll();
$pointsSaleArray = PointSaleModel::searchAll();


$activeMonday = false; $activeMonday = false;
$activeTuesday = false; $activeTuesday = false;
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => $idOrder 'id' => $idOrder
]); ]);


*/ */
public function actionDelete($date, $idOrder) public function actionDelete($date, $idOrder)
{ {
$order = Order::searchOne(['id' => $idOrder]);
$order = OrderModel::searchOne(['id' => $idOrder]);


if ($order) { if ($order) {


// remboursement de la commande // remboursement de la commande
if ($order->id_user && $order->getAmount(Order::AMOUNT_PAID) && Producer::getConfig('credit')) {
if ($order->id_user && $order->getAmount(OrderModel::AMOUNT_PAID) && ProducerModel::getConfig('credit')) {
$order->saveCreditHistory( $order->saveCreditHistory(
CreditHistory::TYPE_REFUND,
$order->getAmount(Order::AMOUNT_PAID),
CreditHistoryModel::TYPE_REFUND,
$order->getAmount(OrderModel::AMOUNT_PAID),
$order->distribution->id_producer, $order->distribution->id_producer,
$order->id_user, $order->id_user,
UserModel::getCurrentId() UserModel::getCurrentId()
} }


$order->delete(); $order->delete();
ProductOrder::deleteAll(['id_order' => $idOrder]);
ProductOrderModel::deleteAll(['id_order' => $idOrder]);
} }


$this->redirect(['index', 'date' => $date]); $this->redirect(['index', 'date' => $date]);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$products = json_decode($products); $products = json_decode($products);
$pointSale = PointSale::findOne($idPointSale);
$distribution = Distribution::searchOne([
$pointSale = PointSaleModel::findOne($idPointSale);
$distribution = DistributionModel::searchOne([
'date' => $date 'date' => $date
]); ]);


$order->id_point_sale = $idPointSale; $order->id_point_sale = $idPointSale;
$order->mean_payment = $meanPayment; $order->mean_payment = $meanPayment;
$order->id_distribution = $distribution->id; $order->id_distribution = $distribution->id;
$order->origin = Order::ORIGIN_ADMIN;
$order->origin = OrderModel::ORIGIN_ADMIN;
$order->comment = $comment; $order->comment = $comment;
$order->status = 'tmp-order'; $order->status = 'tmp-order';


$order->id_user = $idUser; $order->id_user = $idUser;


// commentaire du point de vente // commentaire du point de vente
$userPointSale = UserPointSale::searchOne([
$userPointSale = UserPointSaleModel::searchOne([
'id_point_sale' => $idPointSale, 'id_point_sale' => $idPointSale,
'id_user' => $idUser 'id_user' => $idUser
]); ]);
} }


foreach ($products as $key => $dataProductOrder) { foreach ($products as $key => $dataProductOrder) {
$product = Product::findOne($key);
$quantity = $dataProductOrder->quantity / Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
$product = ProductModel::findOne($key);
$quantity = $dataProductOrder->quantity / ProductModel::$unitsArray[$dataProductOrder->unit]['coefficient'];
if ($product && $quantity) { if ($product && $quantity) {
$productOrder = new ProductOrder; $productOrder = new ProductOrder;
$productOrder->id_order = $order->id; $productOrder->id_order = $order->id;
} }
} }


$order = Order::searchOne(['id' => $order->id]);
$order = OrderModel::searchOne(['id' => $order->id]);
if ($order && $processCredit) { if ($order && $processCredit) {
$order->processCredit(); $order->processCredit();
} }


\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne(['id' => $idOrder]);
$order = OrderModel::searchOne(['id' => $idOrder]);


if ($order && if ($order &&
$order->distribution->id_producer == GlobalParam::getCurrentProducerId()) { $order->distribution->id_producer == GlobalParam::getCurrentProducerId()) {
$order->id_user = $idUser; $order->id_user = $idUser;


// commentaire du point de vente // commentaire du point de vente
$userPointSale = UserPointSale::searchOne([
$userPointSale = UserPointSaleModel::searchOne([
'id_point_sale' => $order->id_point_sale, 'id_point_sale' => $order->id_point_sale,
'id_user' => $idUser 'id_user' => $idUser
]); ]);


$products = json_decode($products); $products = json_decode($products);
foreach ($products as $key => $dataProductOrder) { foreach ($products as $key => $dataProductOrder) {
$productOrder = ProductOrder::findOne([
$productOrder = ProductOrderModel::findOne([
'id_order' => $idOrder, 'id_order' => $idOrder,
'id_product' => $key 'id_product' => $key
]); ]);


$quantity = $dataProductOrder->quantity $quantity = $dataProductOrder->quantity
/ Product::$unitsArray[$dataProductOrder->unit]['coefficient'];
/ ProductModel::$unitsArray[$dataProductOrder->unit]['coefficient'];


if ($quantity) { if ($quantity) {
if ($productOrder) { if ($productOrder) {
$productOrder->quantity = $quantity; $productOrder->quantity = $quantity;
$productOrder->price = $dataProductOrder->price; $productOrder->price = $dataProductOrder->price;
} else { } else {
$product = Product::findOne($key);
$product = ProductModel::findOne($key);


if ($product) { if ($product) {
$productOrder = new ProductOrder; $productOrder = new ProductOrder;


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


$order = Order::searchOne(['id' => $order->id]);
$order = OrderModel::searchOne(['id' => $order->id]);
if ($order && $processCredit) { if ($order && $processCredit) {
// Si changement d'user : on rembourse l'ancien user // Si changement d'user : on rembourse l'ancien user
$amountPaid = $order->getAmount(Order::AMOUNT_PAID);
$amountPaid = $order->getAmount(OrderModel::AMOUNT_PAID);
if($oldIdUser != $idUser && $amountPaid > 0) { if($oldIdUser != $idUser && $amountPaid > 0) {
$order->saveCreditHistory( $order->saveCreditHistory(
CreditHistory::TYPE_REFUND,
CreditHistoryModel::TYPE_REFUND,
$amountPaid, $amountPaid,
GlobalParam::getCurrentProducerId(), GlobalParam::getCurrentProducerId(),
$oldIdUser, $oldIdUser,
UserModel::getCurrentId() UserModel::getCurrentId()
); );
$order = Order::searchOne(['id' => $order->id]);
$order = OrderModel::searchOne(['id' => $order->id]);
} }


$order->processCredit(); $order->processCredit();
public function actionPaymentStatus($idOrder) public function actionPaymentStatus($idOrder)
{ {
$creditHistoryService = \Yii::$app->logic->getCreditHistoryContainer()->getService(); $creditHistoryService = \Yii::$app->logic->getCreditHistoryContainer()->getService();
$order = Order::searchOne(['id' => $idOrder]);
$order = OrderModel::searchOne(['id' => $idOrder]);


if ($order) { if ($order) {
$html = ''; $html = '';
]) ])
->one(); ->one();


$amountPaid = $order->getAmount(Order::AMOUNT_PAID);
$amountPaid = $order->getAmount(OrderModel::AMOUNT_PAID);


if (abs($order->amount - $amountPaid) < 0.0001) { if (abs($order->amount - $amountPaid) < 0.0001) {
$html .= '<span class="label label-success">Payé</span>'; $html .= '<span class="label label-success">Payé</span>';
$buttonsCredit = Html::a('Rembourser ' . $order->getAmountWithTax(Order::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
$buttonsCredit = Html::a('Rembourser ' . $order->getAmountWithTax(OrderModel::AMOUNT_TOTAL, true), 'javascript:void(0);', ['class' => 'btn btn-default btn-xs rembourser', 'data-montant' => $order->amount, 'data-type' => 'refund']);
} elseif ($order->amount > $amountPaid) { } elseif ($order->amount > $amountPaid) {
$amountToPay = $order->amount - $amountPaid; $amountToPay = $order->amount - $amountPaid;
$html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer'; $html .= '<span class="label label-danger">Non payé</span> reste <strong>' . number_format($amountToPay, 2) . ' €</strong> à payer';
. '</span>'; . '</span>';


// historique // historique
$history = CreditHistory::find()
$history = CreditHistoryModel::find()
->with('userAction') ->with('userAction')
->where(['id_order' => $idOrder]) ->where(['id_order' => $idOrder])
->all(); ->all();
. '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryService->getDate($creditHistory))) . '</td>' . '<td>' . date('d/m/Y H:i:s', strtotime($creditHistoryService->getDate($creditHistory))) . '</td>'
. '<td>' . Html::encode($creditHistoryService->getStrUserAction($creditHistory)) . '</td>' . '<td>' . Html::encode($creditHistoryService->getStrUserAction($creditHistory)) . '</td>'
. '<td>' . $creditHistoryService->getStrWording($creditHistory) . '</td>' . '<td>' . $creditHistoryService->getStrWording($creditHistory) . '</td>'
. '<td>' . ($creditHistoryService->isTypeDebit($creditHistory) ? '- ' . $creditHistoryService->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($creditHistoryService->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryService->getAmountWithTax($creditHistory, Order::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($creditHistoryService->isTypeDebit($creditHistory) ? '- ' . $creditHistoryService->getAmountWithTax($creditHistory, OrderModel::AMOUNT_TOTAL, true) : '') . '</td>'
. '<td>' . ($creditHistoryService->isTypeCredit($creditHistory) ? '+ ' . $creditHistoryService->getAmountWithTax($creditHistory, OrderModel::AMOUNT_TOTAL, true) : '') . '</td>'
. '</tr>'; . '</tr>';
} }
} else { } else {
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => $idOrder 'id' => $idOrder
]); ]);


{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


$order = Order::searchOne([
$order = OrderModel::searchOne([
'id' => (int)$idOrder 'id' => (int)$idOrder
]); ]);



+ 9
- 17
backend/controllers/PointSaleController.php View File



use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\models\PointSale;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use common\models\UserModel;
use common\models\UserPointSale;
use common\models\Order ;
use common\models\Producer ;
use common\models\Distribution ;
use yii\helpers\Html; use yii\helpers\Html;


/** /**
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->processPointProduction(); $model->processPointProduction();
$model->processRestrictedAccess(); $model->processRestrictedAccess();
Distribution::linkPointSaleIncomingDistributions($model) ;
DistributionModel::linkPointSaleIncomingDistributions($model) ;
return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
return $this->render('create', array_merge($this->initForm(), [ return $this->render('create', array_merge($this->initForm(), [
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$model = PointSale::find()
$model = PointSaleModel::find()
->with('userPointSale') ->with('userPointSale')
->where(['id' => $id]) ->where(['id' => $id])
->one(); ->one();
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->processPointProduction(); $model->processPointProduction();
$model->processRestrictedAccess(); $model->processRestrictedAccess();
Distribution::linkPointSaleIncomingDistributions($model) ;
DistributionModel::linkPointSaleIncomingDistributions($model) ;
Yii::$app->getSession()->setFlash('success', 'Point de vente modifié.'); Yii::$app->getSession()->setFlash('success', 'Point de vente modifié.');
return $this->redirect(['index']); return $this->redirect(['index']);
} else { } else {
$pointSale->save(); $pointSale->save();


// Suppression du lien entre les utilisateurs et le point de vente // Suppression du lien entre les utilisateurs et le point de vente
UserPointSale::deleteAll(['id_point_sale' => $id]);
UserPointSaleModel::deleteAll(['id_point_sale' => $id]);


// Suppression du lien PointSaleDistribution pour toutes les distributions à venir // Suppression du lien PointSaleDistribution pour toutes les distributions à venir
$incomingDistributions = Distribution::getIncomingDistributions();
$incomingDistributions = DistributionModel::getIncomingDistributions();
foreach ($incomingDistributions as $distribution) { foreach ($incomingDistributions as $distribution) {
PointSaleDistribution::deleteAll(['id_point_sale' => $id, 'id_distribution' => $distribution->id]);
PointSaleDistributionModel::deleteAll(['id_point_sale' => $id, 'id_distribution' => $distribution->id]);
} }


// Suppression de toutes les commandes à venir de ce point de vente // Suppression de toutes les commandes à venir de ce point de vente
$ordersArray = Order::searchAll(
$ordersArray = OrderModel::searchAll(
[ [
'id_point_sale' => $id, 'id_point_sale' => $id,
], ],
{ {
$pointSale = $this->findModel($id) ; $pointSale = $this->findModel($id) ;
if($pointSale) { if($pointSale) {
PointSale::updateAll(['default' => 0], 'id_producer = :id_producer', [':id_producer' => GlobalParam::getCurrentProducerId()]) ;
PointSaleModel::updateAll(['default' => 0], 'id_producer = :id_producer', [':id_producer' => GlobalParam::getCurrentProducerId()]) ;
if(!$pointSale->default) { if(!$pointSale->default) {
$pointSale->default = 1 ; $pointSale->default = 1 ;
$pointSale->save() ; $pointSale->save() ;
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = PointSale::findOne($id)) !== null) {
if (($model = PointSaleModel::findOne($id)) !== null) {
return $model; return $model;
} }
else { else {

+ 9
- 9
backend/controllers/ProducerAdminController.php View File

public function actionIndex() public function actionIndex()
{ {
$dataProviderProducer = new ActiveDataProvider([ $dataProviderProducer = new ActiveDataProvider([
'query' => Producer::find()
'query' => ProducerModel::find()
->with('userProducer', 'user') ->with('userProducer', 'user')
->orderBy('active DESC, free_price DESC'), ->orderBy('active DESC, free_price DESC'),
'pagination' => [ 'pagination' => [
], ],
]); ]);


$producersArray = Producer::find()->where('active = 1')->all();
$producersArray = ProducerModel::find()->where('active = 1')->all();


$sumPrices = 0; $sumPrices = 0;
foreach($producersArray as $producer) { foreach($producersArray as $producer) {


$countOrders = 0; $countOrders = 0;
if($withOrders) { if($withOrders) {
$countOrders = Order::searchCount([
$countOrders = OrderModel::searchCount([
'id_user' => $idUser, 'id_user' => $idUser,
'distribution.id_producer' => $fromProducerId 'distribution.id_producer' => $fromProducerId
], ['conditions' => 'date_delete IS NULL']); ], ['conditions' => 'date_delete IS NULL']);
} }


if(($withOrders && $countOrders) || !$withOrders) { if(($withOrders && $countOrders) || !$withOrders) {
Producer::addUser($idUser, $toProducerId);
ProducerModel::addUser($idUser, $toProducerId);
$count ++; $count ++;
} }
} }
*/ */
public function actionBill($idProducer) public function actionBill($idProducer)
{ {
$producer = Producer::findOne($idProducer);
$producer = ProducerModel::findOne($idProducer);


if ($producer) { if ($producer) {
$period = date('Y-m', strtotime('-1 month')); $period = date('Y-m', strtotime('-1 month'));


$last_invoice = Invoice::getLastInvoice() ;
$last_invoice = InvoiceModel::getLastInvoice() ;
if (!$last_invoice) { if (!$last_invoice) {
$reference = 'BAP000001'; $reference = 'BAP000001';
} else { } else {
public function actionBilling() public function actionBilling()
{ {
$dataProviderInvoice = new ActiveDataProvider([ $dataProviderInvoice = new ActiveDataProvider([
'query' => Invoice::find()
'query' => InvoiceModel::find()
->with('producer') ->with('producer')
->orderBy('reference DESC'), ->orderBy('reference DESC'),
'pagination' => [ 'pagination' => [
public function actionProducerInstallTaxUpdatePrices($idProducer) public function actionProducerInstallTaxUpdatePrices($idProducer)
{ {
// product // product
$productsArray = Product::searchAll([
$productsArray = ProductModel::searchAll([
'id_producer' => $idProducer 'id_producer' => $idProducer
]) ; ]) ;


* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
protected function findModel($id) { protected function findModel($id) {
if (($model = Producer::findOne($id)) !== null) {
if (($model = ProducerModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 4
- 10
backend/controllers/ProducerController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\ProducerPriceRange;
use Yii; use Yii;
use common\models\UserModel;
use backend\models\MailForm;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\helpers\Upload; use common\helpers\Upload;
use common\models\Producer;
use common\models\Invoice;


/** /**
* UserController implements the CRUD actions for User model. * UserController implements the CRUD actions for User model.
public function actionBilling() public function actionBilling()
{ {
$datasInvoices = new ActiveDataProvider([ $datasInvoices = new ActiveDataProvider([
'query' => Invoice::find()
'query' => InvoiceModel::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['id_producer' => GlobalParam::getCurrentProducerId()])
->orderBy('reference DESC'), ->orderBy('reference DESC'),
'pagination' => [ 'pagination' => [
], ],
]); ]);


$producer = Producer::findOne(GlobalParam::getCurrentProducerId());
$producer = ProducerModel::findOne(GlobalParam::getCurrentProducerId());


if ($producer->load(Yii::$app->request->post())) { if ($producer->load(Yii::$app->request->post())) {
$producer->save(); $producer->save();
} }


$dataProviderPrices = new ActiveDataProvider([ $dataProviderPrices = new ActiveDataProvider([
'query' => ProducerPriceRange::find()
'query' => ProducerPriceRangeModel::find()
->orderBy('id ASC'), ->orderBy('id ASC'),
'pagination' => [ 'pagination' => [
'pageSize' => 100, 'pageSize' => 100,
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = Producer::findOne($id)) !== null) {
if (($model = ProducerModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 3
- 5
backend/controllers/ProducerPriceRangeAdminController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\ProducerPriceRange;
use Yii; use Yii;
use common\models\UserModel;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\filters\AccessControl; use yii\filters\AccessControl;
public function actionIndex() public function actionIndex()
{ {
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => ProducerPriceRange::find()->orderBy('range_begin ASC')
'query' => ProducerPriceRangeModel::find()->orderBy('range_begin ASC')
]); ]);


return $this->render('index', [ return $this->render('index', [
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
$producerPriceRange = ProducerPriceRange::searchOne([
$producerPriceRange = ProducerPriceRangeModel::searchOne([
'id' => $id 'id' => $id
]) ; ]) ;
$producerPriceRange->delete(); $producerPriceRange->delete();
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = ProducerPriceRange::findOne($id)) !== null) {
if (($model = ProducerPriceRangeModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 2
- 14
backend/controllers/ProductCategoryController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Product;
use common\models\ProductCategory;
use common\models\UserGroup;
use common\models\UserUserGroup;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\models\PointSale;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use common\models\UserModel;
use common\models\UserPointSale;
use common\models\Order;
use common\models\Producer;
use common\models\Distribution;
use yii\helpers\Html; use yii\helpers\Html;


/** /**
$productCategory = $this->findModel($id); $productCategory = $this->findModel($id);


$productCategory->delete(); $productCategory->delete();
Product::updateAll(['id_product_category' => null], ['id_product_category' => $id]);
ProductModel::updateAll(['id_product_category' => null], ['id_product_category' => $id]);
Yii::$app->getSession()->setFlash('success', 'Catégorie <strong>' . Html::encode($productCategory->name) . '</strong> supprimée.'); Yii::$app->getSession()->setFlash('success', 'Catégorie <strong>' . Html::encode($productCategory->name) . '</strong> supprimée.');


return $this->redirect(['index']); return $this->redirect(['index']);
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = ProductCategory::findOne($id)) !== null) {
if (($model = ProductCategoryModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 11
- 11
backend/controllers/ProductController.php View File



if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {


$lastProductOrder = Product::find()->where('id_producer = :id_producer')->params([':id_producer' => GlobalParam::getCurrentProducerId()])->orderBy('order DESC')->one();
$lastProductOrder = ProductModel::find()->where('id_producer = :id_producer')->params([':id_producer' => GlobalParam::getCurrentProducerId()])->orderBy('order DESC')->one();
if ($lastProductOrder) { if ($lastProductOrder) {
$model->order = ++$lastProductOrder->order; $model->order = ++$lastProductOrder->order;
} }
$this->processAvailabilityPointsSale($model); $this->processAvailabilityPointsSale($model);


// link product / distribution // link product / distribution
Distribution::linkProductIncomingDistributions($model);
DistributionModel::linkProductIncomingDistributions($model);


Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> ajouté'); Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> ajouté');




if ($model->apply_distributions) { if ($model->apply_distributions) {
// link product / distribution // link product / distribution
Distribution::linkProductIncomingDistributions($model);
DistributionModel::linkProductIncomingDistributions($model);
} }


Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> modifié'); Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> modifié');
*/ */
public function processAvailabilityPointsSale($model) public function processAvailabilityPointsSale($model)
{ {
ProductPointSale::deleteAll(['id_product' => $model->id]);
ProductPointSaleModel::deleteAll(['id_product' => $model->id]);


if (is_array($model->pointsSale) && count($model->pointsSale)) { if (is_array($model->pointsSale) && count($model->pointsSale)) {
foreach ($model->pointsSale as $key => $val) { foreach ($model->pointsSale as $key => $val) {
$pointSale = PointSale::findOne($val);
$pointSale = PointSaleModel::findOne($val);
if ($pointSale) { if ($pointSale) {
$productPointSale = new ProductPointSale; $productPointSale = new ProductPointSale;
$productPointSale->id_product = $model->id; $productPointSale->id_product = $model->id;
'conditions' => 'user_producer.product_price_percent != 0', 'conditions' => 'user_producer.product_price_percent != 0',
]); ]);


$pointSaleWithProductPercent = PointSale::searchAll([], [
$pointSaleWithProductPercent = PointSaleModel::searchAll([], [
'conditions' => 'point_sale.product_price_percent != 0' 'conditions' => 'point_sale.product_price_percent != 0'
]); ]);


'from_quantity' => $model->from_quantity ? $model->from_quantity : null, 'from_quantity' => $model->from_quantity ? $model->from_quantity : null,
]; ];


$productPriceExist = ProductPrice::findOne($conditionsProductPriceExist);
$productPriceExist = ProductPriceModel::findOne($conditionsProductPriceExist);


if ($productPriceExist) { if ($productPriceExist) {
$productPriceExist->delete(); $productPriceExist->delete();


if ($confirm) { if ($confirm) {
$product->delete(); $product->delete();
ProductDistribution::deleteAll(['id_product' => $id]);
ProductDistributionModel::deleteAll(['id_product' => $id]);
Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($product->name) . '</strong> supprimé'); Yii::$app->getSession()->setFlash('success', 'Produit <strong>' . Html::encode($product->name) . '</strong> supprimé');
} else { } else {
Yii::$app->getSession()->setFlash('info', 'Souhaitez-vous vraiment supprimer le produit <strong>' . Html::encode($product->name) . '</strong> ? ' Yii::$app->getSession()->setFlash('info', 'Souhaitez-vous vraiment supprimer le produit <strong>' . Html::encode($product->name) . '</strong> ? '
$product->active = (int) $active; $product->active = (int) $active;
$product->save(); $product->save();


Distribution::linkProductIncomingDistributions($product);
DistributionModel::linkProductIncomingDistributions($product);


return ['success', 'id' => $id, 'active' => $active]; return ['success', 'id' => $id, 'active' => $active];
} }
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = Product::findOne($id)) !== null) {
if (($model = ProductModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');


protected function findModelProductPrice($id) protected function findModelProductPrice($id)
{ {
if (($model = ProductPrice::findOne($id)) !== null) {
if (($model = ProductPriceModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 2
- 2
backend/controllers/QuotationController.php View File

'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend();
return UserModel::hasAccessBackend();
} }
] ]
], ],
$invoice->name = str_replace(['Devis', 'devis'], 'Facture', $quotation->name); $invoice->name = str_replace(['Devis', 'devis'], 'Facture', $quotation->name);
$invoice->save() ; $invoice->save() ;


Order::updateAll([
OrderModel::updateAll([
'order.id_invoice' => $invoice->id 'order.id_invoice' => $invoice->id
], [ ], [
'order.id_quotation' => $id 'order.id_quotation' => $id

+ 4
- 6
backend/controllers/ReportController.php View File

use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\models\UserModel;
use common\models\Distribution ;


class ReportController extends BackendController class ReportController extends BackendController
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$usersArray = UserModel::findBy()->all() ; $usersArray = UserModel::findBy()->all() ;
$pointsSaleArray = PointSale::searchAll() ;
$pointsSaleArray = PointSaleModel::searchAll() ;
// distributions // distributions
$firstDistribution = Distribution::searchOne([], [
$firstDistribution = DistributionModel::searchOne([], [
'orderby' => 'date ASC' 'orderby' => 'date ASC'
]) ; ]) ;
$lastDistribution = Distribution::searchOne([], [
$lastDistribution = DistributionModel::searchOne([], [
'orderby' => 'date DESC' 'orderby' => 'date DESC'
]) ; ]) ;
$distributionYearsArray[] = $year ; $distributionYearsArray[] = $year ;
} }
$distributionsArray = Distribution::searchAll([
$distributionsArray = DistributionModel::searchAll([
'distribution.active' => 1 'distribution.active' => 1
], [ ], [
'orderby' => 'date ASC', 'orderby' => 'date ASC',

+ 8
- 14
backend/controllers/SiteController.php View File

use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\forms\LoginForm; use common\forms\LoginForm;
use common\models\UserModel;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use common\models\Product;
use common\models\PointSale;
use common\models\Producer;
use common\models\Distribution;
use common\models\Order;


/** /**
* Site controller * Site controller
{ {


// commandes // commandes
$optionDashboardNumberDistributions = Producer::getConfig('option_dashboard_number_distributions') ;
$optionDashboardNumberDistributions = ProducerModel::getConfig('option_dashboard_number_distributions') ;
$dashboardNumberDistributions = $optionDashboardNumberDistributions ? $optionDashboardNumberDistributions : 3 ; $dashboardNumberDistributions = $optionDashboardNumberDistributions ? $optionDashboardNumberDistributions : 3 ;


$optionDashboardDateStart = Producer::getConfig('option_dashboard_date_start') ;
$optionDashboardDateEnd = Producer::getConfig('option_dashboard_date_end') ;
$optionDashboardDateStart = ProducerModel::getConfig('option_dashboard_date_start') ;
$optionDashboardDateEnd = ProducerModel::getConfig('option_dashboard_date_end') ;


$queryDistributions = Distribution::find()->with('order') ;
$queryDistributions = DistributionModel::find()->with('order') ;


if($optionDashboardDateStart || $optionDashboardDateEnd) { if($optionDashboardDateStart || $optionDashboardDateEnd) {
if($optionDashboardDateStart) { if($optionDashboardDateStart) {
$paramsOrders[':date_start'] = date('Y-m-d 00:00:00') ; $paramsOrders[':date_start'] = date('Y-m-d 00:00:00') ;
} }


$ordersArray = Order::searchAll([],[
$ordersArray = OrderModel::searchAll([],[
'orderby' => 'date DESC', 'orderby' => 'date 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 = \'' . OrderModel::ORIGIN_USER . '\' OR origin = \'' . OrderModel::ORIGIN_ADMIN . '\' OR (origin = \'' . OrderModel::ORIGIN_AUTO . '\' AND (date_update IS NOT NULL OR date_delete IS NOT NULL)))',
'params' => $paramsOrders, 'params' => $paramsOrders,
]); ]);


// paramètres // paramètres
$producer = GlobalParam::getCurrentProducer(); $producer = GlobalParam::getCurrentProducer();


$productsCount = Product::searchCount() ;
$pointsSaleCount = PointSale::searchCount() ;
$productsCount = ProductModel::searchCount() ;
$pointsSaleCount = PointSaleModel::searchCount() ;


return $this->render('index', [ return $this->render('index', [
'distributionsArray' => $distributionsArray, 'distributionsArray' => $distributionsArray,

+ 1
- 4
backend/controllers/StatsController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use yii\web\Controller;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use Yii; use Yii;
use common\models\UserModel;
use common\models\Order;
use DateTime; use DateTime;
use DateInterval; use DateInterval;
use DatePeriod; use DatePeriod;
{ {
if(!$year) $year = date('Y') ; if(!$year) $year = date('Y') ;
$productsArray = Product::searchAll() ;
$productsArray = ProductModel::searchAll() ;
$dataProducts = [] ; $dataProducts = [] ;

+ 16
- 20
backend/controllers/SubscriptionController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\helpers\Debug;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Order ;
use common\models\Product ;
use common\models\SubscriptionSearch ;


class SubscriptionController extends BackendController class SubscriptionController extends BackendController
{ {
'allow' => true, 'allow' => true,
'roles' => ['@'], 'roles' => ['@'],
'matchCallback' => function ($rule, $action) { 'matchCallback' => function ($rule, $action) {
return User::hasAccessBackend() ;
return UserModel::hasAccessBackend() ;
} }
] ]
], ],
$model->id_producer = GlobalParam::getCurrentProducerId(); $model->id_producer = GlobalParam::getCurrentProducerId();


if($idOrder) { if($idOrder) {
$order = Order::searchOne(['id' => $idOrder]);
$order = OrderModel::searchOne(['id' => $idOrder]);
if ($order) { if ($order) {
$model->id_user = $order->id_user; $model->id_user = $order->id_user;
$model->username = $order->username; $model->username = $order->username;
$dateDay = strtolower(date('l',strtotime($order->distribution->date))) ; $dateDay = strtolower(date('l',strtotime($order->distribution->date))) ;
$model->$dateDay = 1 ; $model->$dateDay = 1 ;
$model->week_frequency = 1 ; $model->week_frequency = 1 ;
if($model->id_user && Producer::getConfig('credit')) {
if($model->id_user && ProducerModel::getConfig('credit')) {
$model->auto_payment = 1 ; $model->auto_payment = 1 ;
} }
} }
// produits // produits
$productsArray = Product::searchAll([], [
$productsArray = ProductModel::searchAll([], [
'orderby' => 'product.order ASC' 'orderby' => 'product.order ASC'
]) ; ]) ;
{ {
Yii::$app->getSession()->setFlash('success', 'Abonnement ajouté'); Yii::$app->getSession()->setFlash('success', 'Abonnement ajouté');
$subscription = Subscription::findOne($model->id) ;
$subscription = SubscriptionModel::findOne($model->id) ;
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ; $matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ;
if(count($matchedDistributionsArray)) { if(count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]); return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]);
// form // form
$model = new SubscriptionForm; $model = new SubscriptionForm;
$model->isAdmin = true ; $model->isAdmin = true ;
$subscription = Subscription::findOne($id);
$subscription = SubscriptionModel::findOne($id);
if ($subscription) { if ($subscription) {
$model->id = $id; $model->id = $id;
} }


// produits // produits
$arrayProductsSubscription = ProductSubscription::searchAll([
$arrayProductsSubscription = ProductSubscriptionModel::searchAll([
'id_subscription' => $model->id 'id_subscription' => $model->id
]) ; ]) ;
} }


// produits // produits
$productsArray = Product::searchAll([], [
$productsArray = ProductModel::searchAll([], [
'orderby' => 'product.order ASC' 'orderby' => 'product.order ASC'
]) ; ]) ;




if ($model->save()) { if ($model->save()) {


$subscription = Subscription::findOne($model->id) ;
$subscription = SubscriptionModel::findOne($model->id) ;


$messageOrdersDeleted = ''; $messageOrdersDeleted = '';
if($model->date_end) { if($model->date_end) {
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
$subscription = Subscription::searchOne([
$subscription = SubscriptionModel::searchOne([
'subscription.id' => $id 'subscription.id' => $id
]) ; ]) ;
$subscription->deleteOrdersIncomingDistributions() ; $subscription->deleteOrdersIncomingDistributions() ;
$subscription->delete(); $subscription->delete();
ProductSubscription::deleteAll(['id_subscription' => $id]);
ProductSubscriptionModel::deleteAll(['id_subscription' => $id]);
Yii::$app->getSession()->setFlash('success', 'Abonnement supprimé'); Yii::$app->getSession()->setFlash('success', 'Abonnement supprimé');
return $this->redirect(['subscription/index']); return $this->redirect(['subscription/index']);
} }


public function actionUpdateDistributions($idSubscription, $generate = false, $update = false) public function actionUpdateDistributions($idSubscription, $generate = false, $update = false)
{ {
$subscription = Subscription::findOne($idSubscription) ;
$subscription = SubscriptionModel::findOne($idSubscription) ;
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ; $matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions() ;
if($generate) { if($generate) {
{ {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$productsQuery = Product::find()
$productsQuery = ProductModel::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId(),]) ; ->where(['id_producer' => GlobalParam::getCurrentProducerId(),]) ;
if($idSubscription) { if($idSubscription) {
'price' => $theProduct['price'] 'price' => $theProduct['price']
] ;*/ ] ;*/


$theProduct['wording_unit'] = Product::strUnit($theProduct['unit'], 'wording_short');
$theProduct['wording_unit'] = ProductModel::strUnit($theProduct['unit'], 'wording_short');


if(isset($theProduct['productSubscription'][0])) { if(isset($theProduct['productSubscription'][0])) {
/*if($theProduct['productSubscription'][0]['unit'] != $theProduct['unit']) { /*if($theProduct['productSubscription'][0]['unit'] != $theProduct['unit']) {
$theProduct['units'][] = [ $theProduct['units'][] = [
'unit' => $theProduct['productSubscription'][0]['unit'], 'unit' => $theProduct['productSubscription'][0]['unit'],
'wording_unit' => Product::strUnit($theProduct['productSubscription'][0]['unit'], 'wording_short'),
'wording_unit' => ProductModel::strUnit($theProduct['productSubscription'][0]['unit'], 'wording_short'),
'step' => $theProduct['productSubscription'][0]['step'], 'step' => $theProduct['productSubscription'][0]['step'],
'price' => $theProduct['productSubscription'][0]['price'], 'price' => $theProduct['productSubscription'][0]['price'],
] ; ] ;
$theProduct['step'] = $theProduct['productSubscription'][0]['step'] ; $theProduct['step'] = $theProduct['productSubscription'][0]['step'] ;
$theProduct['price'] = $theProduct['productSubscription'][0]['price'] ; $theProduct['price'] = $theProduct['productSubscription'][0]['price'] ;
}*/ }*/
$theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * Product::$unitsArray[$theProduct['unit']]['coefficient'] ;
$theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * ProductModel::$unitsArray[$theProduct['unit']]['coefficient'] ;
} }
else { else {
$theProduct['quantity'] = '' ; $theProduct['quantity'] = '' ;

+ 3
- 8
backend/controllers/TaxRateAdminController.php View File



namespace backend\controllers; namespace backend\controllers;


use common\models\TaxRate;
use Yii; use Yii;
use common\models\UserModel;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\helpers\Upload;
use common\models\Producer;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use common\models\Invoice;


/** /**
* TaxRateAdminController implements the CRUD actions for TaxRate model. * TaxRateAdminController implements the CRUD actions for TaxRate model.
public function actionIndex() public function actionIndex()
{ {
$dataProviderTaxRate = new ActiveDataProvider([ $dataProviderTaxRate = new ActiveDataProvider([
'query' => TaxRate::find()
'query' => TaxRateModel::find()
]); ]);


return $this->render('index', [ return $this->render('index', [
*/ */
public function actionDelete($id) public function actionDelete($id)
{ {
$taxeRate = TaxRate::searchOne([
$taxeRate = TaxRateModel::searchOne([
'id' => $id 'id' => $id
]) ; ]) ;
$taxeRate->delete(); $taxeRate->delete();
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = TaxRate::findOne($id)) !== null) {
if (($model = TaxRateModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 15
- 15
backend/controllers/UserController.php View File

) )
]); ]);


$producer = Producer::searchOne([
$producer = ProducerModel::searchOne([
'id' => GlobalParam::getCurrentProducerId() 'id' => GlobalParam::getCurrentProducerId()
]); ]);


$pointsSaleArray = PointSale::searchAll();
$pointsSaleArray = PointSaleModel::searchAll();


return $this->render('index', [ return $this->render('index', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,


if ($model->id) { if ($model->id) {
// init points de vente sélectionnés // init points de vente sélectionnés
$userPointSaleArray = UserPointSale::searchAll([
$userPointSaleArray = UserPointSaleModel::searchAll([
'id_user' => $model->id 'id_user' => $model->id
]); ]);
if ($userPointSaleArray && count($userPointSaleArray) > 0) { if ($userPointSaleArray && count($userPointSaleArray) > 0) {
} }


// init groupes d'utilisateurs sélectionnés // init groupes d'utilisateurs sélectionnés
$userUserGroupsArray = UserUserGroup::searchAll([
$userUserGroupsArray = UserUserGroupModel::searchAll([
'id_user' => $model->id 'id_user' => $model->id
]); ]);
if ($userUserGroupsArray && count($userUserGroupsArray) > 0) { if ($userUserGroupsArray && count($userUserGroupsArray) > 0) {
} }


// points de vente // points de vente
$pointsSaleArray = PointSale::find()
$pointsSaleArray = PointSaleModel::find()
->where([ ->where([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
'status' => 1 'status' => 1
->all(); ->all();


// groupes d'utilisateurs // groupes d'utilisateurs
$userGroupsArray = UserGroup::find()
$userGroupsArray = UserGroupModel::find()
->where([ ->where([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
]) ])
} }


if ($userExist) { if ($userExist) {
Producer::addUser($userExist->id, GlobalParam::getCurrentProducerId());
ProducerModel::addUser($userExist->id, GlobalParam::getCurrentProducerId());
$this->processLinkPointSale($userExist); $this->processLinkPointSale($userExist);
$this->processLinkUserGroup($userExist); $this->processLinkUserGroup($userExist);
Yii::$app->getSession()->setFlash('success', "L'utilisateur que vous souhaitez créer possède déjà un compte sur la plateforme. Il vient d'être lié à votre établissement."); Yii::$app->getSession()->setFlash('success', "L'utilisateur que vous souhaitez créer possède déjà un compte sur la plateforme. Il vient d'être lié à votre établissement.");
public function processLinkPointSale($modelUser) public function processLinkPointSale($modelUser)
{ {
$posts = Yii::$app->request->post(); $posts = Yii::$app->request->post();
UserPointSale::deleteAll([
UserPointSaleModel::deleteAll([
'id_user' => $modelUser->id 'id_user' => $modelUser->id
]); ]);
if (is_array($modelUser->points_sale) && count($modelUser->points_sale) > 0) { if (is_array($modelUser->points_sale) && count($modelUser->points_sale) > 0) {
foreach ($modelUser->points_sale as $pointSaleId) { foreach ($modelUser->points_sale as $pointSaleId) {
$userPointSale = UserPointSale::searchOne([
$userPointSale = UserPointSaleModel::searchOne([
'id_user' => $modelUser->id, 'id_user' => $modelUser->id,
'id_point_sale' => $pointSaleId 'id_point_sale' => $pointSaleId
]); ]);
public function processLinkUserGroup($modelUser) public function processLinkUserGroup($modelUser)
{ {
$posts = Yii::$app->request->post(); $posts = Yii::$app->request->post();
UserUserGroup::deleteAll([
UserUserGroupModel::deleteAll([
'id_user' => $modelUser->id 'id_user' => $modelUser->id
]); ]);


if (is_array($modelUser->user_groups) && count($modelUser->user_groups) > 0) { if (is_array($modelUser->user_groups) && count($modelUser->user_groups) > 0) {
foreach ($modelUser->user_groups as $userGroupId) { foreach ($modelUser->user_groups as $userGroupId) {


$userUserGroup = UserUserGroup::searchOne([
$userUserGroup = UserUserGroupModel::searchOne([
'id_user' => $modelUser->id, 'id_user' => $modelUser->id,
'id_user_group' => $userGroupId 'id_user_group' => $userGroupId
]); ]);
$usersArray[] = $user['email']; $usersArray[] = $user['email'];
} }


$pointsSaleArray = PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->all();
$pointsSaleArray = PointSaleModel::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->all();


$pointSale = null; $pointSale = null;
if ($idPointSale) { if ($idPointSale) {
$pointSale = PointSale::findOne(['id' => $idPointSale]);
$pointSale = PointSaleModel::findOne(['id' => $idPointSale]);
} }


$mailForm = new MailForm(); $mailForm = new MailForm();
return $this->redirect(['mail', 'idPointSale' => $idPointSale]); return $this->redirect(['mail', 'idPointSale' => $idPointSale]);
} }


$incomingDistributions = Distribution::getIncomingDistributions();
$incomingDistributions = DistributionModel::getIncomingDistributions();
$incomingDistributionsArray = ['0' => '--']; $incomingDistributionsArray = ['0' => '--'];
foreach ($incomingDistributions as $distribution) { foreach ($incomingDistributions as $distribution) {
$incomingDistributionsArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date)); $incomingDistributionsArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date));
$creditForm = new CreditForm; $creditForm = new CreditForm;
} }


$history = CreditHistory::find()
$history = CreditHistoryModel::find()
->with(['order', 'userAction']) ->with(['order', 'userAction'])
->where([ ->where([
'id_user' => $user->id, 'id_user' => $user->id,

+ 2
- 12
backend/controllers/UserGroupController.php View File

namespace backend\controllers; namespace backend\controllers;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\UserGroup;
use common\models\UserUserGroup;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use common\models\PointSale;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use common\models\UserModel;
use common\models\UserPointSale;
use common\models\Order;
use common\models\Producer;
use common\models\Distribution;
use yii\helpers\Html; use yii\helpers\Html;


/** /**
$userGroup = $this->findModel($id); $userGroup = $this->findModel($id);


$userGroup->delete(); $userGroup->delete();
UserUserGroup::deleteAll(['id_user_group' => $id]);
UserUserGroupModel::deleteAll(['id_user_group' => $id]);
Yii::$app->getSession()->setFlash('success', 'Groupe d\'utilisateur <strong>' . Html::encode($userGroup->name) . '</strong> supprimé.'); Yii::$app->getSession()->setFlash('success', 'Groupe d\'utilisateur <strong>' . Html::encode($userGroup->name) . '</strong> supprimé.');


return $this->redirect(['index']); return $this->redirect(['index']);
*/ */
protected function findModel($id) protected function findModel($id)
{ {
if (($model = UserGroup::findOne($id)) !== null) {
if (($model = UserGroupModel::findOne($id)) !== null) {
return $model; return $model;
} else { } else {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');

+ 3
- 3
backend/models/MailForm.php View File

' ; ' ;
$messageAutoHtml = '<br /><br />' ; $messageAutoHtml = '<br /><br />' ;
$distribution = Distribution::searchOne(['id' => $this->id_distribution]) ;
$distribution = DistributionModel::searchOne(['id' => $this->id_distribution]) ;
if($distribution) { if($distribution) {
'.$linkOrder ; '.$linkOrder ;


if($this->integrate_product_list) { if($this->integrate_product_list) {
$productsArray = Product::find()
$productsArray = ProductModel::find()
->where([ ->where([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
]) ])
} }
if($product->price) { if($product->price) {
$productDescription .= ' / '.Price::format($product->getPriceWithTax()) ; $productDescription .= ' / '.Price::format($product->getPriceWithTax()) ;
$productDescription .= ' ('.Product::strUnit($product->unit, 'wording_unit').')' ;
$productDescription .= ' ('.ProductModel::strUnit($product->unit, 'wording_unit').')' ;
} }


$messageAutoText .= '- '.$productDescription.' $messageAutoText .= '- '.$productDescription.'

+ 1
- 1
backend/views/access/index.php View File

</div> </div>
<div class="panel-body"> <div class="panel-body">
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($modelAccessUserProducerForm, 'id_user')->dropDownList(User::populateDropdownList(), ['class' => 'select2'])->label(''); ?>
<?= $form->field($modelAccessUserProducerForm, 'id_user')->dropDownList(UserModel::populateDropdownList(), ['class' => 'select2'])->label(''); ?>
<?= Html::submitButton('Ajouter', ['class' => 'btn btn-success']) ?> <?= Html::submitButton('Ajouter', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>

+ 3
- 3
backend/views/delivery-note/index.php View File

?> ?>


<div class="delivery-note-index"> <div class="delivery-note-index">
<?php if(DeliveryNote::searchCount()): ?>
<?php if(DeliveryNoteModel::searchCount()): ?>
<?= GridView::widget([ <?= GridView::widget([
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
[ [
'attribute' => 'id_point_sale', 'attribute' => 'id_point_sale',
'header' => 'Point de vente', 'header' => 'Point de vente',
'filter' => ArrayHelper::map(PointSale::searchAll([], ['as_array'=>true]), 'id', 'name'),
'filter' => ArrayHelper::map(PointSaleModel::searchAll([], ['as_array'=>true]), 'id', 'name'),
'format' => 'html', 'format' => 'html',
'value' => function($model) { 'value' => function($model) {
$pointSale = $model->getPointSale() ; $pointSale = $model->getPointSale() ;
'attribute' => 'amount', 'attribute' => 'amount',
'header' => 'Montant', 'header' => 'Montant',
'value' => function($deliveryNote) { 'value' => function($deliveryNote) {
return $deliveryNote->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL, true) ;
return $deliveryNote->getAmountWithTax(OrderModel::INVOICE_AMOUNT_TOTAL, true) ;
} }
], ],
[ [

+ 4
- 4
backend/views/development/_form.php View File

<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'type')->dropDownList([ <?= $form->field($model, 'type')->dropDownList([
Development::TYPE_EVOLUTION => 'Évolution',
Development::TYPE_BUG => 'Anomalie',
DevelopmentModel::TYPE_EVOLUTION => 'Évolution',
DevelopmentModel::TYPE_BUG => 'Anomalie',
]) ?> ]) ?>
<?= $form->field($model, 'status')->dropDownList([ <?= $form->field($model, 'status')->dropDownList([
Development::STATUS_OPEN => 'Ouvert',
Development::STATUS_CLOSED => 'Fermé',
DevelopmentModel::STATUS_OPEN => 'Ouvert',
DevelopmentModel::STATUS_CLOSED => 'Fermé',
]) ?> ]) ?>
<?= $form->field($model, 'subject')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'subject')->textInput(['maxlength' => true]) ?>

+ 8
- 8
backend/views/development/development.php View File

</div> </div>


<ul id="tab-status-developments" class="nav nav-tabs" role="tablist"> <ul id="tab-status-developments" class="nav nav-tabs" role="tablist">
<li role="presentation" class="<?php if ($status == Development::STATUS_OPEN): ?>active<?php endif; ?>"><a
href="<?= Yii::$app->urlManager->createUrl(['development/index', 'status' => Development::STATUS_OPEN]); ?>"
<li role="presentation" class="<?php if ($status == DevelopmentModel::STATUS_OPEN): ?>active<?php endif; ?>"><a
href="<?= Yii::$app->urlManager->createUrl(['development/index', 'status' => DevelopmentModel::STATUS_OPEN]); ?>"
id="" aria-controls="" role="tab">Ouvert</a></li> id="" aria-controls="" role="tab">Ouvert</a></li>
<li role="presentation" class="<?php if ($status == Development::STATUS_CLOSED): ?>active<?php endif; ?>"><a
href="<?= Yii::$app->urlManager->createUrl(['development/index', 'status' => Development::STATUS_CLOSED]); ?>"
<li role="presentation" class="<?php if ($status == DevelopmentModel::STATUS_CLOSED): ?>active<?php endif; ?>"><a
href="<?= Yii::$app->urlManager->createUrl(['development/index', 'status' => DevelopmentModel::STATUS_CLOSED]); ?>"
id="" aria-controls="" role="tab">Fermé</a></li> id="" aria-controls="" role="tab">Fermé</a></li>
</ul> </ul>


'header' => 'Type', 'header' => 'Type',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) { 'value' => function ($model) {
if ($model->type == Development::TYPE_EVOLUTION) {
if ($model->type == DevelopmentModel::TYPE_EVOLUTION) {
return '<span class="label label-success">Évolution</span>'; return '<span class="label label-success">Évolution</span>';
} else { } else {
return '<span class="label label-danger">Anomalie</span>'; return '<span class="label label-danger">Anomalie</span>';
</button> </button>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id]) . '">Non</a></li> <li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id]) . '">Non</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriority::PRIORITY_LOW]) . '">Basse</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriority::PRIORITY_NORMAL]) . '">Normale</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriority::PRIORITY_HIGH]) . '">Haute</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriorityModel::PRIORITY_LOW]) . '">Basse</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriorityModel::PRIORITY_NORMAL]) . '">Normale</a></li>
<li><a href="' . Yii::$app->urlManager->createUrl(['development/priority', 'idDevelopment' => $model->id, 'priority' => DevelopmentPriorityModel::PRIORITY_HIGH]) . '">Haute</a></li>
</ul> </ul>
</div><br />'; </div><br />';



+ 11
- 11
backend/views/distribution/report-bourlingue.php View File

$add = false; $add = false;
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
if($product->id == $productOrder->id_product) { if($product->id == $productOrder->id_product) {
$unit = (Product::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($productOrder->unit, 'wording_short', true) ;
$unit = (ProductModel::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($productOrder->unit, 'wording_short', true) ;
$strProducts .= $product->name . ' (' .$productOrder->quantity .$unit.')<br />'; $strProducts .= $product->name . ' (' .$productOrder->quantity .$unit.')<br />';
$add = true; $add = true;
} }
$credit = '' ; $credit = '' ;


if(isset($order->user) && $order->user->id) { if(isset($order->user) && $order->user->id) {
$userProducer = UserProducer::searchOne([
$userProducer = UserProducerModel::searchOne([
'id_user' => $order->user->id 'id_user' => $order->user->id
]); ]);


$strProducts = ''; $strProducts = '';
$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$strProducts .= $product->name . ' (' .$quantity .$theUnit.')<br />'; $strProducts .= $product->name . ' (' .$quantity .$theUnit.')<br />';
} }
} }


$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$html .= $product->name . ' (' .$quantity .$theUnit.')<br />'; $html .= $product->name . ' (' .$quantity .$theUnit.')<br />';
} }
} }


$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$html .= $product->name . ' (' .$quantity .$theUnit.')<br />'; $html .= $product->name . ' (' .$quantity .$theUnit.')<br />';
} }
} }

+ 2
- 2
backend/views/distribution/report-grid.php View File

foreach ($orders as $order) { foreach ($orders as $order) {
$html .= '<tr>'; $html .= '<tr>';
$strUser = $order->getStrUser(); $strUser = $order->getStrUser();
if ($producer->option_order_reference_type == Producer::ORDER_REFERENCE_TYPE_YEARLY && $order->reference && strlen($order->reference) > 0) {
if ($producer->option_order_reference_type == ProducerModel::ORDER_REFERENCE_TYPE_YEARLY && $order->reference && strlen($order->reference) > 0) {
$strUser .= '<br />' . $order->reference; $strUser .= '<br />' . $order->reference;
} }


$quantity = '' ; $quantity = '' ;
foreach($order->productOrder as $productOrder) { foreach($order->productOrder as $productOrder) {
if($product->id == $productOrder->id_product) { if($product->id == $productOrder->id_product) {
$unit = (Product::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($productOrder->unit, 'wording_short', true) ;
$unit = (ProductModel::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($productOrder->unit, 'wording_short', true) ;


$quantity .= $productOrder->quantity .$unit ; $quantity .= $productOrder->quantity .$unit ;
if($productOrder->quantity > 1) { if($productOrder->quantity > 1) {

+ 17
- 17
backend/views/distribution/report.php View File

} }


// référence // référence
if($producer->option_order_reference_type == Producer::ORDER_REFERENCE_TYPE_YEARLY && $order->reference && strlen($order->reference) > 0) {
if($producer->option_order_reference_type == ProducerModel::ORDER_REFERENCE_TYPE_YEARLY && $order->reference && strlen($order->reference) > 0) {
$strUser .= '<br />'.$order->reference ; $strUser .= '<br />'.$order->reference ;
} }


$add = false; $add = false;
foreach ($order->productOrder as $productOrder) { foreach ($order->productOrder as $productOrder) {
if($product->id == $productOrder->id_product) { if($product->id == $productOrder->id_product) {
$unit = (Product::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($productOrder->unit, 'wording_short', true) ;
$unit = (ProductModel::strUnit($productOrder->unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($productOrder->unit, 'wording_short', true) ;
$strProducts .= '('.$productOrder->quantity .$unit.') '.$product->getNameExport() . '<br />'; $strProducts .= '('.$productOrder->quantity .$unit.') '.$product->getNameExport() . '<br />';
$add = true; $add = true;
} }
$credit = '' ; $credit = '' ;


if(isset($order->user) && $order->user->id) { if(isset($order->user) && $order->user->id) {
$userProducer = UserProducer::searchOne([
$userProducer = UserProducerModel::searchOne([
'id_user' => $order->user->id 'id_user' => $order->user->id
]); ]);


$html .= '<td><strong>'.number_format($order->amount_with_tax, 2) . ' € '; $html .= '<td><strong>'.number_format($order->amount_with_tax, 2) . ' € ';


if($order->getPaymentStatus() == Order::PAYMENT_PAID)
if($order->getPaymentStatus() == OrderModel::PAYMENT_PAID)
{ {
$html .= '(payé)' ; $html .= '(payé)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_UNPAID && $order->getAmount(Order::AMOUNT_PAID))
elseif($order->getPaymentStatus() == OrderModel::PAYMENT_UNPAID && $order->getAmount(OrderModel::AMOUNT_PAID))
{ {
$html .= '(reste '.$order->getAmount(Order::AMOUNT_REMAINING, true).' à payer)' ;
$html .= '(reste '.$order->getAmount(OrderModel::AMOUNT_REMAINING, true).' à payer)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_SURPLUS)
elseif($order->getPaymentStatus() == OrderModel::PAYMENT_SURPLUS)
{ {
$html .= '(surplus : '.$order->getAmount(Order::PAYMENT_SURPLUS, true).' à rembourser)' ;
$html .= '(surplus : '.$order->getAmount(OrderModel::PAYMENT_SURPLUS, true).' à rembourser)' ;
} }
$html .= '</strong></td>' ; $html .= '</strong></td>' ;
$strProducts = ''; $strProducts = '';
$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$strProducts .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />'; $strProducts .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />';
} }
} }


$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$html .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />'; $html .= '(' .$quantity .$theUnit.') '.$product->getNameExport() . '<br />';
} }
} }


$cpt = 0 ; $cpt = 0 ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
foreach(Product::$unitsArray as $unit => $dataUnit) {
$quantity = Order::getProductQuantity($product->id, $ordersArray, false, $unit);
foreach(ProductModel::$unitsArray as $unit => $dataUnit) {
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray, false, $unit);
if ($quantity) { if ($quantity) {
$theUnit = (Product::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.Product::strUnit($unit, 'wording_short', true) ;
$theUnit = (ProductModel::strUnit($unit, 'wording_short', true) == 'p.') ? '' : '&nbsp;'.ProductModel::strUnit($unit, 'wording_short', true) ;
$html .= '(' .$quantity .$theUnit.') '.$product->name . '<br />'; $html .= '(' .$quantity .$theUnit.') '.$product->name . '<br />';
} }
} }

+ 2
- 2
backend/views/document/_download_product_line.php View File

</td> </td>
<?php endif; ?> <?php endif; ?>
<td class="align-center"> <td class="align-center">
<?= $productOrder->quantity * Product::$unitsArray[$productOrder->unit]['coefficient'] ?>
<?= $productOrder->quantity * ProductModel::$unitsArray[$productOrder->unit]['coefficient'] ?>
</td> </td>
<td class="align-center"><?= Product::strUnit($productOrder->unit, 'wording') ?></td>
<td class="align-center"><?= ProductModel::strUnit($productOrder->unit, 'wording') ?></td>
<?php if($displayPrices): ?> <?php if($displayPrices): ?>
<?php if($producer->taxRate->value != 0): ?> <?php if($producer->taxRate->value != 0): ?>
<td class="align-center"><?= $productOrder->taxRate->value * 100 ?> %</td> <td class="align-center"><?= $productOrder->taxRate->value * 100 ?> %</td>

+ 2
- 2
backend/views/document/_form.php View File

'template' => '{label} <a href="' . Yii::$app->urlManager->createUrl(['user/create']) . '" class="btn btn-xs btn-default">Nouvel utilisateur <span class="glyphicon glyphicon-plus"></span></a><div>{input}</div>{hint}', 'template' => '{label} <a href="' . Yii::$app->urlManager->createUrl(['user/create']) . '" class="btn btn-xs btn-default">Nouvel utilisateur <span class="glyphicon glyphicon-plus"></span></a><div>{input}</div>{hint}',
]) ])
->dropDownList( ->dropDownList(
User::populateDropdownList(),
UserModel::populateDropdownList(),
[ [
'@change' => 'changeUser', '@change' => 'changeUser',
'v-model' => 'idUser', 'v-model' => 'idUser',
class="btn btn-sm btn-default"><span class="glyphicon glyphicon-repeat"></span> Regénérer (PDF)</a> class="btn btn-sm btn-default"><span class="glyphicon glyphicon-repeat"></span> Regénérer (PDF)</a>
<?php endif; ?> <?php endif; ?>


<?php if ($model->getClass() == 'Invoice' && Producer::getConfig('option_export_evoliz')): ?>
<?php if ($model->getClass() == 'Invoice' && ProducerModel::getConfig('option_export_evoliz')): ?>
<a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/export-csv-evoliz', 'id' => $model->id]) ?>" <a href="<?= Yii::$app->urlManager->createUrl([Yii::$app->controller->getControllerUrl() . '/export-csv-evoliz', 'id' => $model->id]) ?>"
class="btn btn-sm btn-default"><span class="glyphicon glyphicon-save-file"></span> Export Evoliz class="btn btn-sm btn-default"><span class="glyphicon glyphicon-save-file"></span> Export Evoliz
(CSV)</a> (CSV)</a>

+ 5
- 5
backend/views/document/download.php View File

<?php <?php


$displayPrices = Yii::$app->controller->getClass() != 'DeliveryNote' || (Yii::$app->controller->getClass() == 'DeliveryNote' && Producer::getConfig('document_display_prices_delivery_note'));
$displayProductDescription = Producer::getConfig('document_display_product_description');
$documentPriceDecimals = (int) Producer::getConfig('option_document_price_decimals');
$displayPrices = Yii::$app->controller->getClass() != 'DeliveryNote' || (Yii::$app->controller->getClass() == 'DeliveryNote' && ProducerModel::getConfig('document_display_prices_delivery_note'));
$displayProductDescription = ProducerModel::getConfig('document_display_product_description');
$documentPriceDecimals = (int) ProducerModel::getConfig('option_document_price_decimals');


?> ?>


<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> <?php endif; ?>
<?php if ($displayPrices): ?> <?php if ($displayPrices): ?>
<?php $typeAmount = $document->isInvoicePrice() ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL; ?>
<?php $typeAmount = $document->isInvoicePrice() ? OrderModel::INVOICE_AMOUNT_TOTAL : OrderModel::AMOUNT_TOTAL; ?>


<?php if ($producer->taxRate->value != 0): ?> <?php if ($producer->taxRate->value != 0): ?>


</tr> </tr>


<?php <?php
$taxRateArray = TaxRate::getTaxRateArray();
$taxRateArray = $this->getLogic()->getTaxRateContainer()->getRepository()->getAsArray();
foreach ($document->getTotalVatArray($typeAmount) as $idTaxRate => $totalVat): ?> foreach ($document->getTotalVatArray($typeAmount) as $idTaxRate => $totalVat): ?>
<tr> <tr>
<td class="align-right" colspan="5"> <td class="align-right" colspan="5">

+ 3
- 3
backend/views/invoice/index.php View File



<div class="invoice-index"> <div class="invoice-index">


<?php if(Invoice::searchCount()): ?>
<?php if(InvoiceModel::searchCount()): ?>
<?= GridView::widget([ <?= GridView::widget([
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'attribute' => 'amount', 'attribute' => 'amount',
'header' => 'Montant', 'header' => 'Montant',
'value' => function($invoice) { 'value' => function($invoice) {
return $invoice->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL, true) ;
return $invoice->getAmountWithTax(OrderModel::INVOICE_AMOUNT_TOTAL, true) ;
} }
], ],
[ [
]); ]);
}, },
'export-csv-evoliz' => function($url, $model) { 'export-csv-evoliz' => function($url, $model) {
if(Producer::getConfig('option_export_evoliz')) {
if(ProducerModel::getConfig('option_export_evoliz')) {
return Html::a('<span class="glyphicon glyphicon-save-file"></span> Evoliz', $url, [ return Html::a('<span class="glyphicon glyphicon-save-file"></span> Evoliz', $url, [
'title' => 'Export CSV Evoliz', 'class' => 'btn btn-default' 'title' => 'Export CSV Evoliz', 'class' => 'btn btn-default'
]); ]);

+ 3
- 3
backend/views/layouts/header.php View File



<?php <?php


$pastDistributionsArray = Distribution::find()
$pastDistributionsArray = DistributionModel::find()
->where(['<', 'distribution.date', date('Y-m-d')]) ->where(['<', 'distribution.date', date('Y-m-d')])
->andWhere([ ->andWhere([
'distribution.id_producer' => GlobalParam::getCurrentProducerId(), 'distribution.id_producer' => GlobalParam::getCurrentProducerId(),


$pastDistributionsArray = array_reverse($pastDistributionsArray); $pastDistributionsArray = array_reverse($pastDistributionsArray);


$incomingDistributionsArray = Distribution::find()
$incomingDistributionsArray = DistributionModel::find()
->where(['>=', 'distribution.date', date('Y-m-d')]) ->where(['>=', 'distribution.date', date('Y-m-d')])
->andWhere([ ->andWhere([
'distribution.id_producer' => GlobalParam::getCurrentProducerId(), 'distribution.id_producer' => GlobalParam::getCurrentProducerId(),
</a> </a>
</li> </li>
<li class="header">&nbsp;<strong>Autres producteurs</strong></li> <li class="header">&nbsp;<strong>Autres producteurs</strong></li>
<?php $producersArray = Producer::find()->orderBy('name ASC')->all(); ?>
<?php $producersArray = ProducerModel::find()->orderBy('name ASC')->all(); ?>
<?php foreach ($producersArray as $producer): ?> <?php foreach ($producersArray as $producer): ?>
<li> <li>
<a href="<?= Yii::$app->urlManagerBackend->createUrl(['site/change-producer', 'id' => $producer->id]); ?>"><?= Html::encode($producer->name) ?></a> <a href="<?= Yii::$app->urlManagerBackend->createUrl(['site/change-producer', 'id' => $producer->id]); ?>"><?= Html::encode($producer->name) ?></a>

+ 29
- 29
backend/views/layouts/left.php View File

[ [
'options' => ['class' => 'sidebar-menu tree', 'data-widget' => 'tree'], 'options' => ['class' => 'sidebar-menu tree', 'data-widget' => 'tree'],
'items' => [ 'items' => [
['label' => 'Tableau de bord', 'icon' => 'dashboard', 'url' => ['/site/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Distributions', 'icon' => 'calendar', 'url' => ['/distribution/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Tableau de bord', 'icon' => 'dashboard', 'url' => ['/site/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Distributions', 'icon' => 'calendar', 'url' => ['/distribution/index'], 'visible' => UserModel::isCurrentProducer()],
[ [
'label' => 'Produits', 'label' => 'Produits',
'icon' => 'clone', 'icon' => 'clone',
'url' => ['/product/index'], 'url' => ['/product/index'],
'visible' => User::isCurrentProducer(),
'visible' => UserModel::isCurrentProducer(),
'active' => Yii::$app->controller->id == 'product', 'active' => Yii::$app->controller->id == 'product',
'items' => [ 'items' => [
['label' => 'Liste', 'icon' => 'th-list', 'url' => ['/product/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Catégories', 'icon' => 'book', 'url' => ['/product-category/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Liste', 'icon' => 'th-list', 'url' => ['/product/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Catégories', 'icon' => 'book', 'url' => ['/product-category/index'], 'visible' => UserModel::isCurrentProducer()],
] ]
], ],
['label' => 'Points de vente', 'icon' => 'map-marker', 'url' => ['/point-sale/index'], 'visible' => User::isCurrentProducer(), 'active' => Yii::$app->controller->id == 'point-sale'],
['label' => 'Points de vente', 'icon' => 'map-marker', 'url' => ['/point-sale/index'], 'visible' => UserModel::isCurrentProducer(), 'active' => Yii::$app->controller->id == 'point-sale'],
[ [
'label' => 'Utilisateurs', 'label' => 'Utilisateurs',
'icon' => 'users', 'icon' => 'users',
'url' => ['/user/index'], 'url' => ['/user/index'],
'items' => [ 'items' => [
['label' => 'Liste', 'icon' => 'th-list', 'url' => ['/user/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Groupes', 'icon' => 'users', 'url' => ['/user-group/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Liste', 'icon' => 'th-list', 'url' => ['/user/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Groupes', 'icon' => 'users', 'url' => ['/user-group/index'], 'visible' => UserModel::isCurrentProducer()],
], ],
], ],
['label' => 'Abonnements', 'icon' => 'repeat', 'url' => ['/subscription/index'], 'visible' => User::isCurrentProducer(), 'active' => Yii::$app->controller->id == 'subscription'],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Abonnements', 'icon' => 'repeat', 'url' => ['/subscription/index'], 'visible' => UserModel::isCurrentProducer(), 'active' => Yii::$app->controller->id == 'subscription'],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate/index'], 'visible' => UserModel::isCurrentProducer()],
[ [
'label' => 'Documents', 'label' => 'Documents',
'icon' => 'clone', 'icon' => 'clone',
'url' => ['/delivery-note/index'], 'url' => ['/delivery-note/index'],
'items' => [ 'items' => [
['label' => 'Bons de livraison', 'icon' => 'sticky-note-o', 'url' => ['/delivery-note/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Factures', 'icon' => 'sticky-note-o', 'url' => ['/invoice/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Devis', 'icon' => 'sticky-note-o', 'url' => ['/quotation/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Bons de livraison', 'icon' => 'sticky-note-o', 'url' => ['/delivery-note/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Factures', 'icon' => 'sticky-note-o', 'url' => ['/invoice/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Devis', 'icon' => 'sticky-note-o', 'url' => ['/quotation/index'], 'visible' => UserModel::isCurrentProducer()],
], ],
], ],
[ [
'icon' => 'line-chart', 'icon' => 'line-chart',
'url' => ['/stats/index'], 'url' => ['/stats/index'],
'items' => [ 'items' => [
['label' => 'Chiffre d\'affaire', 'icon' => 'line-chart', 'url' => ['/stats/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Rapports', 'icon' => 'pencil-square-o', 'url' => ['/report/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Produits', 'icon' => 'table', 'url' => ['/stats/products'], 'visible' => User::isCurrentProducer()],
['label' => 'Chiffre d\'affaire', 'icon' => 'line-chart', 'url' => ['/stats/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Rapports', 'icon' => 'pencil-square-o', 'url' => ['/report/index'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Produits', 'icon' => 'table', 'url' => ['/stats/products'], 'visible' => UserModel::isCurrentProducer()],
], ],
], ],
['label' => 'Paramètres', 'icon' => 'cog', 'url' => ['/producer/update'], 'visible' => User::isCurrentProducer()],
['label' => 'Accès', 'icon' => 'lock', 'url' => ['/access/index'], 'visible' => User::isCurrentProducer()],
['label' => 'Paramètres', 'icon' => 'cog', 'url' => ['/producer/update'], 'visible' => UserModel::isCurrentProducer()],
['label' => 'Accès', 'icon' => 'lock', 'url' => ['/access/index'], 'visible' => UserModel::isCurrentProducer()],
[ [
'label' => 'Développement', 'label' => 'Développement',
'icon' => 'code', 'icon' => 'code',
'url' => ['/development/index'], 'url' => ['/development/index'],
'visible' => User::isCurrentProducer(),
'visible' => UserModel::isCurrentProducer(),
'active' => Yii::$app->controller->id == 'development', 'active' => Yii::$app->controller->id == 'development',
'template'=>'<a href="{url}">{icon} {label}'.$newVersionOpendistribTemplate.'</a>' 'template'=>'<a href="{url}">{icon} {label}'.$newVersionOpendistribTemplate.'</a>'
], ],
['label' => 'Tarifs', 'icon' => 'euro', 'url' => ['/producer/billing'], 'visible' => User::isCurrentProducer()],
['label' => 'Tarifs', 'icon' => 'euro', 'url' => ['/producer/billing'], 'visible' => UserModel::isCurrentProducer()],


['label' => 'Administration', 'options' => ['class' => 'header'], 'visible' => User::isCurrentAdmin()],
['label' => 'Producteurs', 'icon' => 'th-list', 'url' => ['/producer-admin/index'], 'visible' => User::isCurrentAdmin()],
['label' => 'Tranches de prix', 'icon' => 'eur', 'url' => ['/producer-price-range-admin/index'], 'visible' => User::isCurrentAdmin()],
['label' => 'Taxes', 'icon' => 'eur', 'url' => ['/tax-rate-admin/index'], 'visible' => User::isCurrentAdmin()],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate-admin/index'], 'visible' => User::isCurrentAdmin()],
['label' => 'Administration', 'options' => ['class' => 'header'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Producteurs', 'icon' => 'th-list', 'url' => ['/producer-admin/index'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Tranches de prix', 'icon' => 'eur', 'url' => ['/producer-price-range-admin/index'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Taxes', 'icon' => 'eur', 'url' => ['/tax-rate-admin/index'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Communiquer', 'icon' => 'bullhorn', 'url' => ['/communicate-admin/index'], 'visible' => UserModel::isCurrentAdmin()],


['label' => 'Outils', 'options' => ['class' => 'header'], 'visible' => User::isCurrentAdmin()],
['label' => 'Gii', 'icon' => 'file-code-o', 'url' => ['/gii'], 'visible' => User::isCurrentAdmin()],
['label' => 'Debug', 'icon' => 'dashboard', 'url' => ['/debug'], 'visible' => User::isCurrentAdmin()],
['label' => 'Login', 'url' => ['site/login'], 'visible' => !User::isCurrentConnected()],
['label' => 'Outils', 'options' => ['class' => 'header'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Gii', 'icon' => 'file-code-o', 'url' => ['/gii'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Debug', 'icon' => 'dashboard', 'url' => ['/debug'], 'visible' => UserModel::isCurrentAdmin()],
['label' => 'Login', 'url' => ['site/login'], 'visible' => !UserModel::isCurrentConnected()],
], ],
] ]
) ?> ) ?>

+ 3
- 3
backend/views/layouts/main-old.php View File



$producer = null; $producer = null;
if (!Yii::$app->user->isGuest) { if (!Yii::$app->user->isGuest) {
$producer = Producer::findOne(GlobalParam::getCurrentProducerId());
$producer = ProducerModel::findOne(GlobalParam::getCurrentProducerId());
} }


?> ?>
<?php elseif (UserModel::getCurrentStatus() == UserModel::STATUS_ADMIN): ?> <?php elseif (UserModel::getCurrentStatus() == UserModel::STATUS_ADMIN): ?>
<?php $form = ActiveForm::begin(['id' => 'select-producer']); ?> <?php $form = ActiveForm::begin(['id' => 'select-producer']); ?>
<?= <?=
Html::dropDownList('select_producer', GlobalParam::getCurrentProducerId(), ArrayHelper::map(Producer::find()->orderBy('name ASC')->all(), 'id', function ($model, $defaultValue) {
Html::dropDownList('select_producer', GlobalParam::getCurrentProducerId(), ArrayHelper::map(ProducerModel::find()->orderBy('name ASC')->all(), 'id', function ($model, $defaultValue) {
return $model->name; return $model->name;
})); }));
?> ?>
<?php endif; ?> <?php endif; ?>


<?php <?php
$producer = Producer::findOne(GlobalParam::getCurrentProducerId());
$producer = ProducerModel::findOne(GlobalParam::getCurrentProducerId());
if (!$producer->active): if (!$producer->active):
?> ?>
<span class="label label-danger" data-toggle="tooltip" data-placement="bottom" <span class="label label-danger" data-toggle="tooltip" data-placement="bottom"

+ 8
- 8
backend/views/order/report.php View File

$html .= '<td><strong>'.number_format($order->amount, 2) . ' € '; $html .= '<td><strong>'.number_format($order->amount, 2) . ' € ';


if($order->getPaymentStatus() == Order::PAYMENT_PAID)
if($order->getPaymentStatus() == OrderModel::PAYMENT_PAID)
{ {
$html .= '(payé)' ; $html .= '(payé)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_UNPAID && $order->getAmount(Order::AMOUNT_PAID))
elseif($order->getPaymentStatus() == OrderModel::PAYMENT_UNPAID && $order->getAmount(OrderModel::AMOUNT_PAID))
{ {
$html .= '(reste '.$order->getAmount(Order::AMOUNT_REMAINING, true).' à payer)' ;
$html .= '(reste '.$order->getAmount(OrderModel::AMOUNT_REMAINING, true).' à payer)' ;
} }
elseif($order->getPaymentStatus() == Order::PAYMENT_SURPLUS)
elseif($order->getPaymentStatus() == OrderModel::PAYMENT_SURPLUS)
{ {
$html .= '(surplus : '.$order->getAmount(Order::PAYMENT_SURPLUS, true).' à rembourser)' ;
$html .= '(surplus : '.$order->getAmount(OrderModel::PAYMENT_SURPLUS, true).' à rembourser)' ;
} }
$html .= '</strong></td>' ; $html .= '</strong></td>' ;
$strProducts = ''; $strProducts = '';
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders);
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders);
$strQuantity = ''; $strQuantity = '';
if ($quantity) { if ($quantity) {
$strQuantity = $quantity; $strQuantity = $quantity;
{ {
$html .= '<tr><td>'.$pointSale->name.'</td><td>' ; $html .= '<tr><td>'.$pointSale->name.'</td><td>' ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$quantity = Order::getProductQuantity($product->id, $pointSale->orders);
$quantity = OrderModel::getProductQuantity($product->id, $pointSale->orders);
$strQuantity = ($quantity) ? $quantity : '' ; $strQuantity = ($quantity) ? $quantity : '' ;
if(strlen($strQuantity)) { if(strlen($strQuantity)) {
// total // total
$html .= '<tr><td><strong>Total</strong></td><td>' ; $html .= '<tr><td><strong>Total</strong></td><td>' ;
foreach ($productsArray as $product) { foreach ($productsArray as $product) {
$quantity = Order::getProductQuantity($product->id, $ordersArray);
$quantity = OrderModel::getProductQuantity($product->id, $ordersArray);
if($quantity) { if($quantity) {
$html .= $quantity . '&nbsp;'.$product->name.', ' ; $html .= $quantity . '&nbsp;'.$product->name.', ' ;
} }

+ 9
- 9
backend/views/point-sale/_form.php View File

<?= $form->field($model, 'id_user', [ <?= $form->field($model, 'id_user', [
'template' => '{label} <a href="' . Yii::$app->urlManager->createUrl(['user/create']) . '" class="btn btn-xs btn-default">Nouvel utilisateur <span class="glyphicon glyphicon-plus"></span></a><div>{input}</div>{hint}', 'template' => '{label} <a href="' . Yii::$app->urlManager->createUrl(['user/create']) . '" class="btn btn-xs btn-default">Nouvel utilisateur <span class="glyphicon glyphicon-plus"></span></a><div>{input}</div>{hint}',
]) ])
->dropDownList(User::populateDropdownList(), ['class' => 'select2'])
->dropDownList(UserModel::populateDropdownList(), ['class' => 'select2'])
->hint('Utilisé lors de la facturation'); ?> ->hint('Utilisé lors de la facturation'); ?>


<?php <?php
$addHintCredit = ''; $addHintCredit = '';
if (!Producer::getConfig('credit')):
if (!ProducerModel::getConfig('credit')):
$addHintCredit = '<br /><strong>Attention, le système de Crédit est désactivé au niveau des ' . Html::a('paramètres globaux', ['producer/update']) . '.</strong>'; $addHintCredit = '<br /><strong>Attention, le système de Crédit est désactivé au niveau des ' . Html::a('paramètres globaux', ['producer/update']) . '.</strong>';
endif; endif;




<?= $form->field($model, 'credit_functioning') <?= $form->field($model, 'credit_functioning')
->dropDownList([ ->dropDownList([
'' => 'Paramètres globaux (' . Producer::$creditFunctioningArray[Producer::getConfig('credit_functioning')] . ')',
Producer::CREDIT_FUNCTIONING_OPTIONAL => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_OPTIONAL],
Producer::CREDIT_FUNCTIONING_MANDATORY => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_MANDATORY],
Producer::CREDIT_FUNCTIONING_USER => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_USER],
], [])->hint(Producer::HINT_CREDIT_FUNCTIONING); ?>
'' => 'Paramètres globaux (' . ProducerModel::$creditFunctioningArray[ProducerModel::getConfig('credit_functioning')] . ')',
ProducerModel::CREDIT_FUNCTIONING_OPTIONAL => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_OPTIONAL],
ProducerModel::CREDIT_FUNCTIONING_MANDATORY => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_MANDATORY],
ProducerModel::CREDIT_FUNCTIONING_USER => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_USER],
], [])->hint(ProducerModel::HINT_CREDIT_FUNCTIONING); ?>


<?php /*$form->field($model, 'product_price_percent') <?php /*$form->field($model, 'product_price_percent')
->dropDownList(ProductPrice::percentValues(), [])->hint('Pourcentage appliqué aux prix de chaque produit dans ce point de vente.');*/ ?>
->dropDownList(ProductPriceModel::percentValues(), [])->hint('Pourcentage appliqué aux prix de chaque produit dans ce point de vente.');*/ ?>


<?= $form->field($model, 'maximum_number_orders')->textInput() ?> <?= $form->field($model, 'maximum_number_orders')->textInput() ?>




<?= Html::activeCheckboxList($model, 'users', ArrayHelper::map($users, 'user_id', function ($model_user, $defaultValue) use ($model) { <?= Html::activeCheckboxList($model, 'users', ArrayHelper::map($users, 'user_id', function ($model_user, $defaultValue) use ($model) {


return Html::encode(User::getUsernameFromArray($model_user)) . '<br />'
return Html::encode(UserModel::getUsernameFromArray($model_user)) . '<br />'
. Html::activeTextInput( . Html::activeTextInput(
$model, $model,
'users_comment[' . $model_user['user_id'] . ']', 'users_comment[' . $model_user['user_id'] . ']',

+ 3
- 3
backend/views/point-sale/index.php View File

], ],
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) { 'value' => function ($model) {
$count = UserPointSale::find()->where(
$count = UserPointSaleModel::find()->where(
['id_point_sale' => $model->id] ['id_point_sale' => $model->id]
)->count(); )->count();
$html = ''; $html = '';
'label' => 'Crédit', 'label' => 'Crédit',
'format' => 'raw', 'format' => 'raw',
'value' => function ($model) { 'value' => function ($model) {
if ($model->credit && isset(Producer::$creditFunctioningArray[$model->credit_functioning])) {
return '<span class="glyphicon glyphicon-euro"></span> ' . Producer::$creditFunctioningArray[$model->credit_functioning];
if ($model->credit && isset(ProducerModel::$creditFunctioningArray[$model->credit_functioning])) {
return '<span class="glyphicon glyphicon-euro"></span> ' . ProducerModel::$creditFunctioningArray[$model->credit_functioning];
} }


return ''; return '';

+ 2
- 2
backend/views/producer-admin/_form.php View File



<h3>Facturation</h3> <h3>Facturation</h3>
<?= $form->field($model, 'option_billing_type') <?= $form->field($model, 'option_billing_type')
->dropDownList(Producer::getBillingTypePopulateDropdown()); ?>
->dropDownList(ProducerModel::getBillingTypePopulateDropdown()); ?>
<?= $form->field($model, 'option_billing_frequency') <?= $form->field($model, 'option_billing_frequency')
->dropDownList(Producer::getBillingFrequencyPopulateDropdown()); ?>
->dropDownList(ProducerModel::getBillingFrequencyPopulateDropdown()); ?>
<?= $form->field($model, 'option_billing_reduction') <?= $form->field($model, 'option_billing_reduction')
->dropDownList([ ->dropDownList([
0 => 'Non', 0 => 'Non',

+ 1
- 1
backend/views/producer-admin/index.php View File

'format' => 'raw', 'format' => 'raw',
'value' => function($model) { 'value' => function($model) {
$str = '<ul style="margin: 0px;padding-left: 15px;">'; $str = '<ul style="margin: 0px;padding-left: 15px;">';
$str .= '<li>'.Producer::$billingFrequencyArray[$model->option_billing_frequency].'</li>';
$str .= '<li>'.ProducerModel::$billingFrequencyArray[$model->option_billing_frequency].'</li>';


if($model->option_billing_permanent_transfer) { if($model->option_billing_permanent_transfer) {
$str .= '<li>Virement permanent : <strong>'.Price::format($model->option_billing_permanent_transfer_amount, 0).'</strong></li>'; $str .= '<li>Virement permanent : <strong>'.Price::format($model->option_billing_permanent_transfer_amount, 0).'</strong></li>';

+ 17
- 17
backend/views/producer/update.php View File



<script> <script>
var appInitValues = { var appInitValues = {
isAdmin: <?= (int)User::isCurrentAdmin() ?>
isAdmin: <?= (int)UserModel::isCurrentAdmin() ?>
}; };
</script> </script>


?> ?>
<?= $form->field($model, 'behavior_home_point_sale_day_list') <?= $form->field($model, 'behavior_home_point_sale_day_list')
->dropDownList([ ->dropDownList([
Producer::BEHAVIOR_HOME_POINT_SALE_DAY_LIST_WEEK => 'Jours de la semaine',
Producer::BEHAVIOR_HOME_POINT_SALE_DAY_LIST_INCOMING_DISTRIBUTIONS => 'Distributions à venir',
ProducerModel::BEHAVIOR_HOME_POINT_SALE_DAY_LIST_WEEK => 'Jours de la semaine',
ProducerModel::BEHAVIOR_HOME_POINT_SALE_DAY_LIST_INCOMING_DISTRIBUTIONS => 'Distributions à venir',
]); ?> ]); ?>
</div> </div>
</div> </div>
<h4>Tunnel de commande</h4> <h4>Tunnel de commande</h4>
<?= $form->field($model, 'option_order_entry_point') <?= $form->field($model, 'option_order_entry_point')
->dropDownList([ ->dropDownList([
Producer::ORDER_ENTRY_POINT_DATE => 'Date',
Producer::ORDER_ENTRY_POINT_POINT_SALE => 'Point de vente',
ProducerModel::ORDER_ENTRY_POINT_DATE => 'Date',
ProducerModel::ORDER_ENTRY_POINT_POINT_SALE => 'Point de vente',
], []); ?> ], []); ?>
<?= $form->field($model, 'behavior_order_select_distribution') <?= $form->field($model, 'behavior_order_select_distribution')
->dropDownList([ ->dropDownList([
Producer::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_CALENDAR => 'Calendrier',
Producer::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST => 'Liste',
ProducerModel::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_CALENDAR => 'Calendrier',
ProducerModel::BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST => 'Liste',
]); ?> ]); ?>
<?= $form->field($model, 'option_delivery') <?= $form->field($model, 'option_delivery')
->dropDownList([ ->dropDownList([
<h4>Divers</h4> <h4>Divers</h4>
<?= $form->field($model, 'option_order_reference_type') <?= $form->field($model, 'option_order_reference_type')
->dropDownList([ ->dropDownList([
Producer::ORDER_REFERENCE_TYPE_NONE => '--',
Producer::ORDER_REFERENCE_TYPE_YEARLY => 'Annuelle',
ProducerModel::ORDER_REFERENCE_TYPE_NONE => '--',
ProducerModel::ORDER_REFERENCE_TYPE_YEARLY => 'Annuelle',
], []); ?> ], []); ?>
<?= $form->field($model, 'option_behavior_cancel_order') <?= $form->field($model, 'option_behavior_cancel_order')
->dropDownList([ ->dropDownList([
Producer::BEHAVIOR_DELETE_ORDER_DELETE => 'Suppression de la commande',
Producer::BEHAVIOR_DELETE_ORDER_STATUS => 'Passage de la commande en statut "supprimé"',
ProducerModel::BEHAVIOR_DELETE_ORDER_DELETE => 'Suppression de la commande',
ProducerModel::BEHAVIOR_DELETE_ORDER_STATUS => 'Passage de la commande en statut "supprimé"',
], []); ?> ], []); ?>
</div> </div>
</div> </div>


<?= $form->field($model, 'credit_functioning') <?= $form->field($model, 'credit_functioning')
->dropDownList([ ->dropDownList([
Producer::CREDIT_FUNCTIONING_OPTIONAL => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_OPTIONAL],
Producer::CREDIT_FUNCTIONING_MANDATORY => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_MANDATORY],
Producer::CREDIT_FUNCTIONING_USER => Producer::$creditFunctioningArray[Producer::CREDIT_FUNCTIONING_USER],
], [])->hint(Producer::HINT_CREDIT_FUNCTIONING); ?>
ProducerModel::CREDIT_FUNCTIONING_OPTIONAL => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_OPTIONAL],
ProducerModel::CREDIT_FUNCTIONING_MANDATORY => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_MANDATORY],
ProducerModel::CREDIT_FUNCTIONING_USER => ProducerModel::$creditFunctioningArray[ProducerModel::CREDIT_FUNCTIONING_USER],
], [])->hint(ProducerModel::HINT_CREDIT_FUNCTIONING); ?>


<?= $form->field($model, 'use_credit_checked_default') <?= $form->field($model, 'use_credit_checked_default')
->dropDownList([ ->dropDownList([
1 => 'Oui', 1 => 'Oui',
], []); ?> ], []); ?>
<?= $form->field($model, 'option_online_payment_minimum_amount') <?= $form->field($model, 'option_online_payment_minimum_amount')
->hint('Valeur par défaut si non défini : '.Producer::ONLINE_PAYMENT_MINIMUM_AMOUNT_DEFAULT.' €')
->hint('Valeur par défaut si non défini : '.ProducerModel::ONLINE_PAYMENT_MINIMUM_AMOUNT_DEFAULT.' €')
->textInput(); ?> ->textInput(); ?>
<?= $form->field($model, 'option_stripe_mode_test')->dropDownList([ <?= $form->field($model, 'option_stripe_mode_test')->dropDownList([
0 => 'Non', 0 => 'Non',
<div class="panel-body"> <div class="panel-body">
<h4>Facturation</h4> <h4>Facturation</h4>
<?= $form->field($model, 'id_tax_rate_default') <?= $form->field($model, 'id_tax_rate_default')
->dropDownList(ArrayHelper::map(TaxRate::find()->all(), 'id', function ($model) {
->dropDownList(ArrayHelper::map(TaxRateModel::find()->all(), 'id', function ($model) {
return $model->name; return $model->name;
})) }))
->label('TVA à appliquer par défaut'); ?> ->label('TVA à appliquer par défaut'); ?>

+ 5
- 5
backend/views/product/_form.php View File

<?= $form->field($model, 'active')->radioList([1 => 'Oui', 0 => 'Non']) ?> <?= $form->field($model, 'active')->radioList([1 => 'Oui', 0 => 'Non']) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'reference')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'reference')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'id_product_category')->dropDownList(ProductCategory::populateDropdownList()); ?>
<?= $form->field($model, 'id_product_category')->dropDownList(ProductCategoryModel::populateDropdownList()); ?>
<?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'description')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'recipe')->textarea()->label('Description longue') ?> <?= $form->field($model, 'recipe')->textarea()->label('Description longue') ?>


<?= $form->field($model, 'unit') <?= $form->field($model, 'unit')
->dropDownList(ArrayHelper::map(Product::$unitsArray, 'unit', 'wording'))
->dropDownList(ArrayHelper::map(ProductModel::$unitsArray, 'unit', 'wording'))
->label('Unité (pièce, poids ou volume)'); ?> ->label('Unité (pièce, poids ou volume)'); ?>




$producer = \common\helpers\GlobalParam::getCurrentProducer(); $producer = \common\helpers\GlobalParam::getCurrentProducer();
$taxRateDefault = $producer->taxRate; $taxRateDefault = $producer->taxRate;


$taxRateNamesArray = array_merge(array(0 => 'Tva par défaut'), ArrayHelper::map(TaxRate::find()->all(), 'id', function ($model) {
$taxRateNamesArray = array_merge(array(0 => 'Tva par défaut'), ArrayHelper::map(TaxRateModel::find()->all(), 'id', function ($model) {
return $model->name; return $model->name;
})); }));
$taxRateValuesArray = array_merge(array(0 => $taxRateDefault->value), ArrayHelper::map(TaxRate::find()->all(), 'id', function ($model) {
$taxRateValuesArray = array_merge(array(0 => $taxRateDefault->value), ArrayHelper::map(TaxRateModel::find()->all(), 'id', function ($model) {
return $model->value; return $model->value;
})); }));
foreach ($taxRateValuesArray as $key => $taxRateValue) { foreach ($taxRateValuesArray as $key => $taxRateValue) {
<?= $form->field($model, 'available_on_points_sale')->radioList([1 => 'Disponible', 0 => 'Indisponible']) ?> <?= $form->field($model, 'available_on_points_sale')->radioList([1 => 'Disponible', 0 => 'Indisponible']) ?>


<strong id="label-availability-points-sale">Et <span><?php if($model->available_on_points_sale): ?>indisponible<?php else: ?>disponible<?php endif; ?></span> sur les points de vente</strong> <strong id="label-availability-points-sale">Et <span><?php if($model->available_on_points_sale): ?>indisponible<?php else: ?>disponible<?php endif; ?></span> sur les points de vente</strong>
<?php $pointSaleArray = PointSale::find()
<?php $pointSaleArray = PointSaleModel::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['id_producer' => GlobalParam::getCurrentProducerId()])
->orderBy('is_bread_box ASC, name ASC') ->orderBy('is_bread_box ASC, name ASC')
->all(); ?> ->all(); ?>

+ 1
- 1
backend/views/product/index.php View File

'value' => function ($model) { 'value' => function ($model) {
$return = ''; $return = '';
if ($model->price) { if ($model->price) {
$return = Price::format($model->getPriceWithTax()) . ' (' . Product::strUnit($model->unit, 'wording_unit', true) . ')';
$return = Price::format($model->getPriceWithTax()) . ' (' . ProductModel::strUnit($model->unit, 'wording_unit', true) . ')';
} }


return $return; return $return;

+ 5
- 5
backend/views/product/update/prices/_form.php View File

]); ?> ]); ?>


<?= $form->field($model, 'id_user')->dropDownList(UserModel::populateDropdownList()); ?> <?= $form->field($model, 'id_user')->dropDownList(UserModel::populateDropdownList()); ?>
<?= $form->field($model, 'id_user_group')->dropDownList(UserGroup::populateDropdownList()); ?>
<?= $form->field($model, 'id_point_sale')->dropDownList(PointSale::populateDropdownList()); ?>
<?= $form->field($model, 'from_quantity')->label('À partir de la quantité ('.Product::strUnit(Product::getRefUnit($modelProduct->unit), 'wording').')'); ?>
<?= $form->field($model, 'id_user_group')->dropDownList(UserGroupModel::populateDropdownList()); ?>
<?= $form->field($model, 'id_point_sale')->dropDownList(PointSaleModel::populateDropdownList()); ?>
<?= $form->field($model, 'from_quantity')->label('À partir de la quantité ('.ProductModel::strUnit(ProductModel::getRefUnit($modelProduct->unit), 'wording').')'); ?>


<?php <?php
$producer = GlobalParam::getCurrentProducer(); $producer = GlobalParam::getCurrentProducer();
'template' => ' 'template' => '
<div class="row"> <div class="row">
<div class="col-xs-6"> <div class="col-xs-6">
<label for="product-price" class="control-label without-tax">Prix ('.Product::strUnit(Product::getRefUnit($modelProduct->unit), 'wording_unit').') HT</label>
<label for="product-price" class="control-label without-tax">Prix ('.ProductModel::strUnit(ProductModel::getRefUnit($modelProduct->unit), 'wording_unit').') HT</label>
<div class="input-group"> <div class="input-group">
{input} <span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span> {input} <span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span>
</div> </div>
</div> </div>
<div class="col-xs-6"> <div class="col-xs-6">
<label for="productprice-price-with-tax" class="control-label with-tax">Prix ('.Product::strUnit(Product::getRefUnit($modelProduct->unit), 'wording_unit').') TTC</label>
<label for="productprice-price-with-tax" class="control-label with-tax">Prix ('.ProductModel::strUnit(ProductModel::getRefUnit($modelProduct->unit), 'wording_unit').') TTC</label>
<div class="input-group"> <div class="input-group">
<input type="text" id="productprice-price-with-tax" class="form-control" name="" value="" data-tax-rate-value="'.$taxRateValue.'"> <input type="text" id="productprice-price-with-tax" class="form-control" name="" value="" data-tax-rate-value="'.$taxRateValue.'">
<span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span> <span class="input-group-addon"><span class="glyphicon glyphicon-euro"></span></span>

+ 1
- 1
backend/views/product/update/prices/list.php View File

'attribute' => 'from_quantity', 'attribute' => 'from_quantity',
'value' => function ($productPrice) { 'value' => function ($productPrice) {
if($productPrice->from_quantity) { if($productPrice->from_quantity) {
return $productPrice->from_quantity.' '.Product::strUnit(Product::getRefUnit($productPrice->product->unit), 'wording');
return $productPrice->from_quantity.' '.ProductModel::strUnit(ProductModel::getRefUnit($productPrice->product->unit), 'wording');
} }


return '' ; return '' ;

+ 2
- 2
backend/views/quotation/index.php View File

?> ?>


<div class="quotation-index"> <div class="quotation-index">
<?php if(Quotation::searchCount()): ?>
<?php if(QuotationModel::searchCount()): ?>
<?= GridView::widget([ <?= GridView::widget([
'filterModel' => $searchModel, 'filterModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'attribute' => 'amount', 'attribute' => 'amount',
'header' => 'Montant', 'header' => 'Montant',
'value' => function($invoice) { 'value' => function($invoice) {
return $invoice->getAmountWithTax(Order::AMOUNT_TOTAL, true) ;
return $invoice->getAmountWithTax(OrderModel::AMOUNT_TOTAL, true) ;
} }
], ],
[ [

+ 1
- 1
backend/views/site/index.php View File

</td> </td>
<td><?= $order->getCartSummary() ; ?></td> <td><?= $order->getCartSummary() ; ?></td>
<td><?= $order->getPointSaleSummary() ; ?></td> <td><?= $order->getPointSaleSummary() ; ?></td>
<td><?= $order->getAmountWithTax(Order::AMOUNT_TOTAL, true) ; ?></td>
<td><?= $order->getAmountWithTax(OrderModel::AMOUNT_TOTAL, true) ; ?></td>
<td class="history"><?= $order->getStrHistory() ; ?></td> <td class="history"><?= $order->getStrHistory() ; ?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>

+ 4
- 4
backend/views/subscription/_form.php View File

<div class="clr"></div> <div class="clr"></div>
<?= $form->field($model, 'id_producer')->hiddenInput() ?> <?= $form->field($model, 'id_producer')->hiddenInput() ?>
<?= $form->field($model, 'id_point_sale')->dropDownList(ArrayHelper::map(PointSale::searchAll(), 'id', function($model, $defaultValue) {
<?= $form->field($model, 'id_point_sale')->dropDownList(ArrayHelper::map(PointSaleModel::searchAll(), 'id', function($model, $defaultValue) {
return $model['name']; return $model['name'];
}), ['prompt' => '--','class' => 'form-control user-id']) ?> }), ['prompt' => '--','class' => 'form-control user-id']) ?>
<?= $form->field($model, 'date_begin') ?> <?= $form->field($model, 'date_begin') ?>


<?= $form->field($model, 'auto_payment') <?= $form->field($model, 'auto_payment')
->dropDownList([ ->dropDownList([
Subscription::AUTO_PAYMENT_DEDUCTED => 'Déduit',
Subscription::AUTO_PAYMENT_YES => 'Oui',
Subscription::AUTO_PAYMENT_NO => 'Non'
SubscriptionModel::AUTO_PAYMENT_DEDUCTED => 'Déduit',
SubscriptionModel::AUTO_PAYMENT_YES => 'Oui',
SubscriptionModel::AUTO_PAYMENT_NO => 'Non'
]) ])
->hint('Attention, un compte client existant doit être spécifié en haut de ce formulaire.') ?> ->hint('Attention, un compte client existant doit être spécifié en haut de ce formulaire.') ?>

+ 3
- 3
backend/views/subscription/index.php View File

$this->addBreadcrumb($this->getTitle()) ; $this->addBreadcrumb($this->getTitle()) ;
$this->addButton(['label' => 'Nouvel abonnement <span class="glyphicon glyphicon-plus"></span>', 'url' => 'subscription/create', 'class' => 'btn btn-primary']) ; $this->addButton(['label' => 'Nouvel abonnement <span class="glyphicon glyphicon-plus"></span>', 'url' => 'subscription/create', 'class' => 'btn btn-primary']) ;


$subscriptionsArray = Subscription::searchAll() ;
$subscriptionsArray = SubscriptionModel::searchAll() ;






foreach($model->productSubscription as $productSubscription) foreach($model->productSubscription as $productSubscription)
{ {
if(isset($productSubscription->product)) { if(isset($productSubscription->product)) {
$html .= Html::encode($productSubscription->product->name).' ('.($productSubscription->quantity * Product::$unitsArray[$productSubscription->product->unit]['coefficient']).'&nbsp;'.Product::strUnit($productSubscription->product->unit, 'wording_short').')<br />' ;
$html .= Html::encode($productSubscription->product->name).' ('.($productSubscription->quantity * ProductModel::$unitsArray[$productSubscription->product->unit]['coefficient']).'&nbsp;'.ProductModel::strUnit($productSubscription->product->unit, 'wording_short').')<br />' ;
} }
else { else {
$html .= 'Produit non défini<br />' ; $html .= 'Produit non défini<br />' ;
'attribute' => 'id_point_sale', 'attribute' => 'id_point_sale',
'label' => 'Point de vente', 'label' => 'Point de vente',
'format' => 'raw', 'format' => 'raw',
'filter' => ArrayHelper::map(PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->asArray()->all(), 'id', 'name'),
'filter' => ArrayHelper::map(PointSaleModel::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->asArray()->all(), 'id', 'name'),
'value' => function($model) { 'value' => function($model) {
return Html::encode($model->pointSale->name) ; return Html::encode($model->pointSale->name) ;
} }

+ 3
- 3
backend/views/user/_form.php View File

]); ?> ]); ?>


<?= $form->field($model, 'type') <?= $form->field($model, 'type')
->dropDownList(User::getTypeChoicesArray(), [
->dropDownList(UserModel::getTypeChoicesArray(), [
'v-model' => 'type' 'v-model' => 'type'
]) ; ?> ]) ; ?>
<?= $form->field($model, 'name_legal_person', ['options' => ['v-show' => "type == 'legal-person'"]])->textInput() ?> <?= $form->field($model, 'name_legal_person', ['options' => ['v-show' => "type == 'legal-person'"]])->textInput() ?>
<?= $form->field($model, 'email')->textInput() ?> <?= $form->field($model, 'email')->textInput() ?>
<?= $form->field($model, 'address')->textarea() ?> <?= $form->field($model, 'address')->textarea() ?>


<?php if(Producer::getConfig('option_export_evoliz')): ?>
<?php if(ProducerModel::getConfig('option_export_evoliz')): ?>
<?= $form->field($model, 'evoliz_code')->textInput() ?> <?= $form->field($model, 'evoliz_code')->textInput() ?>
<?php endif; ?> <?php endif; ?>


?> ?>


<?php /* $form->field($model, 'product_price_percent') <?php /* $form->field($model, 'product_price_percent')
->dropDownList(ProductPrice::percentValues(), [])->hint('Pourcentage appliqué aux prix de chaque produit pour cet utilisateur.');*/ ?>
->dropDownList(ProductPriceModel::percentValues(), [])->hint('Pourcentage appliqué aux prix de chaque produit pour cet utilisateur.');*/ ?>


<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Ajouter' : 'Modifier', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton($model->isNewRecord ? 'Ajouter' : 'Modifier', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

+ 3
- 3
backend/views/user/credit.php View File

<div class="user-credit"> <div class="user-credit">
<?php <?php
$producer = Producer::searchOne([
$producer = ProducerModel::searchOne([
'id' => GlobalParam::getCurrentProducerId() 'id' => GlobalParam::getCurrentProducerId()
]); ]);
<div class="panel-body"> <div class="panel-body">
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($creditForm, 'type')->dropDownList([ <?= $form->field($creditForm, 'type')->dropDownList([
CreditHistory::TYPE_CREDIT => 'Crédit',
CreditHistory::TYPE_DEBIT => 'Débit',
CreditHistoryModel::TYPE_CREDIT => 'Crédit',
CreditHistoryModel::TYPE_DEBIT => 'Débit',
]) ?> ]) ?>
<?= $form->field($creditForm, 'amount')->textInput() ?> <?= $form->field($creditForm, 'amount')->textInput() ?>
<?= $form->field($creditForm, 'mean_payment')->dropDownList([ <?= $form->field($creditForm, 'mean_payment')->dropDownList([

+ 2
- 2
backend/views/user/index.php View File

'buttons' => [ 'buttons' => [
'orders' => function ($url, $model) { 'orders' => function ($url, $model) {
$url = Yii::$app->urlManager->createUrl(['user/orders', 'id' => $model['id']]); $url = Yii::$app->urlManager->createUrl(['user/orders', 'id' => $model['id']]);
$countOrders = Order::searchCount([
$countOrders = OrderModel::searchCount([
'id_user' => $model['id'], 'id_user' => $model['id'],
], ['conditions' => 'date_delete IS NULL']); ], ['conditions' => 'date_delete IS NULL']);


'format' => 'raw', 'format' => 'raw',
'value' => function ($model) use ($producer) { 'value' => function ($model) use ($producer) {


$userProducer = UserProducer::searchOne([
$userProducer = UserProducerModel::searchOne([
'id_user' => $model->id 'id_user' => $model->id
]); ]);
$credit = $userProducer ? $userProducer->credit : 0; $credit = $userProducer ? $userProducer->credit : 0;

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



namespace common\components; namespace common\components;


use common\logic\Config\TaxRate\TaxRateContainer;
use common\logic\Distribution\Distribution\DistributionContainer;
use common\logic\Document\Document\DocumentContainer;
use common\logic\Order\Order\OrderContainer;
use common\logic\Order\OrderStatusHistory\OrderStatusHistoryContainer;
use common\logic\Order\ProductOrder\ProductOrderContainer;
use common\logic\PointSale\PointSale\PointSaleContainer;
use common\logic\Producer\Producer\ProducerContainer; use common\logic\Producer\Producer\ProducerContainer;
use common\logic\Producer\ProducerPriceRange\ProducerPriceRangeContainer; use common\logic\Producer\ProducerPriceRange\ProducerPriceRangeContainer;
use common\logic\Product\Product\ProductContainer;
use common\logic\Product\ProductCategory\ProductCategoryContainer;
use common\logic\Product\ProductPointSale\ProductPointSaleContainer;
use common\logic\Product\ProductPrice\ProductPriceContainer;
use common\logic\Subscription\ProductSubscription\ProductSubscriptionContainer;
use common\logic\Subscription\Subscription\SubscriptionContainer;
use common\logic\User\CreditHistory\CreditHistoryContainer; use common\logic\User\CreditHistory\CreditHistoryContainer;
use common\logic\User\User\UserContainer; use common\logic\User\User\UserContainer;
use common\logic\User\UserGroup\UserGroupContainer;
use common\logic\User\UserGroup\UserUserGroupContainer;
use common\logic\User\UserProducer\UserProducerContainer; use common\logic\User\UserProducer\UserProducerContainer;
use yii\base\ErrorException; use yii\base\ErrorException;


public function getContainers() public function getContainers()
{ {
return [ return [
$this->getTaxRateContainer(),
$this->getUserUserGroupContainer(),
$this->getUserGroupContainer(),
$this->getDocumentContainer(),
$this->getCreditHistoryContainer(), $this->getCreditHistoryContainer(),
$this->getProducerPriceRangeContainer(), $this->getProducerPriceRangeContainer(),
$this->getUserProducerContainer(), $this->getUserProducerContainer(),
$this->getOrderSatusHistoryContainer(),
$this->getProductCategoryContainer(),
$this->getProductPointSaleContainer(),
$this->getProductOrderContainer(),
$this->getProductPriceContainer(),
$this->getProductSubscriptionContainer(),
$this->getSubscriptionContainer(),
$this->getProductContainer(),
$this->getDistributionContainer(),
$this->getUserContainer(), $this->getUserContainer(),
$this->getProducerContainer(), $this->getProducerContainer(),
$this->getOrderContainer(),
]; ];
} }


return new CreditHistoryContainer(); return new CreditHistoryContainer();
} }


public function getDocumentContainer(): DocumentContainer
{
return new DocumentContainer();
}

public function getUserGroupContainer(): UserGroupContainer
{
return new UserGroupContainer();
}

public function getUserUserGroupContainer(): UserUserGroupContainer
{
return new UserUserGroupContainer();
}

public function getDistributionContainer(): DistributionContainer
{
return new DistributionContainer();
}

public function getTaxRateContainer(): TaxRateContainer
{
return new TaxRateContainer();
}

public function getOrderContainer(): OrderContainer
{
return new OrderContainer();
}

public function getOrderSatusHistoryContainer(): OrderStatusHistoryContainer
{
return new OrderStatusHistoryContainer();
}

public function getPointSaleContainer(): PointSaleContainer
{
return new PointSaleContainer();
}

public function getProductOrderContainer(): ProductOrderContainer
{
return new ProductOrderContainer();
}

public function getProductContainer(): ProductContainer
{
return new ProductContainer();
}

public function getProductCategoryContainer(): ProductCategoryContainer
{
return new ProductCategoryContainer();
}

public function getProductPointSaleContainer(): ProductPointSaleContainer
{
return new ProductPointSaleContainer();
}

public function getProductPriceContainer(): ProductPriceContainer
{
return new ProductPriceContainer();
}

public function getSubscriptionContainer(): SubscriptionContainer
{
return new SubscriptionContainer();
}

public function getProductSubscriptionContainer(): ProductSubscriptionContainer
{
return new ProductSubscriptionContainer();
}

/* /*
* Hiérarchie des apps * Hiérarchie des apps
*/ */

common/models/SubscriptionForm.php → common/forms/SubscriptionForm.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\forms;


use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
public function save() public function save()
{ {
if ($this->id) { if ($this->id) {
$subscription = Subscription::searchOne(['id' => $this->id]) ;
$subscription = SubscriptionModel::searchOne(['id' => $this->id]) ;
} }
else { else {
$subscription = new Subscription ; $subscription = new Subscription ;


// produits // produits
if ($this->id) { if ($this->id) {
$productsSubscriptionsArray = ProductSubscription::findAll(['id_subscription' => $this->id]) ;
ProductSubscription::deleteAll(['id_subscription' => $this->id]);
$productsSubscriptionsArray = ProductSubscriptionModel::findAll(['id_subscription' => $this->id]) ;
ProductSubscriptionModel::deleteAll(['id_subscription' => $this->id]);
} }


foreach ($this->products as $nameInput => $quantity) { foreach ($this->products as $nameInput => $quantity) {
if ($quantity) { if ($quantity) {
$idProduct = (int) str_replace('product_', '', $nameInput); $idProduct = (int) str_replace('product_', '', $nameInput);
$product = Product::findOne($idProduct) ;
$product = ProductModel::findOne($idProduct) ;


$newProductSubscription = new ProductSubscription; $newProductSubscription = new ProductSubscription;
$newProductSubscription->id_subscription = $subscription->id; $newProductSubscription->id_subscription = $subscription->id;
$newProductSubscription->id_product = $idProduct; $newProductSubscription->id_product = $idProduct;
$newProductSubscription->quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
$newProductSubscription->quantity = $quantity / ProductModel::$unitsArray[$product->unit]['coefficient'];


$newProductSubscription->save(); $newProductSubscription->save();
} }

+ 3
- 3
common/helpers/Price.php View File

return floatval($priceWithTax) / ($taxRate + 1); return floatval($priceWithTax) / ($taxRate + 1);
} }


public static function getPriceWithTax($priceWithoutTax, $taxRate, $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public static function getPriceWithTax($priceWithoutTax, $taxRate, $taxCalculationMethod = DocumentModel::TAX_CALCULATION_METHOD_DEFAULT)
{ {
$vat = self::getVat($priceWithoutTax, $taxRate, $taxCalculationMethod); $vat = self::getVat($priceWithoutTax, $taxRate, $taxCalculationMethod);


return self::numberTwoDecimals(self::round($priceWithoutTax + $vat)); return self::numberTwoDecimals(self::round($priceWithoutTax + $vat));
} }


public static function getVat($priceTotalWithoutTax, $taxRate, $taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public static function getVat($priceTotalWithoutTax, $taxRate, $taxCalculationMethod = DocumentModel::TAX_CALCULATION_METHOD_DEFAULT)
{ {
$vat = $priceTotalWithoutTax * $taxRate; $vat = $priceTotalWithoutTax * $taxRate;


if($taxCalculationMethod == Document::TAX_CALCULATION_METHOD_SUM_OF_ROUNDINGS) {
if($taxCalculationMethod == DocumentModel::TAX_CALCULATION_METHOD_SUM_OF_ROUNDINGS) {
$vat = self::round($vat); $vat = self::round($vat);
} }



+ 2
- 2
common/helpers/Tiller.php View File

{ {
if ($this->producer_tiller) { if ($this->producer_tiller) {
$ordersTiller = $this->getOrders($date); $ordersTiller = $this->getOrders($date);
$ordersOpendistrib = Order::searchAll([
$ordersOpendistrib = OrderModel::searchAll([
'distribution.date' => $date, 'distribution.date' => $date,
'order.tiller_synchronization' => 1 'order.tiller_synchronization' => 1
], [ ], [
foreach ($ordersTiller->orders as $orderTiller) { foreach ($ordersTiller->orders as $orderTiller) {
if ($orderOpendistrib->tiller_external_id == $orderTiller->id) { if ($orderOpendistrib->tiller_external_id == $orderTiller->id) {
$amountTotalOrderOpendistrib = (int)round( $amountTotalOrderOpendistrib = (int)round(
$orderOpendistrib->getAmountWithTax(Order::AMOUNT_TOTAL) * 100
$orderOpendistrib->getAmountWithTax(OrderModel::AMOUNT_TOTAL) * 100
); );
if ($amountTotalOrderOpendistrib == (int)$orderTiller->currentPayedAmount if ($amountTotalOrderOpendistrib == (int)$orderTiller->currentPayedAmount
|| $amountTotalOrderOpendistrib == (int)$orderTiller->currentBill) { || $amountTotalOrderOpendistrib == (int)$orderTiller->currentBill) {

+ 31
- 0
common/logic/Config/TaxRate/TaxRateContainer.php View File

<?php

namespace common\logic\Config\TaxRate;

use common\logic\ContainerInterface;

class TaxRateContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return TaxRateModel::class;
}

public function getServices(): array
{
return [
TaxRateFactory::class,
TaxRateRepository::class,
];
}

public function getFactory(): TaxRateFactory
{
return new TaxRateFactory();
}

public function getRepository(): TaxRateRepository
{
return new TaxRateRepository();
}
}

+ 17
- 0
common/logic/Config/TaxRate/TaxRateFactory.php View File

<?php

namespace common\logic\Config\TaxRate;

use common\logic\BaseService;
use common\logic\FactoryInterface;
use Stripe\TaxRate;

class TaxRateFactory extends BaseService implements FactoryInterface
{
public function create(): TaxRate
{
$taxRate = new TaxRate();

return $taxRate;
}
}

+ 43
- 0
common/logic/Config/TaxRate/TaxRateModel.php View File

<?php

namespace common\logic\Config\TaxRate;

use common\components\ActiveRecordCommon;

/**
* This is the model class for table "tax_rate".
*
*/
class TaxRateModel extends ActiveRecordCommon
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tax_rate';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['value'], 'number'],
[['name'], 'string', 'max' => 255],
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Nom',
'value' => 'Valeur (0.2 pour 20%)',
];
}
}

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

<?php

namespace common\logic\Config\TaxRate;

use common\logic\BaseService;
use common\logic\RepositoryInterface;

class TaxRateRepository extends BaseService implements RepositoryInterface
{

/**
* Retourne les options de base nécessaires à la fonction de recherche.
*
*/
public function defaultOptionsSearch(): array
{
return [
'with' => [],
'join_with' => [],
'orderby' => 'pourcent ASC',
'attribute_id_producer' => ''
] ;
}

// getTaxRateArray
public function getAsArray(): array
{
$taxRateArrayReturn = [];
$taxRateArray = TaxRateModel::find()->all();

foreach($taxRateArray as $taxRate) {
$taxRateArrayReturn[$taxRate->id] = $taxRate;
}

return $taxRateArrayReturn;
}
}

common/models/Development.php → common/logic/Development/Development/DevelopmentModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Development\Development;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use Yii; use Yii;
use common\components\ActiveRecordCommon ; use common\components\ActiveRecordCommon ;
use common\models\DeveloppementPriorite;


/** /**
* This is the model class for table "development". * This is the model class for table "development".
* @property string $status * @property string $status
* @property double $time_estimate * @property double $time_estimate
*/ */
class Development extends ActiveRecordCommon
class DevelopmentModel extends ActiveRecordCommon
{ {
const STATUS_OPEN = 'open'; const STATUS_OPEN = 'open';
const STATUS_CLOSED = 'closed'; const STATUS_CLOSED = 'closed';
public function getDevelopmentPriority() public function getDevelopmentPriority()
{ {
return $this->hasMany( return $this->hasMany(
DevelopmentPriority::className(),
DevelopmentPriorityModel::className(),
['id_development' => 'id']) ['id_development' => 'id'])
->with('producer'); ->with('producer');
} }
public function getDevelopmentPriorityCurrentProducer() public function getDevelopmentPriorityCurrentProducer()
{ {
return $this->hasOne( return $this->hasOne(
DevelopmentPriority::className(),
DevelopmentPriorityModel::className(),
['id_development' => 'id']) ['id_development' => 'id'])
->where(['id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['id_producer' => GlobalParam::getCurrentProducerId()])
->with('producer'); ->with('producer');

common/models/DevelopmentPriority.php → common/logic/Development/DevelopmentPriority/DevelopmentPriorityModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Development\DevelopmentPriority;


use common\logic\Producer\Producer\ProducerModel; use common\logic\Producer\Producer\ProducerModel;
use Yii;
use common\components\ActiveRecordCommon ; use common\components\ActiveRecordCommon ;
use common\models\Producer;


/** /**
* This is the model class for table "development_priority". * This is the model class for table "development_priority".
* *
* @property integer $id_user
* @property integer $id_development
*/ */
class DevelopmentPriority extends ActiveRecordCommon
class DevelopmentPriorityModel extends ActiveRecordCommon
{ {


const PRIORITY_HIGH = 'high'; const PRIORITY_HIGH = 'high';
public function getClassCssStyleButton() public function getClassCssStyleButton()
{ {
$styleButton = 'default'; $styleButton = 'default';
if ($this->priority == DevelopmentPriority::PRIORITY_LOW) {
if ($this->priority == DevelopmentPriorityModel::PRIORITY_LOW) {
$styleButton = 'info'; $styleButton = 'info';
} }
elseif ($this->priority == DevelopmentPriority::PRIORITY_NORMAL) {
elseif ($this->priority == DevelopmentPriorityModel::PRIORITY_NORMAL) {
$styleButton = 'warning'; $styleButton = 'warning';
} }
elseif ($this->priority == DevelopmentPriority::PRIORITY_HIGH) {
elseif ($this->priority == DevelopmentPriorityModel::PRIORITY_HIGH) {
$styleButton = 'danger'; $styleButton = 'danger';
} }

+ 11
- 0
common/logic/Distribution/Distribution/DistributionBuilder.php View File

<?php

namespace common\logic\Distribution\Distribution;

use common\logic\BaseService;
use common\logic\BuilderInterface;

class DistributionBuilder extends BaseService implements BuilderInterface
{

}

+ 43
- 0
common/logic/Distribution/Distribution/DistributionContainer.php View File

<?php

namespace common\logic\Distribution\Distribution;

use common\logic\ContainerInterface;

class DistributionContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return DistributionModel::class;
}

public function getServices(): array
{
return [
DistributionFactory::class,
DistributionSolver::class,
DistributionRepository::class,
DistributionBuilder::class
];
}

public function getFactory(): DistributionFactory
{
return new DistributionFactory();
}

public function getSolver(): DistributionSolver
{
return new DistributionSolver();
}

public function getRepository(): DistributionRepository
{
return new DistributionRepository();
}

public function getBuilder(): DistributionBuilder
{
return new DistributionBuilder();
}
}

+ 16
- 0
common/logic/Distribution/Distribution/DistributionFactory.php View File

<?php

namespace common\logic\Distribution\Distribution;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class DistributionFactory extends BaseService implements FactoryInterface
{
public function create(): DistributionModel
{
$distribution = new DistributionModel();

return $distribution;
}
}

common/models/Distribution.php → common/logic/Distribution/Distribution/DistributionModel.php View File

* termes. * termes.
*/ */


namespace common\models;
namespace common\logic\Distribution\Distribution;


use common\logic\Producer\Producer\ProducerModel; use common\logic\Producer\Producer\ProducerModel;
use Yii;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Order;
use common\components\ActiveRecordCommon; use common\components\ActiveRecordCommon;


/** /**
* @property string $date * @property string $date
* @property integer $active * @property integer $active
*/ */
class Distribution extends ActiveRecordCommon
class DistributionModel extends ActiveRecordCommon
{ {
/** /**
* @inheritdoc * @inheritdoc


public function getOrder() public function getOrder()
{ {
return $this->hasMany(Order::className(), ['id_distribution' => 'id']);
return $this->hasMany(OrderModel::className(), ['id_distribution' => 'id']);
} }


public function getProductDistribution() public function getProductDistribution()
{ {
return $this->hasMany(ProductDistribution::className(), ['id_distribution' => 'id']);
return $this->hasMany(ProductDistributionModel::className(), ['id_distribution' => 'id']);
} }


public function getPointSaleDistribution() public function getPointSaleDistribution()
{ {
return $this->hasMany(PointSaleDistribution::className(), ['id_distribution' => 'id']) ;
return $this->hasMany(PointSaleDistributionModel::className(), ['id_distribution' => 'id']) ;
} }


/** /**
$idProducer = GlobalParam::getCurrentProducerId(); $idProducer = GlobalParam::getCurrentProducerId();
} }


$distribution = Distribution::searchOne($paramsDistribution);
$distribution = DistributionModel::searchOne($paramsDistribution);


if (!$distribution) { if (!$distribution) {
$distribution = new Distribution; $distribution = new Distribution;
// point_sale_distribution à définir s'ils ne sont pas initialisés // point_sale_distribution à définir s'ils ne sont pas initialisés
if ($distribution) { if ($distribution) {


$countPointSaleDistribution = PointSaleDistribution::searchCount([
$countPointSaleDistribution = PointSaleDistributionModel::searchCount([
'id_distribution' => $distribution->id 'id_distribution' => $distribution->id
]); ]);


if (!$countPointSaleDistribution) { if (!$countPointSaleDistribution) {
PointSaleDistribution::setAll($distribution->id, true);
PointSaleDistributionModel::setAll($distribution->id, true);
} }
} }


// init produits sélectionnés pour cette production // init produits sélectionnés pour cette production
$products = Product::searchAll();
$products = ProductModel::searchAll();


if ($distribution) { if ($distribution) {
$productsDistribution = ProductDistribution::searchAll([
$productsDistribution = ProductDistributionModel::searchAll([
'id_distribution' => $distribution->id 'id_distribution' => $distribution->id
]); ]);
if (!count($productsDistribution)) { if (!count($productsDistribution)) {
*/ */
public static function getIncomingDistributions() public static function getIncomingDistributions()
{ {
$distributionsArray = Distribution::find()
$distributionsArray = DistributionModel::find()
->where('date > \'' . date('Y-m-d') . '\'') ->where('date > \'' . date('Y-m-d') . '\'')
->andWhere([ ->andWhere([
'id_producer' => GlobalParam::getCurrentProducerId(), 'id_producer' => GlobalParam::getCurrentProducerId(),
*/ */
public function linkProduct($product) public function linkProduct($product)
{ {
$productDistribution = ProductDistribution::searchOne([
$productDistribution = ProductDistributionModel::searchOne([
'id_distribution' => $this->id, 'id_distribution' => $this->id,
'id_product' => $product->id 'id_product' => $product->id
]); ]);
$productDistribution->save(); $productDistribution->save();


// update prices product order // update prices product order
$ordersArray = Order::searchAll([
$ordersArray = OrderModel::searchAll([
'distribution.date' => $this->date, 'distribution.date' => $this->date,
'distribution.id_producer' => $this->id_producer 'distribution.id_producer' => $this->id_producer
], ],
*/ */
public function linkProductGift() public function linkProductGift()
{ {
$productGift = Product::getProductGift();
$productGift = ProductModel::getProductGift();


if ($productGift) { if ($productGift) {
$productDistribution = ProductDistribution::searchOne([
$productDistribution = ProductDistributionModel::searchOne([
'id_distribution' => $this->id, 'id_distribution' => $this->id,
'id_product' => $productGift->id 'id_product' => $productGift->id
]); ]);
*/ */
public function linkPointSale($pointSale) public function linkPointSale($pointSale)
{ {
$pointSaleDistribution = PointSaleDistribution::searchOne([
$pointSaleDistribution = PointSaleDistributionModel::searchOne([
'id_distribution' => $this->id, 'id_distribution' => $this->id,
'id_point_sale' => $pointSale->id 'id_point_sale' => $pointSale->id
]); ]);
*/ */
public function active($active = true) public function active($active = true)
{ {
PointSaleDistribution::setAll($this->id, true);
PointSaleDistributionModel::setAll($this->id, true);
$this->active = (int)$active; $this->active = (int)$active;
$this->save(); $this->save();


if ($active) { if ($active) {
// ajout des abonnements // ajout des abonnements
Subscription::addAll($this->date);
SubscriptionModel::addAll($this->date);
} }
} }



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

<?php

namespace common\logic\Distribution\Distribution;

use common\logic\BaseService;
use common\logic\RepositoryInterface;

class DistributionRepository extends BaseService implements RepositoryInterface
{

}

+ 11
- 0
common/logic/Distribution/Distribution/DistributionSolver.php View File

<?php

namespace common\logic\Distribution\Distribution;

use common\logic\BaseService;
use common\logic\SolverInterface;

class DistributionSolver extends BaseService implements SolverInterface
{

}

+ 16
- 0
common/logic/Distribution/PointSaleDistribution/PointSaleDistributionFactory.php View File

<?php

namespace common\logic\Distribution\PointSaleDistribution;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class PointSaleDistributionFactory extends BaseService implements FactoryInterface
{
public function create(): PointSaleDistributionModel
{
$pointSaleDistribution = new PointSaleDistributionModel();

return $pointSaleDistribution;
}
}

common/models/PointSaleDistribution.php → common/logic/Distribution/PointSaleDistribution/PointSaleDistributionModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Distribution\PointSaleDistribution;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use Yii; use Yii;
use common\components\ActiveRecordCommon ; use common\components\ActiveRecordCommon ;
use common\models\PointVente;
use common\models\Production;


/** /**
* This is the model class for table "production_point_vente". * This is the model class for table "production_point_vente".
* @property integer $id_point_sale * @property integer $id_point_sale
* @property integer $delivery * @property integer $delivery
*/ */
class PointSaleDistribution extends ActiveRecordCommon
class PointSaleDistributionModel extends ActiveRecordCommon
{ {


var $points_sale_distribution; var $points_sale_distribution;


public function getPointSale() public function getPointSale()
{ {
return $this->hasOne(PointSale::className(), ['id' => 'id_point_sale']);
return $this->hasOne(PointSaleModel::className(), ['id' => 'id_point_sale']);
} }
/** /**
public static function setAll($idDistribution, $boolDelivery) public static function setAll($idDistribution, $boolDelivery)
{ {
// liaison PointSale / Distribution // liaison PointSale / Distribution
$arrPointsSale = PointSale::find()
$arrPointsSale = PointSaleModel::find()
->with(['pointSaleDistribution' => function($q) use ($idDistribution) { ->with(['pointSaleDistribution' => function($q) use ($idDistribution) {
$q->where(['id_distribution' => $idDistribution]); $q->where(['id_distribution' => $idDistribution]);
}]) }])
} }
} }


$distribution = Distribution::findOne($idDistribution);
$distribution = DistributionModel::findOne($idDistribution);


if ($distribution) { if ($distribution) {
$day = date('N', strtotime($distribution->date)); $day = date('N', strtotime($distribution->date));

+ 16
- 0
common/logic/Distribution/ProductDistribution/ProductDistributionFactory.php View File

<?php

namespace common\logic\Distribution\ProductDistribution;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class ProductDistributionFactory extends BaseService implements FactoryInterface
{
public function create(): ProductDistributionModel
{
$productDistribution = new ProductDistributionModel();

return $productDistribution;
}
}

common/models/ProductDistribution.php → common/logic/Distribution/ProductDistribution/ProductDistributionModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Distribution\ProductDistribution;


use common\components\ActiveRecordCommon ; use common\components\ActiveRecordCommon ;


* @property integer $id_product * @property integer $id_product
* @property integer $active * @property integer $active
*/ */
class ProductDistribution extends ActiveRecordCommon
class ProductDistributionModel extends ActiveRecordCommon
{ {


/** /**
public function getProduct() public function getProduct()
{ {
return $this->hasOne(Product::className(), ['id' => 'id_product']);
return $this->hasOne(ProductModel::className(), ['id' => 'id_product']);
} }
public function getDistribution() public function getDistribution()
*/ */
public static function searchByDistribution($idDistribution) public static function searchByDistribution($idDistribution)
{ {
$arrayProductsDistribution = ProductDistribution::searchAll([
$arrayProductsDistribution = ProductDistributionModel::searchAll([
'id_distribution' => $idDistribution 'id_distribution' => $idDistribution
]) ; ]) ;
$orders = Order::searchAll([
$orders = OrderModel::searchAll([
'distribution.id' => $idDistribution 'distribution.id' => $idDistribution
]) ; ]) ;


'active' => (int) $productDistribution->active, 'active' => (int) $productDistribution->active,
'unavailable' => (int) $productDistribution->product->unavailable, 'unavailable' => (int) $productDistribution->product->unavailable,
'quantity_max' => $productDistribution->quantity_max, 'quantity_max' => $productDistribution->quantity_max,
'quantity_order' => Order::getProductQuantity($productDistribution->id_product, $orders),
'quantity_remaining' => $productDistribution->quantity_max - Order::getProductQuantity($productDistribution->id_product, $orders)
'quantity_order' => OrderModel::getProductQuantity($productDistribution->id_product, $orders),
'quantity_remaining' => $productDistribution->quantity_max - OrderModel::getProductQuantity($productDistribution->id_product, $orders)
]; ];
} }
} }

+ 31
- 0
common/logic/Document/DeliveryNote/DeliveryNoteContainer.php View File

<?php

namespace common\logic\Document\DeliveryNote;

use common\logic\ContainerInterface;

class DeliveryNoteContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return DeliveryNoteModel::class;
}

public function getServices(): array
{
return [
DeliveryNoteFactory::class,
DeliveryNoteSolver::class,
];
}

public function getFactory(): DeliveryNoteFactory
{
return new DeliveryNoteFactory();
}

public function getSolver(): DeliveryNoteSolver
{
return new DeliveryNoteSolver();
}
}

+ 16
- 0
common/logic/Document/DeliveryNote/DeliveryNoteFactory.php View File

<?php

namespace common\logic\Document\DeliveryNote;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class DeliveryNoteFactory extends BaseService implements FactoryInterface
{
public function create(): DeliveryNoteModel
{
$deliveryNote = new DeliveryNoteModel();

return $deliveryNote;
}
}

common/models/DeliveryNote.php → common/logic/Document/DeliveryNote/DeliveryNoteModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Document\DeliveryNote;


use common\components\ActiveRecordCommon; use common\components\ActiveRecordCommon;
use Yii; use Yii;
* @property string $city * @property string $city
* @property string $postcode * @property string $postcode
*/ */
class DeliveryNote extends Document
class DeliveryNoteModel extends Document
{ {


/** /**
$idInvoice = $this->getInvoiceId(); $idInvoice = $this->getInvoiceId();


if($idInvoice) { if($idInvoice) {
$invoice = Invoice::searchOne([
$invoice = InvoiceModel::searchOne([
'id' => $idInvoice 'id' => $idInvoice
]); ]);
} }

common/models/DeliveryNoteSearch.php → common/logic/Document/DeliveryNote/DeliveryNoteSearch.php View File

* termes. * termes.
*/ */


namespace common\models;

namespace common\logic\Document\DeliveryNote;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use yii\data\ActiveDataProvider;


class DeliveryNoteSearch extends DeliveryNote
class DeliveryNoteSearch extends DeliveryNoteModel
{ {
public $id_point_sale ; public $id_point_sale ;
public $date_distribution ; public $date_distribution ;
{ {
$optionsSearch = self::defaultOptionsSearch(); $optionsSearch = self::defaultOptionsSearch();


$query = DeliveryNote::find()
$query = DeliveryNoteModel::find()
->with($optionsSearch['with']) ->with($optionsSearch['with'])
->joinWith($optionsSearch['join_with']) ->joinWith($optionsSearch['join_with'])
->where(['delivery_note.id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['delivery_note.id_producer' => GlobalParam::getCurrentProducerId()])

+ 11
- 0
common/logic/Document/DeliveryNote/DeliveryNoteSolver.php View File

<?php

namespace common\logic\Document\DeliveryNote;

use common\logic\BaseService;
use common\logic\SolverInterface;

class DeliveryNoteSolver extends BaseService implements SolverInterface
{

}

+ 11
- 0
common/logic/Document/Document/DocumentBuilder.php View File

<?php

namespace common\logic\Document\Document;

use common\logic\BaseService;
use common\logic\BuilderInterface;

class DocumentBuilder extends BaseService implements BuilderInterface
{

}

+ 37
- 0
common/logic/Document/Document/DocumentContainer.php View File

<?php

namespace common\logic\Document\Document;

use common\logic\ContainerInterface;

class DocumentContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return DocumentModel::class;
}

public function getServices(): array
{
return [
DocumentSolver::class,
DocumentBuilder::class,
DocumentUtils::class,
];
}

public function getSolver(): DocumentSolver
{
return new DocumentSolver();
}

public function getBuilder(): DocumentBuilder
{
return new DocumentBuilder();
}

public function getUtils(): DocumentUtils
{
return new DocumentUtils();
}
}

common/models/Document.php → common/logic/Document/Document/DocumentModel.php View File

* termes. * termes.
*/ */


namespace common\models;
namespace common\logic\Document\Document;


use common\components\ActiveRecordCommon;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\logic\Producer\Producer\ProducerModel; use common\logic\Producer\Producer\ProducerModel;
use kartik\mpdf\Pdf; use kartik\mpdf\Pdf;
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
use yii\base\ErrorException; use yii\base\ErrorException;


class Document extends ActiveRecordCommon
class DocumentModel extends ActiveRecordCommon
{ {
const STATUS_DRAFT = 'draft'; const STATUS_DRAFT = 'draft';
const STATUS_VALID = 'valid'; const STATUS_VALID = 'valid';


public function relationOrders($fieldIdDocument) public function relationOrders($fieldIdDocument)
{ {
$defaultOptionsSearch = Order::defaultOptionsSearch();
$defaultOptionsSearch = OrderModel::defaultOptionsSearch();


return $this->hasMany(Order::className(), [$fieldIdDocument => 'id'])
return $this->hasMany(OrderModel::className(), [$fieldIdDocument => 'id'])
->with($defaultOptionsSearch['with']) ->with($defaultOptionsSearch['with'])
->joinWith($defaultOptionsSearch['join_with']) ->joinWith($defaultOptionsSearch['join_with'])
->orderBy('distribution.date ASC'); ->orderBy('distribution.date ASC');
* Méthodes * Méthodes
*/ */


public function getAmount($type = Order::AMOUNT_TOTAL, $format = false)
public function getAmount($type = OrderModel::AMOUNT_TOTAL, $format = false)
{ {
return $this->_getAmountGeneric($type, false, $format); return $this->_getAmountGeneric($type, false, $format);
} }


public function getAmountWithTax($type = Order::AMOUNT_TOTAL, $format = false)
public function getAmountWithTax($type = OrderModel::AMOUNT_TOTAL, $format = false)
{ {
return $this->_getAmountGeneric($type, true, $format); return $this->_getAmountGeneric($type, true, $format);
} }


protected function _getAmountGeneric($type = Order::AMOUNT_TOTAL, $withTax = true, $format = false)
protected function _getAmountGeneric($type = OrderModel::AMOUNT_TOTAL, $withTax = true, $format = false)
{ {
$amount = 0; $amount = 0;
$totalVat = 0; $totalVat = 0;
} }


$prefix = ProducerModel::getConfig('document_' . $classLower . '_prefix'); $prefix = ProducerModel::getConfig('document_' . $classLower . '_prefix');
$oneDocumentExist = $class::searchOne(['status' => Document::STATUS_VALID], ['orderby' => 'reference DESC']);
$oneDocumentExist = $class::searchOne(['status' => DocumentModel::STATUS_VALID], ['orderby' => 'reference DESC']);


if ($oneDocumentExist) { if ($oneDocumentExist) {
$reference = $oneDocumentExist->reference; $reference = $oneDocumentExist->reference;


public function changeStatus($status) public function changeStatus($status)
{ {
if ($status == Document::STATUS_VALID) {
if ($status == DocumentModel::STATUS_VALID) {
$this->status = $status; $this->status = $status;
$this->reference = $this->generateReference(); $this->reference = $this->generateReference();
} }

+ 11
- 0
common/logic/Document/Document/DocumentSolver.php View File

<?php

namespace common\logic\Document\Document;

use common\logic\BaseService;
use common\logic\SolverInterface;

class DocumentSolver extends BaseService implements SolverInterface
{

}

+ 11
- 0
common/logic/Document/Document/DocumentUtils.php View File

<?php

namespace common\logic\Document\Document;

use common\logic\BaseService;
use common\logic\UtilsInterface;

class DocumentUtils extends BaseService implements UtilsInterface
{

}

+ 37
- 0
common/logic/Document/Invoice/InvoiceContainer.php View File

<?php

namespace common\logic\Document\Invoice;

use common\logic\ContainerInterface;
use common\logic\Document\Document\DocumentBuilder;
use common\logic\Document\Document\DocumentSolver;

class InvoiceContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return InvoiceModel::class;
}

public function getServices(): array
{
return [
InvoiceFactory::class,
];
}

public function getFactory(): InvoiceFactory
{
return new InvoiceFactory();
}

public function getSolver(): DocumentSolver
{
return new DocumentSolver();
}

public function getBuilder(): DocumentBuilder
{
return new DocumentBuilder();
}
}

+ 16
- 0
common/logic/Document/Invoice/InvoiceFactory.php View File

<?php

namespace common\logic\Document\Invoice;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class InvoiceFactory extends BaseService implements FactoryInterface
{
public function create(): InvoiceModel
{
$invoice = new InvoiceModel();

return $invoice;
}
}

common/models/Invoice.php → common/logic/Document/Invoice/InvoiceModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Document\Invoice;


use common\components\ActiveRecordCommon;
use Yii;
use common\logic\Document\Document\DocumentModel;


/** /**
* This is the model class for table "invoice". * This is the model class for table "invoice".
* @property string $city * @property string $city
* @property string $postcode * @property string $postcode
*/ */
class Invoice extends Document
class InvoiceModel extends DocumentModel
{ {


public $deliveryNotes ; public $deliveryNotes ;

common/models/InvoiceSearch.php → common/logic/Document/Invoice/InvoiceSearch.php View File

* termes. * termes.
*/ */


namespace common\models;
namespace common\logic\Document\Invoice;


use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\models\Invoice;


class InvoiceSearch extends Invoice
class InvoiceSearch extends InvoiceModel
{ {

var $username; var $username;


public function rules() public function rules()
{ {
$optionsSearch = self::defaultOptionsSearch(); $optionsSearch = self::defaultOptionsSearch();


$query = Invoice::find()
$query = InvoiceModel::find()
->with($optionsSearch['with']) ->with($optionsSearch['with'])
->joinWith($optionsSearch['join_with']) ->joinWith($optionsSearch['join_with'])
->where(['invoice.id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['invoice.id_producer' => GlobalParam::getCurrentProducerId()])

+ 39
- 0
common/logic/Document/Quotation/QuotationContainer.php View File

<?php

namespace common\logic\Document\Invoice;

use common\logic\ContainerInterface;
use common\logic\Document\Document\DocumentBuilder;
use common\logic\Document\Document\DocumentSolver;
use common\logic\Document\Quotation\QuotationFactory;
use common\logic\Document\Quotation\QuotationModel;

class QuotationContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return QuotationModel::class;
}

public function getServices(): array
{
return [
QuotationFactory::class,
];
}

public function getFactory(): QuotationFactory
{
return new QuotationFactory();
}

public function getSolver(): DocumentSolver
{
return new DocumentSolver();
}

public function getBuilder(): DocumentBuilder
{
return new DocumentBuilder();
}
}

+ 16
- 0
common/logic/Document/Quotation/QuotationFactory.php View File

<?php

namespace common\logic\Document\Quotation;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class QuotationFactory extends BaseService implements FactoryInterface
{
public function create(): QuotationModel
{
$quotation = new QuotationModel();

return $quotation;
}
}

common/models/Quotation.php → common/logic/Document/Quotation/QuotationModel.php View File

termes. termes.
*/ */


namespace common\models;
namespace common\logic\Document\Quotation;


use Yii;
use common\logic\Document\Document\DocumentModel;


/** /**
* This is the model class for table "quotation". * This is the model class for table "quotation".
* @property string $city * @property string $city
* @property string $postcode * @property string $postcode
*/ */
class Quotation extends Document
class QuotationModel extends DocumentModel
{ {


/** /**

common/models/QuotationSearch.php → common/logic/Document/Quotation/QuotationSearch.php View File

* termes. * termes.
*/ */


namespace common\models;
namespace common\logic\Document\Quotation;


use common\models\Quotation;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use yii\data\ActiveDataProvider;


class QuotationSearch extends Quotation
class QuotationSearch extends QuotationModel
{ {


public function rules() public function rules()
{ {
$optionsSearch = self::defaultOptionsSearch(); $optionsSearch = self::defaultOptionsSearch();


$query = Quotation::find()
$query = QuotationModel::find()
->with($optionsSearch['with']) ->with($optionsSearch['with'])
->joinWith($optionsSearch['join_with']) ->joinWith($optionsSearch['join_with'])
->where(['quotation.id_producer' => GlobalParam::getCurrentProducerId()]) ->where(['quotation.id_producer' => GlobalParam::getCurrentProducerId()])

+ 12
- 0
common/logic/Order/Order/OrderBuilder.php View File

<?php

namespace common\logic\Order\Order;

use common\logic\BaseService;
use common\logic\BuilderInterface;
use common\logic\SolverInterface;

class OrderBuilder extends BaseService implements BuilderInterface
{
}

+ 49
- 0
common/logic/Order/Order/OrderContainer.php View File

<?php

namespace common\logic\Order\Order;

use common\logic\ContainerInterface;

class OrderContainer implements ContainerInterface
{
public function getEntityFqcn(): string
{
return OrderModel::class;
}

public function getServices(): array
{
return [
OrderFactory::class,
OrderSolver::class,
OrderRepository::class,
OrderBuilder::class,
OrderUtils::class
];
}

public function getFactory(): OrderFactory
{
return new OrderFactory();
}

public function getSolver(): OrderSolver
{
return new OrderSolver();
}

public function getRepository(): OrderRepository
{
return new OrderRepository();
}

public function getBuilder(): OrderBuilder
{
return new OrderBuilder();
}

public function getUtils(): OrderUtils
{
return new OrderUtils();
}
}

+ 16
- 0
common/logic/Order/Order/OrderFactory.php View File

<?php

namespace common\logic\Order\Order;

use common\logic\BaseService;
use common\logic\FactoryInterface;

class OrderFactory extends BaseService implements FactoryInterface
{
public function create(): OrderModel
{
$order = new OrderModel();

return $order;
}
}

common/models/Order.php → common/logic/Order/Order/OrderModel.php View File

* termes. * termes.
*/ */


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


use common\helpers\Debug;
use common\helpers\GlobalParam; use common\helpers\GlobalParam;
use common\helpers\Price; use common\helpers\Price;
use common\logic\Producer\Producer\ProducerModel; use common\logic\Producer\Producer\ProducerModel;
use common\logic\User\CreditHistory\CreditHistoryModel; use common\logic\User\CreditHistory\CreditHistoryModel;
use common\logic\User\User\UserModel; use common\logic\User\User\UserModel;
use common\models\Producer;
use Yii; use Yii;
use yii\helpers\Html; use yii\helpers\Html;
use common\components\ActiveRecordCommon; use common\components\ActiveRecordCommon;
/** /**
* This is the model class for table "order". * This is the model class for table "order".
* *
* @property integer $id
* @property integer $id_user
* @property string $date
* @property string $date_update
* @property integer $id_point_sale
* @property integer $id_distribution
* @property boolean $auto_payment
* @property integer $id_subscription
*/ */
class Order extends ActiveRecordCommon
class OrderModel extends ActiveRecordCommon
{ {
var $amount = 0; var $amount = 0;
var $amount_with_tax = 0; var $amount_with_tax = 0;


public function getProductOrder() public function getProductOrder()
{ {
return $this->hasMany(ProductOrder::className(), ['id_order' => 'id'])
return $this->hasMany(ProductOrderModel::className(), ['id_order' => 'id'])
->orderBy(['product.order' => SORT_ASC]) ->orderBy(['product.order' => SORT_ASC])
->joinWith('product'); ->joinWith('product');
} }


public function getPointSale() public function getPointSale()
{ {
return $this->hasOne(PointSale::className(), ['id' => 'id_point_sale'])
return $this->hasOne(PointSaleModel::className(), ['id' => 'id_point_sale'])
->with('userPointSale'); ->with('userPointSale');
} }




public function getSubscription() public function getSubscription()
{ {
return $this->hasOne(Subscription::className(), ['id' => 'id_subscription'])
return $this->hasOne(SubscriptionModel::className(), ['id' => 'id_subscription'])
->with('productSubscription'); ->with('productSubscription');
} }


public function getInvoice() public function getInvoice()
{ {
return $this->hasOne(Invoice::className(), ['id' => 'id_invoice']);
return $this->hasOne(InvoiceModel::className(), ['id' => 'id_invoice']);
} }


public function getQuotation() public function getQuotation()
{ {
return $this->hasOne(Quotation::className(), ['id' => 'id_quotation']);
return $this->hasOne(QuotationModel::className(), ['id' => 'id_quotation']);
} }


public function getDeliveryNote() public function getDeliveryNote()
{ {
return $this->hasOne(DeliveryNote::className(), ['id' => 'id_delivery_note']);
return $this->hasOne(DeliveryNoteModel::className(), ['id' => 'id_delivery_note']);
} }


/** /**
* Initialise le montant total, le montant déjà payé et le poids de la * Initialise le montant total, le montant déjà payé et le poids de la
* commande. * commande.
*/ */
public function init($taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public function init($taxCalculationMethod = DocumentModel::TAX_CALCULATION_METHOD_DEFAULT)
{ {
$this->initAmount($taxCalculationMethod); $this->initAmount($taxCalculationMethod);
$this->initPaidAmount(); $this->initPaidAmount();
* Initialise le montant de la commande. * Initialise le montant de la commande.
* *
*/ */
public function initAmount($taxCalculationMethod = Document::TAX_CALCULATION_METHOD_DEFAULT)
public function initAmount($taxCalculationMethod = DocumentModel::TAX_CALCULATION_METHOD_DEFAULT)
{ {
$this->amount = 0; $this->amount = 0;
$this->amount_with_tax = 0; $this->amount_with_tax = 0;
public function delete($force = false) public function delete($force = false)
{ {
// remboursement si l'utilisateur a payé pour cette commande // remboursement si l'utilisateur a payé pour cette commande
$amountPaid = $this->getAmount(Order::AMOUNT_PAID);
$amountPaid = $this->getAmount(OrderModel::AMOUNT_PAID);
if ($amountPaid > 0.01) { if ($amountPaid > 0.01) {
$this->saveCreditHistory( $this->saveCreditHistory(
CreditHistoryModel::TYPE_REFUND, CreditHistoryModel::TYPE_REFUND,
'option_behavior_cancel_order' 'option_behavior_cancel_order'
) == ProducerModel::BEHAVIOR_DELETE_ORDER_STATUS && strlen($this->date_delete)) || ) == ProducerModel::BEHAVIOR_DELETE_ORDER_STATUS && strlen($this->date_delete)) ||
$force) { $force) {
ProductOrder::deleteAll(['id_order' => $this->id]);
ProductOrderModel::deleteAll(['id_order' => $this->id]);
return parent::delete(); return parent::delete();
} // status 'delete' } // status 'delete'
elseif (ProducerModel::getConfig('option_behavior_cancel_order') == ProducerModel::BEHAVIOR_DELETE_ORDER_STATUS) { elseif (ProducerModel::getConfig('option_behavior_cancel_order') == ProducerModel::BEHAVIOR_DELETE_ORDER_STATUS) {
*/ */
public function getDataJson() public function getDataJson()
{ {
$order = Order::searchOne(['order.id' => $this->id]);
$order = OrderModel::searchOne(['order.id' => $this->id]);


$jsonOrder = []; $jsonOrder = [];
if ($order) { if ($order) {


public function setTillerSynchronization() public function setTillerSynchronization()
{ {
$order = Order::searchOne(['id' => $this->id]);
$order = OrderModel::searchOne(['id' => $this->id]);


$paymentStatus = $order->getPaymentStatus(); $paymentStatus = $order->getPaymentStatus();


public function getCartSummary($htmlFormat = true) public function getCartSummary($htmlFormat = true)
{ {
if (!isset($this->productOrder)) { if (!isset($this->productOrder)) {
$this->productOrder = productOrder::find()->where(['id_order' => $this->id])->all();
$this->productOrder = ProductOrderModel::find()->where(['id_order' => $this->id])->all();
} }


$html = ''; $html = '';
$i = 0; $i = 0;
foreach ($this->productOrder as $p) { foreach ($this->productOrder as $p) {
if (isset($p->product)) { if (isset($p->product)) {
$html .= Html::encode($p->product->name) . ' (' . $p->quantity . '&nbsp;' . Product::strUnit(
$html .= Html::encode($p->product->name) . ' (' . $p->quantity . '&nbsp;' . ProductModel::strUnit(
$p->unit, $p->unit,
'wording_short', 'wording_short',
true true
if ($creditActive) { if ($creditActive) {
$html .= '<br />'; $html .= '<br />';
if ($this->paid_amount) { if ($this->paid_amount) {
if ($this->getPaymentStatus() == Order::PAYMENT_PAID) {
if ($this->getPaymentStatus() == OrderModel::PAYMENT_PAID) {
$html .= '<span class="label label-success">Payée</span>'; $html .= '<span class="label label-success">Payée</span>';
} elseif ($this->getPaymentStatus() == Order::PAYMENT_UNPAID) {
} elseif ($this->getPaymentStatus() == OrderModel::PAYMENT_UNPAID) {
$html .= '<span class="label label-danger">Non payée</span><br /> $html .= '<span class="label label-danger">Non payée</span><br />
Reste <strong>' . $this->getAmount( Reste <strong>' . $this->getAmount(
Order::AMOUNT_REMAINING,
OrderModel::AMOUNT_REMAINING,
true true
) . '</strong> à payer'; ) . '</strong> à payer';
} elseif ($this->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
} elseif ($this->getPaymentStatus() == OrderModel::PAYMENT_SURPLUS) {
$html .= '<span class="label label-success">Payée</span>'; $html .= '<span class="label label-success">Payée</span>';
} }
} else { } else {
$quantity += $po->quantity; $quantity += $po->quantity;
} else { } else {
if (isset($po->product) && $po->product->weight > 0) { if (isset($po->product) && $po->product->weight > 0) {
$quantity += ($po->quantity * Product::$unitsArray[$po->unit]['coefficient']) / $po->product->weight;
$quantity += ($po->quantity * ProductModel::$unitsArray[$po->unit]['coefficient']) / $po->product->weight;
} }
} }
} }
if (is_array($orders)) { if (is_array($orders)) {
if (count($orders)) { if (count($orders)) {
foreach ($orders as $order) { foreach ($orders as $order) {
if (is_a($order, 'common\models\Order')) {
if (is_a($order, 'common\logic\Order\Order\OrderModel')) {
$order->init(); $order->init();
} }
} }
} }
} else { } else {
$order = $orders; $order = $orders;
if (is_a($order, 'common\models\Order')) {
if (is_a($order, 'common\logic\Order\Order\OrderModel')) {
return $order->init(); return $order->init();
} // count } // count
else { else {
$producer = ProducerModel::findOne($idProducer); $producer = ProducerModel::findOne($idProducer);


if (!$this->reference && $producer->option_order_reference_type == ProducerModel::ORDER_REFERENCE_TYPE_YEARLY) { if (!$this->reference && $producer->option_order_reference_type == ProducerModel::ORDER_REFERENCE_TYPE_YEARLY) {
$lastOrder = Order::find()->innerJoinWith('distribution', true)
$lastOrder = OrderModel::find()->innerJoinWith('distribution', true)
->where(['>=', 'distribution.date', date('Y') . '-01-01']) ->where(['>=', 'distribution.date', date('Y') . '-01-01'])
->andWhere([ ->andWhere([
'distribution.id_producer' => $producer->id 'distribution.id_producer' => $producer->id

+ 11
- 0
common/logic/Order/Order/OrderRepository.php View File

<?php

namespace common\logic\Order\Order;

use common\logic\BaseService;
use common\logic\RepositoryInterface;

class OrderRepository extends BaseService implements RepositoryInterface
{

}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save