Pārlūkot izejas kodu

Refactoring services #885

refactoring
Guillaume pirms 1 gada
vecāks
revīzija
dc03b00155
18 mainītis faili ar 300 papildinājumiem un 300 dzēšanām
  1. +59
    -62
      backend/controllers/ProductController.php
  2. +11
    -6
      backend/controllers/QuotationController.php
  3. +12
    -17
      backend/controllers/ReportController.php
  4. +3
    -10
      backend/controllers/SiteController.php
  5. +6
    -9
      backend/controllers/StatsController.php
  6. +57
    -73
      backend/controllers/SubscriptionController.php
  7. +8
    -7
      backend/controllers/TaxRateAdminController.php
  8. +71
    -94
      backend/controllers/UserController.php
  9. +9
    -18
      backend/controllers/UserGroupController.php
  10. +5
    -0
      common/logic/Config/TaxRate/TaxRateRepository.php
  11. +16
    -0
      common/logic/Distribution/Distribution/DistributionRepository.php
  12. +7
    -2
      common/logic/PointSale/UserPointSale/UserPointSaleRepository.php
  13. +3
    -1
      common/logic/Product/Product/ProductRepository.php
  14. +7
    -1
      common/logic/Product/ProductPointSale/ProductPointSaleBuilder.php
  15. +5
    -0
      common/logic/Product/ProductPrice/ProductPriceRepository.php
  16. +8
    -0
      common/logic/Subscription/ProductSubscription/ProductSubscriptionRepository.php
  17. +5
    -0
      common/logic/User/UserGroup/UserGroupRepository.php
  18. +8
    -0
      common/logic/User/UserUserGroup/UserUserGroupRepository.php

+ 59
- 62
backend/controllers/ProductController.php Parādīt failu

@@ -39,8 +39,17 @@
namespace backend\controllers;

use common\helpers\GlobalParam;
use common\logic\Distribution\ProductDistribution\ProductDistribution;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\Product\Product\Product;
use common\logic\Product\Product\ProductSearch;
use common\logic\Product\ProductPointSale\ProductPointSale;
use common\logic\Product\ProductPrice\ProductPrice;
use common\logic\Product\ProductPrice\ProductPriceSearch;
use common\logic\User\UserProducer\UserProducer;
use Yii;
use yii\filters\AccessControl;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\helpers\Upload;
@@ -92,17 +101,17 @@ class ProductController extends BackendController
}

/**
* Crée un modèle Produit.
* Si la création réussit, le navigateur est redirigé vers la page 'index'.
*
* @return mixed
* Crée un Product.
*/
public function actionCreate()
{
$model = new Product();
$productManager = $this->getProductManager();
$distributionManager = $this->getDistributionManager();

$model = $productManager->instanciateProduct();

$model->active = 1;
$model->id_producer = GlobalParam::getCurrentProducerId();

$model->monday = 1;
$model->tuesday = 1;
$model->wednesday = 1;
@@ -112,7 +121,7 @@ class ProductController extends BackendController
$model->sunday = 1;
$model->available_on_points_sale = 1;

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

$lastProductOrder = Product::find()->where('id_producer = :id_producer')->params([':id_producer' => GlobalParam::getCurrentProducerId()])->orderBy('order DESC')->one();
if ($lastProductOrder) {
@@ -120,13 +129,10 @@ class ProductController extends BackendController
}

Upload::uploadFile($model, 'photo');
$model->save();
$productManager->saveUpdate($model);

// availability on points sale
$this->processAvailabilityPointsSale($model);

// link product / distribution
DistributionModel::linkProductIncomingDistributions($model);
$distributionManager->addProductIncomingDistributions($model);

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

@@ -139,16 +145,14 @@ class ProductController extends BackendController
}

/**
* Modifie un modèle Produit existant.
* Si la modification réussit, le navigateur est redirigé vers la page 'index'.
*
* @param integer $id
* @return mixed
* Modifie un Product.
*/
public function actionUpdate($id)
{
$request = Yii::$app->request;
$productManager = $this->getProductManager();
$distributionManager = $this->getDistributionManager();

$request = Yii::$app->request;
$model = $this->findModel($id);

foreach ($model->productPointSale as $productPointSale) {
@@ -157,7 +161,7 @@ class ProductController extends BackendController

$photoFilenameOld = $model->photo;

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

Upload::uploadFile($model, 'photo', $photoFilenameOld);

@@ -167,12 +171,10 @@ class ProductController extends BackendController
$model->save();
}

// availability on points sale
$this->processAvailabilityPointsSale($model);

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

$this->setFlash('success', 'Produit <strong>' . Html::encode($model->name) . '</strong> modifié');
@@ -188,27 +190,29 @@ class ProductController extends BackendController
/**
* Traite les accès restreints d'un point de vente.
*/
public function processAvailabilityPointsSale($model)
public function processAvailabilityPointsSale($product)
{
ProductPointSale::deleteAll(['id_product' => $model->id]);
$pointSaleManager = $this->getPointSaleManager();
$productPointSaleManager = $this->getProductPointSaleManager();

ProductPointSale::deleteAll(['id_product' => $product->id]);

if (is_array($model->pointsSale) && count($model->pointsSale)) {
foreach ($model->pointsSale as $key => $val) {
$pointSale = PointSale::findOne($val);
if (is_array($product->pointsSale) && count($product->pointsSale)) {
foreach ($product->pointsSale as $key => $idPointSale) {
$pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
if ($pointSale) {
$productPointSale = new ProductPointSale;
$productPointSale->id_product = $model->id;
$productPointSale->id_point_sale = $pointSale->id;
$productPointSale->available = ($model->available_on_points_sale) ? 0 : 1;
$productPointSale->save();
$productPointSaleManager->createProductPointSale(
$product,
$pointSale,
($product->available_on_points_sale) ? false : true
);
}
}
}
}

public function actionPricesList($id)
public function actionPricesList(int $id)
{
$request = Yii::$app->request;
$model = $this->findModel($id);

$searchModel = new ProductPriceSearch();
@@ -247,10 +251,10 @@ class ProductController extends BackendController

$conditionsProductPriceExist = [
'id_product' => $idProduct,
'id_user' => $model->id_user ? $model->id_user : null,
'id_user_group' => $model->id_user_group ? $model->id_user_group : null,
'id_point_sale' => $model->id_point_sale ? $model->id_point_sale : null,
'from_quantity' => $model->from_quantity ? $model->from_quantity : null,
'id_user' => $model->id_user ?? null,
'id_user_group' => $model->id_user_group ?? null,
'id_point_sale' => $model->id_point_sale ?? null,
'from_quantity' => $model->from_quantity ?? null,
];

$productPriceExist = ProductPrice::findOne($conditionsProductPriceExist);
@@ -274,8 +278,6 @@ class ProductController extends BackendController

public function actionPricesUpdate($id)
{
$request = Yii::$app->request;

$model = $this->findModelProductPrice($id);
$modelProduct = $this->findModel($model->id_product);

@@ -300,20 +302,16 @@ class ProductController extends BackendController
}

/**
* Supprime un modèle Produit.
* Si la suppression réussit, le navigateur est redirigé vers la page
* 'index'.
*
* @param integer $id
* @return mixed
* Supprime un Product.
*/
public function actionDelete($id, $confirm = false)
public function actionDelete(int $id, bool $confirm = false)
{
$product = $this->findModel($id);

if ($confirm) {
$product->delete();
ProductDistributionModel::deleteAll(['id_product' => $id]);
ProductDistribution::deleteAll(['id_product' => $id]);

$this->setFlash('success', 'Produit <strong>' . Html::encode($product->name) . '</strong> supprimé');
} else {
$this->setFlash('info', 'Souhaitez-vous vraiment supprimer le produit <strong>' . Html::encode($product->name) . '</strong> ? '
@@ -325,8 +323,6 @@ class ProductController extends BackendController

/**
* Modifie l'ordre des produits.
*
* @param array $array
*/
public function actionOrder()
{
@@ -343,26 +339,27 @@ class ProductController extends BackendController
public function actionAjaxToggleActive($id, $active)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$distributionManager = $this->getDistributionManager();

$product = $this->findModel($id);
$product->active = (int)$active;
$product->active = (int) $active;
$product->save();

DistributionModel::linkProductIncomingDistributions($product);
$distributionManager->addProductIncomingDistributions($product);

return ['success', 'id' => $id, 'active' => $active];
}

/**
* Recherche un produit en fonction de son ID.
*
* @param integer $id
* @return Produit
* @throws NotFoundHttpException si le modèle n'est pas trouvé
*/
protected function findModel($id)
protected function findModel(int $id)
{
if (($model = Product::findOne($id)) !== null) {
return $model;
$productManager = $this->getProductManager();

if (($product = $productManager->findOneProductById($id)) !== null) {
return $product;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
@@ -370,11 +367,11 @@ class ProductController extends BackendController

protected function findModelProductPrice($id)
{
if (($model = ProductPrice::findOne($id)) !== null) {
return $model;
$productPriceManager = $this->getProductPriceManager();
if (($productPrice = $productPriceManager->findOneProductPriceById($id)) !== null) {
return $productPrice;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}

}

+ 11
- 6
backend/controllers/QuotationController.php Parādīt failu

@@ -39,9 +39,13 @@
namespace backend\controllers;

use common\helpers\GlobalParam;
use common\logic\Document\Quotation\QuotationSearch;
use common\logic\Order\Order\Order;
use Yii;
use yii\base\UserException;

use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\Html;

class QuotationController extends DocumentController
{
@@ -86,17 +90,19 @@ class QuotationController extends DocumentController

public function actionTransform($id)
{
$quotationManager = $this->getQuotationManager();
$invoiceManager = $this->getInvoiceManager();
$quotation = $this->findModel($id);
if ($quotation->isStatusValid()) {
if ($quotationManager->isStatusValid($quotation)) {

$invoice = new Invoice;
$invoice->initTaxCalculationMethod();
$invoice = $invoiceManager->instanciateInvoice();
$invoiceManager->initTaxCalculationMethod($invoice);
$invoice->id_producer = GlobalParam::getCurrentProducerId();
$invoice->id_user = $quotation->id_user;
$invoice->address = $quotation->address;
$invoice->comment = $quotation->comment;
$invoice->name = str_replace(['Devis', 'devis'], 'Facture', $quotation->name);
$invoice->save();
$invoiceManager->saveCreate($invoice);

Order::updateAll([
'order.id_invoice' => $invoice->id
@@ -110,5 +116,4 @@ class QuotationController extends DocumentController
throw new UserException('Vous ne pouvez pas transformer en facture un devis non validé.');
}
}

}

+ 12
- 17
backend/controllers/ReportController.php Parādīt failu

@@ -39,6 +39,8 @@
namespace backend\controllers;

use common\helpers\GlobalParam;
use common\helpers\Price;
use common\logic\Distribution\Distribution\Distribution;
use Yii;
use yii\filters\AccessControl;

@@ -74,30 +76,24 @@ class ReportController extends BackendController
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$usersArray = User::findBy()->all();
$pointsSaleArray = PointSale::searchAll();

// distributions
$firstDistribution = DistributionModel::searchOne([], [
'orderby' => 'date ASC'
]);
$lastDistribution = DistributionModel::searchOne([], [
'orderby' => 'date DESC'
]);
$userManager = $this->getUserManager();
$pointSaleManager = $this->getPointSaleManager();
$distributionManager = $this->getDistributionManager();

$usersArray = $userManager->findUsers();
$pointsSaleArray = $pointSaleManager->findPointSales();
$firstDistribution = $distributionManager->findOneFirstDistribution();
$lastDistribution = $distributionManager->findOneLastDistribution();
$firstYear = date('Y', strtotime($firstDistribution->date));
$lastYear = date('Y', strtotime($lastDistribution->date));

$distributionYearsArray = [];
for ($year = $firstYear; $year <= $lastYear; $year++) {
$distributionYearsArray[] = $year;
}

$distributionsArray = DistributionModel::searchAll([
'distribution.active' => 1
], [
'orderby' => 'date ASC',
]);
$distributionsByMonthArray = [];
$distributionsArray = $distributionManager->findDistributionsActive();
foreach ($distributionsArray as $distribution) {
$month = date('Y-m', strtotime($distribution->date));
if (!isset($distributionsByMonthArray[$month])) {
@@ -123,10 +119,9 @@ class ReportController extends BackendController
public function actionAjaxReport()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$posts = Yii::$app->request->post();

$posts = Yii::$app->request->post();
$resArray = [];

$conditionUsers = $this->_generateConditionSqlReport($posts, 'users', 'id_user');
$conditionPointsSale = $this->_generateConditionSqlReport($posts, 'pointsSale', 'id_point_sale');
$conditionDistributions = $this->_generateConditionSqlReport($posts, 'distributions', 'id_distribution');

+ 3
- 10
backend/controllers/SiteController.php Parādīt failu

@@ -117,7 +117,6 @@ class SiteController extends BackendController
$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();

// commandes
$optionDashboardNumberDistributions = $producerManager->getConfig('option_dashboard_number_distributions');
$dashboardNumberDistributions = $optionDashboardNumberDistributions ? $optionDashboardNumberDistributions : 3;

@@ -182,9 +181,7 @@ class SiteController extends BackendController
->andWhere('user_producer.credit < 0')
->all();

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

$producerCurrent = GlobalParam::getCurrentProducer();
$productsCount = Product::searchCount();
$pointsSaleCount = PointSale::searchCount();

@@ -193,7 +190,7 @@ class SiteController extends BackendController
'ordersArray' => $ordersArray,
'usersArray' => $usersArray,
'usersNegativeCredit' => $usersNegativeCredit,
'producer' => $producer,
'producer' => $producerCurrent,
'productsCount' => $productsCount,
'pointsSaleCount' => $pointsSaleCount
]);
@@ -220,8 +217,6 @@ class SiteController extends BackendController

/**
* Déconnecte l'utilisateur et le redirige à la page d'accueil.
*
* @return mixed
*/
public function actionLogout()
{
@@ -233,10 +228,8 @@ class SiteController extends BackendController
/**
* Change le producteur courant de l'utilisateur connecté.
* Permet de passer d'un producteur à un autre en tant qu'administrateur.
*
* @param integer $id
*/
public function actionChangeProducer($id)
public function actionChangeProducer(int $id)
{
Yii::$app->user->identity->id_producer = $id;
Yii::$app->user->identity->save();

+ 6
- 9
backend/controllers/StatsController.php Parādīt failu

@@ -68,15 +68,12 @@ class StatsController extends BackendController

/**
* Affiche les statistiques de l'année avec le CA réalisé par mois.
*
* @return mixed
*/
public function actionIndex()
{
/*
* Volume de commande de l'année passée (par mois)
*/

$dateStart = date('Y-m-d', time() - 60 * 60 * 24 * 365);
$dateEnd = date('Y-m-d', time() + 60 * 60 * 24 * 31);

@@ -133,16 +130,16 @@ class StatsController extends BackendController
/**
* Affiche un tableau avec les totaux (maximums, commandés) de chaque produit
* par mois d'une année donnée.
*
* @param integer $year
* @return mixed
*/
public function actionProducts($year = 0, $section = 1)
public function actionProducts(int $year = 0, $section = 1)
{
if (!$year) $year = date('Y');
$productManager = $this->getProductManager();

$productsArray = Product::searchAll();
if (!$year) {
$year = date('Y');
}

$productsArray = $productManager->findProducts();
$dataProducts = [];

$dataProducts[self::TOTALS] = ['max' => [], 'orders' => []];

+ 57
- 73
backend/controllers/SubscriptionController.php Parādīt failu

@@ -37,7 +37,12 @@

namespace backend\controllers;

use common\forms\SubscriptionForm;
use common\helpers\GlobalParam;
use common\logic\Product\Product\Product;
use common\logic\Subscription\Subscription\SubscriptionSearch;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;

class SubscriptionController extends BackendController
{
@@ -70,7 +75,7 @@ class SubscriptionController extends BackendController
{
$this->checkProductsPointsSale();

$searchModel = new SubscriptionSearch;
$searchModel = new SubscriptionSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);

return $this->render('index', [
@@ -81,18 +86,21 @@ class SubscriptionController extends BackendController

/**
* Crée un abonnement.
*
* @return string
*/
public function actionCreate($idOrder = 0)
{
// form
$model = new SubscriptionForm;
$orderManager = $this->getOrderManager();
$producerManager = $this->getProducerManager();
$productManager = $this->getProductManager();
$subscriptionManger = $this->getSubscriptionManager();
$distributionManager = $this->getDistributionManager();

$model = new SubscriptionForm();
$model->isAdmin = true;
$model->id_producer = GlobalParam::getCurrentProducerId();

if ($idOrder) {
$order = Order::searchOne(['id' => $idOrder]);
$order = $orderManager->findOneOrderById($idOrder);
if ($order) {
$model->id_user = $order->id_user;
$model->username = $order->username;
@@ -101,11 +109,10 @@ class SubscriptionController extends BackendController
$dateDay = strtolower(date('l', strtotime($order->distribution->date)));
$model->$dateDay = 1;
$model->week_frequency = 1;
if ($model->id_user && Producer::getConfig('credit')) {
if ($model->id_user && $producerManager->getConfig('credit')) {
$model->auto_payment = 1;
}

// produits
foreach ($order->productOrder as $productOrder) {
$model->products['product_' . $productOrder->id_product] = $productOrder->quantity;
}
@@ -115,16 +122,15 @@ class SubscriptionController extends BackendController
}

// produits
$productsArray = Product::searchAll([], [
'orderby' => 'product.order ASC'
]);
$productsArray = $productManager->findProducts();
if ($model->load(\Yii::$app->request->post()) && $model->validate() && $model->save()) {

if ($model->load(\Yii::$app->request->post()) && $model->validate()
&& $model->save()) {
$this->setFlash('success', 'Abonnement ajouté');

$subscription = Subscription::findOne($model->id);
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions();
$subscription = $subscriptionManger->findOneSubscriptionById($model->id);
$matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);

if (count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]);
} else {
@@ -140,17 +146,18 @@ class SubscriptionController extends BackendController

/**
* Modifie un abonnement.
*
* @param integer $id
* @return string
* @throws NotFoundHttpException
*/
public function actionUpdate($id)
{
// form
$subscriptionManager = $this->getSubscriptionManager();
$productSubscriptionManager = $this->getProductSubscriptionManager();
$productManager = $this->getProductManager();
$orderManager = $this->getOrderManager();
$distributionManager = $this->getDistributionManager();

$model = new SubscriptionForm;
$model->isAdmin = true;
$subscription = Subscription::findOne($id);
$subscription = $subscriptionManager->findOneSubscriptionById($id);

if ($subscription) {
$model->id = $id;
@@ -177,11 +184,7 @@ class SubscriptionController extends BackendController
$model->comment = $subscription->comment;
}

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

$arrayProductsSubscription = $productSubscriptionManager->findProductSubscriptionsBySubscription($subscription);
foreach ($arrayProductsSubscription as $productSubscription) {
$model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
}
@@ -190,9 +193,7 @@ class SubscriptionController extends BackendController
}

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

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

@@ -202,12 +203,11 @@ class SubscriptionController extends BackendController

if ($model->save()) {

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

$subscription = $subscriptionManager->findOneSubscriptionById($model->id);
$messageOrdersDeleted = '';
if ($model->date_end) {
$countOrdersDeleted = $subscription->deleteOrdersIncomingDistributions(true);

if ($model->date_end) {
$countOrdersDeleted = $orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription, true);
if ($countOrdersDeleted) {
$messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées';
}
@@ -215,7 +215,7 @@ class SubscriptionController extends BackendController

$this->setFlash('success', 'Abonnement modifié' . $messageOrdersDeleted);

$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions();
$matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);
if (count($matchedDistributionsArray)) {
return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id, 'update' => true]);
} else {
@@ -232,32 +232,36 @@ class SubscriptionController extends BackendController

/**
* Supprime une commande récurrente.
*
* @param integer $id
*/
public function actionDelete($id)
public function actionDelete(int $id)
{
$subscription = Subscription::searchOne([
'subscription.id' => $id
]);
$subscription->deleteOrdersIncomingDistributions();
$subscription->delete();
ProductSubscription::deleteAll(['id_subscription' => $id]);
$subscriptionManager = $this->getSubscriptionManager();
$orderManager = $this->getOrderManager();

$subscription = $subscriptionManager->findOneSubscriptionById($id);
$orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription);
$subscriptionManager->deleteSubscription($subscription);

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

return $this->redirect(['subscription/index']);
}

public function actionUpdateDistributions($idSubscription, $generate = false, $update = false)
public function actionUpdateDistributions(int $idSubscription, bool $generate = false, bool $update = false)
{
$subscription = Subscription::findOne($idSubscription);
$matchedDistributionsArray = $subscription->searchMatchedIncomingDistributions();
$subscriptionManager = $this->getSubscriptionManager();
$distributionManager = $this->getDistributionManager();
$orderManager = $this->getOrderManager();

$subscription = $subscriptionManager->findOneSubscriptionById($idSubscription);
$matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);

if ($generate) {
if ($update) {
$subscription->deleteOrdersIncomingDistributions();
$orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription);
}
foreach ($matchedDistributionsArray as $distribution) {
$subscription->add($distribution->date);
$orderManager->createOrderFromSubscription($subscription, $distribution->date);
}
$this->setFlash('success', 'Commandes ' . ($update ? 're-' : '') . 'générées dans les distributions futures.');
return $this->redirect(['subscription/index']);
@@ -270,10 +274,12 @@ class SubscriptionController extends BackendController
]);
}

public function actionAjaxInfos($idSubscription = 0)
public function actionAjaxInfos(int $idSubscription = 0)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

$productManager = $this->getProductManager();

$productsQuery = Product::find()
->where(['id_producer' => GlobalParam::getCurrentProducerId(),]);

@@ -284,31 +290,11 @@ class SubscriptionController extends BackendController
}

$productsArray = $productsQuery->asArray()->orderBy('order ASC')->all();
/*Debug::dump($productsArray);*/
foreach ($productsArray as &$theProduct) {
/*$theProduct['unit_save'] = $theProduct['unit'] ;
$theProduct['units'] = [] ;
$theProduct['units'][] = [
'unit' => $theProduct['unit'],

'step' => $theProduct['step'],
'price' => $theProduct['price']
] ;*/

$theProduct['wording_unit'] = Product::strUnit($theProduct['unit'], 'wording_short');
foreach ($productsArray as &$theProduct) {
$theProduct['wording_unit'] = $productManager->strUnit($theProduct['unit'], 'wording_short');

if (isset($theProduct['productSubscription'][0])) {
/*if($theProduct['productSubscription'][0]['unit'] != $theProduct['unit']) {
$theProduct['units'][] = [
'unit' => $theProduct['productSubscription'][0]['unit'],
'wording_unit' => Product::strUnit($theProduct['productSubscription'][0]['unit'], 'wording_short'),
'step' => $theProduct['productSubscription'][0]['step'],
'price' => $theProduct['productSubscription'][0]['price'],
] ;
$theProduct['unit'] = $theProduct['productSubscription'][0]['unit'] ;
$theProduct['step'] = $theProduct['productSubscription'][0]['step'] ;
$theProduct['price'] = $theProduct['productSubscription'][0]['price'] ;
}*/
$theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * Product::$unitsArray[$theProduct['unit']]['coefficient'];
} else {
$theProduct['quantity'] = '';
@@ -319,6 +305,4 @@ class SubscriptionController extends BackendController
'products' => $productsArray
];
}


}

+ 8
- 7
backend/controllers/TaxRateAdminController.php Parādīt failu

@@ -87,7 +87,7 @@ class TaxRateAdminController extends BackendController

public function actionCreate()
{
$model = $this->getTaxRateManager()->createTaxRate();
$model = $this->getTaxRateManager()->instanciateTaxRate();

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
$this->setFlash('success', 'Taxe créée.');
@@ -115,19 +115,20 @@ class TaxRateAdminController extends BackendController

public function actionDelete(int $id)
{
$taxeRate = TaxRate::searchOne([
'id' => $id
]);
$taxeRate->delete();
$taxRateManager = $this->getTaxRateManager();
$taxRate = $this->findModel($id);
$taxRateManager->delete($taxRate);

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

return $this->redirect(['tax-rate-admin/index']);
}

protected function findModel($id)
{
if (($model = TaxRate::findOne($id)) !== null) {
return $model;
$taxRateManager = $this->getTaxRateManager();
if (($taxRate = $taxRateManager->findOneTaxRateById($id)) !== null) {
return $taxRate;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}

+ 71
- 94
backend/controllers/UserController.php Parādīt failu

@@ -47,12 +47,10 @@ use common\logic\Distribution\Distribution\Distribution;
use common\logic\Order\Order\OrderSearch;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\PointSale\UserPointSale\UserPointSale;
use common\logic\Producer\Producer\Producer;
use common\logic\User\CreditHistory\CreditHistory;
use common\logic\User\User\UserSearch;
use common\logic\User\UserGroup\UserGroup;
use common\logic\User\UserGroup\UserUserGroup;
use common\logic\User\UserProducer\UserProducer;
use common\logic\User\UserUserGroup\UserUserGroup;
use yii\base\UserException;
use yii\debug\models\search\User;
use yii\filters\AccessControl;
@@ -65,7 +63,6 @@ use yii\web\NotFoundHttpException;
*/
class UserController extends BackendController
{

public function behaviors()
{
return [
@@ -91,19 +88,21 @@ class UserController extends BackendController

/**
* Liste les utilisateurs.
*
* @return mixed
*/
public function actionIndex(
$idPointSale = 0, $sectionSubscribers = false, $sectionInactiveUsers = false)
int $idPointSale = 0,
bool $sectionSubscribers = false,
bool $sectionInactiveUsers = false)
{
$pointSaleManager = $this->getPointSaleManager();

$searchModel = new UserSearch();
$dataProvider = $searchModel->search([
'UserSearch' => array_merge(
[
'id_point_sale' => $idPointSale,
'inactive' => (int)$sectionInactiveUsers,
'subscribers' => (int)$sectionSubscribers
'inactive' => (int) $sectionInactiveUsers,
'subscribers' => (int) $sectionSubscribers
],
isset(\Yii::$app->request->queryParams['UserSearch']) ?
Yii::$app->request->queryParams['UserSearch'] :
@@ -111,11 +110,8 @@ class UserController extends BackendController
)
]);

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

$pointsSaleArray = PointSale::searchAll();
$producer = $this->getProducerCurrent();
$pointsSaleArray = $pointSaleManager->findPointSales();

return $this->render('index', [
'searchModel' => $searchModel,
@@ -130,37 +126,31 @@ class UserController extends BackendController

public function initForm($model)
{
$userPointSaleManager = $this->getUserPointSaleManager();
$userUserGroupManager = $this->getUserUserGroupManager();
$userProducerManager = $this->getUserProducerManager();
$userGroupManager = $this->getUserGroupManager();

$producerCurrent = $this->getProducerCurrent();

if ($model->id) {
// init points de vente sélectionnés
$userPointSaleArray = UserPointSale::searchAll([
'id_user' => $model->id
]);
$userPointSaleArray = $userPointSaleManager->findUserPointSalesByUser($model);
if ($userPointSaleArray && count($userPointSaleArray) > 0) {
foreach ($userPointSaleArray as $userPointSaleArray) {
$model->points_sale[] = $userPointSaleArray->id_point_sale;
foreach ($userPointSaleArray as $userPointSale) {
$model->points_sale[] = $userPointSale->id_point_sale;
}
}

// init groupes d'utilisateurs sélectionnés
$userUserGroupsArray = UserUserGroup::searchAll([
'id_user' => $model->id
]);
$userUserGroupsArray = $userUserGroupManager->findUserUserGroupsByUser($model);
if ($userUserGroupsArray && count($userUserGroupsArray) > 0) {
foreach ($userUserGroupsArray as $userUserGroup) {
$model->user_groups[] = $userUserGroup->id_user_group;
}
}

// product price percent
$userProducer = UserProducer::searchOne([
'id_producer' => GlobalParam::getCurrentProducerId(),
'id_user' => $model->id
]);
$userProducer = $userProducerManager->findOneUserProducer($model, $producerCurrent);
$model->product_price_percent = $userProducer->product_price_percent;
}

// points de vente
$pointsSaleArray = PointSale::find()
->where([
'id_producer' => GlobalParam::getCurrentProducerId(),
@@ -173,12 +163,7 @@ class UserController extends BackendController
}])
->all();

// groupes d'utilisateurs
$userGroupsArray = UserGroup::find()
->where([
'id_producer' => GlobalParam::getCurrentProducerId(),
])
->all();
$userGroupsArray = $userGroupManager->findUserGroups();

return [
'pointsSaleArray' => $pointsSaleArray,
@@ -189,33 +174,33 @@ class UserController extends BackendController
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new User();
$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();

$producerCurrent = $this->getProducerCurrent();
$model = $userManager->instanciateUser();

$userExist = false;
$posts = Yii::$app->request->post();

if ($posts && isset($posts['User']['email']) && strlen($posts['User']['email']) > 0) {
$userExist = User::searchOne([
'email' => $posts['User']['email']
]);
$userExist = $userManager->findOneUserByEmail($posts['User']['email']);
}

if ($userExist) {
Producer::addUser($userExist->id, GlobalParam::getCurrentProducerId());
$producerManager->addUser($userExist, $producerCurrent);
$this->processLinkPointSale($userExist);
$this->processLinkUserGroup($userExist);
$this->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.");
} else {
if ($model->load(\Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
// save user
$password = Password::generate();
$model->id_producer = 0;
$model->setPassword($password);
$model->generateAuthKey();
$password = Password::generate();
$userManager->setPassword($model, $password);
$userManager->generateAuthKey($model);
$model->username = $model->email;
if (!strlen($model->email)) {
$model->username = 'inconnu@opendistrib.net';
@@ -231,13 +216,13 @@ class UserController extends BackendController
$useProducer->active = 1;
$useProducer->save();

$model->sendMailWelcome($password);
$userManager->sendMailWelcome($model, $password);
$this->processLinkPointSale($model);
$this->processLinkUserGroup($model);
$this->processProductPricePercent($model);

$this->setFlash('success', 'Utilisateur créé.');
$model = new User();
$model = $userManager->instanciateUser();
}
}

@@ -250,11 +235,12 @@ class UserController extends BackendController
/**
* Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$userManager = $this->getUserManager();
$producerManager = $this->getProducerManager();

$model = $this->findModel($id);

// Moodification du profil
@@ -267,13 +253,14 @@ class UserController extends BackendController
// on envoie le mail de bienvenue si le mail vient d'être défini
if (!strlen($previousMail) && strlen($model->email)) {
$password = Password::generate();
$model->setPassword($password);
$userManager->setPassword($model, $password);
$model->username = $model->email;
$model->sendMailWelcome($password);
$userManager->sendMailWelcome($model, $password);
}
$this->processLinkPointSale($model);
$this->processLinkUserGroup($model);
$this->processProductPricePercent($model);

$this->setFlash('success', 'Utilisateur modifié.');
}
} else {
@@ -287,13 +274,13 @@ class UserController extends BackendController
$model->setPassword($password);
$model->save();

$producer = GlobalParam::getCurrentProducer();
$producer = $this->getProducerCurrent();

Mailjet::sendMail([
'from_email' => $producer->getEmailOpendistrib(),
'from_email' => $producerManager->getEmailOpendistrib($producer),
'from_name' => $producer->name,
'to_email' => $model->email,
'to_name' => $model->getUsername(),
'to_name' => $userManager->getUsername($user),
'subject' => '[' . $producer->name . '] Nouveau mot de passe',
'content_view_text' => '@common/mail/newPasswordUserAdmin-text.php',
'content_view_html' => '@common/mail/newPasswordUserAdmin-html.php',
@@ -314,10 +301,8 @@ class UserController extends BackendController

/**
* Lie un utilisateur aux points de vente sélectionnés.
*
* @param User $modelUser
*/
public function processLinkPointSale($modelUser)
public function processLinkPointSale(User $modelUser)
{
$posts = Yii::$app->request->post();
UserPointSale::deleteAll([
@@ -342,12 +327,9 @@ class UserController extends BackendController

/**
* Lie un utilisateur aux groupes d'utilisateurs sélectionnés.
*
* @param User $modelUser
*/
public function processLinkUserGroup($modelUser)
{
$posts = Yii::$app->request->post();
UserUserGroup::deleteAll([
'id_user' => $modelUser->id
]);
@@ -383,19 +365,17 @@ class UserController extends BackendController

/**
* Désactive l'utilisateur de l'établissement.
*
* @param integer $id ID de l'utilisateur
*/
public function actionDelete($id)
public function actionDelete(int $id)
{
$userProducer = UserProducer::findOne([
'id_user' => $id,
'id_producer' => GlobalParam::getCurrentProducerId()
]);
$userProducerManager = $this->getUserProducerManager();
$userProducer = $userProducerManager->findOneUserProducer($userProducer);

if ($userProducer) {
$userProducer->active = 0;
$userProducer->bookmark = 0;
$userProducer->save();

$this->setFlash('success', 'L\'utilisateur a bien été supprimé de votre établissement.');
} else {
throw new \yii\web\NotFoundHttpException('L\'enregistrement UserProducer est introuvable', 404);
@@ -408,11 +388,7 @@ class UserController extends BackendController
}

/**
* Affiche la liste des emails des utilisateurs liés à un point de vente
* donné.
*
* @param integer $idPointSale
* @return mixed
* Affiche la liste des emails des utilisateurs liés à un point de vente donné.
*/
public function actionMail(
$idPointSale = 0,
@@ -421,11 +397,14 @@ class UserController extends BackendController
$usersPointSaleLink = 0,
$usersPointSaleHasOrder = 0)
{
$userManager = $this->getUserManager();
$distributionManager = $this->getDistributionManager();

if ($idPointSale && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
$usersPointSaleLink = 1;
}

$users = User::findBy([
$users = $userManager->queryUsersBy([
'id_producer' => GlobalParam::getCurrentProducerId(),
'id_point_sale' => $idPointSale,
'users_point_sale_link' => $usersPointSaleLink,
@@ -474,7 +453,7 @@ class UserController extends BackendController
return $this->redirect(['mail', 'idPointSale' => $idPointSale]);
}

$incomingDistributions = Distribution::getIncoming();
$incomingDistributions = $distributionManager->findDistributionsIncoming();
$incomingDistributionsArray = ['0' => '--'];
foreach ($incomingDistributions as $distribution) {
$incomingDistributionsArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date));
@@ -495,19 +474,14 @@ class UserController extends BackendController
}

/**
* Affiche les données liées au crédit d'un utilisateur (formulaire,
* historique).
*
* @param integer $id
* @return mixed
* @throws UserException
* Affiche les données liées au crédit d'un utilisateur (formulaire, historique).
*/
public function actionCredit($id)
public function actionCredit(int $id)
{
$user = User::find()->with('userProducer')->where(['id' => $id])->one();
$userProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]);

if (($userProducer) || User::getCurrentStatus() == User::STATUS_ADMIN) {
if (($userProducer) || $this->isUserCurrentAdmin()) {

$creditForm = new CreditForm();
if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
@@ -545,7 +519,9 @@ class UserController extends BackendController
*/
public function actionOrders($id)
{
$user = User::findOne($id);
$userManager = $this->getUserManager();

$user = $userManager->findOneUserById($id);
$searchModel = new OrderSearch();
$dataProvider = $searchModel->search(array_merge(\Yii::$app->request->queryParams, ['id_user' => $id]));

@@ -559,15 +535,15 @@ class UserController extends BackendController
/**
* Modifie l'option "credit_active" d'un utilisateur pour le producteur courant.
* Redirige vers la page de crédit de l'utilisateur.
*
* @param integer $idUser
* @param boolean $state
*/
public function actionStateCredit($idUser, $state)
{
$userProducer = UserProducer::searchOne([
'id_user' => $idUser
]);
$userManager = $this->getUserManager();
$userProducerManager = $this->getUserProducerManager();

$user = $userManager->findOneUserById($idUser);
$producerCurrent = $this->getproducerCurrent();
$userProducer = $userProducerManager->findOneUserProducer($user,$producerCurrent);

if ($userProducer) {
$userProducer->credit_active = $state;
@@ -583,11 +559,12 @@ class UserController extends BackendController
*/
protected function findModel($id)
{
if (($model = User::findOne($id)) !== null) {
return $model;
$userManager = $this->getUserManager();

if (($user = $userManager->findOneUserById($id)) !== null) {
return $user;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}

}

+ 9
- 18
backend/controllers/UserGroupController.php Parādīt failu

@@ -39,6 +39,8 @@
namespace backend\controllers;

use common\helpers\GlobalParam;
use common\logic\User\UserGroup\UserGroupSearch;
use common\logic\User\UserUserGroup\UserUserGroup;
use Yii;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
@@ -92,13 +94,12 @@ class UserGroupController extends BackendController

/**
* Crée un groupe d'utilisateur.
*
* @return mixed
*/
public function actionCreate()
{
$model = new UserGroup();
$userGroupManager = $this->getUserGroupManager();

$model = $userGroupManager->instanciateUserGroup();
$model->id_producer = GlobalParam::getCurrentProducerId();

if ($model->load(\Yii::$app->request->post()) && $model->save()) {
@@ -113,11 +114,8 @@ class UserGroupController extends BackendController

/**
* Modifie un groupe d'utilisateur.
*
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
public function actionUpdate(int $id)
{
$model = $this->findModel($id);

@@ -133,14 +131,10 @@ class UserGroupController extends BackendController

/**
* Supprime un groupe d'utilisateur.
*
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
public function actionDelete(int $id)
{
$userGroup = $this->findModel($id);

$userGroup->delete();
UserUserGroup::deleteAll(['id_user_group' => $id]);
$this->setFlash('success', 'Groupe d\'utilisateur <strong>' . Html::encode($userGroup->name) . '</strong> supprimé.');
@@ -150,14 +144,11 @@ class UserGroupController extends BackendController

/**
* Recherche un groupe d'utilisateur en fonction de son ID.
*
* @param integer $id
* @return UserGroup
* @throws NotFoundHttpException si le modèle n'est pas trouvé
*/
protected function findModel($id)
protected function findModel(int $id)
{
if (($model = UserGroup::findOne($id)) !== null) {
$userGroupManager = $this->getUserGroupManager();
if (($model = $userGroupManager->findOneUserGroupById($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');

+ 5
- 0
common/logic/Config/TaxRate/TaxRateRepository.php Parādīt failu

@@ -17,6 +17,11 @@ class TaxRateRepository extends BaseService implements RepositoryInterface
] ;
}

public function findOneTaxRateById(int $id): ?TaxRate
{
return TaxRate::searchOne(['id' => $id]);
}

public function findTaxRates(): array
{
return TaxRate::find()->all();

+ 16
- 0
common/logic/Distribution/Distribution/DistributionRepository.php Parādīt failu

@@ -58,10 +58,26 @@ class DistributionRepository extends BaseService implements RepositoryInterface
]);
}

public function findOneFirstDistribution(): ?Distribution
{
return Distribution::searchOne([], [
'orderby' => 'date ASC'
]);
}

public function findOneLastDistribution(): ?Distribution
{
return Distribution::searchOne([], [
'orderby' => 'date DESC'
]);
}

public function findDistributionsActive(): array
{
return Distribution::searchAll([
'active' => 1
], [
'orderby' => 'date ASC',
]);
}


+ 7
- 2
common/logic/PointSale/UserPointSale/UserPointSaleRepository.php Parādīt failu

@@ -3,9 +3,7 @@
namespace common\logic\PointSale\UserPointSale;

use common\logic\BaseService;
use common\logic\BuilderInterface;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\PointSale\UserPointSale\UserPointSale;
use common\logic\RepositoryInterface;
use common\logic\User\User\User;

@@ -21,6 +19,13 @@ class UserPointSaleRepository extends BaseService implements RepositoryInterface
] ;
}

public function findUserPointSalesByUser(User $user): array
{
return UserPointSale::searchAll([
'id_user' => $user->id
]);
}

public function findOneUserPointSale(User $user, PointSale $pointSale)
{
return UserPointSale::find()

+ 3
- 1
common/logic/Product/Product/ProductRepository.php Parādīt failu

@@ -43,7 +43,9 @@ class ProductRepository extends BaseService implements RepositoryInterface

public function findProducts(): array
{
return Product::searchAll();
return Product::searchAll([], [
'orderby' => 'product.order ASC'
]);
}

/**

+ 7
- 1
common/logic/Product/ProductPointSale/ProductPointSaleBuilder.php Parādīt failu

@@ -4,6 +4,8 @@ namespace common\logic\Product\ProductPointSale;

use common\logic\BaseBuilder;
use common\logic\BuilderInterface;
use common\logic\PointSale\PointSale\PointSale;
use common\logic\Product\Product\Product;

class ProductPointSaleBuilder extends BaseBuilder implements BuilderInterface
{
@@ -14,9 +16,13 @@ class ProductPointSaleBuilder extends BaseBuilder implements BuilderInterface
return $productPointSale;
}

public function createProductPointSale(): ProductPointSale
public function createProductPointSale(Product $product, PointSale $pointSale, bool $available): ProductPointSale
{
$productPointSale = $this->instanciateProductPointSale();
$productPointSale->populateProduct($product);
$productPointSale->populatePointSale($pointSale);
$productPointSale->availability = $available;

$this->saveCreate($productPointSale);

return $productPointSale;

+ 5
- 0
common/logic/Product/ProductPrice/ProductPriceRepository.php Parādīt failu

@@ -19,4 +19,9 @@ class ProductPriceRepository extends BaseService implements RepositoryInterface
'attribute_id_producer' => 'product.id_producer'
];
}

public function findOneProductPriceById(int $id): ?ProductPrice
{
return ProductPrice::searchOne(['id' => $id]);
}
}

+ 8
- 0
common/logic/Subscription/ProductSubscription/ProductSubscriptionRepository.php Parādīt failu

@@ -4,6 +4,7 @@ namespace common\logic\Subscription\ProductSubscription;

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

class ProductSubscriptionRepository extends BaseService implements RepositoryInterface
{
@@ -19,4 +20,11 @@ class ProductSubscriptionRepository extends BaseService implements RepositoryInt
'attribute_id_producer' => ''
];
}

public function findProductSubscriptionsBySubscription(Subscription $subscription): array
{
return ProductSubscription::searchAll([
'id_subscription' => $subscription->id
]);
}
}

+ 5
- 0
common/logic/User/UserGroup/UserGroupRepository.php Parādīt failu

@@ -18,6 +18,11 @@ class UserGroupRepository extends BaseService implements RepositoryInterface
];
}

public function findOneUserGroupById(int $id)
{
return UserGroup::searchOne(['id' => $id]);
}

public function findUserGroups()
{
return UserGroup::find()->where('id_producer = ' . GlobalParam::getCurrentProducerId())->all();

+ 8
- 0
common/logic/User/UserUserGroup/UserUserGroupRepository.php Parādīt failu

@@ -4,6 +4,7 @@ namespace common\logic\User\UserUserGroup;

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

class UserUserGroupRepository extends BaseService implements RepositoryInterface
{
@@ -16,4 +17,11 @@ class UserUserGroupRepository extends BaseService implements RepositoryInterface
'attribute_id_producer' => ''
] ;
}

public function findUserUserGroupsByUser(User $user)
{
return UserUserGroup::searchAll([
'id_user' => $user->id
]);
}
}

Notiek ielāde…
Atcelt
Saglabāt